public abstract class AbstractTemplateSource extends ValueBindingObjectImpl {

	private String m_databaseName;

	public AbstractTemplateSource() {
		super();
	}

	public String getDatabaseName() {
		if (m_databaseName != null) {
			return m_databaseName;
		}
		ValueBinding vb = getValueBinding("databaseName");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setDatabaseName(String databaseName) {
		m_databaseName = databaseName;
	}

	public Database getSourceDatabase(boolean asSigner) {
		return DatabaseProvider.INSTANCE.getDatabase(getDatabaseName(), asSigner);
	}

	@Override
	public void restoreState(FacesContext context, Object value) {
		Object[] state = (Object[]) value;
		super.restoreState(context, state[0]);
		m_databaseName = (String) state[1];

	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[2];
		state[0] = super.saveState(context);
		state[1] = m_databaseName;
		return state;

	}

} public class AttachmentTemplateSource extends AbstractTemplateSource implements ITemplateSource {

	String m_viewName;
	String m_keyName;
	String m_fieldName;

	private DataTempStore m_tempDataStore;

	protected static class DataTempStore {
		public Database m_Database;
		public View m_View;
		public Document m_Document;
		public RichTextItem m_Item;
		public EmbeddedObject m_EmbObject;
	}

	public String getViewName() {
		if (m_viewName != null) {
			return m_viewName;
		}
		ValueBinding vb = getValueBinding("viewName");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setViewName(String viewName) {
		m_viewName = viewName;
	}

	public String getKeyName() {
		if (m_keyName != null) {
			return m_keyName;
		}
		ValueBinding vb = getValueBinding("keyName");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setKeyName(String keyName) {
		m_keyName = keyName;
	}

	public String getFieldName() {
		if (m_fieldName != null) {
			return m_fieldName;
		}
		ValueBinding vb = getValueBinding("fieldName");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setFieldName(String _fieldName) {
		m_fieldName = _fieldName;
	}

	@Override
	public InputStream getFileStream() {
		Logger log = LoggerFactory.getLogger(getClass().getCanonicalName());
		try {
			if (m_tempDataStore != null) {
				log.info("EmbeddedObject: " + m_tempDataStore.m_EmbObject);
				return m_tempDataStore.m_EmbObject.getInputStream();
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public int accessTemplate() {
		Logger log = LoggerFactory.getLogger(getClass().getCanonicalName());
		m_tempDataStore = null;
		String strView = getViewName();
		String strKey = getKeyName();
		String strFieldName = getFieldName();

		log.info("View: " + strView);
		log.info("Key: " + strKey);
		log.info("FieldName: " + strFieldName);
		if (strView == null || strKey == null || strFieldName == null) {
			return -1;
		}
		try {
			Database ndbAccess = getSourceDatabase(false);
			if (ndbAccess == null) {
				return -2;
			}
			View viwLUP = ndbAccess.getView(strView);
			if (viwLUP == null) {
				DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);
				return -3;
			}
			Document docCurrent = viwLUP.getDocumentByKey(getKeyName(), true);
			if (docCurrent == null) {
				viwLUP.recycle();
				DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);
				return -4;
			}
			if (!docCurrent.hasItem(strFieldName)) {
				docCurrent.recycle();
				viwLUP.recycle();
				DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);
				return -5;
			}
			Item itmBody = docCurrent.getFirstItem(strFieldName);
			if (itmBody instanceof RichTextItem) {
				RichTextItem rtiBody = (RichTextItem) itmBody;
				if (rtiBody.getEmbeddedObjects().size() > 0) {
					EmbeddedObject eoCurrent = (EmbeddedObject) rtiBody.getEmbeddedObjects().elementAt(0);
					m_tempDataStore = new DataTempStore();
					m_tempDataStore.m_Database = ndbAccess;
					m_tempDataStore.m_Document = docCurrent;
					m_tempDataStore.m_Item = rtiBody;
					m_tempDataStore.m_View = viwLUP;
					m_tempDataStore.m_EmbObject = eoCurrent;
					return 1;
				} else {
					itmBody.recycle();
					docCurrent.recycle();
					viwLUP.recycle();
					DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);

					return -6;
				}
			} else {
				itmBody.recycle();
				docCurrent.recycle();
				viwLUP.recycle();
				DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);

				return -7;
			}
		} catch (Exception e) {
			return -10;
		}
	}

	@Override
	public void cleanUP() {
		try {
			if (m_tempDataStore != null) {
				m_tempDataStore.m_EmbObject.recycle();
				m_tempDataStore.m_Item.recycle();
				m_tempDataStore.m_Document.recycle();
				m_tempDataStore.m_View.recycle();
				DatabaseProvider.INSTANCE.handleRecylce(m_tempDataStore.m_Database);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		m_tempDataStore = null;

	}

	@Override
	public void restoreState(FacesContext context, Object value) {
		Object[] state = (Object[]) value;
		super.restoreState(context, state[0]);
		m_fieldName = (String) state[1];
		m_keyName = (String) state[2];
		m_viewName = (String) state[3];

	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[4];
		state[0] = super.saveState(context);
		state[1] = m_fieldName;
		state[2] = m_keyName;
		state[3] = m_viewName;
		return state;

	}

} public interface ITemplateSource {

	public InputStream getFileStream();

	public int accessTemplate();

	public void cleanUP();
} public class ResourceTemplateSource extends AbstractTemplateSource implements ITemplateSource {

	private String m_FileName;

	private TemplateData m_Data;

	private static class TemplateData {
		public String m_Base64data;
	}

	public String getFileName() {
		if (m_FileName != null) {
			return m_FileName;
		}
		ValueBinding vb = getValueBinding("fileName");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setFileName(String _fieldName) {
		m_FileName = _fieldName;
	}

	@Override
	public InputStream getFileStream() {
		if (m_Data == null) {
			return null;
		}
		try {
			Session sesCurrent = POILibUtil.getCurrentSession();
			Stream stream = sesCurrent.createStream();
			Stream streamOut = sesCurrent.createStream();
			Document docTMP = sesCurrent.getCurrentDatabase().createDocument();
			MIMEEntity mime = docTMP.createMIMEEntity("body");
			stream.writeText(m_Data.m_Base64data);
			mime.setContentFromText(stream, "binary", MIMEEntity.ENC_BASE64);
			mime.getContentAsBytes(streamOut);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			streamOut.getContents(bos);
			docTMP.recycle();
			mime.recycle();
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			return bis;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int accessTemplate() {
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());
		String strFileName = getFileName();
		if (strFileName == null) {
			return -1;
		}
		try {
			Database ndbAccess = getSourceDatabase(true);
			if (ndbAccess == null) {
				return -2;
			}
			Session sesSigner = POILibUtil.getCurrentSessionAsSigner();
			if (sesSigner == null) {
				sesSigner = POILibUtil.getCurrentSession();
			}
			logCurrent.info("Getting NoteCollection");
			NoteCollection ncCurrent = ndbAccess.createNoteCollection(false);
			logCurrent.info("Select only MiscFormaElements");
			// ncCurrent.selectAllDesignElements(true);
			ncCurrent.setSelectMiscFormatElements(true);
			logCurrent.info("buildColleciton");
			// ncCurrent.selectAllCodeElements(true);
			ncCurrent.buildCollection();
			logCurrent.info("browseColllection");
			String strID = ncCurrent.getFirstNoteID();
			while (strID != null) {
				Document docNode = ndbAccess.getDocumentByID(strID);

				if (docNode.hasItem("$Title") && docNode.hasItem("$FileData")) {
					Item itmTitle = docNode.getFirstItem("$Title");
					if (itmTitle.containsValue(strFileName)) {
						String str64 = getBASE64StringFormFileResource(docNode, sesSigner);
						if (str64 != null) {
							m_Data = new TemplateData();
							m_Data.m_Base64data = str64;
							strID = null;
						}
					}
				}
				if (strID != null) {
					strID = ncCurrent.getNextNoteID(strID);
					if (strID != null && strID.length() == 0) {
						strID = null;
					}
				}
				docNode.recycle();
			}
			logCurrent.info("DONE");

			ncCurrent.recycle();
			DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);
			if (m_Data != null) {
				return 1;
			}
			// ndbAccess.get
		} catch (Exception e) {
			e.printStackTrace();
			return -9;
		}
		return -4;
	}

	@Override
	public void cleanUP() {
		m_Data = null;
	}

	private String getBASE64StringFormFileResource(Document docCurrent, Session sesCurrent) {
		try {
			DxlExporter dxle = sesCurrent.createDxlExporter();
			dxle.setOutputDOCTYPE(false);
			String strDOM = dxle.exportDxl(docCurrent);

			DocumentBuilder build = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(strDOM));
			org.w3c.dom.Document domDoc = build.parse(is);
			NodeList nlCurrent = domDoc.getElementsByTagName("filedata");
			if (nlCurrent.getLength() == 0) {
				return null;
			} else {
				Node nCheck = nlCurrent.item(0);
				return ((org.w3c.dom.Text) nCheck.getFirstChild()).getTextContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void restoreState(FacesContext context, Object value) {
		Object[] state = (Object[]) value;
		super.restoreState(context, state[0]);
		m_FileName = (String) state[1];

	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[2];
		state[0] = super.saveState(context);
		state[1] = m_FileName;
		return state;

	}
} public class DocumentBookmark extends ValueBindingObjectImpl implements IDocumentBookmark {

	private String m_Name;
	private String m_Value;

	@Override
	public String getName() {
		if (m_Name != null) {
			return m_Name;
		}
		ValueBinding vb = getValueBinding("name");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setName(String name) {
		m_Name = name;
	}

	@Override
	public String getValue() {
		if (m_Value != null) {
			return m_Value;
		}
		ValueBinding vb = getValueBinding("value");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setValue(String value) {
		m_Value = value;
	}

	@Override
	public void restoreState(FacesContext context, Object value) {
		Object[] state = (Object[]) value;
		super.restoreState(context, state[0]);
		m_Name = (String) state[1];
		m_Value = (String) state[2];

	}
    @Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[3];
		state[0] = super.saveState(context);
		state[1] = m_Name;
		state[2] = m_Value;
		return state;

	}

} public interface IDocumentBookmark {
	public String getName();
	public String getValue();
} public class DocumentTable extends AbstractDataExporter {

	/*
	 * private String m_Var; private String m_Index; private Integer m_StepSize;
	 * private IExportSource m_DataSource; private String m_DataSourceVar;
	 */
	private Integer m_StartRow;
	private List<DocColumnDefinition> m_DocColumns;
	private Integer m_MaxRow;
	private Integer m_TableNr;
	private List<DocCellValue> m_DocCellValues;
	private Boolean m_IncludeHeader;

	public List<DocCellValue> getDocCellValues() {
		return m_DocCellValues;
	}

	public void setDocCellValues(List<DocCellValue> docCellValues) {
		m_DocCellValues = docCellValues;
	}

	public void addDocCellValue(DocCellValue icvCurrent) {
		if (m_DocCellValues == null) {
			m_DocCellValues = new ArrayList<>();
		}
		m_DocCellValues.add(icvCurrent);
	}

	public int getStartRow() {
		if (m_StartRow != null) {
			return m_StartRow;
		}
		ValueBinding vb = getValueBinding("startRow");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null)
				return intValue;
		}
		return 0;

	}

	public void setStartRow(int startRow) {
		m_StartRow = startRow;
	}


	public List<DocColumnDefinition> getDocColumns() {
		return m_DocColumns;
	}

	public void setDocColumns(List<DocColumnDefinition> docColumns) {
		m_DocColumns = docColumns;
	}

	public void addDocColumn(DocColumnDefinition cdCurrent) {
		if (m_DocColumns == null) {
			m_DocColumns = new ArrayList<>();
		}
		m_DocColumns.add(cdCurrent);
	}

	public int getMaxRow() {
		if (m_MaxRow != null) {
			return m_MaxRow;
		}
		ValueBinding vb = getValueBinding("maxRow");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null)
				return intValue;
		}
		return 100;

	}

	public void setMaxRow(int maxRow) {
		m_MaxRow = maxRow;
	}

	public int getTableNr() {
		return m_TableNr;
	}

	public void setTableNr(int tableNr) {
		m_TableNr = tableNr;
	}
	/*
	 * public IExportSource getDataSource() { return m_DataSource; }
	 *
	 * public void setDataSource(IExportSource dataSource) { m_DataSource =
	 * dataSource; }
	 *
	 * public int getStepSize() { if (m_StepSize != null) { return m_StepSize; }
	 * ValueBinding vb = getValueBinding("stepSize"); if (vb != null) { Integer
	 * intValue = (Integer) vb.getValue(getFacesContext()); if (intValue !=
	 * null) return intValue; } return 1; }
	 *
	 * public void setStepSize(int stepSize) { m_StepSize = stepSize; }
	 *
	 * public String getVar() { return m_Var; }
	 *
	 * public void setVar(String var) { m_Var = var; }
	 *
	 * public String getIndex() { return m_Index; }
	 *
	 * public void setIndex(String index) { m_Index = index; }
	 *
	 * public String getDataSourceVar() { if (m_DataSourceVar != null) { return
	 * m_DataSourceVar; } ValueBinding vb = getValueBinding("dataSourceVar"); if
	 * (vb != null) { String strValue = (String) vb.getValue(getFacesContext());
	 * if (strValue != null) return strValue; } return null;
	 *
	 * }
	 *
	 * public void setDataSourceVar(String dataSourceVar) { m_DataSourceVar =
	 * dataSourceVar; }
	 *
	 * public DataSource getPageDataSource() { String strName =
	 * getDataSourceVar(); System.out.println(strName); if
	 * (StringUtil.isNotEmpty(strName)) {
	 *
	 * UIViewRoot vrCurrent = getFacesContext().getViewRoot(); if (vrCurrent
	 * instanceof UIViewRootEx) { for (DataSource dsCurrent : ((UIViewRootEx)
	 * vrCurrent).getData()) { if (strName.equals(dsCurrent.getVar())) { return
	 * dsCurrent; } } } } System.out.println("Datasource name:" +
	 * m_DataSourceVar); return null;
	 *
	 * }
	 */





	public boolean getIncludeHeader() {
		if (null != m_IncludeHeader) {
			return m_IncludeHeader;
		}
		ValueBinding _vb = getValueBinding("includeHeader"); //$NON-NLS-1$
		if (_vb != null) {
			return (Boolean) _vb.getValue(FacesContext.getCurrentInstance());
		} else {
			return false;
		}
	}

	public void setIncludeHeader(boolean includeHeader) {
		m_IncludeHeader = includeHeader;
	}

	@Override
	public Object saveState(FacesContext context) {
		try {

			Object[] state = new Object[7];
			state[0] = super.saveState(context);
			state[1] = StateHolderUtil.saveList(context, m_DocCellValues);
			state[2] = m_StartRow;
			state[3] = StateHolderUtil.saveList(context, m_DocColumns);
			state[4] = m_MaxRow;
			state[5] = m_TableNr;
			state[6] = m_IncludeHeader;
			/*
			 * state[5] = m_StepSize; state[6] =
			 * FacesUtil.objectToSerializable(getFacesContext(), m_DataSource);
			 * state[7] = m_DataSourceVar; state[8] = m_Var; state[9] = m_Index;
			 */
			return state;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_DocCellValues = StateHolderUtil.restoreList(context, getComponent(), state[1]);
		m_StartRow = (Integer) state[2];
		m_DocColumns = StateHolderUtil.restoreList(context, getComponent(), state[3]);
		m_MaxRow = (Integer) state[4];
		m_TableNr = (Integer) state[5];
		m_IncludeHeader = (Boolean) state[6];
	}


} public class Data2ColumnExporter extends AbstractDataExporter implements
		IListDataExporter {

	List<RowDefinition> m_Rows;
	Integer m_StartColumn;

	public int getStartColumn() {
		if (m_StartColumn != null) {
			return m_StartColumn;
		}
		ValueBinding vb = getValueBinding("startColumn");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null)
				return intValue;
		}
		return 0;
	}

	public void setStartColumn(int startColumn) {
		m_StartColumn = startColumn;
	}

	public void addRow(RowDefinition rdCurrent) {
		if (m_Rows == null) {
			m_Rows = new ArrayList<>();
		}
		m_Rows.add(rdCurrent);
	}

	public List<RowDefinition> getRows() {
		return m_Rows;
	}

	public void setRows(List<RowDefinition> rows) {
		m_Rows = rows;
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[3];
		state[0] = super.saveState(context);
		state[1] = m_StartColumn;
		state[2] = StateHolderUtil.saveList(getFacesContext(), m_Rows);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_StartColumn = (Integer) state[1];
		m_Rows = StateHolderUtil.restoreList(getFacesContext(), getComponent(),
				state[2]);

	}

} public class Data2RowExporter extends AbstractDataExporter implements
		IListDataExporter {
	private Integer m_StartRow;
	private List<ColumnDefinition> m_Columns;

	public int getStartRow() {
		if (m_StartRow != null) {
			return m_StartRow;
		}
		ValueBinding vb = getValueBinding("startRow");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null)
				return intValue;
		}
		return 0;

	}

	public void setStartRow(int startRow) {
		m_StartRow = startRow;
	}

	public List<ColumnDefinition> getColumns() {
		return m_Columns;
	}

	public void setColumns(List<ColumnDefinition> columns) {
		m_Columns = columns;
	}

	public void addColumn(ColumnDefinition cdCurrent) {
		if (m_Columns == null) {
			m_Columns = new ArrayList<>();
		}
		m_Columns.add(cdCurrent);
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[5];
		state[0] = super.saveState(context);
		state[1] = m_StartRow;
		state[2] = StateHolderUtil.saveList(context, m_Columns);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_StartRow = (Integer) state[1];
		m_Columns = StateHolderUtil.restoreList(context, getComponent(),
				state[2]);

	}
} public interface IListDataExporter {
	public IExportSource getDataSource();

} public class Spreadsheet extends ValueBindingObjectImpl {

	private String m_Name;
	private Boolean m_Create;
	private List<IListDataExporter> m_ExportDefinition;
	private List<ICellValue> m_CellValues;

	public String getName() {
		if (m_Name != null) {
			return m_Name;
		}
		ValueBinding vb = getValueBinding("name");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setName(String name) {
		m_Name = name;
	}

	public boolean isCreate() {
		if (m_Create != null) {
			return m_Create;
		}
		ValueBinding vb = getValueBinding("create");
		if (vb != null) {
			Boolean blValue = (Boolean) vb.getValue(getFacesContext());
			if (blValue != null) {
				return blValue;
			}
		}
		return false;
	}

	public void setCreate(boolean create) {
		m_Create = create;
	}

	public List<IListDataExporter> getExportDefinitions() {
		return m_ExportDefinition;
	}

	public void setExportDefinitions(List<IListDataExporter> exportDefinition) {
		m_ExportDefinition = exportDefinition;
	}

	public void addExportDefinition(IListDataExporter ilCurrent) {
		if (m_ExportDefinition == null) {
			m_ExportDefinition = new ArrayList<>();
		}
		m_ExportDefinition.add(ilCurrent);
	}

	public List<ICellValue> getCellValues() {
		return m_CellValues;
	}

	public void setCellValues(List<ICellValue> cellValues) {
		m_CellValues = cellValues;
	}

	public void addCellValue(ICellValue icvCurrent) {
		if (m_CellValues == null) {
			m_CellValues = new ArrayList<>();
		}
		m_CellValues.add(icvCurrent);
	}

	@Override
	public Object saveState(FacesContext context) {
		try {

			Object[] state = new Object[5];
			state[0] = super.saveState(context);
			state[1] = m_Create;
			state[2] = m_Name;
			state[3] = StateHolderUtil.saveList(context, m_ExportDefinition);
			state[4] = StateHolderUtil.saveList(context, m_CellValues);
			return state;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_Create = (Boolean) state[1];
		m_Name = (String) state[2];
		m_ExportDefinition = StateHolderUtil.restoreList(context,
				getComponent(), state[3]);
		m_CellValues = StateHolderUtil.restoreList(context, getComponent(),
				state[4]);
	}
} public class CellBookmark extends ValueBindingObjectImpl implements ICellValue {

	private Object m_Value;
	private String m_Name;

	@Override
	public Object getValue() {
		if (m_Value != null) {
			return m_Value;
		}
		ValueBinding vb = getValueBinding("value");
		if (vb != null) {
			return vb.getValue(getFacesContext());
		}
		return null;
	}

	public String getName() {
		if (m_Name != null) {
			return m_Name;
		}
		ValueBinding vb = getValueBinding("name");
		if (vb != null) {
			return (String) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setName(String name) {
		m_Name = name;
	}

	public void setValue(Object value) {
		m_Value = value;
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[3];
		state[0] = super.saveState(context);
		state[1] = m_Name;
		state[2] = m_Value;
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_Name = (String)state[1];
		m_Value = state[2];
	}
} public class CellValue extends ValueBindingObjectImpl implements ICellValue {

	private Object m_Value;
	private Integer m_ColumnNumber;
	private Integer m_RowNumber;
	private Boolean m_CellFormula = false;
	private PoiCellStyle m_PoiCellStyle;

	public int getRowNumber() {
		if (m_RowNumber != null) {
			return m_RowNumber;
		}
		ValueBinding vb = getValueBinding("rowNumber");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;

	}

	public void setRowNumber(int rowNumber) {
		m_RowNumber = rowNumber;
	}

	@Override
	public Object getValue() {
		if (m_Value != null) {
			return m_Value;
		}
		ValueBinding vb = getValueBinding("value");
		if (vb != null) {
			return vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setValue(Object value) {
		m_Value = value;
	}

	public int getColumnNumber() {
		if (m_ColumnNumber != null) {
			return m_ColumnNumber;
		}
		ValueBinding vb = getValueBinding("columnNumber");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;
	}

	public void setColumnNumber(int columnNumber) {
		m_ColumnNumber = columnNumber;
	}


	public boolean isCellFormula() {
		return m_CellFormula;
	}

	public void setCellFormula(boolean cellFormula) {
		m_CellFormula = cellFormula;
	}

	public PoiCellStyle getPoiCellStyle() {
			return m_PoiCellStyle;
	}

	public void setPoiCellStyle(PoiCellStyle poiCellStyle) {
		m_PoiCellStyle = poiCellStyle;
	}

	public PoiCellStyle getCellStyle() {
		return getPoiCellStyle();
	}

	public void setCellStyle(PoiCellStyle poiCellStyle) {
		setPoiCellStyle(poiCellStyle);
	}
	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[6];
		state[0] = super.saveState(context);
		state[1] = m_ColumnNumber;
		state[2] = m_RowNumber;
		state[3] = m_Value;
		state[4] = m_CellFormula;
		state[5] = FacesUtil.objectToSerializable(context, m_PoiCellStyle);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_ColumnNumber = (Integer)state[1];
		m_RowNumber = (Integer)state[2];
		m_Value = state[3];
		m_CellFormula = (Boolean) state[4];
		m_PoiCellStyle = (PoiCellStyle) FacesUtil.objectFromSerializable(context, state[5]);
	}
} public class ColumnDefinition extends AbstractDefinition implements IDefinition {
	private Integer m_ColumnNumber;
	private String m_ColumnTitle;
	private Integer m_RowShift = 0;
	private Boolean m_CellFormula = false;
	private PoiCellStyle m_PoiCellStyle;

	public int getColumnNumber() {
		if (m_ColumnNumber != null) {
			return m_ColumnNumber;
		}
		ValueBinding vb = getValueBinding("columnNumber");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;

	}

	public void setColumnNumber(int columnNumber) {
		m_ColumnNumber = columnNumber;
	}

	public int getRowShift() {
		if (m_RowShift != null) {
			return m_RowShift;
		}
		ValueBinding vb = getValueBinding("rowShift");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;

	}

	public void setRowShift(int rowShift) {
		m_RowShift = rowShift;
	}

	public boolean isCellFormula() {
		return m_CellFormula;
	}

	public void setCellFormula(boolean cellFormula) {
		m_CellFormula = cellFormula;
	}

	public PoiCellStyle getPoiCellStyle() {
		return m_PoiCellStyle;
	}

	public void setPoiCellStyle(PoiCellStyle poiCellStyle) {
		m_PoiCellStyle = poiCellStyle;
	}

	public PoiCellStyle getCellStyle() {
		return getPoiCellStyle();
	}

	public void setCellStyle(PoiCellStyle poiCellStyle) {
		setPoiCellStyle(poiCellStyle);
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[7];
		state[0] = super.saveState(context);
		state[1] = m_ColumnNumber;
		state[2] = m_RowShift;
		state[3] = m_ColumnTitle;
		state[4] = StateHolderUtil
				.saveMethodBinding(context, getComputeValue());
		state[5] = m_CellFormula;
		state[6] = FacesUtil.objectToSerializable(context, m_PoiCellStyle);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_ColumnNumber = (Integer) state[1];
		m_RowShift = (Integer) state[2];
		m_ColumnTitle = (String) state[3];
		setComputeValue(StateHolderUtil.restoreMethodBinding(context,
				getComponent(), state[4]));
		m_CellFormula = (Boolean) state[5];
		m_PoiCellStyle = (PoiCellStyle) FacesUtil.objectFromSerializable(context, state[6]);
	}

	@Override
	public String getColumnTitle() {
		if (m_ColumnTitle != null) {
			return m_ColumnTitle;
		}
		ValueBinding vb = getValueBinding("columnTitle");
		if (vb != null) {
			String strValue = (String) vb.getValue(getFacesContext());
			if (strValue != null) {
				return strValue;
			}
		}
		return null;
	}

	public void setColumnTitle(String columnTitle) {
		m_ColumnTitle = columnTitle;
	}

} public interface ICellValue {

	public Object getValue();
} public class RowDefinition extends AbstractDefinition implements IDefinition {
	private Integer m_RowNumber;
	private String m_ColumnTitle;
	private Integer m_ColumnShift = 0;
	private Boolean m_CellFormula = false;
	private PoiCellStyle m_PoiCellStyle;

	public int getRowNumber() {
		if (m_RowNumber != null)
			return m_RowNumber;
		ValueBinding vb = getValueBinding("rowNumber");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;

	}

	public void setRowNumber(int rowNumber) {
		m_RowNumber = rowNumber;
	}

	public int getColumnShift() {
		if (m_ColumnShift != null) {
			return m_ColumnShift;
		}
		ValueBinding vb = getValueBinding("columnShift");
		if (vb != null) {
			Integer intValue = (Integer) vb.getValue(getFacesContext());
			if (intValue != null) {
				return intValue;
			}
		}
		return 0;

	}

	public void setColumnShift(int columnShift) {
		m_ColumnShift = columnShift;
	}

	public boolean isCellFormula() {
		return m_CellFormula;
	}

	public void setCellFormula(boolean cellFormula) {
		m_CellFormula = cellFormula;
	}

	public PoiCellStyle getPoiCellStyle() {
			return m_PoiCellStyle;
	}

	public void setPoiCellStyle(PoiCellStyle poiCellStyle) {
		m_PoiCellStyle = poiCellStyle;
	}

	public PoiCellStyle getCellStyle() {
		return getPoiCellStyle();
	}

	public void setCellStyle(PoiCellStyle poiCellStyle) {
		setPoiCellStyle(poiCellStyle);
	}
	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[7];
		state[0] = super.saveState(context);
		state[1] = m_RowNumber;
		state[2] = m_ColumnShift;
		state[3] = m_ColumnTitle;
		state[4] = StateHolderUtil
				.saveMethodBinding(context, getComputeValue());
		state[5] = m_CellFormula;
		state[6] = FacesUtil.objectToSerializable(context, m_PoiCellStyle);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_RowNumber = (Integer) state[1];
		m_ColumnShift = (Integer) state[2];
		m_ColumnTitle = (String) state[3];
		setComputeValue(StateHolderUtil.restoreMethodBinding(context,
				getComponent(), state[4]));
		m_CellFormula = (Boolean) state[5];
		m_PoiCellStyle = (PoiCellStyle) FacesUtil.objectFromSerializable(context, state[6]);
	}

	@Override
	public String getColumnTitle() {
		if (m_ColumnTitle != null) {
			return m_ColumnTitle;
		}
		ValueBinding vb = getValueBinding("columnTitle");
		if (vb != null) {
			String strValue = (String) vb.getValue(getFacesContext());
			if (strValue != null) {
				return strValue;
			}
		}
		return null;
	}

	public void setColumnTitle(String columnTitle) {
		m_ColumnTitle = columnTitle;
	}

} public enum DocumentProcessor {
	INSTANCE;

	/**
	 * gets the Instance of the DocumentProcessor.
	 *
	 * @deprecated -> Use DocumentProcessor.INSTANCE instead
	 *
	 * @return Instance of the DocumentProcessor
	 */
	@Deprecated
	public static DocumentProcessor getInstance() {
		return DocumentProcessor.INSTANCE;
	}

	public XWPFDocument getDocument(InputStream inDocument) {

		try {
			Logger log = LoggerFactory.getLogger(getClass().getCanonicalName());
			log.info("inDocument -> " + inDocument);
			XWPFDocument dxReturn = new XWPFDocument(inDocument);
			return dxReturn;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public int processBookmarks2Document(XWPFDocument dxProcess, List<IDocumentBookmark> arrBookmarks) {
		// First Prozessing all paragraphs.
		for (XWPFParagraph paraCurrent : dxProcess.getParagraphs()) {
			processBookmarks2Paragraph(arrBookmarks, paraCurrent);
		}

		for (XWPFTable tabCurrent : dxProcess.getTables()) {
			processBookmarks2Table(arrBookmarks, tabCurrent);
		}
		for (XWPFHeader headCurrent : dxProcess.getHeaderList()) {
			for (XWPFParagraph paraCurrent : headCurrent.getParagraphs()) {
				processBookmarks2Paragraph(arrBookmarks, paraCurrent);
			}
			for (XWPFTable tabCurrent : headCurrent.getTables()) {
				processBookmarks2Table(arrBookmarks, tabCurrent);
			}
		}
		for (XWPFFooter footCurrent : dxProcess.getFooterList()) {
			for (XWPFParagraph paraCurrent : footCurrent.getParagraphs()) {
				processBookmarks2Paragraph(arrBookmarks, paraCurrent);
			}
			for (XWPFTable tabCurrent : footCurrent.getTables()) {
				processBookmarks2Table(arrBookmarks, tabCurrent);
			}
		}

		return 1;
	}

	private void processBookmarks2Table(List<IDocumentBookmark> arrBookmarks, XWPFTable tabCurrent) {
		for (XWPFTableRow tabRow : tabCurrent.getRows()) {
			for (XWPFTableCell tabCell : tabRow.getTableCells()) {
				for (XWPFParagraph paraCurrent : tabCell.getParagraphs()) {
					processBookmarks2Paragraph(arrBookmarks, paraCurrent);
				}
			}
		}
	}

	private void processBookmarks2Paragraph(List<IDocumentBookmark> arrBookmarks, XWPFParagraph paraCurrent) {
		for (XWPFRun runCurrent : paraCurrent.getRuns()) {
			processBookmarks2Run(runCurrent, arrBookmarks);
		}
	}

	public int processBookmarks2Run(XWPFRun runCurrent, List<IDocumentBookmark> arrBookmarks) {
		String strText = runCurrent.getText(0);
		if (strText != null) {
			boolean found = false;
			for (IDocumentBookmark bmCurrent : arrBookmarks) {
				String strValue = bmCurrent.getValue();
				strValue = strValue == null ? "" : strValue;
				if (bmCurrent.getName() != null && strText.contains("<<" + bmCurrent.getName() + ">>")) {
					found = true;
					strText = strText.replace("<<" + bmCurrent.getName() + ">>", strValue);
				}
			}
			if (found) {
				String lines[] = strText.split("\\r?\\n");
				for (int i = 0; i < lines.length; i++) {
					String line = lines[i];
					if (i == 0) {
						runCurrent.setText(line, 0);
					} else {
						runCurrent.setText(line);
					}
					if (i + 1 < lines.length) {
						runCurrent.addBreak(BreakType.TEXT_WRAPPING);
					}
				}
			}
		}
		return 1;
	}

	public void generateNewFile(ITemplateSource itsCurrent, HttpServletResponse httpResponse, FacesContext context, UIDocument uiDoc, boolean noDownload, MethodBinding preDownload)
			throws IOException {
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());
		List<IDocumentBookmark> bookmarks = uiDoc.getBookmarks();
		List<DocumentTable> tables = uiDoc.getTables();
		String strFileName = uiDoc.getDownloadFileName();
		try {
			int nTemplateAccess = itsCurrent.accessTemplate();
			if (nTemplateAccess == 1) {
				XWPFDocument dxDocument = processDocument(itsCurrent, bookmarks, tables, context, uiDoc);
				if (uiDoc.getPdfOutput()) {

					logCurrent.info("Build PDF");
					ByteArrayOutputStream bosDoc = new ByteArrayOutputStream();
					dxDocument.write(bosDoc);
					bosDoc.flush();
					logCurrent.info("Size of worddocument ByteArrayOutputStream: " + bosDoc.size());
					ByteArrayInputStream is = new ByteArrayInputStream(bosDoc.toByteArray());
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					IPDFService isCurrent = PDFConversionService.getInstance().getPDFService();

					isCurrent.buildPDF(is, bos);
					is.close();
					bos.flush();

					MethodExecutor.INSTANCE.execute(preDownload, uiDoc, context, bos);
					if (!noDownload) {
						logCurrent.info("Size of pdf ByteArrayOutputStream: " + bos.size());
						httpResponse.setContentType("application/octet-stream");
						httpResponse.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\"");
						OutputStream os = httpResponse.getOutputStream();
						bos.writeTo(os);
						bos.close();
						os.close();
					} else {
						OutputStream os = httpResponse.getOutputStream();
						os.close();
					}
				} else {
					logCurrent.info("Build docx");
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					dxDocument.write(bos);
					MethodExecutor.INSTANCE.execute(preDownload, uiDoc, context, bos);
					if (!noDownload) {
						httpResponse.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
						httpResponse.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\"");
						OutputStream os = httpResponse.getOutputStream();
						bos.writeTo(os);
						bos.close();
						os.close();
					} else {
						OutputStream os = httpResponse.getOutputStream();
						os.close();
					}
				}
			} else {
				ErrorPageBuilder.getInstance().processError(httpResponse, "TemplateAccess Problem NR: " + nTemplateAccess, null);
			}
		} catch (Exception e) {
			ErrorPageBuilder.getInstance().processError(httpResponse, "Error during Documentgeneration", e);
		}
	}

	public XWPFDocument processDocument(ITemplateSource itsCurrent, List<IDocumentBookmark> bookmarks, List<DocumentTable> tables, FacesContext context, UIDocument uiDocument) throws POIException {

		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());

		InputStream is = itsCurrent.getFileStream();
		XWPFDocument dxDocument = getDocument(is);
		itsCurrent.cleanUP();
		if (bookmarks != null && bookmarks.size() > 0) {
			processBookmarks2Document(dxDocument, bookmarks);
		}
		logCurrent.finest("Start export Tables");
		if (tables != null && tables.size() > 0) {
			for (DocumentTable tblExport : tables) {
				XWPFTable dxTable = EmbeddedDataSourceExportProcessor.INSTANCE.processExportTable(tblExport, dxDocument, context, tblExport.getVar(), tblExport.getIndex());
				logCurrent.finest("exportTable created");
				// logCurrent.finer("Start Processing Cells");
				if (tblExport.getDocCellValues() != null && tblExport.getDocCellValues().size() > 0) {
					for (ICellValue iCV : tblExport.getDocCellValues()) {
						if (iCV instanceof DocCellValue) {
							DocCellValue cv = (DocCellValue) iCV;
							if (cv.getRowNumber() <= tblExport.getMaxRow()) {
								EmbeddedDataSourceExportProcessor.INSTANCE.setDocCellValue(dxTable, cv.getRowNumber(), cv.getColumnNumber(), cv.getValue(), tblExport.getMaxRow(), false);
							} else {
								logCurrent.finer("MaxValue < CellValue.getRowNumber()");
							}
						}
					}

				}
			}

		}

		if (uiDocument != null) {
			uiDocument.postGenerationProcess(context, dxDocument);
		}
		return dxDocument;
	}

	public void processCall(FacesContext context, UIDocument uiDocument, boolean noDownload, MethodBinding preDownload) {
		HttpServletResponse httpResponse = (HttpServletResponse) context.getExternalContext().getResponse();
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());

		if (httpResponse instanceof XspHttpServletResponse) {
			XspHttpServletResponse r = (XspHttpServletResponse) httpResponse;
			r.setCommitted(true);
			httpResponse = r.getDelegate();
		}

		ITemplateSource itsCurrent = uiDocument.getTemplateSource();
		if (itsCurrent == null) {
			ErrorPageBuilder.getInstance().processError(httpResponse, "No Templatesource found!", null);
			logCurrent.severe("No Template found!");
			return;
		}
		logCurrent.info("Start processing UIDocument generation");
		try {
			DocumentProcessor.INSTANCE.generateNewFile(itsCurrent, httpResponse, context, uiDocument, noDownload, preDownload);
		} catch (Exception e) {
			try {
				logCurrent.log(Level.SEVERE, "Error in UIGeneration", e);
				e.printStackTrace();
				e.printStackTrace(httpResponse.getWriter());
				ErrorPageBuilder.getInstance().processError(httpResponse, "General Error!", e);
			} catch (Exception e2) {
				e2.printStackTrace();
				e.printStackTrace();
				ErrorPageBuilder.getInstance().processError(httpResponse, "General Error!", e2);

			}
		}
	}

} public enum WorkbookProcessor {
	INSTANCE;

	public static WorkbookProcessor getInstance() {
		return WorkbookProcessor.INSTANCE;
	}

	public void generateNewFile(ITemplateSource itsCurrent, HttpServletResponse httpResponse, FacesContext context, UIWorkbook uiWB, boolean noDownload, MethodBinding preDownload) {
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());
		List<Spreadsheet> lstSP = uiWB.getSpreadsheets();
		String strFileName = uiWB.getDownloadFileName();
		try {
			logCurrent.finer("First getting the File");
			// First getting the File
			int nTemplateAccess = itsCurrent.accessTemplate();
			if (nTemplateAccess == 1) {
				Workbook wbCurrent = processWorkbook(itsCurrent, lstSP, context, uiWB);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				wbCurrent.write(bos);

				MethodExecutor.INSTANCE.execute(preDownload, uiWB, context, bos);
				if (!noDownload) {
					logCurrent.finer("Push the Result to the HttpServlet");
					// Push the Result to the HttpServlet
					if (strFileName.toLowerCase().endsWith(".xlsx")) {
						httpResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
					} else if (strFileName.toLowerCase().endsWith("xls")) {
						httpResponse.setContentType("application/vnd.ms-excel");

					} else {
						httpResponse.setContentType("application/octet-stream");
					}
					httpResponse.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\"");
					OutputStream os = httpResponse.getOutputStream();
					bos.writeTo(os);
					os.close();
				} else {
					OutputStream os = httpResponse.getOutputStream();
					os.close();
				}
				wbCurrent.close();
			} else {
				ErrorPageBuilder.getInstance().processError(httpResponse, "TemplateAccess Problem NR: " + nTemplateAccess, null);
			}
		} catch (Exception e) {
			ErrorPageBuilder.getInstance().processError(httpResponse, "Error during Workbookgeneration", e);
		}

	}

	public Workbook processWorkbook(ITemplateSource itsCurrent, List<Spreadsheet> lstSP, FacesContext context, UIWorkbook uiWB) throws IOException, InvalidFormatException, POIException {
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());

		InputStream is = itsCurrent.getFileStream();
		// Workbook wbCurrent = WorkbookFactory.create(is);
		// ;
		Workbook wbCurrent1 = WorkbookFactory.create(is);
		Workbook wbCurrent = wbCurrent1;
		is.close();
		if (wbCurrent1 instanceof XSSFWorkbook && uiWB.isUseStreamingModel()) {
			logCurrent.info("Generation SXSSFWorkbook");
			wbCurrent = new SXSSFWorkbook((XSSFWorkbook) wbCurrent1);
		}
		itsCurrent.cleanUP();
		// Processing all Spreadsheets to the File
		logCurrent.finer("Push the Result to the HttpServlet");

		for (Spreadsheet spCurrent : lstSP) {
			processSpreadSheet(spCurrent, wbCurrent, context);
		}
		if (uiWB != null) {
			logCurrent.finer("Post Generation Process");
			uiWB.postGenerationProcess(context, wbCurrent);
		}
		return wbCurrent;
	}

	private void processSpreadSheet(Spreadsheet spCurrent, Workbook wbCurrent, FacesContext context) throws POIException {
		// Checking for Replacement Values
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());

		logCurrent.finer("Proccess Spread Sheet");
		String strName = spCurrent.getName();
		Sheet shProcess = wbCurrent.getSheet(strName);
		if (shProcess == null && !spCurrent.isCreate()) {
			return;
		}
		if (shProcess == null) {
			shProcess = wbCurrent.createSheet(strName);
		}

		logCurrent.finer("Proccess Cell Values");
		if (spCurrent.getCellValues() != null) {
			for (ICellValue iCV : spCurrent.getCellValues()) {
				if (iCV instanceof CellBookmark) {
					CellBookmark cb = (CellBookmark) iCV;
					if (StringUtil.isNotEmpty(cb.getName())) {
						findAndReplaceAll(shProcess, "<<" + cb.getName() + ">>", cb.getValue());
					}
				}
				if (iCV instanceof CellValue) {
					CellValue cv = (CellValue) iCV;
					setCellValue(shProcess, cv.getRowNumber(), cv.getColumnNumber(), cv.getValue(), cv.isCellFormula(), cv.getPoiCellStyle());
				}
			}
		}

		logCurrent.finer("Proccess ExportDefinition");
		if (spCurrent.getExportDefinitions() != null) {
			for (IListDataExporter lstExport : spCurrent.getExportDefinitions()) {
				if (lstExport instanceof Data2ColumnExporter) {
					if (lstExport.getDataSource() != null) {
						EmbeddedDataSourceExportProcessor.getInstance().processExportCol((Data2ColumnExporter) lstExport, shProcess, context, ((Data2ColumnExporter) lstExport).getVar(),
								((Data2ColumnExporter) lstExport).getIndex());
					} else {
						XPagesDataSourceExportProcessor.getInstances().processExportCol((Data2ColumnExporter) lstExport, shProcess, context, ((Data2ColumnExporter) lstExport).getVar(),
								((Data2ColumnExporter) lstExport).getIndex());
					}
				} else if (lstExport instanceof Data2RowExporter) {
					if (lstExport.getDataSource() != null) {
						EmbeddedDataSourceExportProcessor.getInstance().processExportRow((Data2RowExporter) lstExport, shProcess, context, ((Data2RowExporter) lstExport).getVar(),
								((Data2RowExporter) lstExport).getIndex());
					} else {
						XPagesDataSourceExportProcessor.getInstances().processExportRow((Data2RowExporter) lstExport, shProcess, context, ((Data2RowExporter) lstExport).getVar(),
								((Data2RowExporter) lstExport).getIndex());
					}

				}
			}
		}
	}

	public void setCellValue(Sheet shProcess, int nRow, int nCol, Object objValue, boolean isFormula, PoiCellStyle pCellStyle) {
		try {
			Row rw = shProcess.getRow(nRow);
			if (rw == null) {
				rw = shProcess.createRow(nRow);
			}
			Cell c = rw.getCell(nCol);
			if (c == null) {
				c = rw.createCell(nCol);
			}
			if (isFormula) {
				c.setCellFormula((String) objValue);
			} else if (objValue instanceof Double) {
				c.setCellValue((Double) objValue);
			} else if (objValue instanceof Integer) {
				c.setCellValue((Integer) objValue);
			} else {
				if (objValue instanceof Date) {
					c.setCellValue((Date) objValue);
				} else {
					c.setCellValue("" + objValue);
				}
			}
			if (pCellStyle != null) {
				CellStyle style = POICellStyleProcessor.INSTANCE.buildStyle(shProcess, pCellStyle);
				c.setCellStyle(style);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void findAndReplaceAll(Sheet sheet, String find, Object replace) {
		if (replace == null) {
			replace = "";
		}
		int iLastRow = sheet.getLastRowNum();
		for (int i1 = 0; i1 < iLastRow; i1++) {
			Row currentRow = sheet.getRow(i1);
			if (currentRow != null) {
				int iLastCell = currentRow.getLastCellNum();
				for (int i = 0; i < iLastCell; i++) {
					Cell currentCell = currentRow.getCell(i);
					if (currentCell != null && currentCell.getCellType() == CellType.STRING) {
						if (currentCell.getStringCellValue().contains(find)) {
							currentCell.setCellValue(currentCell.getStringCellValue().replace(find, "" + replace));
						}
					}
				}
			}
		}
	}

	public void processCall(FacesContext context, UIWorkbook uiWorkbook, boolean noDownload, MethodBinding preDownload) {
		HttpServletResponse httpResponse = (HttpServletResponse) context.getExternalContext().getResponse();

		// Disable the XPages response buffer as this will collide with the
		// engine one
		// We mark it as committed and use its delegate instead

		if (httpResponse instanceof XspHttpServletResponse) {
			XspHttpServletResponse r = (XspHttpServletResponse) httpResponse;
			r.setCommitted(true);
			httpResponse = r.getDelegate();
		}

		ITemplateSource itsCurrent = uiWorkbook.getTemplateSource();
		if (itsCurrent == null) {
			ErrorPageBuilder.getInstance().processError(httpResponse, "No Templatesource found!", null);
			return;
		}
		try {
			WorkbookProcessor.INSTANCE.generateNewFile(itsCurrent, httpResponse, context, uiWorkbook, noDownload, preDownload);
		} catch (Exception e) {
			try {
				e.printStackTrace();
				e.printStackTrace(httpResponse.getWriter());
				ErrorPageBuilder.getInstance().processError(httpResponse, "General Error!", e);
			} catch (Exception e2) {
				e2.printStackTrace();
				e.printStackTrace();
				ErrorPageBuilder.getInstance().processError(httpResponse, "General Error!", e2);
			}
		}

	}
} public class DominoView extends ValueBindingObjectImpl implements IExportSource {

	private String m_ViewName;
	private String m_Database;
	private String m_Key;
	private String m_Search;
	private int m_maxRow = 1000;

	private DataTempStore m_tempDataStore;

	protected static class DataTempStore {
		public Database m_Database;
		public View m_View;
		public ViewEntry m_Entry;
		public ViewEntryCollection m_Col;
		public List<String> m_ColTitle;
		public int m_rowCount;
		public Vector<?> m_ColValues;
	}

	public int getMaxRow() {
		return m_maxRow;
	}

	public void setMaxRow(int maxRow) {
		m_maxRow = maxRow;
	}

	@Override
	public int accessNextRow() {
		if (m_tempDataStore == null) {
			return -1;
		}
		try {
			if (m_tempDataStore.m_Entry == null) {
				m_tempDataStore.m_Entry = m_tempDataStore.m_Col.getFirstEntry();
			} else {
				ViewEntry ve = m_tempDataStore.m_Entry;
				m_tempDataStore.m_Entry = m_tempDataStore.m_Col.getNextEntry(ve);
				ve.recycle();
			}
			if (m_tempDataStore.m_Entry == null) {
				return 0;
			}
			m_tempDataStore.m_ColValues = m_tempDataStore.m_Entry.getColumnValues();
			m_tempDataStore.m_rowCount++;
			if (m_tempDataStore.m_rowCount > m_maxRow) {
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -10;
		}
		return 1;
	}

	@Override
	public int accessSource() {
		if (m_tempDataStore == null) {
			m_tempDataStore = new DataTempStore();
			String strDB = getDatabase();
			String strView = getViewName();
			String strKey = getKey();
			String strSearch = getSearch();
			if (strView == null) {
				return -1;
			}
			try {
				Database ndbAccess = DatabaseProvider.INSTANCE.getDatabase(strDB, false);
				if (ndbAccess == null) {
					return -2;
				}
				View viwLUP = ndbAccess.getView(strView);

				if (viwLUP == null) {
					DatabaseProvider.INSTANCE.handleRecylce(ndbAccess);
					return -3;
				}
				ViewEntryCollection nvcCurrent = viwLUP.getAllEntries();
				if (strKey != null) {
					nvcCurrent = viwLUP.getAllEntriesByKey(strKey, true);
					System.out.println("Build collection with Key: " + strKey + "(" + nvcCurrent.getCount() + ")");
				} else if (strSearch != null) {
					nvcCurrent.FTSearch(strSearch);

				}
				m_tempDataStore.m_Database = ndbAccess;
				m_tempDataStore.m_View = viwLUP;
				m_tempDataStore.m_Col = nvcCurrent;
				m_tempDataStore.m_ColTitle = new ArrayList<>();
				m_tempDataStore.m_rowCount = 0;
				for (Iterator<?> itNames = viwLUP.getColumnNames().iterator(); itNames.hasNext();) {
					String strCLNAME = (String) itNames.next();
					m_tempDataStore.m_ColTitle.add(strCLNAME);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return -10;
			}
		}
		return 1;
	}

	@Override
	public int closeSource() {
		try {
			if (m_tempDataStore != null) {
				if (m_tempDataStore.m_Entry != null) {
					m_tempDataStore.m_Entry.recycle();
				}
				if (m_tempDataStore.m_Col != null) {
					m_tempDataStore.m_Col.recycle();
				}
				if (m_tempDataStore.m_View != null) {
					m_tempDataStore.m_View.recycle();
				}
				if (m_tempDataStore.m_Database != null) {
					DatabaseProvider.INSTANCE.handleRecylce(m_tempDataStore.m_Database);
				}
			}
			m_tempDataStore = null;
		} catch (Exception e) {
			e.printStackTrace();
			return -10;
		}
		return 1;
	}

	@Override
	public Object getValue(IDefinition idCurrent, FacesContext context) {
		try {
			String strTitle = idCurrent.getColumnTitle();
			if (strTitle != null && !"".equals(strTitle)) {
				if (m_tempDataStore.m_ColTitle.contains(strTitle)) {
					int nPos = m_tempDataStore.m_ColTitle.indexOf(strTitle);
					return m_tempDataStore.m_ColValues.elementAt(nPos);
				}
			} else {

				return idCurrent.executeComputeValue(context);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getViewName() {
		if (m_ViewName != null) {
			return m_ViewName;
		}
		return ValueBindingSupport.getVBString("viewName", this, getFacesContext());

	}

	public void setViewName(String viewName) {
		m_ViewName = viewName;
	}

	public String getDatabase() {
		if (m_Database != null) {
			return m_Database;
		}
		return ValueBindingSupport.getVBString("database", this, getFacesContext());

	}

	public void setDatabase(String database) {
		m_Database = database;
	}

	public String getKey() {
		if (m_Key != null) {
			return m_Key;
		}
		return ValueBindingSupport.getVBString("key", this, getFacesContext());

	}

	public void setKey(String key) {
		m_Key = key;
	}

	public String getSearch() {
		if (m_Search != null) {
			return m_Search;
		}
		return ValueBindingSupport.getVBString("search", this, getFacesContext());

	}

	public void setSearch(String search) {
		m_Search = search;
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[6];
		state[0] = super.saveState(context);
		state[1] = m_Database;
		state[2] = m_ViewName;
		state[3] = m_Key;
		state[4] = m_Search;
		state[5] = Integer.valueOf(m_maxRow);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_Database = (String) state[1];
		m_ViewName = (String) state[2];
		m_Key = (String) state[3];
		m_Search = (String) state[4];
		m_maxRow = (Integer) state[5];
	}

	@Override
	public Object getDataRow() {
		if (m_tempDataStore == null) {
			return null;
		}
		return m_tempDataStore.m_Entry;
	}

} public interface IExportSource {

	public Object getValue(IDefinition idCurrent, FacesContext context);

	public int accessNextRow();

	public int accessSource() throws POIException;

	public int closeSource();

	public Object getDataRow();
} public class ListObjectDataSource extends ValueBindingObjectImpl implements IExportSource {

	private MethodBinding m_BuildValues;

	public MethodBinding getBuildValues() {
		return m_BuildValues;
	}

	public void setBuildValues(MethodBinding buildValues) {
		m_BuildValues = buildValues;
	}

	private List<?> m_Values;
	private List<?> m_ValuesProcess;
	private Iterator<?> m_tempIt;
	private Object m_tempObj;

	public List<?> getValues() throws POIException {
		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());
		if (m_BuildValues != null) {
			logCurrent.info("Exectue BuildValues");
			Object objCurrent = m_BuildValues.invoke(getFacesContext(), null);
			logCurrent.info(objCurrent.getClass().getCanonicalName());
			if (objCurrent instanceof List<?>) {
				return (List<?>) objCurrent;
			} else {
				throw new POIException("buildValues must return a java.util.List Object");
			}
		}
		if (m_Values != null) {
			return m_Values;
		}
		ValueBinding vb = getValueBinding("values");
		if (vb != null) {
			return (List<?>) vb.getValue(getFacesContext());
		}
		return null;
	}

	public void setValues(List<?> values) {
		m_Values = values;
	}

	@Override
	public Object getValue(IDefinition idCurrent, FacesContext context) {

		Logger logCurrent = LoggerFactory.getLogger(this.getClass().getCanonicalName());
		String strCT = idCurrent.getColumnTitle();

		if (strCT != null && !"".equals(strCT)) {
			try {
				Method mt = m_tempObj.getClass().getMethod("get" + idCurrent.getColumnTitle());
				logCurrent.info("ColumnTitle = " + idCurrent.getColumnTitle());
				logCurrent.info("MT =" + mt);
				Object objRC = mt.invoke(m_tempObj);
				logCurrent.info("Result =" + objRC);
				return objRC;
			} catch (Exception e) {
				logCurrent.log(Level.SEVERE, "Error on getValue()", e);
			}
		} else {
			try {
				return idCurrent.executeComputeValue(context);
			} catch (Exception e) {
				logCurrent.log(Level.SEVERE, "Error on getValue()", e);
			}
		}
		return null;
	}

	@Override
	public int accessNextRow() {
		int nResult = m_tempIt.hasNext() ? 1 : 0;
		if (nResult == 1) {
			m_tempObj = m_tempIt.next();
		}
		return nResult;
	}

	@Override
	public int accessSource() throws POIException {
		m_ValuesProcess = getValues();
		if (m_ValuesProcess != null) {
			m_tempIt = m_ValuesProcess.iterator();
		}
		return m_ValuesProcess != null ? 1 : 0;
	}

	@Override
	public int closeSource() {
		m_tempIt = null;
		m_tempObj = null;
		return 1;
	}

	@Override
	public Object saveState(FacesContext context) {
		Object[] state = new Object[3];
		state[0] = super.saveState(context);
		state[1] = StateHolderUtil.saveList(context, m_Values);
		state[2] = StateHolderUtil.saveMethodBinding(context, m_BuildValues);
		return state;
	}

	@Override
	public void restoreState(FacesContext context, Object arg1) {
		Object[] state = (Object[]) arg1;
		super.restoreState(context, state[0]);
		m_Values = StateHolderUtil.restoreList(context, getComponent(), state[1]);
		m_BuildValues = StateHolderUtil.restoreMethodBinding(context, getComponent(), state[2]);
	}

	@Override
	public Object getDataRow() {
		return m_tempObj;
	}

} @SuppressWarnings("deprecation")
public class POILibUtil {

	private static Boolean _9;
	public static final boolean isXPages9() {
		if (_9 == null) {
			Version v = Version.CurrentRuntimeVersion;
			_9 = (v.getMajor() == 9);
		}
		return _9;
	}



	public static String getPOILibUtilVersion() {
		try {
			String s = AccessController
					.doPrivileged((PrivilegedAction<String>) () -> {
						Object o = Activator.getContext().getBundle()
								.getHeaders().get("Bundle-Version"); // $NON-NLS-1$
						if (o != null) {
							return o.toString();
						}
						return null;
					});
			if (s != null) {
				return s;
			}
		} catch (SecurityException ex) {
		}
		return "";
	}

	public static Database getCurrentDatabase() {
		NotesContext nc = NotesContext.getCurrentUnchecked();
		return nc != null ? nc.getCurrentDatabase() : null;
	}

	public static Session getCurrentSession() {
		NotesContext nc = NotesContext.getCurrentUnchecked();
		return nc != null ? nc.getCurrentSession() : null;
	}

	/**
	 * Return the signer session.
	 */
	public static Session getCurrentSessionAsSigner() {
		NotesContext nc = NotesContext.getCurrentUnchecked();
		return nc != null ? nc.getSessionAsSigner() : null;
	}

	public static XWPFDocument getDocument(InputStream inDocument) {
		XWPFDocument dxReturn = null;
		try {
			dxReturn = new XWPFDocument(inDocument);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dxReturn;
	}

	public static Workbook getWorkbook(InputStream inExcel) {
		Workbook wbRC = null;
		try {
			wbRC = WorkbookFactory.create(inExcel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return wbRC;
	}
} public class DocX2HTMLAction extends AbstractPOIPowerActionExtended<OutputStream, InputStream> {

	@Override
	protected OutputStream doItPriv(InputStream inputObj, OutputStream outputStream, HashMap<String, String> hsCurrent) throws Exception {
		XWPFDocument document = new XWPFDocument(inputObj); // createDocument(is);

		XHTMLOptions options = XHTMLOptions.create(); // createOptions();

		OutputStream out = new ByteArrayOutputStream();// new
		if (outputStream != null) {
			out = outputStream;
		}

		XHTMLConverter.getInstance().convert(document, out, options);

		out.flush();
		return out;
	}

} public class DocX2PDFAction extends AbstractPOIPowerActionExtended<OutputStream, InputStream> {

	@Override
	protected OutputStream doItPriv(InputStream inputObj, OutputStream outputStream, HashMap<String, String> hsCurrent) throws Exception {
		IPDFService service = PDFConversionService.getInstance().getPDFService();
		OutputStream out = new ByteArrayOutputStream();
		if (outputStream != null) {
			out = outputStream;
		}
		service.buildPDF(inputObj, out);
		return out;
	}

}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import biz.webgate.dominoext.poi.component.data.AbstractTemplateSource;
import biz.webgate.dominoext.poi.component.data.AttachmentTemplateSource;
import biz.webgate.dominoext.poi.component.data.ITemplateSource;
import biz.webgate.dominoext.poi.component.data.ResourceTemplateSource;
import biz.webgate.dominoext.poi.component.data.document.DocumentBookmark;
import biz.webgate.dominoext.poi.component.data.document.IDocumentBookmark;
import biz.webgate.dominoext.poi.component.data.document.table.DocumentTable;
import biz.webgate.dominoext.poi.component.data.ss.Data2ColumnExporter;
import biz.webgate.dominoext.poi.component.data.ss.Data2RowExporter;
import biz.webgate.dominoext.poi.component.data.ss.IListDataExporter;
import biz.webgate.dominoext.poi.component.data.ss.Spreadsheet;
import biz.webgate.dominoext.poi.component.data.ss.cell.CellBookmark;
import biz.webgate.dominoext.poi.component.data.ss.cell.CellValue;
import biz.webgate.dominoext.poi.component.data.ss.cell.ColumnDefinition;
import biz.webgate.dominoext.poi.component.data.ss.cell.ICellValue;
import biz.webgate.dominoext.poi.component.data.ss.cell.RowDefinition;
import biz.webgate.dominoext.poi.component.kernel.DocumentProcessor;
import biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor;
import biz.webgate.dominoext.poi.component.sources.DominoView;
import biz.webgate.dominoext.poi.component.sources.IExportSource;
import biz.webgate.dominoext.poi.component.sources.ListObjectDataSource;
import biz.webgate.dominoext.poi.util.POILibUtil;
import biz.webgate.dominoext.poi.util.action.DocX2HTMLAction;
import biz.webgate.dominoext.poi.util.action.DocX2PDFAction;
		final XWPFDocument doc = processDocument(itsCurrent, bookmarks, tables);
		if (doc == null) {
			throw new NullPointerException("The result of processDocument is null");
		}
		return AccessController.doPrivileged((PrivilegedAction<ByteArrayOutputStream>) () -> {
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				doc.write(bos);
				return bos;
			} catch (Exception e) {
				throw new FacesException("poiBean:processDocument2Stream", e);
			}
		});
	}

	public IDocumentBookmark buildDocumentBookmark(String strName, String strValue) {
		DocumentBookmark bmRC = new DocumentBookmark();
		bmRC.setName(strName);
		bmRC.setValue(strValue);
		return bmRC;
	}

	public AbstractTemplateSource buildAttachmentTemplateSource(String strDB, String strView, String strKey, String strField) {
		AttachmentTemplateSource attRC = new AttachmentTemplateSource();
		attRC.setDatabaseName(strDB);
		attRC.setViewName(strView);
		attRC.setKeyName(strKey);
		attRC.setFieldName(strField);
		return attRC;
	}

	public ResourceTemplateSource buildResourceTemplateSource(String strDB, String strFileName) {
		ResourceTemplateSource rtsRC = new ResourceTemplateSource();
		rtsRC.setDatabaseName(strDB);
		rtsRC.setFileName(strFileName);
		return rtsRC;
	}

	public Workbook processWorkbook(ITemplateSource itsCurrent, List<Spreadsheet> lstSP) {
		if (itsCurrent.accessTemplate() == 1) {
			final ITemplateSource itsCurrentFIN = itsCurrent;
			final List<Spreadsheet> lstSPFIN = lstSP;
			return AccessController.doPrivileged((PrivilegedAction<Workbook>) () -> {
				try {
					return WorkbookProcessor.INSTANCE.processWorkbook(itsCurrentFIN, lstSPFIN, FacesContext.getCurrentInstance(), null);
				} catch (Exception e) {
					throw new FacesException("poiBean:processWorkbook", e);
				}
			});
		}
		return null;
	}

	@Deprecated
	public ByteArrayOutputStream processWorkbook2Stream(ITemplateSource itsCurrent, List<Spreadsheet> lstSP, FacesContext context) {
		return processWorkbook2Stream(itsCurrent, lstSP);
	}

	public ByteArrayOutputStream processWorkbook2Stream(ITemplateSource itsCurrent, List<Spreadsheet> lstSP) {
		final Workbook wb = processWorkbook(itsCurrent, lstSP);
		if (wb == null) {
			throw new NullPointerException("the result of processWorkbook is null");
		}
		return AccessController.doPrivileged((PrivilegedAction<ByteArrayOutputStream>) () -> {
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				wb.write(bos);
				return bos;
			} catch (Exception e) {
				throw new FacesException("poiBean:processWorkbook2Stream", e);
			}
		});
	}

	public CellBookmark buildCellBookmark(String strName, Object strValue) {
		CellBookmark cbRC = new CellBookmark();
		cbRC.setName(strName);
		cbRC.setValue(strValue);
		return cbRC;
	}

	public CellValue buildCellValue(int nCol, int nRow, Object objValue) {
		CellValue cbRC = new CellValue();
		cbRC.setColumnNumber(nCol);
		cbRC.setRowNumber(nRow);
		cbRC.setValue(objValue);
		return cbRC;
	}

	public DominoView buildDominoViewSource(String strDB, String strView, String strKey, String strSearch) {
		DominoView dvRC = new DominoView();
		dvRC.setDatabase(strDB);
		dvRC.setViewName(strView);
		dvRC.setKey(strKey);
		dvRC.setSearch(strSearch);
		return dvRC;
	}

	public ListObjectDataSource buildListObjectDataSource(List<?> lstValues) {
		ListObjectDataSource lodsRC = new ListObjectDataSource();
		lodsRC.setValues(lstValues);
		return lodsRC;
	}

	public ColumnDefinition buildColumnDefinition(int nCol, int nShift, String strColumnTitle) {
		ColumnDefinition cdRC = new ColumnDefinition();
		cdRC.setColumnNumber(nCol);
		cdRC.setRowShift(nShift);
		cdRC.setColumnTitle(strColumnTitle);
		return cdRC;
	}

	public RowDefinition buildRowDefinition(int nRow, int nShift, String strColumnTitle) {
		RowDefinition cdRC = new RowDefinition();
		cdRC.setRowNumber(nRow);
		cdRC.setColumnShift(nShift);
		cdRC.setColumnTitle(strColumnTitle);
		return cdRC;
	}

	public Data2ColumnExporter buildData2ColumnExporter(IExportSource dataSource, String dataSourceVar, List<RowDefinition> rows, int startColumn, int stepSize) {