package com.setralubs;
import com.ibm.xsp.webapp.XspHttpServletResponse;
import com.poiji.annotation.ExcelCellName;
import com.poiji.bind.Poiji;
import com.poiji.exception.PoijiExcelType;
import com.poiji.option.PoijiOptions;
import com.poiji.option.PoijiOptions.PoijiOptionsBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.*;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.openntf.domino.*;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.xsp.XspOpenLogUtil;
public class BatchChecker {
private final String classID="::"
+ new Throwable().getStackTrace()[0].getClassName() + "::";
@ExcelCellName("Material")
String fusion;
@ExcelCellName("Material Description")
String prodName_Pack;
@ExcelCellName("Batch")
String batch;
@ExcelCellName("Production date (PRK)")
String prodDateSAP;
@ExcelCellName("Prod.date (Molcom)")
String prodDateWH;
private Session ses;
private Database db;
private View view;
private PrintWriter opw;
private OutputStream os;
private ZipOutputStream append;
public BatchChecker() {
ses = Factory.getSession();
db = ses.getCurrentDatabase();
view = db.getView("batches");
}
public <T> List<T> checking(InputStream inStream, Class<T> type){
List<T> ret=new ArrayList<T>();
Throwable throwable = new Throwable();
try{
XspOpenLogUtil.logEvent(throwable, this.classID + "<-"
+ throwable.getStackTrace()[1].getClassName() + "."
+ throwable.getStackTrace()[1].getMethodName()
+": Loading", Level.INFO,
null);
List<BatchChecker> list=Poiji.fromExcel(inStream, PoijiExcelType.XLSX, BatchChecker.class);
//new File("wh-report.xlsx"), BatchChecker.class);
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()
+": Loading has completed", Level.INFO,
null);
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()
+": Searching...", Level.INFO,
null);
for(BatchChecker el:list){
ViewEntry entry=view.getFirstEntryByKey(el.batch,true);
if (entry!=null)
ret.add(type.cast(el.batch));
}
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()
+": Searching has completed", Level.INFO,
null);
}catch(Exception e){
e.printStackTrace();
XspOpenLogUtil.logError(e);
}
return (List<T>)ret;
}
public void checking(InputStream is, PrintWriter os, boolean exists){
Throwable throwable = new Throwable();
if (os !=null){
this.opw=os;
//PoijiOptions options = PoijiOptionsBuilder.settings().sheetIndex(0).build();
if (exists){
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()
+": Creating list for existing batches...", Level.INFO,
null);
Poiji.fromExcel(is, PoijiExcelType.XLSX, BatchChecker.class, this::dbCheck);//, options, this::dbCheck);
}
else{
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()
+": Creating list for absent batches...", Level.INFO,
null);
Poiji.fromExcel(is, PoijiExcelType.XLSX, BatchChecker.class, this::dbCheckNo);//, options, this::dbCheckNo);
}
}else{
XspOpenLogUtil.logErrorEx(throwable, this.classID + "PrintWriter is null"
, Level.INFO, null);
}
}
/**
* process input and write result as zip to output
*/
public int checking2ZIP(){
Throwable throwable = new Throwable();
int status=HttpURLConnection.HTTP_INTERNAL_ERROR;
InputStream is=null;
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ex = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ex.getRequest();
try {
is=request.getInputStream();
status=HttpURLConnection.HTTP_NOT_FOUND;
if( is!=null
&& request.getContentType()!=null
&& request.getContentType().contains(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
)
{
XspHttpServletResponse xspResponse = (XspHttpServletResponse) ex.getResponse();
javax.servlet.http.HttpServletResponse response=xspResponse.getDelegate();
String type=MIMEType.get("zip");
response.setHeader("Content-Type",type);
response.setHeader("Content-Disposition","attachment; filename=allFiles.zip");
this.os =response.getOutputStream();
append = new ZipOutputStream(os);
//PoijiOptions options = PoijiOptionsBuilder.settings().sheetIndex(0).build();
Poiji.fromExcel(is, PoijiExcelType.XLSX, BatchChecker.class, this::add2Zip);//, options, this::dbCheck);
append.finish();
status=HttpURLConnection.HTTP_OK;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
XspOpenLogUtil.logError(e);
}
return status;
}
private void add2Zip(BatchChecker instance){
try{
ViewEntry entry=view.getFirstEntryByKey(instance.batch,true);
InputStream is=null;String fName=null;
if (entry!=null){
EmbeddedObject eo=entry.getDocument().getAttachments().get(0);
if (eo!=null){
is=eo.getInputStream();
fName=eo.getName();
}
}
if (is!=null) {
ZipEntry e=new ZipEntry(fName);
append.putNextEntry(e);
long bc=IOUtils.copy(is, append);
//e.setMethod(ZipEntry.STORED);
//e.setCompressedSize(bc);
//e.setSize(bc);
//append.closeEntry();
//is.close();
}
} catch (IOException e1) {
e1.printStackTrace();
//LOG.error("IO error",e1);
}
}
private void dbCheck(BatchChecker instance){
Throwable throwable = new Throwable();
//System.out.println("check batch: "+instance.batch);
if (view.getFirstEntryByKey(instance.batch,true)!=null){
opw.write("="+instance.batch+";");
}else{
opw.write(instance.batch+";");
}
}
private void dbCheckNo(BatchChecker instance){
if (view.getFirstEntryByKey(instance.batch,true)==null){
opw.write(instance.batch+";");
}
}
ViewEntry getBatchEntry(String batch){
return view.getFirstEntryByKey(batch,true);
}
static File createExcel(List<BatchChecker> list, String urlBase) throws IOException {
File ret=File.createTempFile("out", ".xlsx");
OutputStream os=new FileOutputStream(ret);
Workbook wb= new XSSFWorkbook();
Sheet sh=wb.createSheet("Batches");
int i=0;
for(BatchChecker el:list) {
Row row=sh.createRow(i++);
setCells(el, urlBase, row);
}
wb.write(os);
wb.close();
return ret;
}
private static void setCells(BatchChecker el, String urlBase, Row row){
short cellIdx=0;
Cell cell = row.createCell(cellIdx++);
if (urlBase==null) {
cell.setCellValue(el.batch);
cell = row.createCell(cellIdx);
cell.setCellValue(el.prodName_Pack);
}else {
cell.setCellValue(el.batch + ":" + el.prodName_Pack);
Workbook wb = row.getSheet().getWorkbook();
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(HSSFColor.HSSFColorPredefined.DARK_BLUE.getIndex());
hlink_style.setFont(hlink_font);
CreationHelper creationHelper = wb.getCreationHelper();
Hyperlink link = creationHelper.createHyperlink(HyperlinkType.URL);
String url = urlBase + el.batch;
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
}
}
public int getBatch(String id){//, javax.servlet.http.HttpServletResponse response){
int status=HttpURLConnection.HTTP_INTERNAL_ERROR;
Throwable throwable = new Throwable();
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ex = fc.getExternalContext();
XspHttpServletResponse xspResponse = (XspHttpServletResponse) ex.getResponse();
javax.servlet.http.HttpServletResponse response=xspResponse.getDelegate();
if (id!=null && !id.isEmpty()){
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()+"(): "
+"get first entry for: "+id, Level.INFO,
null);
ViewEntry entry=getBatchEntry(id);
//Document doc=db.getDocumentByUNID(id);
if (entry!=null){
List<org.openntf.domino.EmbeddedObject> atts=entry.getDocument().getAttachments();
String fName=atts.get(0).getName();
String type=MIMEType.get(fName.substring(fName.lastIndexOf(".")+1));
//response.setContentType(type);
response.setHeader("Content-Type",type);
response.setHeader("Content-Disposition","attachment; filename="+fName);
/* XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()+"(): "
+"mime type: "+type+"\n"
+"attach name: "+atts.get(0).getName(), Level.INFO,
null);
*/
//File tmp=obj.createExcel(obj.testCheckingBC(), "");
try {
IOUtils.copy(atts.get(0).getInputStream(),response.getOutputStream());
status=HttpURLConnection.HTTP_OK;
} catch (IOException e) {
// TODO Auto-generated catch block
XspOpenLogUtil.logError(e);
}
}else{
String statusTxt="entry hasn't been found ";
XspOpenLogUtil.logEvent(throwable, this.classID
+ throwable.getStackTrace()[1].getMethodName()+"(): "
+statusTxt, Level.INFO,
null);
status=HttpURLConnection.HTTP_NOT_FOUND;
String type= "application/json; charset=UTF-8";
response.setHeader("Content-Type",type);
try {
xspResponse.getWriter().write("{\"error\":\""+statusTxt+"\"}");
} catch (IOException e) {
// TODO Auto-generated catch block
XspOpenLogUtil.logError(e);
}
}
}else{
status=checking2ZIP();
}
return status;
}
public List<String> testChecking(){
BatchChecker obj=new BatchChecker();
return obj.checking(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("wh-report.xlsx"),String.class);
}
public List<BatchChecker> testCheckingBC(){
BatchChecker obj=new BatchChecker();
return obj.checking(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("wh-report.xlsx"),BatchChecker.class);
}
public void testCheckingOut(PrintWriter os){
BatchChecker obj=new BatchChecker();
obj.checking(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("wh-report.xlsx"),os, true);
}
public static void main(String args[]){
BatchChecker obj=new BatchChecker();
obj.checking(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("wh-report.xlsx"),String.class);
}
}