private static int findPairBracketPosition(final String str, final int startPos) {

		int bracketNum = 0;
	    for (int i = startPos; i < str.length(); i++)
	    {
	        char current = str.charAt(i);
	        if (current == TieConstants.EL_START_BRACKET)
	        {
	            bracketNum++;
	        } else if (current == TieConstants.EL_END )
	        {
	        	bracketNum--;
	        	if (bracketNum <=0 ) {
	                return i;
	        	}
	        }
	    }
	    return -1;
	}

private static int findPairBracketPosition ( final String str , final int startPos ) { int bracketNum = 0 ; for ( int i = startPos ; i < str . length ( ) ; i ++ ) { char current = str . charAt ( i ) ; if ( current == TieConstants . EL_START_BRACKET ) { bracketNum ++ ; } else if ( current == TieConstants . EL_END ) { bracketNum -- ; if ( bracketNum <= 0 ) { return i ; } } } return - 1 ; }

Find pair bracket position.

@param str the str
@param startPos the start pos
@return the int


public static Map<String, String> parseCommandAttributes(
			final String attrString) {
		Map<String, String> attrMap = new LinkedHashMap<>();
		Matcher attrMatcher = TieConstants.ATTR_REGEX_PATTERN
				.matcher(attrString);
		while (attrMatcher.find()) {
			String attrData = attrMatcher.group();
			int attrNameEndIndex = attrData.indexOf('=');
			String attrName = attrData.substring(0, attrNameEndIndex)
					.trim();
			String attrValuePart = attrData.substring(attrNameEndIndex + 1)
					.trim();
			String attrValue = attrValuePart.substring(1,
					attrValuePart.length() - 1);
			attrMap.put(attrName, attrValue);
		}
		return attrMap;
	}

public static Map < String , String > parseCommandAttributes ( final String attrString ) { Map < String , String > attrMap = new LinkedHashMap <> ( ) ; Matcher attrMatcher = TieConstants . ATTR_REGEX_PATTERN . matcher ( attrString ) ; while ( attrMatcher . find ( ) ) { String attrData = attrMatcher . group ( ) ; int attrNameEndIndex = attrData . indexOf ( ' ' ) ; String attrName = attrData . substring ( 0 , attrNameEndIndex ) . trim ( ) ; String attrValuePart = attrData . substring ( attrNameEndIndex + 1 ) . trim ( ) ; String attrValue = attrValuePart . substring ( 1 , attrValuePart . length ( ) - 1 ) ; attrMap . put ( attrName , attrValue ) ; } return attrMap ; }

Parse the attributes from string.

@param attrString
command string.
@return attributes map.


public static void parseInputAttributes(
			final List<CellFormAttributes> clist,
			final String controlAttrs) {
		// only one type control allowed for one cell.
		clist.clear();
		if (controlAttrs != null) {
			String[] cattrs = controlAttrs.split(
					TieConstants.SPLIT_SPACE_SEPERATE_ATTRS_REGX, -1);
			for (String cattr : cattrs) {
				String[] details = splitByEualSign(cattr);
				if (details.length > 1) {
					CellFormAttributes attr = new CellFormAttributes();
					attr.setType(details[0].trim());
					attr.setValue(details[1].replaceAll("\"", ""));
					clist.add(attr);
				}
			}
		}
	}

parse input attributes.

@param clist
list of cellformattributes.
@param controlAttrs
control attrs.


public static void parseValidateAttributes(
			final List<CellFormAttributes> clist,
			final String controlAttrs) {
		// one cell could have multiple validation rules.
		if (controlAttrs == null) {
			return;
		}
		String[] cattrs = controlAttrs
				.split(TieConstants.SPLIT_SPACE_SEPERATE_ATTRS_REGX, -1);

		CellFormAttributes attr = new CellFormAttributes();
		for (String cattr : cattrs) {
			extractValidationAttributes(attr, cattr);
		}
		if ((attr.getValue() != null) && (!attr.getValue().isEmpty())) {
			clist.add(attr);
		}
	}

parse validate attributes.

@param clist
list of cellformattributes.
@param controlAttrs
control attrs.


private static String[] splitByEualSign(final String attrData) {
		int attrNameEndIndex = attrData.indexOf('=');
		if (attrNameEndIndex < 0) {
			return new String[0];
		}
		String attrName = attrData.substring(0, attrNameEndIndex).trim();
		String attrValue = attrData.substring(attrNameEndIndex + 1).trim();
		String[] rlist = new String[2];
		rlist[0] = attrName;
		rlist[1] = attrValue;
		return rlist;
	}

private static String [ ] splitByEualSign ( final String attrData ) { int attrNameEndIndex = attrData . indexOf ( ' ' ) ; if ( attrNameEndIndex < 0 ) { return new String [ 0 ] ; } String attrName = attrData . substring ( 0 , attrNameEndIndex ) . trim ( ) ; String attrValue = attrData . substring ( attrNameEndIndex + 1 ) . trim ( ) ; String [ ] rlist = new String [ 2 ] ; rlist [ 0 ] = attrName ; rlist [ 1 ] = attrValue ; return rlist ; }

split string by = sign.

@param attrData
string.
@return splitted string array.


public static void parseSpecialAttributes(final String key,
			final String type, final List<CellFormAttributes> inputs,
			final CellAttributesMap cellAttributesMap) {

		SpecialAttributes sAttr = new SpecialAttributes();

		for (CellFormAttributes attr : inputs) {
			gatherSpecialAttributes(type, sAttr, attr);
		}

		if (sAttr.selectLabels != null) {
			processSelectItemAttributes(key, cellAttributesMap, sAttr);
		}
		if (type.equalsIgnoreCase(TieConstants.WIDGET_CALENDAR)) {
			processCalendarAttributes(key, cellAttributesMap, sAttr);
		}
	}

public static void parseSpecialAttributes ( final String key , final String type , final List < CellFormAttributes > inputs , final CellAttributesMap cellAttributesMap ) { SpecialAttributes sAttr = new SpecialAttributes ( ) ; for ( CellFormAttributes attr : inputs ) { gatherSpecialAttributes ( type , sAttr , attr ) ; } if ( sAttr . selectLabels != null ) { processSelectItemAttributes ( key , cellAttributesMap , sAttr ) ; } if ( type . equalsIgnoreCase ( TieConstants . WIDGET_CALENDAR ) ) { processCalendarAttributes ( key , cellAttributesMap , sAttr ) ; } }

parse select item attributes.

@param key
key.
@param type
type.
@param inputs
inputs.
@param cellAttributesMap
cellattributesmap.


private static void processCalendarAttributes(final String key,
			final CellAttributesMap cellAttributesMap,
			final SpecialAttributes sAttr) {
		cellAttributesMap.getCellDatePattern().put(key,
				sAttr.defaultDatePattern);
	}

private static void processCalendarAttributes ( final String key , final CellAttributesMap cellAttributesMap , final SpecialAttributes sAttr ) { cellAttributesMap . getCellDatePattern ( ) . put ( key , sAttr . defaultDatePattern ) ; }

Process calendar attributes.

@param key
the key
@param cellAttributesMap
the cell attributes map
@param sAttr
the s attr


private static void processSelectItemAttributes(final String key,
			final CellAttributesMap cellAttributesMap,
			final SpecialAttributes sAttr) {
		if ((sAttr.selectValues == null)
				|| (sAttr.selectValues.length != sAttr.selectLabels.length)) {
			sAttr.selectValues = sAttr.selectLabels;
		}
		Map<String, String> smap = cellAttributesMap
				.getCellSelectItemsAttributes().get(key);
		if (smap == null) {
			smap = new LinkedHashMap<>();
		}
		smap.clear();
		if (sAttr.defaultSelectLabel != null) {
			smap.put(sAttr.defaultSelectLabel, sAttr.defaultSelectValue);
		}
		for (int i = 0; i < sAttr.selectLabels.length; i++) {
			smap.put(sAttr.selectLabels[i], sAttr.selectValues[i]);
		}
		cellAttributesMap.getCellSelectItemsAttributes().put(key, smap);
	}

private static void processSelectItemAttributes ( final String key , final CellAttributesMap cellAttributesMap , final SpecialAttributes sAttr ) { if ( ( sAttr . selectValues == null ) || ( sAttr . selectValues . length != sAttr . selectLabels . length ) ) { sAttr . selectValues = sAttr . selectLabels ; } Map < String , String > smap = cellAttributesMap . getCellSelectItemsAttributes ( ) . get ( key ) ; if ( smap == null ) { smap = new LinkedHashMap <> ( ) ; } smap . clear ( ) ; if ( sAttr . defaultSelectLabel != null ) { smap . put ( sAttr . defaultSelectLabel , sAttr . defaultSelectValue ) ; } for ( int i = 0 ; i < sAttr . selectLabels . length ; i ++ ) { smap . put ( sAttr . selectLabels [ i ] , sAttr . selectValues [ i ] ) ; } cellAttributesMap . getCellSelectItemsAttributes ( ) . put ( key , smap ) ; }

Process select item attributes.

@param key
the key
@param cellAttributesMap
the cell attributes map
@param sAttr
the s attr


private static void gatherSpecialAttributes(final String type,
			final SpecialAttributes sAttr, final CellFormAttributes attr) {
		String attrKey = attr.getType();
		if (attrKey.equalsIgnoreCase(TieConstants.SELECT_ITEM_LABELS)) {
			sAttr.selectLabels = attr.getValue().split(";");
		}
		if (attrKey.equalsIgnoreCase(TieConstants.SELECT_ITEM_VALUES)) {
			sAttr.selectValues = attr.getValue().split(";");
		}
		if (attrKey.equalsIgnoreCase(
				TieConstants.DEFAULT_SELECT_ITEM_LABEL)) {
			sAttr.defaultSelectLabel = attr.getValue();
		}
		if (attrKey.equalsIgnoreCase(
				TieConstants.DEFAULT_SELECT_ITEM_VALUE)) {
			sAttr.defaultSelectValue = attr.getValue();
		}
		if (type.equalsIgnoreCase(TieConstants.WIDGET_CALENDAR)
				&& attrKey.equalsIgnoreCase(
						TieConstants.WIDGET_ATTR_PATTERN)) {
			sAttr.defaultDatePattern = attr.getValue();
		}
	}

private static void gatherSpecialAttributes ( final String type , final SpecialAttributes sAttr , final CellFormAttributes attr ) { String attrKey = attr . getType ( ) ; if ( attrKey . equalsIgnoreCase ( TieConstants . SELECT_ITEM_LABELS ) ) { sAttr . selectLabels = attr . getValue ( ) . split ( ";" ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . SELECT_ITEM_VALUES ) ) { sAttr . selectValues = attr . getValue ( ) . split ( ";" ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . DEFAULT_SELECT_ITEM_LABEL ) ) { sAttr . defaultSelectLabel = attr . getValue ( ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . DEFAULT_SELECT_ITEM_VALUE ) ) { sAttr . defaultSelectValue = attr . getValue ( ) ; } if ( type . equalsIgnoreCase ( TieConstants . WIDGET_CALENDAR ) && attrKey . equalsIgnoreCase ( TieConstants . WIDGET_ATTR_PATTERN ) ) { sAttr . defaultDatePattern = attr . getValue ( ) ; } }

Gather special attributes.

@param type
the type
@param sAttr
the s attr
@param attr
the attr


public static void parseCommentToMap(final String cellKey,
			final String newComment,
			final Map<String, Map<String, String>> sheetCommentMap,
			final boolean normalComment) {
		if ((newComment != null) && (!newComment.trim().isEmpty())) {
			// normal comment key is $$
			String commentKey = TieConstants.NORMAL_COMMENT_KEY_IN_MAP;
			if (!normalComment) {
				// not normal comment. e.g. ${... or $init{... or
				// key = $ or key = $init
				commentKey = newComment.substring(0,
						newComment.indexOf(TieConstants.EL_START_BRACKET));
			}
			Map<String, String> map = sheetCommentMap.get(commentKey);
			if (map == null) {
				map = new HashMap<>();
			}
			// inner map's key is sheetName!$columnIndex$rowIndex
			map.put(cellKey, newComment);
			sheetCommentMap.put(commentKey, map);
		}
	}

Parse Comment To Map

Normal comment : key $$ Not Normal comment: key e.g. $save

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


public static int findFirstNonCellNamePosition(String input, int startPosition) {
		char c;
	    for (int i = startPosition; i < input.length(); i++) {
	    	c = input.charAt(i);
	        if ( c!='$' && !Character.isLetterOrDigit(c)) {
	            return i;
	        }
	    }
	    return -1; // not found
	}

public
static
int
findFirstNonCellNamePosition
(
String
input
,
int
startPosition
)
{
char
c
;
for
(
int
i
=
startPosition
;
i
<
input
.
length
(
)
;
i
++
)
{
c
=
input
.
charAt
(
i
)
;
if
(
c
!=
'
'
&&
!
Character
.
isLetterOrDigit
(
c
)
)
{
return
i
;
}
}
return
1
;
// not found
}

find first non letterordigit position from string.

@param input input string
@param startPosition startposition
@return first position

find first non letterordigit position from string .


public static String removeCharsFromString(String inputStr, int start, int end) {
    	 StringBuilder sb = new StringBuilder(inputStr);
    	 sb.delete(start, end);
//    	 if ((start > 0) && (inputStr.charAt(start - 1) ==' ')) {
//    		 // if end with a space, then remove it as well.
//    		 sb.deleteCharAt(start - 1);
//    	 }
    	 return sb.toString();
    }

Removes the chars from string.

@param inputStr the input str
@param start the start
@param end the end
@return the string


public static String getExcelColumnName(final int pnumber) {
		StringBuilder converted = new StringBuilder();
		// Repeatedly divide the number by 26 and convert the
		// remainder into the appropriate letter.
		int number = pnumber;
		while (number >= 0) {
			int remainder = number % TieConstants.EXCEL_LETTER_NUMBERS;
			converted.insert(0, (char) (remainder + 'A'));
			number = (number / TieConstants.EXCEL_LETTER_NUMBERS) - 1;
		}

		return converted.toString();
	}

Gets the excel column name.

@param pnumber
the number
@return the string


public static int convertColToInt(final String col) {
		String name = col.toUpperCase();
		int number = 0;
		int pow = 1;
		for (int i = name.length() - 1; i >= 0; i--) {
			number += (name.charAt(i) - 'A' + 1) * pow;
			pow *= TieConstants.EXCEL_LETTER_NUMBERS;
		}

		return number - 1;
	}

public static int convertColToInt ( final String col ) { String name = col . toUpperCase ( ) ; int number = 0 ; int pow = 1 ; for ( int i = name . length ( ) - 1 ; i >= 0 ; i -- ) { number += ( name . charAt ( i ) - ' ' + 1 ) * pow ; pow *= TieConstants . EXCEL_LETTER_NUMBERS ; } return number - 1 ; }

Convert col to int.

@param col
the col
@return the int


public static Cell getCellByReference(final String cellRef,
			final Sheet sheet) {

		Cell c = null;
		try {
			CellReference ref = new CellReference(cellRef);
			Row r = sheet.getRow(ref.getRow());
			if (r != null) {
				c = r.getCell(ref.getCol(),
						MissingCellPolicy.CREATE_NULL_AS_BLANK);
			}
		} catch (Exception ex) {
			// use log.debug because mostly it's expected
			LOG.log(Level.SEVERE,
					"WebForm WebFormHelper getCellByReference cellRef = "
							+ cellRef + "; error = "
							+ ex.getLocalizedMessage(),
					ex);
		}
		return c;
	}

Gets the cell by reference.

@param cellRef
the cell ref
@param sheet
the sheet
@return the cell by reference


public static int heightUnits2Pixel(final short heightUnits) {
		int pixels = heightUnits / EXCEL_ROW_HEIGHT_FACTOR;
		int offsetHeightUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
		pixels += Math.round((float) offsetHeightUnits
				/ ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH
						/ 2));
		pixels += (Math.floor(pixels / PIXEL_HEIGHT_ASPC_ADJUST) + 1) * 4;

		return pixels;
	}

public static int heightUnits2Pixel ( final short heightUnits ) { int pixels = heightUnits / EXCEL_ROW_HEIGHT_FACTOR ; int offsetHeightUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR ; pixels += Math . round ( ( float ) offsetHeightUnits / ( ( float ) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH / 2 ) ) ; pixels += ( Math . floor ( pixels / PIXEL_HEIGHT_ASPC_ADJUST ) + 1 ) * 4 ; return pixels ; }

Height units 2 pixel.

@param heightUnits
the height units
@return the int


public static boolean isDate(final String s) {
		Pattern pattern = Pattern.compile(DATE_REGEX_4_DIGIT_YEAR);
		String[] terms = s.split(" ");
		Matcher matcher;
		for (String term : terms) {
			matcher = pattern.matcher(term);
			if (matcher.matches()) {
				return true;
			}
		}
		pattern = Pattern.compile(DATE_REGEX_2_DIGIT_YEAR);
		terms = s.split(" ");
		for (String term : terms) {
			matcher = pattern.matcher(term);
			if (matcher.matches()) {
				return true;
			}
		}
		return false;
	}

public
static
boolean
isDate
(
final
String
s
)
{
Pattern
pattern
=
Pattern
.
compile
(
DATE_REGEX_4_DIGIT_YEAR
)
;
String
[
]
terms
=
s
.
split
(
" "
)
;
Matcher
matcher
;
for
(
String
term
:
terms
)
{
matcher
=
pattern
.
matcher
(
term
)
;
if
(
matcher
.
matches
(
)
)
{
return
true
;
}
}
pattern
=
Pattern
.
compile
(
DATE_REGEX_2_DIGIT_YEAR
)
;
terms
=
s
.
split
(
" "
)
;
for
(
String
term
:
terms
)
{
matcher
=
pattern
.
matcher
(
term
)
;
if
(
matcher
.
matches
(
)
)
{
return
true
;
}
}
return
false
;
}

Checks if is date.

@param s
the s
@return true, if is date


public static String parseDate(final String entry) {
		Pattern pattern = Pattern.compile(DATE_REGEX_4_DIGIT_YEAR);
		String[] terms = entry.split(" ");
		Matcher matcher;
		for (String term : terms) {
			matcher = pattern.matcher(term);
			if (matcher.matches()) {
				return matcher.group();
			}
		}
		pattern = Pattern.compile(DATE_REGEX_2_DIGIT_YEAR);
		terms = entry.split(" ");
		for (String term : terms) {
			matcher = pattern.matcher(term);
			if (matcher.matches()) {
				return matcher.group();
			}
		}
		return "";
	}

public
static
String
parseDate
(
final
String
entry
)
{
Pattern
pattern
=
Pattern
.
compile
(
DATE_REGEX_4_DIGIT_YEAR
)
;
String
[
]
terms
=
entry
.
split
(
" "
)
;
Matcher
matcher
;
for
(
String
term
:
terms
)
{
matcher
=
pattern
.
matcher
(
term
)
;
if
(
matcher
.
matches
(
)
)
{
return
matcher
.
group
(
)
;
}
}
pattern
=
Pattern
.
compile
(
DATE_REGEX_2_DIGIT_YEAR
)
;
terms
=
entry
.
split
(
" "
)
;
for
(
String
term
:
terms
)
{
matcher
=
pattern
.
matcher
(
term
)
;
if
(
matcher
.
matches
(
)
)
{
return
matcher
.
group
(
)
;
}
}
return
""
;
}

Parses the date.

@param entry
the entry
@return the string


public static boolean isNumeric(final String str) {

		String s = str;
		if (s.startsWith("-")) {
			s = s.substring(1);
		}
		char c;
		int i;
		int sLen = s.length();
		ShouldContinueParameter sPara = new ShouldContinueParameter(false,
				false, 0);

		for (i = 0; i < sLen; i++) {
			c = s.charAt(i);
			if (c < '0' || c > '9') {
				if (!shouldContinue(c, sPara)) {
					return false;
				}
			} else {
				if (sPara.isCommaHit()) {
					sPara.setSinceLastComma(sPara.getSinceLastComma() + 1);
				}
			}
		}
		return true;
	}

public static boolean isNumeric ( final String str ) { String s = str ; if ( s . startsWith ( "-" ) ) { s = s . substring ( 1 ) ; } char c ; int i ; int sLen = s . length ( ) ; ShouldContinueParameter sPara = new ShouldContinueParameter ( false , false , 0 ) ; for ( i = 0 ; i < sLen ; i ++ ) { c = s . charAt ( i ) ; if ( c < ' ' || c > ' ' ) { if ( ! shouldContinue ( c , sPara ) ) { return false ; } } else { if ( sPara . isCommaHit ( ) ) { sPara . setSinceLastComma ( sPara . getSinceLastComma ( ) + 1 ) ; } } } return true ; }

Checks if is numeric.

@param str
the str
@return true, if is numeric


private static boolean shouldContinue(final char c,
			final ShouldContinueParameter para) {
		if (c == '.' && !para.isDecimalHit()) {
			para.setDecimalHit(true);
			if (para.isCommaHit() && para.getSinceLastComma() != 3) {
				return false;
			}
			return true;
		} else if (c == ',' && !para.isDecimalHit()) {
			if (para.isCommaHit()) {
				if (para.getSinceLastComma() != 3) {
					return false;
				}
				para.setSinceLastComma(0);
			}
			para.setCommaHit(true);
			return true;
		}
		return false;
	}

private static boolean shouldContinue ( final char c , final ShouldContinueParameter para ) { if ( c == ' ' && ! para . isDecimalHit ( ) ) { para . setDecimalHit ( true ) ; if ( para . isCommaHit ( ) && para . getSinceLastComma ( ) != 3 ) { return false ; } return true ; } else if ( c == ' ' && ! para . isDecimalHit ( ) ) { if ( para . isCommaHit ( ) ) { if ( para . getSinceLastComma ( ) != 3 ) { return false ; } para . setSinceLastComma ( 0 ) ; } para . setCommaHit ( true ) ; return true ; } return false ; }

Should continue.

@param c
the c
@param para
the para
@return true, if successful


public static void setObjectProperty(final Object obj,
			final String propertyName, final String propertyValue,
			final boolean ignoreNonExisting) {
		try {
			Method method = obj.getClass().getMethod(
					"set" + Character.toUpperCase(propertyName.charAt(0))
							+ propertyName.substring(1),
					new Class[] { String.class });
			method.invoke(obj, propertyValue);
		} catch (Exception e) {
			String msg = "failed to set property '" + propertyName
					+ "' to value '" + propertyValue + "' for object "
					+ obj;
			if (ignoreNonExisting) {
				LOG.info(msg);
			} else {
				LOG.warning(msg);
				throw new IllegalArgumentException(e);
			}
		}
	}

public
static
void
setObjectProperty
(
final
Object
obj
,
final
String
propertyName
,
final
String
propertyValue
,
final
boolean
ignoreNonExisting
)
{
try
{
Method
method
=
obj
.
getClass
(
)
.
getMethod
(
"set"
+
Character
.
toUpperCase
(
propertyName
.
charAt
(
0
)
)
+
propertyName
.
substring
(
1
)
,
new
Class
[
]
{
String
.
class
}
)
;
method
.
invoke
(
obj
,
propertyValue
)
;
}
catch
(
Exception
e
)
{
String
msg
=
"failed to set property '"
+
propertyName
+
"' to value '"
+
propertyValue
+
"' for object "
+
obj
;
if
(
ignoreNonExisting
)
{
LOG
.
info
(
msg
)
;
}
else
{
LOG
.
warning
(
msg
)
;
throw
new
IllegalArgumentException
(
e
)
;
}
}
}

Sets the object property.

@param obj
the obj
@param propertyName
the property name
@param propertyValue
the property value
@param ignoreNonExisting
the ignore non existing


public static int cellCompareTo(final Cell thisCell,
			final Cell otherCell) {
		int r = thisCell.getRowIndex() - otherCell.getRowIndex();
		if (r != 0) {
			return r;
		}

		r = thisCell.getColumnIndex() - otherCell.getColumnIndex();
		if (r != 0) {
			return r;
		}

		return 0;
	}

public static int cellCompareTo ( final Cell thisCell , final Cell otherCell ) { int r = thisCell . getRowIndex ( ) - otherCell . getRowIndex ( ) ; if ( r != 0 ) { return r ; } r = thisCell . getColumnIndex ( ) - otherCell . getColumnIndex ( ) ; if ( r != 0 ) { return r ; } return 0 ; }

Cell compare to.

@param thisCell
the this cell
@param otherCell
the other cell
@return the int


public static boolean insideRange(final ConfigRange child,
			final ConfigRange parent) {

		return ((cellCompareTo(child.getFirstRowRef(),
				parent.getFirstRowRef()) >= 0)
				&& (cellCompareTo(child.getLastRowPlusRef(),
						parent.getLastRowPlusRef()) <= 0));
	}

public static boolean insideRange ( final ConfigRange child , final ConfigRange parent ) { return ( ( cellCompareTo ( child . getFirstRowRef ( ) , parent . getFirstRowRef ( ) ) >= 0 ) && ( cellCompareTo ( child . getLastRowPlusRef ( ) , parent . getLastRowPlusRef ( ) ) <= 0 ) ) ; }

Inside range.

@param child
the child
@param parent
the parent
@return true, if successful


public static void clearHiddenColumns(final Sheet sheet) {

		for (Row row : sheet) {
			if (row.getLastCellNum() > TieConstants.MAX_COLUMNS_IN_SHEET) {
				deleteHiddenColumnsInRow(row);
			}
		}

	}

public static void clearHiddenColumns ( final Sheet sheet ) { for ( Row row : sheet ) { if ( row . getLastCellNum ( ) > TieConstants . MAX_COLUMNS_IN_SHEET ) { deleteHiddenColumnsInRow ( row ) ; } } }

Clear hidden columns.

@param sheet
the sheet


private static void deleteHiddenColumnsInRow(final Row row) {
		deleteCellFromRow(row,
				TieConstants.HIDDEN_SAVE_OBJECTS_COLUMN);
		deleteCellFromRow(row,
				TieConstants.HIDDEN_ORIGIN_ROW_NUMBER_COLUMN);
		deleteCellFromRow(row,
				TieConstants.HIDDEN_FULL_NAME_COLUMN);
	}

private static void deleteHiddenColumnsInRow ( final Row row ) { deleteCellFromRow ( row , TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN ) ; deleteCellFromRow ( row , TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN ) ; deleteCellFromRow ( row , TieConstants . HIDDEN_FULL_NAME_COLUMN ) ; }

Delete hidden columns in row.

@param row
the row


private static void deleteCellFromRow(final Row row,
			final int cellNum) {
		Cell cell = row.getCell(cellNum);
		if (cell != null) {
			row.removeCell(cell);
		}
	}

private static void deleteCellFromRow ( final Row row , final int cellNum ) { Cell cell = row . getCell ( cellNum ) ; if ( cell != null ) { row . removeCell ( cell ) ; } }

Delete cell from row.

@param row
the row
@param cellNum
the cell num


@Override
	public final void processEvent(final SystemEvent event) {

		LOGGER.log(Level.INFO, "Running on TieFaces {0}",
				AppUtils.getBuildVersion());
	}

@
Override
public
final
void
processEvent
(
final
SystemEvent
event
)
{
LOGGER
.
log
(
Level
.
INFO
,
"Running on TieFaces {0}"
,
AppUtils
.
getBuildVersion
(
)
)
;
}

process event.

@param event
systemevent.
@throws AbortProcessingException
abort process exception.


private void refreshAfterStatusChanged(final boolean oldStatus, final boolean newStatus, final int formRow,
			final int formCol, final FacesCell cell, final boolean updateGui) {

		if (!newStatus) {
			cell.setErrormsg("");
		}
		cell.setInvalid(newStatus);
		if (updateGui && (oldStatus != newStatus) && (parent.getWebFormClientId() != null)) {
			RequestContext.getCurrentInstance()
					.update(parent.getWebFormClientId() + ":" + (formRow) + ":group" + (formCol));
		}

	}

private void refreshAfterStatusChanged ( final boolean oldStatus , final boolean newStatus , final int formRow , final int formCol , final FacesCell cell , final boolean updateGui ) { if ( ! newStatus ) { cell . setErrormsg ( "" ) ; } cell . setInvalid ( newStatus ) ; if ( updateGui && ( oldStatus != newStatus ) && ( parent . getWebFormClientId ( ) != null ) ) { RequestContext . getCurrentInstance ( ) . update ( parent . getWebFormClientId ( ) + ":" + ( formRow ) + ":group" + ( formCol ) ) ; } }

Refresh after status changed.

@param oldStatus
the old status
@param newStatus
the new status
@param formRow
the form row
@param formCol
the form col
@param cell
the cell
@param updateGui
update gui flag.
if true then update gui.


public boolean validateWithRowColInCurrentPage(final int row, final int col, boolean updateGui) {

		//until now passEmptyCheck has one to one relation to submitMode
		//e.g. when passEmptyCheck = false, then submitMode = true.

		boolean submitMode = parent.getSubmitMode();
		boolean passEmptyCheck = !submitMode;

		int topRow = parent.getCurrent().getCurrentTopRow();
		int leftCol = parent.getCurrent().getCurrentLeftColumn();
		boolean pass = true;

		FacesRow fRow = CellUtility.getFacesRowFromBodyRow(row, parent.getBodyRows(), topRow);
		if (fRow == null) {
			return pass;
		}

		FacesCell cell = CellUtility.getFacesCellFromBodyRow(row, col, parent.getBodyRows(), topRow, leftCol);
		if (cell == null) {
			return pass;
		}

		Cell poiCell = parent.getCellHelper().getPoiCellWithRowColFromCurrentPage(row, col);
		boolean oldStatus = cell.isInvalid();

		String value = CellUtility.getCellValueWithoutFormat(poiCell);
		if (value == null) {
			value = "";
		} else {
			value = value.trim();
		}

		if (passEmptyCheck && value.isEmpty()) {
			refreshAfterStatusChanged(oldStatus, false, row - topRow, col - leftCol, cell, updateGui);
			return pass;
		}

		if (((parent.isOnlyValidateInSubmitMode() && submitMode ) || !parent.isOnlyValidateInSubmitMode())
		&& !validateByTieWebSheetValidationBean(poiCell, topRow, leftCol, cell, value, updateGui)) {
			return false;
		}

		SheetConfiguration sheetConfig = parent.getSheetConfigMap().get(parent.getCurrent().getCurrentTabName());
		List<CellFormAttributes> cellAttributes = CellControlsUtility.findCellValidateAttributes(
				parent.getCellAttributesMap().getCellValidateAttributes(), fRow.getOriginRowIndex(), poiCell);

		if (parent.isAdvancedContext() && parent.getConfigAdvancedContext().getErrorSuffix() != null
				&& !checkErrorMessageFromObjectInContext(row - topRow, col - leftCol, cell, poiCell, value,
						sheetConfig, updateGui)) {
			return false;
		}

		if (cellAttributes != null) {
			pass = validateAllRulesForSingleCell(row - topRow, col - leftCol, cell, poiCell, value, sheetConfig,
					cellAttributes, updateGui);
		}

		if (pass) {
			refreshAfterStatusChanged(oldStatus, false, row - topRow, col - leftCol, cell, updateGui);
		}
		return pass;

	}

Validate with row col in current page.

@param row
the row
@param col
the col
@param updateGui
if true then update gui.
@return true, if successful


private boolean validateByTieWebSheetValidationBean(final Cell poiCell, final int topRow, final int leftCol,
			final FacesCell cell, final String value, boolean updateGui) {
		if (parent.getTieWebSheetValidationBean() != null) {
			String errormsg = null;
			String fullName = ConfigurationUtility.getFullNameFromRow(poiCell.getRow());
			String saveAttr = SaveAttrsUtility.prepareContextAndAttrsForCell(poiCell, fullName, parent.getCellHelper());
			if (saveAttr != null) {
				int row = poiCell.getRowIndex();
				int col = poiCell.getColumnIndex();
				errormsg = parent.getTieWebSheetValidationBean().validate(
						parent.getSerialDataContext().getDataContext(), saveAttr, ConfigurationUtility
								.getFullNameFromRow(poiCell.getRow()), poiCell.getSheet().getSheetName(),
						row, col, value);
				if ((errormsg != null) && (!errormsg.isEmpty())) {
					cell.setErrormsg(errormsg);
					refreshAfterStatusChanged(false, true, row - topRow, col - leftCol, cell, updateGui);
					return false;
				}
			}
		}
		return true;
	}

private boolean validateByTieWebSheetValidationBean ( final Cell poiCell , final int topRow , final int leftCol , final FacesCell cell , final String value , boolean updateGui ) { if ( parent . getTieWebSheetValidationBean ( ) != null ) { String errormsg = null ; String fullName = ConfigurationUtility . getFullNameFromRow ( poiCell . getRow ( ) ) ; String saveAttr = SaveAttrsUtility . prepareContextAndAttrsForCell ( poiCell , fullName , parent . getCellHelper ( ) ) ; if ( saveAttr != null ) { int row = poiCell . getRowIndex ( ) ; int col = poiCell . getColumnIndex ( ) ; errormsg = parent . getTieWebSheetValidationBean ( ) . validate ( parent . getSerialDataContext ( ) . getDataContext ( ) , saveAttr , ConfigurationUtility . getFullNameFromRow ( poiCell . getRow ( ) ) , poiCell . getSheet ( ) . getSheetName ( ) , row , col , value ) ; if ( ( errormsg != null ) && ( ! errormsg . isEmpty ( ) ) ) { cell . setErrormsg ( errormsg ) ; refreshAfterStatusChanged ( false , true , row - topRow , col - leftCol , cell , updateGui ) ; return false ; } } } return true ; }

Validate by tie web sheet validation bean.

@param poiCell the poi cell
@param topRow the top row
@param leftCol the left col
@param cell the cell
@param value the value
@param updateGui the update gui
@return true, if successful

Validate by tie web sheet validation bean .


private boolean checkErrorMessageFromObjectInContext(final int formRow, final int formCol, final FacesCell cell,
			final Cell poiCell, final String value, final SheetConfiguration sheetConfig, boolean updateGui) {

		@SuppressWarnings("unchecked")
		HashMap<String, TieCell> tieCells = (HashMap<String, TieCell>) parent.getSerialDataContext().getDataContext()
				.get("tiecells");

		if (tieCells != null) {

			TieCell tieCell = tieCells.get(CellUtility.getSkeyFromPoiCell(poiCell));

			if (tieCell != null && tieCell.getContextObject() != null) {

				String errorMethod = tieCell.getMethodStr() + parent.getConfigAdvancedContext().getErrorSuffix();

				String errorMessage = CellControlsUtility.getObjectPropertyValue(tieCell.getContextObject(),
						errorMethod, true);

				if (errorMessage != null && !errorMessage.isEmpty()) {
					cell.setErrormsg(errorMessage);
					LOG.log(Level.INFO, "Validation failed for sheet {0} row {1} column {2} : {3}",
							new Object[] { poiCell.getSheet().getSheetName(), poiCell.getRowIndex(),
									poiCell.getColumnIndex(), errorMessage });
					refreshAfterStatusChanged(false, true, formRow, formCol, cell, updateGui);
					return false;
				}

			}
		}

		return true;

	}

Check error message from object in context.

@param formRow the form row
@param formCol the form col
@param cell the cell
@param poiCell the poi cell
@param value the value
@param sheetConfig the sheet config
@param updateGui the update gui
@return true, if successful

Check error message from object in context .


private boolean validateAllRulesForSingleCell(final int formRow, final int formCol, final FacesCell cell,
			final Cell poiCell, final String value, final SheetConfiguration sheetConfig,
			final List<CellFormAttributes> cellAttributes, boolean updateGui) {
		Sheet sheet1 = parent.getWb().getSheet(sheetConfig.getSheetName());
		for (CellFormAttributes attr : cellAttributes) {
			boolean pass = doValidation(value, attr, poiCell.getRowIndex(), poiCell.getColumnIndex(), sheet1);
			if (!pass) {
				String errmsg = attr.getMessage();
				if (errmsg == null) {
					errmsg = TieConstants.DEFALT_MSG_INVALID_INPUT;
				}
				cell.setErrormsg(errmsg);
				LOG.log(Level.INFO, "Validation failed for sheet {0} row {1} column {2} : {3}", new Object[] {
						poiCell.getSheet().getSheetName(), poiCell.getRowIndex(), poiCell.getColumnIndex(), errmsg });
				refreshAfterStatusChanged(false, true, formRow, formCol, cell, updateGui);
				return false;
			}

		}
		return true;
	}

Validate all rules for single cell.

@param formRow            the form row
@param formCol            the form col
@param cell            the cell
@param poiCell            the poi cell
@param value            the value
@param sheetConfig            the sheet config
@param cellAttributes            the cell attributes
@param updateGui the update gui
@return true, if successful


private boolean doValidation(final Object value, final CellFormAttributes attr, final int rowIndex,
			final int colIndex, final Sheet sheet) {
		boolean pass;

		String attrValue = attr.getValue();
		attrValue = attrValue.replace("$value", value.toString() + "").replace("$rowIndex", rowIndex + "")
				.replace("$colIndex", colIndex + "").replace("$sheetName", sheet.getSheetName());
		attrValue = ConfigurationUtility.replaceExpressionWithCellValue(attrValue, rowIndex, sheet);
		if (attrValue.contains(TieConstants.EL_START)) {
			Object returnObj = FacesUtility.evaluateExpression(attrValue, Object.class);
			attrValue = returnObj.toString();
			pass = Boolean.parseBoolean(attrValue);
		} else {
			pass = parent.getCellHelper().evalBoolExpression(attrValue);
		}
		return pass;

	}

private boolean doValidation ( final Object value , final CellFormAttributes attr , final int rowIndex , final int colIndex , final Sheet sheet ) { boolean pass ; String attrValue = attr . getValue ( ) ; attrValue = attrValue . replace ( "$value" , value . toString ( ) + "" ) . replace ( "$rowIndex" , rowIndex + "" ) . replace ( "$colIndex" , colIndex + "" ) . replace ( "$sheetName" , sheet . getSheetName ( ) ) ; attrValue = ConfigurationUtility . replaceExpressionWithCellValue ( attrValue , rowIndex , sheet ) ; if ( attrValue . contains ( TieConstants . EL_START ) ) { Object returnObj = FacesUtility . evaluateExpression ( attrValue , Object . class ) ; attrValue = returnObj . toString ( ) ; pass = Boolean . parseBoolean ( attrValue ) ; } else { pass = parent . getCellHelper ( ) . evalBoolExpression ( attrValue ) ; } return pass ; }

Do validation.

@param value            the value
@param attr            the attr
@param rowIndex            the row index
@param colIndex the col index
@param sheet            the sheet
@return true, if successful


public final boolean validateCell(final UIComponent target) {

		int[] rowcol = CellUtility.getRowColFromComponentAttributes(target);
		int row = rowcol[0];
		int col = rowcol[1];
		return validateWithRowColInCurrentPage(row, col, true);
	}

public final boolean validateCell ( final UIComponent target ) { int [ ] rowcol = CellUtility . getRowColFromComponentAttributes ( target ) ; int row = rowcol [ 0 ] ; int col = rowcol [ 1 ] ; return validateWithRowColInCurrentPage ( row , col , true ) ; }

Validate cell.

@param target
the target
@return true, if successful


public final boolean validateCurrentPage() {
		boolean allpass = true;

		int top = parent.getCurrent().getCurrentTopRow();
		for (int irow = 0; irow < parent.getBodyRows().size(); irow++) {
			if (!validateRowInCurrentPage(irow + top, false)) {
				allpass = false;
			}
		}
		return allpass;
	}

public final boolean validateCurrentPage ( ) { boolean allpass = true ; int top = parent . getCurrent ( ) . getCurrentTopRow ( ) ; for ( int irow = 0 ; irow < parent . getBodyRows ( ) . size ( ) ; irow ++ ) { if ( ! validateRowInCurrentPage ( irow + top , false ) ) { allpass = false ; } } return allpass ; }

Validate current page.

@return true, if successful


public final boolean validateRowInCurrentPage(final int irow, final boolean updateGui) {
		SheetConfiguration sheetConfig = parent.getSheetConfigMap().get(parent.getCurrent().getCurrentTabName());
		return this.validateRow(irow, sheetConfig, updateGui);
	}

public final boolean validateRowInCurrentPage ( final int irow , final boolean updateGui ) { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( parent . getCurrent ( ) . getCurrentTabName ( ) ) ; return this . validateRow ( irow , sheetConfig , updateGui ) ; }

Validate row in current page.

@param irow the irow
@param updateGui the update gui
@return true, if successful


private boolean validateRow(final int irow, final SheetConfiguration sheetConfig, boolean updateGui) {
		boolean pass = true;
		if (sheetConfig == null) {
			return pass;
		}
		int top = sheetConfig.getBodyCellRange().getTopRow();
		List<FacesCell> cellRow = parent.getBodyRows().get(irow - top).getCells();
		for (int index = 0; index < cellRow.size(); index++) {
			FacesCell fcell = cellRow.get(index);
			if ((fcell != null) && (!validateWithRowColInCurrentPage(irow, fcell.getColumnIndex(), updateGui))) {
				pass = false;
			}
		}
		return pass;
	}

private boolean validateRow ( final int irow , final SheetConfiguration sheetConfig , boolean updateGui ) { boolean pass = true ; if ( sheetConfig == null ) { return pass ; } int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; List < FacesCell > cellRow = parent . getBodyRows ( ) . get ( irow - top ) . getCells ( ) ; for ( int index = 0 ; index < cellRow . size ( ) ; index ++ ) { FacesCell fcell = cellRow . get ( index ) ; if ( ( fcell != null ) && ( ! validateWithRowColInCurrentPage ( irow , fcell . getColumnIndex ( ) , updateGui ) ) ) { pass = false ; } } return pass ; }

Validate row.

@param irow the irow
@param sheetConfig the sheet config
@param updateGui the update gui
@return true, if successful


private void refreshCachedCellsInCurrentPage(final FacesContext facesContext, final String tblName) {
		// refresh current page calculation fields
		UIComponent s = facesContext.getViewRoot().findComponent(tblName);
		if (s == null) {
			return;
		}
		DataTable webDataTable = (DataTable) s;
		int first = webDataTable.getFirst();
		int rowsToRender = webDataTable.getRowsToRender();
		int rowCounts = webDataTable.getRowCount();
		int top = parent.getCurrent().getCurrentTopRow();
		int left = parent.getCurrent().getCurrentLeftColumn();

		for (int i = first; i <= (first + rowsToRender); i++) {
			if (i < rowCounts) {
				refreshCachedCellsInRow(tblName, top, left, i);
			}

		}
	}

Refresh cached cells in current page.

@param facesContext
the faces context
@param tblName
the tbl name


private void refreshCachedCellsInRow(final String tblName, final int top, final int left, final int i) {
		FacesRow dataRow = parent.getBodyRows().get(i);
		int isize = dataRow.getCells().size();
		for (int index = 0; index < isize; index++) {
			FacesCell fcell = dataRow.getCells().get(index);
			Cell poiCell = parent.getCellHelper().getPoiCellWithRowColFromCurrentPage(i + top, index + left);
			if (poiCell != null) {
				parent.getHelper().getWebSheetLoader().refreshCachedCell(tblName, i, index, poiCell, fcell);
			}
		}
	}

private void refreshCachedCellsInRow ( final String tblName , final int top , final int left , final int i ) { FacesRow dataRow = parent . getBodyRows ( ) . get ( i ) ; int isize = dataRow . getCells ( ) . size ( ) ; for ( int index = 0 ; index < isize ; index ++ ) { FacesCell fcell = dataRow . getCells ( ) . get ( index ) ; Cell poiCell = parent . getCellHelper ( ) . getPoiCellWithRowColFromCurrentPage ( i + top , index + left ) ; if ( poiCell != null ) { parent . getHelper ( ) . getWebSheetLoader ( ) . refreshCachedCell ( tblName , i , index , poiCell , fcell ) ; } } }

Refresh cached cells in row.

@param tblName
the tbl name
@param top
the top
@param left
the left
@param i
the i


public void setSubmitModeInView(final Boolean fullflag) {

		if (FacesContext.getCurrentInstance() != null) {
			Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
			if (viewMap != null) {
				Boolean flag = (Boolean) viewMap.get(TieConstants.SUBMITMODE);
				if ((flag == null) || (!flag.equals(fullflag))) {
					viewMap.put(TieConstants.SUBMITMODE, fullflag);
				}
			}
		}
	}

public void setSubmitModeInView ( final Boolean fullflag ) { if ( FacesContext . getCurrentInstance ( ) != null ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; if ( viewMap != null ) { Boolean flag = ( Boolean ) viewMap . get ( TieConstants . SUBMITMODE ) ; if ( ( flag == null ) || ( ! flag . equals ( fullflag ) ) ) { viewMap . put ( TieConstants . SUBMITMODE , fullflag ) ; } } } }

set submit mode flag with javascript for holding in client side.

@param fullflag
true or false

set submit mode flag with javascript for holding in client side .


public boolean preValidation() {

		String currentTabName = parent.getCurrent().getCurrentTabName();
		String tabName = null;
		String firstInvalidTabName = null;
		boolean reload = false;
		for (Map.Entry<String, SheetConfiguration> entry : parent.getSheetConfigMap().entrySet()) {
			tabName = entry.getKey();
			// if not reload and tabname==current then skip reloading.
			if (reload || (!tabName.equals(currentTabName))) {
				parent.getWebSheetLoader().prepareWorkShee(tabName);
				reload = true;
			}
			if (!parent.getValidationHandler().validateCurrentPage() &&
				(firstInvalidTabName == null)) {
				firstInvalidTabName = tabName;
			}
		}
		if (firstInvalidTabName != null)  {
			if (!tabName.equals(firstInvalidTabName)) {
				parent.getHelper().getWebSheetLoader().loadWorkSheet(firstInvalidTabName);
			}
			return false;
		}
		return true;
	}

triggered validation process before actions like save or submit.

@return true (pass) false (failed)

triggered validation process before actions like save or submit .


public final void clear() {
		if (this.templateCommentMap != null) {
			this.templateCommentMap.clear();
		}
		if (this.cellDatePattern != null) {
			this.cellDatePattern.clear();
		}
		if (this.cellInputAttributes != null) {
			this.cellInputAttributes.clear();
		}
		if (this.cellInputType != null) {
			this.cellInputType.clear();
		}
		if (this.cellSelectItemsAttributes != null) {
			this.cellSelectItemsAttributes.clear();
		}

	}

public final void clear ( ) { if ( this . templateCommentMap != null ) { this . templateCommentMap . clear ( ) ; } if ( this . cellDatePattern != null ) { this . cellDatePattern . clear ( ) ; } if ( this . cellInputAttributes != null ) { this . cellInputAttributes . clear ( ) ; } if ( this . cellInputType != null ) { this . cellInputType . clear ( ) ; } if ( this . cellSelectItemsAttributes != null ) { this . cellSelectItemsAttributes . clear ( ) ; } }


private void loadHeaderRows(final SheetConfiguration sheetConfig, final Map<String, CellRangeAddress> cellRangeMap,
			final List<String> skippedRegionCells) {

		int top = sheetConfig.getHeaderCellRange().getTopRow();
		int bottom = sheetConfig.getHeaderCellRange().getBottomRow();
		int left = sheetConfig.getHeaderCellRange().getLeftCol();
		int right = sheetConfig.getHeaderCellRange().getRightCol();

		String sheetName = sheetConfig.getSheetName();
		Sheet sheet1 = parent.getWb().getSheet(sheetName);

		int totalWidth = CellStyleUtility.calcTotalWidth(sheet1, left, right,
				WebSheetUtility.pixel2WidthUnits(parent.getLineNumberColumnWidth() + parent.getAddRowColumnWidth()));

		RangeBuildRef rangeBuildRef = new RangeBuildRef(left, right, totalWidth, sheet1);

		if (sheetConfig.isFixedWidthStyle()) {
			parent.setTableWidthStyle(
					"table-layout: fixed; width:" + WebSheetUtility.widthUnits2Pixel(totalWidth) + "px;");
		}

		parent.setLineNumberColumnWidthStyle(
				getWidthStyle(WebSheetUtility.pixel2WidthUnits(parent.getLineNumberColumnWidth()), totalWidth));
		parent.setAddRowColumnWidthStyle("width:" + parent.getAddRowColumnWidth() + "px;");

		parent.getHeaderRows().clear();

		if (top < 0) {
			// this is blank configuration. set column letter as header
			parent.getHeaderRows().add(loadHeaderRowWithoutConfigurationTab(rangeBuildRef, true));
			// set showlinenumber to true as default
			parent.setShowLineNumber(true);
		} else {
			parent.getHeaderRows().add(loadHeaderRowWithoutConfigurationTab(rangeBuildRef, false));
			for (int i = top; i <= bottom; i++) {
				parent.getHeaderRows().add(loadHeaderRowWithConfigurationTab(sheetConfig, rangeBuildRef, i,
						cellRangeMap, skippedRegionCells));

			}
			// set showlinenumber to false as default
			parent.setShowLineNumber(false);

		}

	}

Load header rows.

@param sheetConfig
the sheet config
@param cellRangeMap
the cell range map
@param skippedRegionCells
the skipped region cells


private List<HeaderCell> loadHeaderRowWithoutConfigurationTab(final RangeBuildRef rangeBuildRef,
			final boolean rendered) {

		int firstCol = rangeBuildRef.getLeft();
		int lastCol = rangeBuildRef.getRight();
		double totalWidth = (double) rangeBuildRef.getTotalWidth();
		Sheet sheet1 = rangeBuildRef.getSheet();
		List<HeaderCell> headercells = new ArrayList<>();
		for (int i = firstCol; i <= lastCol; i++) {
			if (!sheet1.isColumnHidden(i)) {
				String style = getHeaderColumnStyle(parent.getWb(), null, sheet1.getColumnWidth(i), totalWidth);
				headercells.add(
						new HeaderCell("1", "1", style, style, WebSheetUtility.getExcelColumnName(i), rendered, true));
			}
		}
		fillToMaxColumns(headercells);
		return headercells;

	}

private List < HeaderCell > loadHeaderRowWithoutConfigurationTab ( final RangeBuildRef rangeBuildRef , final boolean rendered ) { int firstCol = rangeBuildRef . getLeft ( ) ; int lastCol = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Sheet sheet1 = rangeBuildRef . getSheet ( ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int i = firstCol ; i <= lastCol ; i ++ ) { if ( ! sheet1 . isColumnHidden ( i ) ) { String style = getHeaderColumnStyle ( parent . getWb ( ) , null , sheet1 . getColumnWidth ( i ) , totalWidth ) ; headercells . add ( new HeaderCell ( "1" , "1" , style , style , WebSheetUtility . getExcelColumnName ( i ) , rendered , true ) ) ; } } fillToMaxColumns ( headercells ) ; return headercells ; }

Load header row without configuration tab.

@param rangeBuildRef
the range build ref
@param rendered
the rendered
@return the list

Load header row without configuration tab .


private void fillToMaxColumns(final List<HeaderCell> headercells) {
		if (headercells.size() < parent.getMaxColCounts()) {
			int fills = parent.getMaxColCounts() - headercells.size();
			for (int s = 0; s < fills; s++) {
				headercells.add(new HeaderCell("1", "1", "", "", "", false, false));
			}
		}
	}

private void fillToMaxColumns ( final List < HeaderCell > headercells ) { if ( headercells . size ( ) < parent . getMaxColCounts ( ) ) { int fills = parent . getMaxColCounts ( ) - headercells . size ( ) ; for ( int s = 0 ; s < fills ; s ++ ) { headercells . add ( new HeaderCell ( "1" , "1" , "" , "" , "" , false , false ) ) ; } } }

Fill to max columns.

@param headercells
the headercells


private String getHeaderColumnStyle(final Workbook wb, final Cell cell, final double colWidth,
			final double totalWidth) {

		String columnstyle = "";
		if (cell != null) {
			columnstyle += CellStyleUtility.getCellStyle(wb, cell, "") + CellStyleUtility.getCellFontStyle(wb, cell); // +
		}

		columnstyle = columnstyle + getWidthStyle(colWidth, totalWidth);
		return columnstyle;
	}

private
String
getHeaderColumnStyle
(
final
Workbook
wb
,
final
Cell
cell
,
final
double
colWidth
,
final
double
totalWidth
)
{
String
columnstyle
=
""
;
if
(
cell
!=
)
{
columnstyle
+=
CellStyleUtility
.
getCellStyle
(
wb
,
cell
,
""
)
+
CellStyleUtility
.
getCellFontStyle
(
wb
,
cell
)
;
// +
}
columnstyle
=
columnstyle
+
getWidthStyle
(
colWidth
,
totalWidth
)
;
return
columnstyle
;
}

Gets the header column style.

@param wb
the wb
@param cell
the cell
@param colWidth
the col width
@param totalWidth
the total width
@return the header column style


private String getWidthStyle(final double colWidth, final double totalWidth) {
		double percentage = FacesUtility.round(TieConstants.CELL_FORMAT_PERCENTAGE_VALUE * colWidth / totalWidth, 2);
		return "width:" + percentage + TieConstants.CELL_FORMAT_PERCENTAGE_SYMBOL + ";";
	}

private String getWidthStyle ( final double colWidth , final double totalWidth ) { double percentage = FacesUtility . round ( TieConstants . CELL_FORMAT_PERCENTAGE_VALUE * colWidth / totalWidth , 2 ) ; return "width:" + percentage + TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL + ";" ; }

Gets the width style.

@param colWidth
the col width
@param totalWidth
the total width
@return the width style


private List<HeaderCell> loadHeaderRowWithConfigurationTab(final SheetConfiguration sheetConfig,
			final RangeBuildRef rangeBuildRef, final int currentRow, final Map<String, CellRangeAddress> cellRangeMap,
			final List<String> skippedRegionCells) {

		Sheet sheet1 = rangeBuildRef.getSheet();
		int left = rangeBuildRef.getLeft();
		int right = rangeBuildRef.getRight();
		double totalWidth = (double) rangeBuildRef.getTotalWidth();
		Row row = sheet1.getRow(currentRow);
		List<HeaderCell> headercells = new ArrayList<>();
		for (int cindex = left; cindex <= right; cindex++) {
			String cellindex = CellUtility.getCellIndexNumberKey(cindex, currentRow);

			if (!skippedRegionCells.contains(cellindex) && !sheet1.isColumnHidden(cindex)) {
				Cell cell = null;
				if (row != null) {
					cell = row.getCell(cindex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
				}
				int originRowIndex = ConfigurationUtility.getOriginalRowNumInHiddenColumn(row);
				if (cell != null) {
					FacesCell fcell = new FacesCell();

					CellUtility.convertCell(sheetConfig, fcell, cell, cellRangeMap, originRowIndex,
							parent.getCellAttributesMap(), null);
					parent.getPicHelper().setupFacesCellPictureCharts(sheet1, fcell, cell,
							WebSheetUtility.getFullCellRefName(sheet1, cell));
					CellStyleUtility.setupCellStyle(parent.getWb(), fcell, cell, row.getHeightInPoints());
					fcell.setColumnStyle(fcell.getColumnStyle()
							+ getColumnWidthStyle(sheet1, cellRangeMap, cellindex, cindex, totalWidth));
					fcell.setColumnIndex(cindex);

					headercells.add(
							new HeaderCell(Integer.toString(fcell.getRowspan()), Integer.toString(fcell.getColspan()),
									fcell.getStyle(), fcell.getColumnStyle(), CellUtility.getCellValueWithFormat(cell,
											parent.getFormulaEvaluator(), parent.getDataFormatter()),
									true, true));
				}
			}

		}
		fillToMaxColumns(headercells);
		return headercells;
	}

private List < HeaderCell > loadHeaderRowWithConfigurationTab ( final SheetConfiguration sheetConfig , final RangeBuildRef rangeBuildRef , final int currentRow , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { Sheet sheet1 = rangeBuildRef . getSheet ( ) ; int left = rangeBuildRef . getLeft ( ) ; int right = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Row row = sheet1 . getRow ( currentRow ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , currentRow ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } int originRowIndex = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , originRowIndex , parent . getCellAttributesMap ( ) , null ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnStyle ( fcell . getColumnStyle ( ) + getColumnWidthStyle ( sheet1 , cellRangeMap , cellindex , cindex , totalWidth ) ) ; fcell . setColumnIndex ( cindex ) ; headercells . add ( new HeaderCell ( Integer . toString ( fcell . getRowspan ( ) ) , Integer . toString ( fcell . getColspan ( ) ) , fcell . getStyle ( ) , fcell . getColumnStyle ( ) , CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) , true , true ) ) ; } } } fillToMaxColumns ( headercells ) ; return headercells ; }

Load header row with configuration tab.

@param sheetConfig
the sheet config
@param rangeBuildRef
the range build ref
@param currentRow
the current row
@param cellRangeMap
the cell range map
@param skippedRegionCells
the skipped region cells
@return the list

Load header row with configuration tab .


private String getColumnWidthStyle(final Sheet sheet1, final Map<String, CellRangeAddress> cellRangeMap,
			final String cellindex, final int cindex, final double totalWidth) {

		CellRangeAddress caddress = cellRangeMap.get(cellindex);
		double colWidth;
		// check whether the cell has rowspan or colspan
		if (caddress != null) {
			colWidth = CellStyleUtility.calcTotalWidth(sheet1, caddress.getFirstColumn(), caddress.getLastColumn(), 0);
		} else {
			colWidth = sheet1.getColumnWidth(cindex);
		}

		return getWidthStyle(colWidth, totalWidth);

	}

Gets the column width style.

@param sheet1
the sheet 1
@param cellRangeMap
the cell range map
@param cellindex
the cellindex
@param cindex
the cindex
@param totalWidth
the total width
@return the column width style


private void clearWorkbook() {
		parent.setFormulaEvaluator(null);
		parent.setDataFormatter(null);
		parent.setSheetConfigMap(null);
		parent.setTabs(null);
		parent.getSerialDataContext().setDataContext(null);
		parent.setPicturesMap(null);
		parent.setHeaderRows(null);
		parent.setBodyRows(null);
		parent.setWb(null);
		parent.getHeaderRows().clear();
		parent.getBodyRows().clear();
		parent.getCharsData().getChartsMap().clear();
		parent.getCharsData().getChartDataMap().clear();
		parent.getCharsData().getChartAnchorsMap().clear();
		parent.getCharsData().getChartPositionMap().clear();
		parent.getCellAttributesMap().clear();
	}

private void clearWorkbook ( ) { parent . setFormulaEvaluator ( null ) ; parent . setDataFormatter ( null ) ; parent . setSheetConfigMap ( null ) ; parent . setTabs ( null ) ; parent . getSerialDataContext ( ) . setDataContext ( null ) ; parent . setPicturesMap ( null ) ; parent . setHeaderRows ( null ) ; parent . setBodyRows ( null ) ; parent . setWb ( null ) ; parent . getHeaderRows ( ) . clear ( ) ; parent . getBodyRows ( ) . clear ( ) ; parent . getCharsData ( ) . getChartsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartDataMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartAnchorsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartPositionMap ( ) . clear ( ) ; parent . getCellAttributesMap ( ) . clear ( ) ; }


private void initTabs() {
		parent.setTabs(new ArrayList<TabModel>());
		if (parent.getSheetConfigMap() != null) {
			for (String key : parent.getSheetConfigMap().keySet()) {
				parent.getTabs().add(new TabModel("form_" + key, key, "form"));
			}
		}
	}

private void initTabs ( ) { parent . setTabs ( new ArrayList < TabModel > ( ) ) ; if ( parent . getSheetConfigMap ( ) != null ) { for ( String key : parent . getSheetConfigMap ( ) . keySet ( ) ) { parent . getTabs ( ) . add ( new TabModel ( "form_" + key , key , "form" ) ) ; } } }


private void loadData() {

		if (parent.getSerialDataContext().getDataContext() == null) {
			// no data objects available.
			return;
		}

		if (parent.isAdvancedContext()) {
			parent.getSerialDataContext().getDataContext().put("tiecells", new HashMap<String, TieCell>());
		}

		for (SheetConfiguration sheetConfig : parent.getSheetConfigMap().values()) {
			List<RowsMapping> currentRowsMappingList = null;
			ConfigBuildRef configBuildRef = new ConfigBuildRef(parent.getWbWrapper(),
					parent.getWb().getSheet(sheetConfig.getSheetName()), parent.getExpEngine(), parent.getCellHelper(),
					sheetConfig.getCachedCells(), parent.getCellAttributesMap(), sheetConfig.getFinalCommentMap());
			int length = sheetConfig.getFormCommand().buildAt(null, configBuildRef,
					sheetConfig.getFormCommand().getTopRow(), parent.getSerialDataContext().getDataContext(),
					currentRowsMappingList);
			sheetConfig.setShiftMap(configBuildRef.getShiftMap());
			sheetConfig.setCollectionObjNameMap(configBuildRef.getCollectionObjNameMap());
			sheetConfig.setCommandIndexMap(configBuildRef.getCommandIndexMap());
			sheetConfig.setWatchList(configBuildRef.getWatchList());
			sheetConfig.setBodyAllowAddRows(configBuildRef.isBodyAllowAdd());
			sheetConfig.getBodyCellRange().setBottomRow(sheetConfig.getFormCommand().getTopRow() + length - 1);
			sheetConfig.setBodyPopulated(true);
		}
		parent.getCellHelper().reCalc();

	}

private
void
loadData
(
)
{
if
(
parent
.
getSerialDataContext
(
)
.
getDataContext
(
)
==
)
{
// no data objects available.
return
;
}
if
(
parent
.
isAdvancedContext
(
)
)
{
parent
.
getSerialDataContext
(
)
.
getDataContext
(
)
.
put
(
"tiecells"
,
new
HashMap
<
String
,
TieCell
>
(
)
)
;
}
for
(
SheetConfiguration
sheetConfig
:
parent
.
getSheetConfigMap
(
)
.
values
(
)
)
{
List
<
RowsMapping
>
currentRowsMappingList
=
;
ConfigBuildRef
configBuildRef
=
new
ConfigBuildRef
(
parent
.
getWbWrapper
(
)
,
parent
.
getWb
(
)
.
getSheet
(
sheetConfig
.
getSheetName
(
)
)
,
parent
.
getExpEngine
(
)
,
parent
.
getCellHelper
(
)
,
sheetConfig
.
getCachedCells
(
)
,
parent
.
getCellAttributesMap
(
)
,
sheetConfig
.
getFinalCommentMap
(
)
)
;
int
length
=
sheetConfig
.
getFormCommand
(
)
.
buildAt
(
,
configBuildRef
,
sheetConfig
.
getFormCommand
(
)
.
getTopRow
(
)
,
parent
.
getSerialDataContext
(
)
.
getDataContext
(
)
,
currentRowsMappingList
)
;
sheetConfig
.
setShiftMap
(
configBuildRef
.
getShiftMap
(
)
)
;
sheetConfig
.
setCollectionObjNameMap
(
configBuildRef
.
getCollectionObjNameMap
(
)
)
;
sheetConfig
.
setCommandIndexMap
(
configBuildRef
.
getCommandIndexMap
(
)
)
;
sheetConfig
.
setWatchList
(
configBuildRef
.
getWatchList
(
)
)
;
sheetConfig
.
setBodyAllowAddRows
(
configBuildRef
.
isBodyAllowAdd
(
)
)
;
sheetConfig
.
getBodyCellRange
(
)
.
setBottomRow
(
sheetConfig
.
getFormCommand
(
)
.
getTopRow
(
)
+
length
1
)
;
sheetConfig
.
setBodyPopulated
(
true
)
;
}
parent
.
getCellHelper
(
)
.
reCalc
(
)
;
}


public void refreshData() {

		if (parent.getSerialDataContext().getDataContext() == null) {
			// no data objects available.
			return;
		}

		for (SheetConfiguration sheetConfig : parent.getSheetConfigMap().values()) {
			for (int irow = sheetConfig.getFormCommand().getTopRow(); irow < sheetConfig.getFormCommand()
					.getLastRow(); irow++) {

				refreshDataForRow(parent.getWb().getSheet(sheetConfig.getSheetName()).getRow(irow));
			}

		}
		parent.getCellHelper().reCalc();

	}

public
void
refreshData
(
)
{
if
(
parent
.
getSerialDataContext
(
)
.
getDataContext
(
)
==
)
{
// no data objects available.
return
;
}
for
(
SheetConfiguration
sheetConfig
:
parent
.
getSheetConfigMap
(
)
.
values
(
)
)
{
for
(
int
irow
=
sheetConfig
.
getFormCommand
(
)
.
getTopRow
(
)
;
irow
<
sheetConfig
.
getFormCommand
(
)
.
getLastRow
(
)
;
irow
++
)
{
refreshDataForRow
(
parent
.
getWb
(
)
.
getSheet
(
sheetConfig
.
getSheetName
(
)
)
.
getRow
(
irow
)
)
;
}
}
parent
.
getCellHelper
(
)
.
reCalc
(
)
;
}


private void refreshDataForRow(Row row) {
		if (row == null) {
			return;
		}
		String saveAttrList = SaveAttrsUtility.getSaveAttrListFromRow(row);
		if (saveAttrList!= null) {
			String[] saveAttrs = saveAttrList.split(",");
			for (String fullSaveAttr : saveAttrs) {
				refreshDataForCell(row, fullSaveAttr);
			}
		}
	}

private void refreshDataForRow ( Row row ) { if ( row == null ) { return ; } String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; if ( saveAttrList != null ) { String [ ] saveAttrs = saveAttrList . split ( "," ) ; for ( String fullSaveAttr : saveAttrs ) { refreshDataForCell ( row , fullSaveAttr ) ; } } }

Refresh data for row.

@param row the row


private void refreshDataForCell(Row row, String fullSaveAttr) {
		if (fullSaveAttr != null) {
			try {
				String fullName = ConfigurationUtility.getFullNameFromRow(row);
				if (fullName != null) {
					parent.getCellHelper().restoreDataContext(fullName);
					SaveAttrsUtility.refreshSheetRowFromContext(parent.getSerialDataContext().getDataContext(),
							fullSaveAttr, row, parent.getExpEngine());
				}
			}catch (Exception ex) {
				LOG.log(Level.SEVERE, "refreshDataForCell with fullAaveAttr ="+fullSaveAttr+" error = " + ex.getMessage(), ex);
			}

		}
	}

refresh data for single cell.

@param row row.
@param fullSaveAttr fullSaveAttr.


public final int findTabIndexWithName(final String tabname) {

		for (int i = 0; i < parent.getTabs().size(); i++) {
			if (parent.getTabs().get(i).getTitle().equalsIgnoreCase(tabname)) {
				return i;
			}
		}
		return -1;

	}

public final int findTabIndexWithName ( final String tabname ) { for ( int i = 0 ; i < parent . getTabs ( ) . size ( ) ; i ++ ) { if ( parent . getTabs ( ) . get ( i ) . getTitle ( ) . equalsIgnoreCase ( tabname ) ) { return i ; } } return - 1 ; }

Find tab index with name.

@param tabname
the tabname
@return the int


public final void loadWorkSheet(final String tabName) {

		prepareWorkShee(tabName);
		parent.getValidationHandler().validateCurrentPage();
		createDynamicColumns(tabName);
		// reset datatable current page to 1
		setDataTablePage(0);
		parent.getCurrent().setCurrentDataContextName(null);
		saveObjs();
		if ((RequestContext.getCurrentInstance() != null) && (parent.getClientId() != null)) {
			RequestContext.getCurrentInstance().update(parent.getClientId() + ":websheettab");
		}
	}

public
final
void
loadWorkSheet
(
final
String
tabName
)
{
prepareWorkShee
(
tabName
)
;
parent
.
getValidationHandler
(
)
.
validateCurrentPage
(
)
;
createDynamicColumns
(
tabName
)
;
// reset datatable current page to 1
setDataTablePage
(
0
)
;
parent
.
getCurrent
(
)
.
setCurrentDataContextName
(
)
;
saveObjs
(
)
;
if
(
(
RequestContext
.
getCurrentInstance
(
)
!=
)
&&
(
parent
.
getClientId
(
)
!=
)
)
{
RequestContext
.
getCurrentInstance
(
)
.
update
(
parent
.
getClientId
(
)
+
":websheettab"
)
;
}
}

Load work sheet.

@param tabName
the tab name


public final void prepareWorkShee(final String tabName) {

		int tabIndex = findTabIndexWithName(tabName);
		if (parent.getWebFormTabView() != null) {
			parent.getWebFormTabView().setActiveIndex(tabIndex);
		}
		parent.getCurrent().setCurrentTabName(tabName);
		String sheetName = parent.getSheetConfigMap().get(tabName).getSheetName();
		Sheet sheet1 = parent.getWb().getSheet(sheetName);
		parent.getWb().setActiveSheet(parent.getWb().getSheetIndex(sheet1));

		SheetConfiguration sheetConfig = parent.getSheetConfigMap().get(tabName);

		parent.setMaxRowsPerPage(parent.getSheetConfigMap().get(tabName).getMaxRowPerPage());
		parent.setBodyAllowAddRows(parent.getSheetConfigMap().get(tabName).isBodyAllowAddRows());

		// populate repeat rows before setup cell range map

		Map<String, CellRangeAddress> cellRangeMap = ConfigurationUtility.indexMergedRegion(sheet1);
		List<String> skippedRegionCells = ConfigurationUtility.skippedRegionCells(sheet1);
		loadHeaderRows(sheetConfig, cellRangeMap, skippedRegionCells);
		loadBodyRows(sheetConfig, cellRangeMap, skippedRegionCells);
	}

prepare worksheet for loading.
this only load at backend without refresh gui.

@param tabName the tab name

prepare worksheet for loading . this only load at backend without refresh gui .


private void setDataTablePage(final int first) {
		if (parent.getWebFormClientId() != null) {
			final DataTable d = (DataTable) FacesContext.getCurrentInstance().getViewRoot()
					.findComponent(parent.getWebFormClientId());
			if (d != null) {
				d.setFirst(first);
			}
		}
	}

private void setDataTablePage ( final int first ) { if ( parent . getWebFormClientId ( ) != null ) { final DataTable d = ( DataTable ) FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . findComponent ( parent . getWebFormClientId ( ) ) ; if ( d != null ) { d . setFirst ( first ) ; } } }

Sets the data table page.

@param first
the new data table page


private void saveObjs() {

		try {
			if (FacesContext.getCurrentInstance() != null) {
				Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
				viewMap.put("currentTabName", parent.getCurrent().getCurrentTabName());
				viewMap.put(TieConstants.SUBMITMODE, parent.getSubmitMode());
			}
		} catch (Exception ex) {
			LOG.log(Level.SEVERE, "saveobjs in viewMap error = " + ex.getMessage(), ex);

		}

	}

private
void
saveObjs
(
)
{
try
{
if
(
FacesContext
.
getCurrentInstance
(
)
!=
)
{
Map
<
String
,
Object
>
viewMap
=
FacesContext
.
getCurrentInstance
(
)
.
getViewRoot
(
)
.
getViewMap
(
)
;
viewMap
.
put
(
"currentTabName"
,
parent
.
getCurrent
(
)
.
getCurrentTabName
(
)
)
;
viewMap
.
put
(
TieConstants
.
SUBMITMODE
,
parent
.
getSubmitMode
(
)
)
;
}
}
catch
(
Exception
ex
)
{
LOG
.
log
(
Level
.
SEVERE
,
"saveobjs in viewMap error = "
+
ex
.
getMessage
(
)
,
ex
)
;
}
}


private void setupRowInfo(final FacesRow facesRow, final Sheet sheet1, final Row row, final int rowIndex,
			final boolean allowAdd) {

		facesRow.setAllowAdd(allowAdd);
		if (row != null) {
			facesRow.setRendered(!row.getZeroHeight());
			facesRow.setRowheight(row.getHeight());
			int rowNum = ConfigurationUtility.getOriginalRowNumInHiddenColumn(row);
			facesRow.setOriginRowIndex(rowNum);
		} else {
			facesRow.setRendered(true);
			facesRow.setRowheight(sheet1.getDefaultRowHeight());
			facesRow.setOriginRowIndex(rowIndex);
		}

	}

private void setupRowInfo ( final FacesRow facesRow , final Sheet sheet1 , final Row row , final int rowIndex , final boolean allowAdd ) { facesRow . setAllowAdd ( allowAdd ) ; if ( row != null ) { facesRow . setRendered ( ! row . getZeroHeight ( ) ) ; facesRow . setRowheight ( row . getHeight ( ) ) ; int rowNum = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; facesRow . setOriginRowIndex ( rowNum ) ; } else { facesRow . setRendered ( true ) ; facesRow . setRowheight ( sheet1 . getDefaultRowHeight ( ) ) ; facesRow . setOriginRowIndex ( rowIndex ) ; } }

Setup row info.

@param facesRow
the faces row
@param sheet1
the sheet 1
@param row
the row
@param rowIndex
the row index
@param allowAdd
the allow add


private void loadBodyRows(final SheetConfiguration sheetConfig, final Map<String, CellRangeAddress> cellRangeMap,
			final List<String> skippedRegionCells) {

		int top = sheetConfig.getBodyCellRange().getTopRow();
		int bottom = CellUtility.getBodyBottomFromConfig(sheetConfig);
		int left = sheetConfig.getBodyCellRange().getLeftCol();
		int right = sheetConfig.getBodyCellRange().getRightCol();

		String sheetName = sheetConfig.getSheetName();
		Sheet sheet1 = parent.getWb().getSheet(sheetName);

		parent.getBodyRows().clear();
		clearCache();

		for (int i = top; i <= bottom; i++) {

			parent.getBodyRows()
					.add(assembleFacesBodyRow(i, sheet1, left, right, sheetConfig, cellRangeMap, skippedRegionCells));

		}
		sheetConfig.setBodyPopulated(true);
		parent.getCurrent().setCurrentTopRow(top);
		parent.getCurrent().setCurrentLeftColumn(left);
	}

private void loadBodyRows ( final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int bottom = CellUtility . getBodyBottomFromConfig ( sheetConfig ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; String sheetName = sheetConfig . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; parent . getBodyRows ( ) . clear ( ) ; clearCache ( ) ; for ( int i = top ; i <= bottom ; i ++ ) { parent . getBodyRows ( ) . add ( assembleFacesBodyRow ( i , sheet1 , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } sheetConfig . setBodyPopulated ( true ) ; parent . getCurrent ( ) . setCurrentTopRow ( top ) ; parent . getCurrent ( ) . setCurrentLeftColumn ( left ) ; }

Load body rows.

@param sheetConfig
the sheet config
@param cellRangeMap
the cell range map
@param skippedRegionCells
the skipped region cells


private FacesRow assembleFacesBodyRow(final int rowIndex, final Sheet sheet1, final int left, final int right,
			final SheetConfiguration sheetConfig, final Map<String, CellRangeAddress> cellRangeMap,
			final List<String> skippedRegionCells) {

		FacesRow facesRow = new FacesRow(rowIndex);
		Row row = sheet1.getRow(rowIndex);
		setupRowInfo(facesRow, sheet1, row, rowIndex, CommandUtility.isRowAllowAdd(row, sheetConfig));
		String saveAttrList = SaveAttrsUtility.getSaveAttrListFromRow(row);
		List<FacesCell> bodycells = new ArrayList<>();
		for (int cindex = left; cindex <= right; cindex++) {
			String cellindex = CellUtility.getCellIndexNumberKey(cindex, rowIndex);
			if (!skippedRegionCells.contains(cellindex) && !sheet1.isColumnHidden(cindex)) {
				Cell cell = null;
				if (row != null) {
					cell = row.getCell(cindex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
				}
				if (cell != null) {
					FacesCell fcell = new FacesCell();

					CellUtility.convertCell(sheetConfig, fcell, cell, cellRangeMap, facesRow.getOriginRowIndex(),
							parent.getCellAttributesMap(), saveAttrList);
					parent.getPicHelper().setupFacesCellPictureCharts(sheet1, fcell, cell,
							WebSheetUtility.getFullCellRefName(sheet1, cell));
					CellStyleUtility.setupCellStyle(parent.getWb(), fcell, cell, row.getHeightInPoints());
					fcell.setColumnIndex(cindex);
					bodycells.add(fcell);
					addCache(cell);
				} else {
					bodycells.add(null);
				}
			} else {
				bodycells.add(null);
			}
		}
		facesRow.setCells(bodycells);
		return facesRow;
	}

private FacesRow assembleFacesBodyRow ( final int rowIndex , final Sheet sheet1 , final int left , final int right , final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { FacesRow facesRow = new FacesRow ( rowIndex ) ; Row row = sheet1 . getRow ( rowIndex ) ; setupRowInfo ( facesRow , sheet1 , row , rowIndex , CommandUtility . isRowAllowAdd ( row , sheetConfig ) ) ; String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; List < FacesCell > bodycells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , rowIndex ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , facesRow . getOriginRowIndex ( ) , parent . getCellAttributesMap ( ) , saveAttrList ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnIndex ( cindex ) ; bodycells . add ( fcell ) ; addCache ( cell ) ; } else { bodycells . add ( null ) ; } } else { bodycells . add ( null ) ; } } facesRow . setCells ( bodycells ) ; return facesRow ; }

Assemble faces body row.

@param rowIndex
the row index
@param sheet1
the sheet 1
@param left
the left
@param right
the right
@param sheetConfig
the sheet config
@param cellRangeMap
the cell range map
@param skippedRegionCells
the skipped region cells
@return the faces row


public final void refreshCachedCell(final String tblName, final int i, final int index, final Cell cell,
			final FacesCell fcell) {

		if ((cell != null) && (cell.getCellTypeEnum() == CellType.FORMULA) && (tblName != null)) {
			try {
				processRefreshCell(tblName, i, index, cell, fcell);
			} catch (Exception ex) {
				LOG.log(Level.SEVERE, "refresh Cached Cell error : " + ex.getLocalizedMessage(), ex);
			}
		}
	}

public
final
void
refreshCachedCell
(
final
String
tblName
,
final
int
i
,
final
int
index
,
final
Cell
cell
,
final
FacesCell
fcell
)
{
if
(
(
cell
!=
)
&&
(
cell
.
getCellTypeEnum
(
)
==
CellType
.
FORMULA
)
&&
(
tblName
!=
)
)
{
try
{
processRefreshCell
(
tblName
,
i
,
index
,
cell
,
fcell
)
;
}
catch
(
Exception
ex
)
{
LOG
.
log
(
Level
.
SEVERE
,
"refresh Cached Cell error : "
+
ex
.
getLocalizedMessage
(
)
,
ex
)
;
}
}
}

Refresh cached cell.

@param tblName
the tbl name
@param i
the i
@param index
the index
@param cell
the cell
@param fcell
the fcell


private void processRefreshCell(final String tblName, final int i, final int index, final Cell cell,
			final FacesCell fcell) {
		String newValue = CellUtility.getCellValueWithFormat(cell, parent.getFormulaEvaluator(),
				parent.getDataFormatter());
		if (parent.getCachedCells().isValueChanged(cell, newValue)) {
			if (fcell.isHasSaveAttr()) {
				parent.getCellHelper().saveDataInContext(cell, newValue);
			}
			RequestContext.getCurrentInstance().update(tblName + ":" + i + ":cocalc" + index);
			parent.getCachedCells().put(cell, CellType.FORMULA);
		}
	}

private void processRefreshCell ( final String tblName , final int i , final int index , final Cell cell , final FacesCell fcell ) { String newValue = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; if ( parent . getCachedCells ( ) . isValueChanged ( cell , newValue ) ) { if ( fcell . isHasSaveAttr ( ) ) { parent . getCellHelper ( ) . saveDataInContext ( cell , newValue ) ; } RequestContext . getCurrentInstance ( ) . update ( tblName + ":" + i + ":cocalc" + index ) ; parent . getCachedCells ( ) . put ( cell , CellType . FORMULA ) ; } }

Process refresh cell.

@param tblName
the tbl name
@param i
the i
@param index
the index
@param cell
the cell
@param fcell
the fcell


private void createDynamicColumns(final String tabName) {

		SheetConfiguration sheetConfig = parent.getSheetConfigMap().get(tabName);

		int left = sheetConfig.getBodyCellRange().getLeftCol();
		int right = sheetConfig.getBodyCellRange().getRightCol();

		parent.getColumns().clear();

		for (int i = left; i <= right; i++) {
			parent.getColumns().add("column" + (i - left));
		}

	}

private void createDynamicColumns ( final String tabName ) { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( tabName ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; parent . getColumns ( ) . clear ( ) ; for ( int i = left ; i <= right ; i ++ ) { parent . getColumns ( ) . add ( "column" + ( i - left ) ) ; } }

Creates the dynamic columns.

@param tabName
the tab name


public final void addRepeatRow(final int rowIndex) {

		try {
			SheetConfiguration sheetConfig = parent.getSheetConfigMap().get(parent.getCurrent().getCurrentTabName());
			Sheet sheet = parent.getWb().getSheet(sheetConfig.getSheetName());
			ConfigBuildRef configBuildRef = new ConfigBuildRef(parent.getWbWrapper(), sheet, parent.getExpEngine(),
					parent.getCellHelper(), sheetConfig.getCachedCells(), parent.getCellAttributesMap(),
					sheetConfig.getFinalCommentMap());
			// set add mode
			configBuildRef.setAddMode(true);
			configBuildRef.setCollectionObjNameMap(sheetConfig.getCollectionObjNameMap());
			configBuildRef.setCommandIndexMap(sheetConfig.getCommandIndexMap());
			configBuildRef.setShiftMap(sheetConfig.getShiftMap());
			configBuildRef.setWatchList(sheetConfig.getWatchList());
			int length = CommandUtility.addRow(configBuildRef, rowIndex,
					parent.getSerialDataContext().getDataContext());
			refreshBodyRowsInRange(configBuildRef.getInsertPosition(), length, sheet, sheetConfig);
			parent.getCellHelper().reCalc();
		} catch (AddRowException e) {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "Add Row Error", e.getMessage()));
			LOG.log(Level.SEVERE, "Add row error = " + e.getLocalizedMessage(), e);

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

		}

	}

public
final
void
addRepeatRow
(
final
int
rowIndex
)
{
try
{
SheetConfiguration
sheetConfig
=
parent
.
getSheetConfigMap
(
)
.
get
(
parent
.
getCurrent
(
)
.
getCurrentTabName
(
)
)
;
Sheet
sheet
=
parent
.
getWb
(
)
.
getSheet
(
sheetConfig
.
getSheetName
(
)
)
;
ConfigBuildRef
configBuildRef
=
new
ConfigBuildRef
(
parent
.
getWbWrapper
(
)
,
sheet
,
parent
.
getExpEngine
(
)
,
parent
.
getCellHelper
(
)
,
sheetConfig
.
getCachedCells
(
)
,
parent
.
getCellAttributesMap
(
)
,
sheetConfig
.
getFinalCommentMap
(
)
)
;
// set add mode
configBuildRef
.
setAddMode
(
true
)
;
configBuildRef
.
setCollectionObjNameMap
(
sheetConfig
.
getCollectionObjNameMap
(
)
)
;
configBuildRef
.
setCommandIndexMap
(
sheetConfig
.
getCommandIndexMap
(
)
)
;
configBuildRef
.
setShiftMap
(
sheetConfig
.
getShiftMap
(
)
)
;
configBuildRef
.
setWatchList
(
sheetConfig
.
getWatchList
(
)
)
;
int
length
=
CommandUtility
.
addRow
(
configBuildRef
,
rowIndex
,
parent
.
getSerialDataContext
(
)
.
getDataContext
(
)
)
;
refreshBodyRowsInRange
(
configBuildRef
.
getInsertPosition
(
)
,
length
,
sheet
,
sheetConfig
)
;
parent
.
getCellHelper
(
)
.
reCalc
(
)
;
}
catch
(
AddRowException
e
)
{
FacesContext
.
getCurrentInstance
(
)
.
addMessage
(
,
new
FacesMessage
(
FacesMessage
.
SEVERITY_ERROR
,
"Add Row Error"
,
e
.
getMessage
(
)
)
)
;
LOG
.
log
(
Level
.
SEVERE
,
"Add row error = "
+
e
.
getLocalizedMessage
(
)
,
e
)
;
}
catch
(
Exception
ex
)
{
LOG
.
log
(
Level
.
SEVERE
,
"Add row error = "
+
ex
.
getLocalizedMessage
(
)
,
ex
)
;
}
}

Adds the repeat row.

@param rowIndex
the row index


private void refreshBodyRowsInRange(final int insertPosition, final int length, final Sheet sheet,
			final SheetConfiguration sheetConfig) {
		Map<String, CellRangeAddress> cellRangeMap = ConfigurationUtility.indexMergedRegion(sheet);
		List<String> skippedRegionCells = ConfigurationUtility.skippedRegionCells(sheet);
		int top = sheetConfig.getBodyCellRange().getTopRow();
		int left = sheetConfig.getBodyCellRange().getLeftCol();
		int right = sheetConfig.getBodyCellRange().getRightCol();
		for (int irow = insertPosition; irow < (insertPosition + length); irow++) {
			parent.getBodyRows().add(irow - top,
					assembleFacesBodyRow(irow, sheet, left, right, sheetConfig, cellRangeMap, skippedRegionCells));
		}
		for (int irow = insertPosition + length - top; irow < parent.getBodyRows().size(); irow++) {
			FacesRow facesrow = parent.getBodyRows().get(irow);
			facesrow.setRowIndex(facesrow.getRowIndex() + length);
		}
	}

private void refreshBodyRowsInRange ( final int insertPosition , final int length , final Sheet sheet , final SheetConfiguration sheetConfig ) { Map < String , CellRangeAddress > cellRangeMap = ConfigurationUtility . indexMergedRegion ( sheet ) ; List < String > skippedRegionCells = ConfigurationUtility . skippedRegionCells ( sheet ) ; int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; for ( int irow = insertPosition ; irow < ( insertPosition + length ) ; irow ++ ) { parent . getBodyRows ( ) . add ( irow - top , assembleFacesBodyRow ( irow , sheet , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } for ( int irow = insertPosition + length - top ; irow < parent . getBodyRows ( ) . size ( ) ; irow ++ ) { FacesRow facesrow = parent . getBodyRows ( ) . get ( irow ) ; facesrow . setRowIndex ( facesrow . getRowIndex ( ) + length ) ; } }

Refresh body rows in range.

@param insertPosition
the insert position
@param length
the length
@param sheet
the sheet
@param sheetConfig
the sheet config


public void setUnsavedStatus(final RequestContext requestContext, final Boolean statusFlag) {

		// in client js should have setUnsavedState method
		if (requestContext != null) {
			LOG.log(Level.FINE, "run setUnsavedState( {} )", statusFlag.toString());
			requestContext.execute("setUnsavedState(" + statusFlag.toString() + ")");
		}

	}

Sets the unsaved status.

@param requestContext
the request context
@param statusFlag
the status flag


public final Boolean isUnsavedStatus() {
		Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
		Boolean flag = (Boolean) viewMap.get(TieConstants.UNSAVEDSTATE);
		if (flag == null) {
			return false;
		}
		return flag;
	}

public final Boolean isUnsavedStatus ( ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; Boolean flag = ( Boolean ) viewMap . get ( TieConstants . UNSAVEDSTATE ) ; if ( flag == null ) { return false ; } return flag ; }

Checks if is unsaved status.

@return the boolean


public static <T> Constructor<T> commonConstructor(Class<T> type)
			throws NoMethodForDependency {
		Constructor<?>[] cs = type.getDeclaredConstructors();
		if (cs.length == 0)
			throw new NoMethodForDependency(raw(type));
		Constructor<?> mostParamsConstructor = null;
		for (Constructor<?> c : cs) {
			if (!arrayContains(c.getParameterTypes(), type, (a, b) -> a == b) // avoid self referencing constructors (synthetic) as they cause endless loop
				&& (mostParamsConstructor == null //
					|| (moreVisible(c, mostParamsConstructor) == c
						&& (moreVisible(mostParamsConstructor, c) == c
							|| c.getParameterCount() > mostParamsConstructor.getParameterCount())))) {
				mostParamsConstructor = c;
			}
		}
		if (mostParamsConstructor == null)
			throw new NoMethodForDependency(raw(type));
		@SuppressWarnings("unchecked")
		Constructor<T> c = (Constructor<T>) mostParamsConstructor;
		return c;
	}

Returns the constructor with most visible visibility and longest argument
list. Self-referencing constructors are ignored.

@param type constructed type
@return The highest visibility constructor with the most parameters that
does not have the declaring class itself as parameter type (some
compiler seam to generate such a synthetic constructor)
@throws NoMethodForDependency in case the type is not constructible (has
no constructors at all)

Returns the constructor with most visible visibility and longest argument list . Self - referencing constructors are ignored .


protected static void writeInputStreamToOutput(final Context context, final InputStream source, final OutputStream output) throws IOException {
    BuffersPool pool = BeansManager.get(context).getContainer().getBean(BuffersPool.class);
    IoUtils.transfer(source, output, pool);
  }

protected static void writeInputStreamToOutput ( final Context context , final InputStream source , final OutputStream output ) throws IOException { BuffersPool pool = BeansManager . get ( context ) . getContainer ( ) . getBean ( BuffersPool . class ) ; IoUtils . transfer ( source , output , pool ) ; }

Utility method for transferring input stream to output.
@param context application context (needed to retrieve a buffers pool)
@param source input stream
@param output output stream
@throws IOException if I/O error happens

Utility method for transferring input stream to output .


protected static void writeLong(final Writer writer, final long value) throws IOException {
    writer.write(new StringBuilder().append(value).append('\n').toString());
  }

protected static void writeLong ( final Writer writer , final long value ) throws IOException { writer . write ( new StringBuilder ( ) . append ( value ) . append ( ' ' ) . toString ( ) ) ; }

Write next line as a long.
@param writer output writer
@param value integer value
@throws IOException if error happens


protected final void writeString(final Writer writer, final String line) throws IOException {
    if (line != null) {
      writer.write(line + '\n');
    } else {
      writer.write('\n');
    }
  }

protected final void writeString ( final Writer writer , final String line ) throws IOException { if ( line != null ) { writer . write ( line + ' ' ) ; } else { writer . write ( ' ' ) ; } }

Write next line to the output.
@param writer output writer
@param line line to write (if null just a new empty line is inserted)
@throws IOException if error happens


protected void setConvertedTrafficStatsTag(final String tag) {
    result.statsTag = Utils.getTrafficStatsTag(tag);
    if (config.isDebugRest()) {
      Log.d(TAG, "TrafficStats tag <" + tag + ">=" + Integer.toHexString(result.statsTag));
    }
  }

protected
void
setConvertedTrafficStatsTag
(
final
String
tag
)
{
result
.
statsTag
=
Utils
.
getTrafficStatsTag
(
tag
)
;
if
(
config
.
isDebugRest
(
)
)
{
Log
.
d
(
TAG
,
"TrafficStats tag <"
+
tag
+
">="
+
Integer
.
toHexString
(
result
.
statsTag
)
)
;
}
}

Set network stats tag. Converts string tag to integer one.
@param tag string tag

Set network stats tag . Converts string tag to integer one .


protected void addBitmap(final String name, final Bitmap bitmap, final String fileName) {
    final BitmapBinaryData bdata = new BitmapBinaryData();
    bdata.setName(name);
    bdata.setContentName(fileName);
    bdata.setBitmap(bitmap);
    result.addBinaryData(bdata);
  }

protected void addBitmap ( final String name , final Bitmap bitmap , final String fileName ) { final BitmapBinaryData bdata = new BitmapBinaryData ( ) ; bdata . setName ( name ) ; bdata . setContentName ( fileName ) ; bdata . setBitmap ( bitmap ) ; result . addBinaryData ( bdata ) ; }

Setup binary content with the bitmap.
@param name parameter name
@param bitmap bitmap object
@param fileName file name


protected void addFileDescriptor(final String name, final AssetFileDescriptor fd, final String contentType, final String fileName) {
    final AssetFdBinaryData bdata = new AssetFdBinaryData();
    bdata.setFileDescriptor(fileName, fd);
    bdata.setName(name);
    bdata.setContentType(contentType);
    result.addBinaryData(bdata);
  }

protected void addFileDescriptor ( final String name , final AssetFileDescriptor fd , final String contentType , final String fileName ) { final AssetFdBinaryData bdata = new AssetFdBinaryData ( ) ; bdata . setFileDescriptor ( fileName , fd ) ; bdata . setName ( name ) ; bdata . setContentType ( contentType ) ; result . addBinaryData ( bdata ) ; }

Setup binary content with the file descriptor.
@param name parameter name
@param fd file descriptor
@param contentType content MIME-type
@param fileName file name

Setup binary content with the file descriptor .


protected Parameter removeParameter(final String name) {
    if (name == null) { throw new IllegalArgumentException("Parameter name cannot be null"); }
    final Iterator<Parameter> iter = result.simpleParameters.getChildren().iterator();
    while (iter.hasNext()) {
      final Parameter p = iter.next();
      if (name.equals(p.name)) {
        iter.remove();
        return p;
      }
    }
    return null;
  }

protected
Parameter
removeParameter
(
final
String
name
)
{
if
(
name
==
)
{
throw
new
IllegalArgumentException
(
"Parameter name cannot be null"
)
;
}
final
Iterator
<
Parameter
>
iter
=
result
.
simpleParameters
.
getChildren
(
)
.
iterator
(
)
;
while
(
iter
.
hasNext
(
)
)
{
final
Parameter
p
=
iter
.
next
(
)
;
if
(
name
.
equals
(
p
.
name
)
)
{
iter
.
remove
(
)
;
return
p
;
}
}
return
;
}

Remove parameter with the specified name from request description.
@param name parameter name
@return removed parameter instance, null if no parameter was found

Remove parameter with the specified name from request description .


protected BaseRequestBuilder<MT> addHeader(final String name, final String value) {
    result.addHeader(name, value);
    return this;
  }

protected BaseRequestBuilder < MT > addHeader ( final String name , final String value ) { result . addHeader ( name , value ) ; return this ; }

Add header to request description.
@param name header name
@param value header value
@return this for chaining


public void clear() {
    final RequestDescription result = this.result;
    result.simpleParameters.children.clear();
    result.clearBinaryData();
    result.contentType = null;
    result.clearHeaders();
  }

public void clear ( ) { final RequestDescription result = this . result ; result . simpleParameters . children . clear ( ) ; result . clearBinaryData ( ) ; result . contentType = null ; result . clearHeaders ( ) ; }


protected void callPlay(final Uri uri, final int volume, final Bundle params) {
    playing = true;
    paused = false;
    context.startService(
        createPlayIntent().setData(uri)
        .putExtra(StreamingPlaybackService.EXTRA_VOLUME, volume)
        .putExtra(StreamingPlaybackService.EXTRA_TRACK_INFO, params)
    );
    bind();
    onPlayingChanged();
    preparing = true;
    onPreparingChanged();
  }

protected void callPlay ( final Uri uri , final int volume , final Bundle params ) { playing = true ; paused = false ; context . startService ( createPlayIntent ( ) . setData ( uri ) . putExtra ( StreamingPlaybackService . EXTRA_VOLUME , volume ) . putExtra ( StreamingPlaybackService . EXTRA_TRACK_INFO , params ) ) ; bind ( ) ; onPlayingChanged ( ) ; preparing = true ; onPreparingChanged ( ) ; }


protected void callStop() {
    playing = false;
    paused = false;
    context.startService(createStopIntent());
    onPlayingChanged();
    preparing = false;
    onPreparingChanged();
  }

protected void callStop ( ) { playing = false ; paused = false ; context . startService ( createStopIntent ( ) ) ; onPlayingChanged ( ) ; preparing = false ; onPreparingChanged ( ) ; }


protected final void bind() {
    if (bindRequested) { return; }
    final boolean result = context.bindService(createBindIntent(), serviceConnection, 0);
    if (DEBUG) { Log.v(TAG, "Bind to streaming service: " + result); }
    bindRequested = result;
    onBind(result);
  }

protected
final
void
bind
(
)
{
if
(
bindRequested
)
{
return
;
}
final
boolean
result
=
context
.
bindService
(
createBindIntent
(
)
,
serviceConnection
,
0
)
;
if
(
DEBUG
)
{
Log
.
v
(
TAG
,
"Bind to streaming service: "
+
result
)
;
}
bindRequested
=
result
;
onBind
(
result
)
;
}


protected final void unbind() {
    if (streamingPlayback != null) { dropListener(); }
    try {
      context.unbindService(serviceConnection);
    } catch (final RuntimeException e) {
      if (DEBUG) { Log.w(TAG, "Cannot unbind radio", e); }
    }
    bindRequested = false;
  }

protected
final
void
unbind
(
)
{
if
(
streamingPlayback
!=
)
{
dropListener
(
)
;
}
try
{
context
.
unbindService
(
serviceConnection
)
;
}
catch
(
final
RuntimeException
e
)
{
if
(
DEBUG
)
{
Log
.
w
(
TAG
,
"Cannot unbind radio"
,
e
)
;
}
}
bindRequested
=
false
;
}


protected final void dropListener() {
    if (DEBUG) { Log.v(TAG, "Drop listener"); }
    if (streamingPlayback != null) {
      try {
        streamingPlayback.removeListener();
      } catch (final RemoteException e) {
        Log.e(TAG, "Cannot remove listener", e);
      }
      bindRequested = false;
    }
  }

protected
final
void
dropListener
(
)
{
if
(
DEBUG
)
{
Log
.
v
(
TAG
,
"Drop listener"
)
;
}
if
(
streamingPlayback
!=
)
{
try
{
streamingPlayback
.
removeListener
(
)
;
}
catch
(
final
RemoteException
e
)
{
Log
.
e
(
TAG
,
"Cannot remove listener"
,
e
)
;
}
bindRequested
=
false
;
}
}


public void storeToDisk() throws IOException {
    if (manager.isPresentOnDisk(url)) {
      return;
    }

    if (!hasAllowedSize()) {
      IoUtils.consumeStream(getRemoteInputStream(), manager.getBuffersPool());
      return;
    }

    ImageResult result = decodeStream(getRemoteInputStream(), true);
    if (result.getType() == ImageSourceType.NETWORK && result.getBitmap() != null) {
      // image was scaled
      writeBitmapToDisk(result.getBitmap());
    }
  }

public
void
storeToDisk
(
)
throws
IOException
{
if
(
manager
.
isPresentOnDisk
(
url
)
)
{
return
;
}
if
(
!
hasAllowedSize
(
)
)
{
IoUtils
.
consumeStream
(
getRemoteInputStream
(
)
,
manager
.
getBuffersPool
(
)
)
;
return
;
}
ImageResult
result
=
decodeStream
(
getRemoteInputStream
(
)
,
true
)
;
if
(
result
.
getType
(
)
==
ImageSourceType
.
NETWORK
&&
result
.
getBitmap
(
)
!=
)
{
// image was scaled
writeBitmapToDisk
(
result
.
getBitmap
(
)
)
;
}
}

Store image to the disk cache.
If max allowed size is set image may be rescaled on disk.
@throws IOException if error happens

Store image to the disk cache . If max allowed size is set image may be rescaled on disk .


public static String streamToString(final InputStream stream, final String charset, final BuffersPool buffersPool) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    transfer(stream, output, buffersPool);
    return new String(output.toByteArray(), charset);
  }

public static String streamToString ( final InputStream stream , final String charset , final BuffersPool buffersPool ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; transfer ( stream , output , buffersPool ) ; return new String ( output . toByteArray ( ) , charset ) ; }

Read all the bytes from input stream and convert them to a string.
Input stream is closed after this method invocation.
@param stream input stream
@param charset input characters set name
@param buffersPool buffers pool instance, may be null
@return string
@throws IOException if an error happens

Read all the bytes from input stream and convert them to a string . Input stream is closed after this method invocation .


public static String streamToString(final InputStream stream, final BuffersPool buffersPool) throws IOException {
    return streamToString(stream, UTF_8_NAME, buffersPool);
  }

public static String streamToString ( final InputStream stream , final BuffersPool buffersPool ) throws IOException { return streamToString ( stream , UTF_8_NAME , buffersPool ) ; }

Read all the bytes from input stream and convert them to a string using UTF-8 charset.
Input stream is closed after this method invocation.
@param stream input stream
@param buffersPool buffers pool instance, may be null
@return string
@throws IOException if an error happens

Read all the bytes from input stream and convert them to a string using UTF - 8 charset . Input stream is closed after this method invocation .


@Override
  protected void sendData(final OutputStream out) throws IOException {
    if (DEBUG) { Log.v(TAG, "enter sendData(OutputStream)"); }
    out.write(getContent());
  }

@
Override
protected
void
sendData
(
final
OutputStream
out
)
throws
IOException
{
if
(
DEBUG
)
{
Log
.
v
(
TAG
,
"enter sendData(OutputStream)"
)
;
}
out
.
write
(
getContent
(
)
)
;
}

Writes the data to the given OutputStream.
@param out the OutputStream to write to
@throws IOException if there is a write error

Writes the data to the given OutputStream .


@Override
  public synchronized int available() throws IOException {
    final InputStream localIn = in; // 'in' could be invalidated by close()
    if (buf == null || localIn == null) { throw new IOException("Stream is closed"); }
    return count - pos + localIn.available();
  }

Returns the number of bytes that are available before this stream will
block. This method returns the number of bytes available in the buffer
plus those available in the source stream.

@return the number of bytes available before blocking.
@throws IOException
if this stream is closed.

Returns the number of bytes that are available before this stream will block . This method returns the number of bytes available in the buffer plus those available in the source stream .


@Override
  public void close() throws IOException {
    final byte[] localBuf = buf;
    buf = null;
    final InputStream localIn = in;
    in = null;
    pool.release(localBuf);
    if (localIn != null) { localIn.close(); }
  }

@ Override public void close ( ) throws IOException { final byte [ ] localBuf = buf ; buf = null ; final InputStream localIn = in ; in = null ; pool . release ( localBuf ) ; if ( localIn != null ) { localIn . close ( ) ; } }

Closes this stream. The source stream is closed and any resources
associated with it are released.

@throws IOException
if an error occurs while closing this stream.

Closes this stream . The source stream is closed and any resources associated with it are released .


@Override
  public synchronized int read() throws IOException {
    // Use local refs since buf and in may be invalidated by an
    // unsynchronized close()
    byte[] localBuf = buf;
    final InputStream localIn = in;
    if (localBuf == null || localIn == null) { throw new IOException("Stream is closed"); }

    /* Are there buffered bytes available? */
    if (pos >= count && fillbuf(localIn, localBuf) == -1) {
      return -1; /* no, fill buffer */
    }
    // localBuf may have been invalidated by fillbuf
    if (localBuf != buf) {
      localBuf = buf;
      if (localBuf == null) { throw new IOException("Stream is closed"); }
    }

    /* Did filling the buffer fail with -1 (EOF)? */
    final int mask = 0xFF;
    if (count - pos > 0) {
      return localBuf[pos++] & mask;
    }
    return -1;
  }

Reads a single byte from this stream and returns it as an integer in the
range from 0 to 255. Returns -1 if the end of the source string has been
reached. If the internal buffer does not contain any available bytes then
it is filled from the source stream and the first byte is returned.

@return the byte read or -1 if the end of the source stream has been
reached.
@throws IOException
if this stream is closed or another IOException occurs.

Reads a single byte from this stream and returns it as an integer in the range from 0 to 255 . Returns - 1 if the end of the source string has been reached . If the internal buffer does not contain any available bytes then it is filled from the source stream and the first byte is returned .


@Override
  public synchronized void reset() throws IOException {
    // BEGIN android-changed
    /*
     * These exceptions get thrown in some "normalish" circumstances,
     * so it is preferable to avoid loading up the whole big set of
     * messages just for these cases.
     */
    if (buf == null) {
      throw new IOException("Stream is closed");
    }
    if (-1 == markpos) {
      throw new IOException("Mark has been invalidated.");
    }
    // END android-changed
    pos = markpos;
  }

Resets this stream to the last marked location.

@throws IOException
if this stream is closed, no mark has been set or the mark is
no longer valid because more than {@code readlimit} bytes
have been read since setting the mark.
@see #mark(int)

Resets this stream to the last marked location .