You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1961 lines
93 KiB
1961 lines
93 KiB
package de.superx.servlet; |
|
|
|
import java.io.BufferedInputStream; |
|
import java.io.BufferedOutputStream; |
|
import java.io.BufferedWriter; |
|
import java.io.ByteArrayOutputStream; |
|
import java.io.File; |
|
import java.io.FileInputStream; |
|
import java.io.FileNotFoundException; |
|
import java.io.FileOutputStream; |
|
import java.io.FileWriter; |
|
import java.io.IOException; |
|
import java.io.InputStream; |
|
import java.io.OutputStream; |
|
import java.io.PrintWriter; |
|
import java.io.StringReader; |
|
import java.lang.reflect.Constructor; |
|
import java.lang.reflect.InvocationTargetException; |
|
import java.nio.file.Files; |
|
import java.nio.file.Path; |
|
import java.nio.file.attribute.FileAttribute; |
|
import java.sql.Connection; |
|
import java.sql.ResultSet; |
|
import java.sql.ResultSetMetaData; |
|
import java.sql.SQLException; |
|
import java.sql.Statement; |
|
import java.sql.Types; |
|
import java.text.ParseException; |
|
import java.util.HashMap; |
|
import java.util.Hashtable; |
|
import java.util.Iterator; |
|
import java.util.LinkedList; |
|
import java.util.List; |
|
import java.util.Locale; |
|
import java.util.Map; |
|
import java.util.StringTokenizer; |
|
import java.util.logging.Level; |
|
import java.util.logging.Logger; |
|
import java.util.regex.Matcher; |
|
import java.util.regex.Pattern; |
|
import java.util.zip.GZIPOutputStream; |
|
import java.util.zip.ZipEntry; |
|
import java.util.zip.ZipOutputStream; |
|
|
|
import javax.servlet.ServletConfig; |
|
import javax.servlet.ServletContext; |
|
import javax.servlet.ServletException; |
|
import javax.servlet.ServletOutputStream; |
|
import javax.servlet.http.HttpServletRequest; |
|
import javax.servlet.http.HttpServletResponse; |
|
import javax.sql.DataSource; |
|
import javax.xml.parsers.FactoryConfigurationError; |
|
import javax.xml.parsers.ParserConfigurationException; |
|
import javax.xml.transform.Transformer; |
|
import javax.xml.transform.TransformerConfigurationException; |
|
import javax.xml.transform.TransformerException; |
|
import javax.xml.transform.TransformerFactory; |
|
|
|
import org.apache.commons.fileupload.DiskFileUpload; |
|
import org.apache.commons.fileupload.FileItem; |
|
import org.apache.commons.fileupload.FileUpload; |
|
import org.apache.commons.fileupload.FileUploadException; |
|
import org.apache.poi.hssf.usermodel.HSSFCell; |
|
import org.apache.poi.hssf.usermodel.HSSFCellStyle; |
|
import org.apache.poi.hssf.util.HSSFColor; |
|
import org.apache.poi.ss.usermodel.BorderStyle; |
|
import org.apache.poi.ss.usermodel.Cell; |
|
import org.apache.poi.ss.usermodel.CellStyle; |
|
import org.apache.poi.ss.usermodel.CreationHelper; |
|
import org.apache.poi.ss.usermodel.Font; |
|
import org.apache.poi.ss.usermodel.Row; |
|
import org.apache.poi.ss.usermodel.Sheet; |
|
import org.apache.poi.xssf.streaming.SXSSFSheet; |
|
import org.apache.poi.xssf.streaming.SXSSFWorkbook; |
|
import org.dom4j.DocumentException; |
|
import org.springframework.context.ApplicationContext; |
|
import org.springframework.jdbc.core.JdbcTemplate; |
|
import org.springframework.web.context.support.WebApplicationContextUtils; |
|
import org.xml.sax.SAXException; |
|
|
|
import com.google.common.io.ByteStreams; |
|
|
|
import de.destatis.core.inspector.InspectionProblem; |
|
import de.destatis.core.inspector.InspectionReport; |
|
import de.destatis.core.inspector.ProblemPosition; |
|
import de.memtext.db.NichtAngemeldetException; |
|
import de.memtext.tree.KeyParentEqualException; |
|
import de.memtext.tree.NoMainEntryException; |
|
import de.memtext.util.CryptUtils; |
|
import de.memtext.util.EqualsUtil; |
|
import de.memtext.util.FileUtils; |
|
import de.memtext.util.ServletHelper; |
|
import de.memtext.util.StringUtils; |
|
import de.memtext.util.TimeUtils; |
|
import de.superx.bin.KettleExecutor; |
|
import de.superx.common.ChartCreator; |
|
import de.superx.common.DBServletException; |
|
import de.superx.common.GraphicFormat; |
|
import de.superx.common.InvalidDataTypeException; |
|
import de.superx.common.InvalidKeyException; |
|
import de.superx.common.Maske; |
|
import de.superx.common.ObligatoryFieldEmptyException; |
|
import de.superx.common.SichtException; |
|
import de.superx.common.Stylesheet; |
|
import de.superx.common.SxUser; |
|
import de.superx.common.TransletCache; |
|
import de.superx.common.UngueltigeEingabeException; |
|
import de.superx.stat.StatisticExport; |
|
import de.superx.stat.StatisticExport.ExportFormat; |
|
import de.superx.stat.StatisticsBase.DistributionType; |
|
import de.superx.util.SqlStringUtils; |
|
import freemarker.template.TemplateException; |
|
import net.sf.jasperreports.engine.JRException; |
|
|
|
/* |
|
* Servlet, das eine ErgebnisTabelle anzeigt |
|
* |
|
*/ |
|
public class SuperXmlTabelle extends AbstractSuperXServlet { |
|
|
|
private static final String PARAM_IS_SENT_SUFFIX = "-isSent"; |
|
|
|
private static final String PARAM_TRUE = "true"; |
|
|
|
private static final String PARAM_XML_ = "/xml"; |
|
|
|
private static final String PARAM_CLASS = "class"; |
|
|
|
private static final long serialVersionUID = 1L; |
|
|
|
TimeUtils tutil = new TimeUtils(); |
|
|
|
// public static int maxRows = 100; |
|
|
|
public static int maxOffset = 30; |
|
|
|
private static final int MAX_MACRO = 20; |
|
|
|
// private currentLocale = null; |
|
|
|
private static int cacheSecs = 300;// wie lange Ergebnis im Cache aktiv |
|
|
|
private final String STYLESHEET_XML = "tabelle_xml.xsl"; |
|
|
|
private final String STYLESHEET_PDF = "tabelle_pdf.xsl"; |
|
|
|
private final String STYLESHEET_RTF = "tabelle_rtf.xsl"; |
|
|
|
private final String STYLESHEET_TXT = "tabelle_text.xsl"; |
|
|
|
protected TransformerFactory tFactory; |
|
|
|
@Override |
|
public void init(ServletConfig config) throws ServletException { |
|
super.init(config); |
|
//tomcat8 verlangt einen virtual Path separator / vor xml |
|
//vergl. http://stackoverflow.com/questions/25555541/getservletcontext-getrealpath-in-tomcat-8-returns-wrong-path |
|
|
|
ChartCreator.initPath(getServletConfig().getServletContext().getRealPath("/xml")); |
|
this.tFactory = TransformerFactory.newInstance(); |
|
String mxr = config.getInitParameter("maxRows"); |
|
/* |
|
* if (mxr == null || mxr.equals("")) maxRows = 3000; else maxRows = |
|
* (Integer.parseInt(mxr)); |
|
*/ |
|
mxr = config.getInitParameter("maxOffset"); |
|
if (mxr == null || mxr.equals("")) { |
|
maxOffset = 30; |
|
} else { |
|
maxOffset = (Integer.parseInt(mxr)); |
|
} |
|
|
|
} |
|
|
|
/** |
|
* Es werden Ergebnisse berechnet und zurückgeliefert. Falls im Request |
|
* username und passwort rüberkommen, wird zuerst der User initialisiert. |
|
* Falls ein Parameter auf -aktualisieren endet wird die Sicht aktualisiert |
|
* |
|
*/ |
|
|
|
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
|
setEncoding(request); |
|
|
|
/* |
|
* Enumeration en=request.getParameterNames(); |
|
* |
|
* while (en.hasMoreElements()) { String p=(String) en.nextElement(); |
|
* System.out.println(p+":"+request.getParameter(p)); } |
|
*/ |
|
if (request.getParameter("checkFor") != null) { |
|
checkFor(request, response); |
|
|
|
} else { |
|
if (!hasProperSession(request)) { |
|
infoNeuAnmelden(response); |
|
} else { |
|
// String ie = SqlStringUtils.getEncoding(); |
|
// System.out.println(DateUtils.getNowString() + " " + ie); |
|
// request.setCharacterEncoding(ie); |
|
checkCacheClearing(request); |
|
boolean sessionCreated = checkAnmeldungImRequest(request); |
|
List<FileItem> multipartData = new LinkedList<FileItem>(); |
|
if (FileUpload.isMultipartContent(request)) multipartData = getMultipartContent(request); |
|
|
|
if (SichtChanger.isSichtChangeWanted(request)) { |
|
SichtChanger sichtChanger = new SichtChanger(request, response, true); |
|
sichtChanger.run(true); |
|
} else { |
|
if (ServletBasics.getParameter(request, "getKidRows") != null) { |
|
KidRowsResponder kr = new KidRowsResponder(request, response); |
|
kr.run(true); |
|
} else if (ServletBasics.getParameter(request, "getchart") != null) { |
|
getChartResponse(request, response); |
|
} else if (ServletBasics.getParameter(request, "getDynChart") != null) { |
|
getDynamicChartResponse(request, response); |
|
} else if (isKettleJobMaske(multipartData)) { |
|
KettleHelper kh = new KettleHelper(multipartData, request, response); |
|
kh.run(true); |
|
} else if (FileUpload.isMultipartContent(request) || EqualsUtil.areEqual(ServletBasics.getParameter(request, "csvupload"), "true")) { |
|
CSVUploadHelper cup = new CSVUploadHelper(request, response, multipartData); |
|
cup.run(true); |
|
} else { |
|
// Für Portlets ist synchronized wichtig, damit bei genau gleichzeitigem Aufruf alles läuft |
|
//bei normalen Abfragen hat fiesen Nebeneffekt, dass Ergebnis einer Maske erst angezeigt wird, wenn bereits laufende Maske fertig ist |
|
//synchronized (this) { |
|
TableCreator tc = new TableCreator(request, response); |
|
tc.run(true); |
|
//} |
|
} |
|
} |
|
} |
|
} |
|
} |
|
|
|
private List<FileItem> getMultipartContent(HttpServletRequest request) throws IOException { |
|
List<FileItem> result = null; |
|
try { |
|
DiskFileUpload fu = new DiskFileUpload(); |
|
result = fu.parseRequest(request); |
|
} catch (FileUploadException e) { |
|
throw new IOException(e); |
|
} |
|
return result; |
|
} |
|
|
|
private boolean isKettleJobMaske(List<FileItem> multipartData) { |
|
boolean result = false; |
|
Iterator iter = multipartData.iterator(); |
|
while (iter.hasNext()) { |
|
FileItem item = (FileItem) iter.next(); |
|
if (item.isFormField()) { |
|
String fieldName = item.getFieldName(); |
|
if (fieldName != null && ((fieldName.equals("tid") && item.getString().equals("71540")) || fieldName.equals("dokettlejob"))) { |
|
result = true; |
|
break; |
|
} |
|
} |
|
} |
|
return result; |
|
} |
|
|
|
private void getChartResponse(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { |
|
ChartResponder cr = new ChartResponder(request, response); |
|
cr.run(true); |
|
|
|
} |
|
|
|
/* |
|
* Moeglichkeit dynamische Chartklasse zu übergeben |
|
*/ |
|
private void getDynamicChartResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException { |
|
String classname = ServletHelper.getParameter(request, "class"); |
|
if (classname == null || classname.equals("")) { |
|
throw new IllegalArgumentException("Parameter class missing"); |
|
} |
|
try { |
|
Object[] constr = new Object[2]; |
|
constr[0] = request; |
|
constr[1] = response; |
|
; |
|
Class grafclass = Class.forName(classname); |
|
Class[] classparams = { HttpServletRequest.class, HttpServletResponse.class }; |
|
Constructor con = grafclass.getConstructor(classparams); |
|
SuperXServletHelper graphHelper = (SuperXServletHelper) con.newInstance(constr); |
|
graphHelper.run(true); |
|
} catch (Exception e) { |
|
e.printStackTrace(); |
|
throw new ServletException("Problem bei Grafikerzeugung :\n" + e); |
|
} |
|
} |
|
|
|
@Override |
|
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
|
Integer tid = Integer.valueOf(getTid(request)); |
|
if (SuperXManager.httpGetAccessGuard.isHttpGetAllowed(tid)) { |
|
if (request.getParameter(RequestParameter.bigexcel.toString()) != null && request.getParameter(RequestParameter.bigexcel.toString()).equals(PARAM_TRUE)) { |
|
BigExcelCreator b = new BigExcelCreator(request, response); |
|
|
|
b.run(true); |
|
} else if (request.getParameter(RequestParameter.checkFor.toString()) != null) { |
|
checkFor(request, response); |
|
} else { |
|
doPost(request, response); |
|
} |
|
} else if (ServletBasics.getParameter(request, RequestParameter.getKidRows) != null) { |
|
// dieser Ausführungszweig sorgt dafür, dass XHR-Requests für die Aufklappfunktion in hierarchischen/drilldown |
|
// Berichten auch dann noch funktioniert, wenn der betroffene Bericht generell für HTTP GET |
|
// gesperrt/-blacklisted ist |
|
KidRowsResponder kr = new KidRowsResponder(request, response); |
|
kr.run(true); |
|
} else { |
|
// es dürfen nicht alle Masken über HTTP GET genutzt werden - siehe HISzilla Anfrage #283628 |
|
System.out.println("GET-Aufruf von Maske " + tid.toString() + " wurde aufgrund von black-/whitelisting-policy abgewiesen"); |
|
response.setStatus(java.net.HttpURLConnection.HTTP_FORBIDDEN); |
|
} |
|
} |
|
|
|
|
|
/** |
|
* Prüft ob für Maske schon etwas zurückgeschickt wurde, Rückmeldung, wenn |
|
* ja, oder nach 5 Minuten |
|
* |
|
* @param request |
|
* @param response |
|
* @throws IOException |
|
*/ |
|
private void checkFor(HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
// checkFor isSent |
|
String tidString = getTid(request); |
|
|
|
int i = 0; |
|
String isSent = (String) request.getSession().getAttribute(tidString + "-isSent"); |
|
|
|
while (!EqualsUtil.areEqual(isSent, "true") && i < 10) { |
|
isSent = (String) request.getSession().getAttribute(tidString + "-isSent"); |
|
try { |
|
Thread.sleep(1000); |
|
} catch (InterruptedException e) { |
|
|
|
} |
|
i++; |
|
} |
|
response.getWriter().write("done"); |
|
} |
|
|
|
/** |
|
* Returns servlet information |
|
*/ |
|
@Override |
|
public String getServletInfo() { |
|
return "SuperXTabelle 4.2"; |
|
} |
|
|
|
private class BigExcelCreator extends SuperXServletHelper { |
|
private HashMap styles = new HashMap(); |
|
|
|
private SxUser user; |
|
|
|
BigExcelCreator(HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
super(request, response); |
|
|
|
} |
|
|
|
protected void perform() throws SQLException, DBServletException, TransformerException, KeyParentEqualException, NichtAngemeldetException, IOException, ParseException, |
|
ParserConfigurationException, FactoryConfigurationError, SAXException, DocumentException, IllegalArgumentException, SecurityException, |
|
InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException, TemplateException, |
|
InvalidKeyException, SichtException, IOException, ServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { |
|
checkUserAndMaskAuthentification(); |
|
String tidString = getTid(request); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
|
|
Maske maske = mc.getMaske(tidString); |
|
if (maske == null) throw new ServletException("Maske " + tidString + " nicht in maskencontainer gefunden"); |
|
|
|
Connection con = SxPools.get(getMandantenID()).getConnection(); |
|
SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in |
|
// memory, exceeding |
|
// rows will be flushed |
|
// to disk |
|
initStyles(wb); |
|
try { |
|
Statement stm = con.createStatement(); |
|
|
|
ResultSet rs = executeQuery(maske, stm); |
|
|
|
Sheet sh = wb.createSheet("Tabelle 1"); |
|
int rownum = 0; |
|
int colcount = rs.getMetaData().getColumnCount(); |
|
Runtime rt = Runtime.getRuntime(); |
|
de.memtext.util.TimeUtils t = new de.memtext.util.TimeUtils(); |
|
t.start(); |
|
ResultSetMetaData rsmd = rs.getMetaData(); |
|
int[] coltypes = new int[rsmd.getColumnCount() + 1]; |
|
|
|
for (int i = 0; i < rsmd.getColumnCount(); i++) { |
|
coltypes[i] = rsmd.getColumnType(i + 1); |
|
((SXSSFSheet) sh).trackColumnForAutoSizing(i); |
|
|
|
} |
|
// Title |
|
Row row = sh.createRow(rownum); |
|
row.setHeight(Short.parseShort("600")); |
|
Cell cell = row.createCell(0); |
|
cell.setCellValue(maske.getName()); |
|
cell.setCellStyle((CellStyle) styles.get("title")); |
|
rownum++; |
|
// Legende |
|
row = sh.createRow(rownum); |
|
row.setHeight(Short.parseShort("1000")); |
|
cell = row.createCell(0); |
|
cell.setCellValue(maske.getLegendText(user)); |
|
rownum++; |
|
// Leerzeile |
|
row = sh.createRow(rownum); |
|
rownum++; |
|
createHeaders(maske, sh, rownum); |
|
rownum++; |
|
while (rs.next()) { |
|
|
|
if (rownum % 50000 == 0) { |
|
|
|
long mb = (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024; |
|
// long mb=rt.freeMemory()/1024/1024; |
|
// if (mb<400) { |
|
System.gc(); |
|
// System.out.println("Speicher freiräumen"); |
|
// } |
|
// System.out.println(mb); |
|
} |
|
row = sh.createRow(rownum); |
|
for (int cellnum = 0; cellnum < colcount; cellnum++) { |
|
//((SXSSFSheet) sh).trackColumnForAutoSizing(cellnum); |
|
cell = row.createCell(cellnum); |
|
Object o = rs.getObject(cellnum + 1); |
|
if (o == null) { |
|
cell.setCellType(HSSFCell.CELL_TYPE_BLANK); |
|
} else { |
|
switch (coltypes[cellnum]) { |
|
case Types.DATE: |
|
cell.setCellStyle((CellStyle) styles.get("date")); |
|
cell.setCellValue((java.util.Date) o); |
|
break; |
|
case Types.DECIMAL: |
|
case Types.DOUBLE: |
|
case Types.FLOAT: |
|
case Types.NUMERIC: |
|
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); |
|
cell.setCellStyle((CellStyle) styles.get("double")); |
|
Double d = new Double(o.toString()); |
|
cell.setCellValue(d.doubleValue()); |
|
break; |
|
case Types.INTEGER: |
|
case Types.SMALLINT: |
|
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); |
|
cell.setCellStyle((CellStyle) styles.get("integer")); |
|
Double d2 = new Double(o.toString()); |
|
cell.setCellValue(d2.doubleValue()); |
|
break; |
|
default: |
|
cell.setCellValue(o.toString()); |
|
} |
|
} |
|
|
|
} |
|
rownum++; |
|
|
|
} |
|
for (int i = 1; i < rsmd.getColumnCount(); i++) { |
|
sh.autoSizeColumn(i); |
|
} |
|
// System.out.println(t.getSinceStart()); |
|
stm.execute(maske.getCleanup_stmt()); |
|
stm.close(); |
|
con.close(); |
|
sendResponse(maske, wb); |
|
|
|
} catch (SQLException e) { |
|
SxPools.invalidate(getMandantenID(), con); |
|
} finally { |
|
// dispose of temporary files backing this workbook on disk |
|
wb.dispose(); |
|
} |
|
|
|
} |
|
|
|
private void createHeaders(Maske maske, Sheet sh, int rownum) { |
|
Row row; |
|
Cell cell; |
|
List headers = maske.getHeaderCaptionList(getMandantenID(), true); |
|
row = sh.createRow(rownum); |
|
for (int i = 0; i < headers.size(); i++) { |
|
cell = row.createCell(i); |
|
cell.setCellValue((String) headers.get(i)); |
|
cell.setCellStyle((CellStyle) styles.get("header")); |
|
((SXSSFSheet) sh).trackColumnForAutoSizing(i); |
|
|
|
|
|
|
|
} |
|
} |
|
|
|
private void sendResponse(Maske maske, SXSSFWorkbook wb) throws IOException { |
|
/* |
|
* FileOutputStream out = new FileOutputStream( |
|
* "/home/superx/tmp/sxssf.xlsx"); wb.write(out); out.close(); |
|
*/ |
|
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); |
|
// und schließlich das Workbook selbst |
|
wb.write(outStream); |
|
response.reset(); |
|
//response.setContentType("application/vnd.ms-excel"); |
|
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); |
|
response.setHeader("Content-disposition", "attachment; filename=" + FileUtils.removeProblemChars(maske.getName()) + ".xlsx"); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
response.setContentLength(outStream.size()); |
|
ServletOutputStream sos; |
|
sos = response.getOutputStream(); |
|
outStream.writeTo(sos); |
|
sos.flush(); |
|
wb.dispose(); |
|
} |
|
|
|
private ResultSet executeQuery(Maske maske, Statement stm) throws SQLException { |
|
String cleanup = maske.getCleanup_stmt(); |
|
String query = maske.getLastsql(); |
|
if (cleanup != null && !cleanup.trim().equals("")) query = StringUtils.replace(query, maske.getCleanup_stmt(), ""); // cleanup entfernen |
|
|
|
StringTokenizer st = new StringTokenizer(query, ";"); |
|
|
|
while (st.hasMoreTokens()) { |
|
String sqlstmt = st.nextToken().trim(); |
|
if (sqlstmt.length() > 3) stm.execute(sqlstmt); |
|
} |
|
ResultSet rs = stm.getResultSet(); |
|
return rs; |
|
} |
|
|
|
private void initStyles(SXSSFWorkbook wb) { |
|
CreationHelper createHelper = wb.getCreationHelper(); |
|
|
|
CellStyle cellStyle = wb.createCellStyle(); |
|
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd.mm.yyyy")); |
|
styles.put("date", cellStyle); |
|
cellStyle = wb.createCellStyle(); |
|
cellStyle.setDataFormat(wb.createDataFormat().getFormat("0.00")); |
|
styles.put("double", cellStyle); |
|
cellStyle = wb.createCellStyle(); |
|
cellStyle.setDataFormat(wb.createDataFormat().getFormat("#")); |
|
styles.put("integer", cellStyle); |
|
|
|
Font titleFont = wb.createFont(); |
|
titleFont.setFontHeightInPoints((short) 18); |
|
titleFont.setBold(true); |
|
cellStyle = wb.createCellStyle(); |
|
|
|
cellStyle.setFont(titleFont); |
|
styles.put("title", cellStyle); |
|
|
|
cellStyle = wb.createCellStyle(); |
|
cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index); |
|
cellStyle.setBorderLeft(BorderStyle.MEDIUM); |
|
cellStyle.setBorderRight(BorderStyle.MEDIUM); |
|
cellStyle.setBorderTop(BorderStyle.MEDIUM); |
|
cellStyle.setBorderBottom(BorderStyle.MEDIUM); |
|
styles.put("header", cellStyle); |
|
|
|
} |
|
|
|
private void checkUserAndMaskAuthentification() { |
|
String tidString = getTid(request); |
|
user = (SxUser) request.getSession().getAttribute("user"); |
|
if (user == null) { |
|
throw new IllegalStateException("Kein user (SxUser-Objekt) in der Session gefunden!"); |
|
} |
|
|
|
user.checkAuthentificationForMask(tidString); |
|
} |
|
|
|
} |
|
|
|
private class KettleHelper extends SuperXServletHelper { |
|
private List<FileItem> multipartData; |
|
|
|
private SxUser sxuser; |
|
|
|
private Locale desiredLocale; |
|
|
|
private File uploadFile; |
|
|
|
private String pathstart = ""; |
|
|
|
KettleHelper(List<FileItem> multipartData, HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
super(request, response); |
|
this.multipartData = multipartData; |
|
desiredLocale = getDesiredLocale(); |
|
//pathstart=getServletConfig().getServletContext().getRealPath("/")+"WEB-INF"+File.separator; |
|
pathstart = System.getProperty("java.io.tmpdir"); |
|
if (!this.pathstart.endsWith("/") && !this.pathstart.endsWith("\\")) this.pathstart = this.pathstart + File.separator; |
|
} |
|
|
|
private void checkUserAndMaskAuthentification(String maskNumber) { |
|
sxuser = (SxUser) request.getSession().getAttribute("user"); |
|
if (sxuser == null) { |
|
throw new IllegalStateException("Kein user in der Session gefunden - bitte Browser neu starten!"); |
|
} |
|
|
|
sxuser.checkAuthentificationForMask(maskNumber); |
|
//Rechte für Job per Sachgebiet wird durch maske.executeQuery (setFieldSelections) durchgeführt |
|
} |
|
|
|
@Override |
|
protected void perform() throws SQLException, DBServletException, TransformerException, KeyParentEqualException, NichtAngemeldetException, IOException, ParseException, |
|
ParserConfigurationException, FactoryConfigurationError, SAXException, DocumentException, IllegalArgumentException, SecurityException, |
|
InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException, TemplateException, |
|
InvalidKeyException, SichtException, IOException, ServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { |
|
String maskNumber = getMaskNumber(); |
|
checkUserAndMaskAuthentification(maskNumber); |
|
uploadSourceFile(); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
Maske maske = mc.getMaske(maskNumber); |
|
maske.setMultipartData(multipartData); |
|
try { |
|
currentXml = maske.runQuery(sxuser, request, null).toString(); |
|
KettleExecutor ke = new KettleExecutor(ServletUtils.getMandantenID(request)); |
|
ke.setParams(getParams()); |
|
StringBuffer results = ke.perform(); |
|
if (uploadFile != null && uploadFile.exists()) { |
|
boolean isDeleted = uploadFile.delete(); |
|
if (isDeleted) results.append("\n Temporäre Datei " + uploadFile + " gelöscht"); |
|
} |
|
returnHtml(maske, results); |
|
|
|
} catch (ObligatoryFieldEmptyException e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.WARNING, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
output.println(de.superx.servlet.SuperXManager.htmlPageHead("Problem") + "<p class='errmsg'>" + e.getMessage() + "</p></body></html>"); |
|
} finally { |
|
if (uploadFile != null && uploadFile.exists()) uploadFile.delete(); |
|
} |
|
} |
|
|
|
private Map<String, String> getParams() { |
|
Map<String, String> jobParams = new HashMap<String, String>(); |
|
String uploadFileParam = ""; |
|
if (uploadFile != null) uploadFileParam = uploadFile.getAbsolutePath(); |
|
jobParams.put("PATH_TO_UPLOADFILE", uploadFileParam); |
|
Iterator iter = multipartData.iterator(); |
|
while (iter.hasNext()) { |
|
FileItem item = (FileItem) iter.next(); |
|
if (item.isFormField()) { |
|
String paramName = item.getFieldName(); |
|
if (isParamNeeded(paramName)) jobParams.put(paramName, item.getString()); |
|
} |
|
} |
|
return jobParams; |
|
} |
|
|
|
private boolean isParamNeeded(String param) { |
|
boolean result = true; |
|
if (param.equals("navi") || param.equals("keyfieldsused") || param.equals("tid") || param.equals("stylesheet") || param.startsWith("select_") |
|
|| param.startsWith("label_")) result = false; |
|
return result; |
|
} |
|
|
|
private String getMaskNumber() { |
|
String tid = null; |
|
Iterator iter = multipartData.iterator(); |
|
while (iter.hasNext()) { |
|
FileItem item = (FileItem) iter.next(); |
|
if (item.isFormField() && item.getFieldName().equals("tid")) { |
|
tid = item.getString(); |
|
} |
|
} |
|
return tid; |
|
} |
|
|
|
private void uploadSourceFile() throws IOException { |
|
try { |
|
Iterator iter = multipartData.iterator(); |
|
while (iter.hasNext()) { |
|
FileItem item = (FileItem) iter.next(); |
|
if (item.isFormField()) { |
|
} else { |
|
if (item.getSize() == 0) continue; |
|
uploadFile = new File(pathstart + item.getName()); |
|
if (uploadFile.exists()) uploadFile.delete(); |
|
item.write(uploadFile); |
|
} |
|
} |
|
} catch (Exception e) { |
|
throw new IOException("Hochladen nicht erfolgreich: " + e); |
|
} |
|
} |
|
|
|
|
|
|
|
private void returnHtml(Maske maske, StringBuffer results) |
|
throws DBServletException, FactoryConfigurationError, IOException, ParserConfigurationException, TransformerException { |
|
StringTokenizer st = new StringTokenizer(results.toString(), "\n"); |
|
StringBuffer logxml = new StringBuffer(); |
|
int i = 0; |
|
while (st.hasMoreTokens()) { |
|
String aline = st.nextToken(); |
|
logxml.append("<row no=\"" + i + "\" > \n" + "<col id=\"0\" typ=\"1\"> \n" + "<f_name>Log</f_name> \n" + "<wert><![CDATA[" + aline + "]]></wert> \n" |
|
+ "</col></row>"); |
|
i++; |
|
} |
|
currentXml = currentXml.replaceAll("<sqlerg.*>", "<sqlerg max=\"" + (i + 1) + "\" maxOffset= \"30\" offset=\"0\" istreetable=\"false\">"); |
|
|
|
currentXml = StringUtils.replace(currentXml, "</sqlerg>", logxml + "\n</sqlerg>\n"); |
|
currentXml.replaceAll("<msg>Insgesamt.*</msg>", "<msg>Insgesamt 1 Sätze gefunden</msg>"); |
|
SuperXManager.setLastXml(currentXml); |
|
SuperXManager.setLastXmlMandantid(request.getSession().getAttribute("MandantenID").toString()); |
|
XmlTransformer xmlTransformer = new XmlTransformer(getServletConfig(), request, response, getMandantenID(), getBrowser()); |
|
xmlTransformer.setMaske(maske); |
|
xmlTransformer.transform(maske.getName(), maske.getTmpFiles(), currentXml, desiredLocale, maske.getSelectedTableStylesheetFilename(), "text/html", |
|
ServletHelper.getParameter(request, "encrypt")); |
|
|
|
|
|
request.getSession().setAttribute(maske.getId() + "-isSent", "true"); |
|
} |
|
|
|
|
|
|
|
|
|
} |
|
|
|
private class TableCreator extends SuperXServletHelper { |
|
|
|
private final Hashtable formular = new Hashtable(); |
|
|
|
private StringBuffer msgAboutEmptyFields; |
|
|
|
private Maske maske; |
|
|
|
private Stylesheet mainStylesheet; |
|
|
|
private Locale desiredLocale; |
|
|
|
private SxUser sxuser; |
|
|
|
TableCreator(HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
super(request, response); |
|
|
|
} |
|
|
|
private void checkUserAndMaskAuthentification() { |
|
String tidString = getTid(request); |
|
sxuser = (SxUser) request.getSession().getAttribute("user"); |
|
if (sxuser == null) { |
|
throw new IllegalStateException("Kein user in der Session gefunden - bitte Browser neu starten!"); |
|
} |
|
|
|
sxuser.checkAuthentificationForMask(tidString); |
|
} |
|
|
|
/** |
|
* wird nur ausgeführt, wenn die authentifizierung in ServletHelper.run |
|
* Ok war |
|
* |
|
* @throws ParserConfigurationException |
|
* @throws FactoryConfigurationError |
|
* @throws SAXException |
|
* @throws TransformerException |
|
* @throws DocumentException |
|
* @throws SQLException |
|
* @throws NumberFormatException |
|
* @throws TemplateException |
|
* @throws IOException |
|
* @throws InvalidKeyException |
|
* @throws ParseException |
|
* @throws DBServletException |
|
* @throws KeyParentEqualException |
|
* @throws CloneNotSupportedException |
|
* @throws SichtException |
|
* @throws UngueltigeEingabeException |
|
* @throws NoMainEntryException |
|
* @throws InvalidDataTypeException |
|
* @throws ServletException |
|
*/ |
|
@Override |
|
protected void perform() throws ParserConfigurationException, FactoryConfigurationError, SAXException, TransformerException, SQLException, NumberFormatException, |
|
TemplateException, IOException, InvalidKeyException, ParseException, DBServletException, KeyParentEqualException, CloneNotSupportedException, |
|
SichtException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException, ServletException { |
|
checkUserAndMaskAuthentification(); |
|
desiredLocale = getDesiredLocale(); |
|
boolean isClassicRunNeeded = true; |
|
String tidString = getTid(request); |
|
String preparedxmlfileappendix = ServletHelper.getParameter(request, "preparedxmlfileappendix"); |
|
if (preparedxmlfileappendix != null) { |
|
String contenttype = ServletHelper.getParameter(request, "contenttype"); |
|
PreparedXmlProcessor px = new PreparedXmlProcessor(getServletConfig(), request, response, getMandantenID(), getBrowser()); |
|
String filename = sxuser.getId() + "_" + tidString + "_" + preparedxmlfileappendix + ".xml"; |
|
if (px.isFileOk(filename, ServletHelper.getParameter(request, "preparedxmlnotolderthan"))) { |
|
|
|
boolean success = px.process(filename, ServletHelper.getParameter(request, "stylesheet"), contenttype, |
|
ServletHelper.getParameter(request, "preparedxmlencrypted")); |
|
|
|
isClassicRunNeeded = !success; |
|
} |
|
} |
|
|
|
if (isClassicRunNeeded) { |
|
classicRun(); |
|
} |
|
} |
|
|
|
private void loadMask() throws CloneNotSupportedException, TemplateException, KeyParentEqualException, SichtException, IOException, SQLException, DBServletException, |
|
ParseException, UngueltigeEingabeException, TransformerException, NumberFormatException, NoMainEntryException, InvalidDataTypeException { |
|
String tidString = getTid(request); |
|
userid = request.getSession().getAttribute("UserID").toString(); |
|
SxUser user = (SxUser) request.getSession().getAttribute("user"); |
|
|
|
formular.put("UserID", userid); |
|
formular.put("locale", desiredLocale.getLanguage()); |
|
request.getSession().setAttribute(tidString + "-isSent", "false"); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
|
|
String cm = ServletHelper.getParameter(request, "cachingcontrol"); |
|
if (cm != null && cm.toLowerCase().equals("clearmask")) { |
|
mc.removeMaske(tidString); |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " removing cached mask " + tidString); |
|
} else { |
|
maske = mc.getMaske(tidString); |
|
} |
|
|
|
tutil.start(); |
|
// falls die Maske noch nicht in der Session hinterlegt wurde |
|
|
|
if (maske == null) { |
|
|
|
if (SxPools.get(getMandantenID()).hasMaske(new Integer(tidString))) { |
|
maske = SxPools.get(getMandantenID()).getMaskenclone(new Integer(tidString)); |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " using mask clone"); |
|
} else { |
|
maske = new Maske(getMandantenID(), user, new Integer(tidString), desiredLocale); |
|
} |
|
|
|
maske.setFieldDefaults(sxuser, request, true); |
|
|
|
mc.addMaske(maske); |
|
// request.getSession().setAttribute("Maske-" + maske.getId(), |
|
// maske); |
|
} |
|
} |
|
|
|
private void classicRun() throws CloneNotSupportedException, TransformerConfigurationException, TemplateException, KeyParentEqualException, SichtException, IOException, |
|
DBServletException, ParseException, InvalidKeyException, TransformerException, FactoryConfigurationError, ParserConfigurationException, |
|
UngueltigeEingabeException, NoMainEntryException, NumberFormatException, InvalidDataTypeException, ServletException, SQLException { |
|
try { |
|
// Nun wird die Maske geladen |
|
loadMask(); |
|
|
|
|
|
if (getParameter(request, "Statistikexport") != null) { |
|
String ausgabeFormat = getParameter(request, "Exportformat"); |
|
logger.debug("Amtliche Statistik. Ausgabeformat = " + ausgabeFormat); |
|
if (xmlStatisticExport(ausgabeFormat)) { |
|
return; |
|
} |
|
} |
|
|
|
String contenttype = ServletHelper.getParameter(request, "contenttype"); |
|
//MB 4/14 Bug excelexport alle Zeilen, zurück-button des Browsers neu abschicken, zeigt keine Ebenen |
|
if (contenttype == null) maske.setDesiredContenttype(null); |
|
if (contenttype != null && contenttype.startsWith("application/pdf") && maske.isMaxRowsReached()) { |
|
sendBackHtml(de.superx.servlet.SuperXManager.htmlPageHead("Datenproblem") |
|
+ "<h2>Achtung</h2><p>Datenmenge ist zu groß - bitte schränken Sie Ihre Abfrage ggfs. stärker ein</p></body></html>"); |
|
} else if (contenttype != null && contenttype.indexOf("spreadsheetml") > -1 && maske.isMaxRowsReached()) { |
|
sendBackHtml(de.superx.servlet.SuperXManager.htmlPageHead("Datenproblem") |
|
+ "<center><h2>Achtung</h2><p>Große Datenmenge <br> <input id='ss' type='submit' value='Alle Daten als Exceldatei downloaden' onclick='document.getElementById(\"ss\").disabled=\"true\";location.href=\"/superx/servlet/SuperXmlTabelle?tid=" |
|
+ maske.getId() + "&bigexcel=true\"'><br><br>(Kann länger dauern)</p></center></body></html>"); |
|
} else { |
|
if (ServletHelper.getParameter(request, "maxoffset") != null && !ServletHelper.getParameter(request, "maxoffset").equals("")) { |
|
maske.setMaxOffset(Integer.parseInt(ServletHelper.getParameter(request, "maxoffset"))); |
|
} else { |
|
if (contenttype != null && contenttype.indexOf("html") == -1) { |
|
maske.setMaxOffset(10000000); |
|
} else { |
|
maske.setMaxOffset(maxOffset); |
|
} |
|
} |
|
|
|
maske.setOffset(getOffset()); |
|
boolean isReuseResult = false; |
|
String reuse = ServletHelper.getParameter(request, "reuseresult"); |
|
if (reuse != null && reuse.equals("true")) { |
|
isReuseResult = true; |
|
} |
|
String openHeader = ServletHelper.getParameter(request, "openHeader"); |
|
if (openHeader != null) { |
|
maske.openHeader(openHeader); |
|
isReuseResult = true; |
|
} |
|
String closeHeader = ServletHelper.getParameter(request, "closeHeader"); |
|
if (closeHeader != null) { |
|
maske.closeHeader(closeHeader); |
|
isReuseResult = true; |
|
} |
|
maske.setReuseResult(isReuseResult); |
|
maske.resetTableStylesheet(); |
|
if (ServletHelper.getParameter(request, "stylesheet") != null && !ServletHelper.getParameter(request, "stylesheet").toString().trim().equals("")) { |
|
maske.setSelectedTableStylesheetFileAndContenttype(ServletHelper.getParameter(request, "stylesheet")); |
|
} |
|
// ggfs von Standard-contenttype von stylesheet in db durch |
|
// param überlagern |
|
if (contenttype != null && !contenttype.equals("")) { |
|
maske.setDesiredContenttype(contenttype); |
|
} |
|
SuperXManager.clearLog(); |
|
|
|
// maske.kostenstellenSichtAufAuswahlPruefen(); |
|
// erst in runQuery. setFieldSelections wird tablestylesheet |
|
// gesetzt |
|
currentXml = maske.runQuery(sxuser, request, null).toString(); |
|
|
|
Logger.getLogger("superx_" + getMandantenID() + "_xml").log(Level.FINE, "--Ergebnis\n" + currentXml); |
|
SuperXManager.setLastXml(currentXml); |
|
|
|
Logger.getLogger("superx_" + getMandantenID() + "_xml").log(Level.FINEST, "Ergebnisxml:\n" + currentXml); |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " ausführen der Abfrage " + tutil.getSinceStart()); |
|
tutil.start(); |
|
|
|
setExpires(cacheSecs); |
|
if (contenttype != null && contenttype.equals("text/csv")) { |
|
csvExport(); |
|
} else |
|
// neu MB |
|
if (maske.getSelectedTableStylesheetFilename() != null && maske.getSelectedTableStylesheetFilename().equals("tabelle_xml.xsl")) { |
|
response.setContentType("application/x-xml; charset=" + SqlStringUtils.getEncoding()); |
|
response.setHeader("Content-disposition", "attachment; filename=" + FileUtils.removeProblemChars(maske.getName()) + ".xml"); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
// hier wird für xml-output localiziert für andere |
|
// formate in xmlTransformer könnte |
|
// man evtl vorziehen |
|
|
|
currentXml = SxPools.get(getMandantenID()).localize(currentXml, desiredLocale); |
|
if (currentXml.indexOf("Insgesamt 0 Sätze gefunden") < 1) { |
|
} |
|
|
|
PrintWriter out = response.getWriter(); |
|
if (ServletHelper.getParameter(request, "encrypted") != null && ServletHelper.getParameter(request, "encrypted").equals("true")) { |
|
currentXml = CryptUtils.simpleEncryptString2(currentXml); |
|
} |
|
out.write(currentXml); |
|
|
|
} else if (maske.getSelectedTableStylesheetFilename() != null && maske.getSelectedTableStylesheetFilename().endsWith(".jrxml")) { |
|
|
|
if ((currentXml.indexOf("Insgesamt 0 Sätze gefunden") < 1 |
|
//im Makro immer ausführen: |
|
|| currentXml.indexOf("ergebnis ordnr=\"1\"") > -1) |
|
&& currentXml.indexOf("Zeilen liegen über max. Grenze") < 1) { |
|
try { |
|
turnCacheOff(); |
|
String reports_dir = getServletConfig().getServletContext().getRealPath("/WEB-INF/reports") + System.getProperty("file.separator"); |
|
|
|
JasperCreator jc = new JasperCreator(request, response, (SxUser) request.getSession().getAttribute("user"), maske, |
|
maske.getSelectedTableStylesheetFilename(), maske.getDesiredContenttype(), reports_dir); |
|
|
|
if (maske.getSelectedTableStylesheetFilename().indexOf("_xmlsource") > -1) { |
|
currentXml = SxPools.get(getMandantenID()).localize(currentXml, desiredLocale); |
|
jc.perform(getMandantenID(), currentXml, null); |
|
} |
|
if (maske.getSelectedTableStylesheetFilename().indexOf("_dbsource") > -1) { |
|
jc.perform(getMandantenID(), maske, null); |
|
} else { |
|
jc.perform(getMandantenID(), maske, null); |
|
} |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " schicken des JasperReport an Client " + tutil.getSinceStart()); |
|
|
|
|
|
} catch (JRException e) { |
|
writeExceptionText("log", e, "JasperReport-Erzeugung "); |
|
} |
|
} else { |
|
// HTML reinschreiben |
|
String sendBack = ""; |
|
if (currentXml.indexOf("Zeilen liegen über max. Grenze") >= 1) |
|
sendBack = de.superx.servlet.SuperXManager.htmlPageHead("Zu viele Daten") |
|
+ "<h5 style='font-family:sans-serif'>Für den ausgewählten Zeitraum ist die Datenmenge größer als die max. Zeilenanzahl.</h5>"; |
|
else if (currentXml.indexOf("Insgesamt 0 Sätze gefunden") >= 1) |
|
sendBack = de.superx.servlet.SuperXManager.htmlPageHead("Keine Daten") |
|
+ "<h5 style='font-family:sans-serif'>Für den ausgewählten Zeitraum sind keine Daten vorhanden.</h5>"; |
|
else |
|
sendBack = de.superx.servlet.SuperXManager.htmlPageHead("Datenproblem") |
|
+ "<h5 style='font-family:sans-serif'>Für den ausgewählten Zeitraum gibt es keine Daten.</h5>"; |
|
|
|
if (contenttype != null && contenttype.startsWith("image/")) { |
|
returnHtmlAsImage(sendBack, contenttype); |
|
} else { |
|
sendBackHtml(sendBack); |
|
//sendBackHtml(sendBack |
|
// + "<p style='font-family:sans-serif'><a href='javascript:history.go(-1)'>Zurück</a></p></body></html>"); |
|
} |
|
} |
|
|
|
} else { |
|
//DQ XSL_JR start |
|
if (contenttype != null && contenttype.equalsIgnoreCase("application/jrxml") |
|
&& maske.getSelectedTableStylesheet().getStylesheetType().equals("XSL_JRXML")) |
|
{ |
|
transformToJrxmlAndExecute(currentXml,maske.getSelectedTableStylesheetFilename(),null, request, response ,maske,getMandantenID()); |
|
} |
|
else |
|
{ |
|
|
|
// generic (non Jasper) export |
|
if (contenttype != null |
|
&& (contenttype.startsWith("text/xml") || |
|
contenttype.startsWith("application")) |
|
) |
|
{ |
|
//special contenttypes to open browser download dialogue |
|
String filename_extension=""; |
|
if(contenttype.indexOf("/")>-1) |
|
{ |
|
filename_extension="."+contenttype.substring(contenttype.lastIndexOf("/")+1); |
|
|
|
// open browser download dialogue |
|
response.setContentType("application/x-xml; charset=" + SqlStringUtils.getEncoding()); |
|
response.setHeader("Content-disposition", "attachment; filename=" + FileUtils.removeProblemChars(maske.getName()) + filename_extension); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
} |
|
} |
|
XmlTransformer xmlTransformer = new XmlTransformer( |
|
getServletConfig(), request, response, |
|
getMandantenID(), getBrowser()); |
|
xmlTransformer.setMaske(maske); |
|
xmlTransformer.transform(maske.getName(), |
|
maske.getTmpFiles(), currentXml, desiredLocale, |
|
maske.getSelectedTableStylesheetFilename(), |
|
maske.getSelectedTableStylesheetContenttype(contenttype), |
|
ServletHelper.getParameter(request, "encrypt")); |
|
} |
|
} |
|
request.getSession().setAttribute(maske.getId() + "-isSent", "true"); |
|
} //von XSL ohne JR |
|
|
|
} catch (ObligatoryFieldEmptyException e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.WARNING, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
output.println(de.superx.servlet.SuperXManager.htmlPageHead("Problem") + "<p class='errmsg'>" + e.getMessage() + "</p></body></html>"); |
|
} |
|
/* catch (SQLException e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log( |
|
Level.SEVERE, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" |
|
+ SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
StringBuffer msg = new StringBuffer(e.getMessage()); |
|
StringUtils.replace(msg, "java.sql.SQLException:", ""); |
|
StringUtils.replace(msg, "org.postgresql.util.PSQLException:", ""); |
|
StringUtils.replace(msg, "<", "<"); |
|
StringUtils.replace(msg, ">", ">"); |
|
|
|
output.println(de.superx.servlet.SuperXManager |
|
.htmlPageHead("Tabelle Problem") |
|
+ "<b>" |
|
+ msg |
|
+ "</b></body></html>"); |
|
|
|
}*/ |
|
} |
|
|
|
private void csvExport() throws IOException { |
|
/* Spezieller ISO Export für MS Excel*/ |
|
StringBuffer csv = maske.getCSV(getMandantenID()); |
|
String outp = new String(csv.toString().getBytes("iso-8859-1")); |
|
response.setHeader("Content-disposition", "attachment; filename=" + FileUtils.removeProblemChars(maske.getName()) + ".csv"); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
response.setHeader("ContentType", "text/plain"); //; charset=ISO-8859-1 |
|
sendBackIso(csv.toString(), "text/csv; charset=ISO-8859-1"); |
|
|
|
} |
|
void sendBackIso(String txt, String contenttype) throws IOException { |
|
|
|
OutputStream out = null; |
|
TimeUtils t = new TimeUtils(); |
|
t.start(); |
|
|
|
// Check the Accepting-Encoding header from the HTTP request. |
|
// If the header includes gzip, choose GZIP. |
|
// If the header includes compress, choose ZIP. |
|
// Otherwise choose no compression. |
|
byte[] stuff = txt.getBytes("iso-8859-1"); |
|
|
|
String encoding = request.getHeader("Accept-Encoding"); |
|
if (!SuperXManager.isResponseCompressionWanted) encoding = "none"; |
|
if (encoding != null && encoding.indexOf("gzip") != -1) { |
|
response.setHeader("Content-Encoding", "gzip"); |
|
out = new GZIPOutputStream(response.getOutputStream()); |
|
} else if (encoding != null && encoding.indexOf("compress") != -1) { |
|
response.setHeader("Content-Encoding", "compress"); |
|
out = new ZipOutputStream(response.getOutputStream()); |
|
} else { |
|
|
|
|
|
response.setContentLength(stuff.length); |
|
out = response.getOutputStream(); |
|
} |
|
if (contenttype != null) { |
|
response.setContentType(contenttype); |
|
} |
|
out.write(stuff); |
|
out.close(); |
|
} |
|
|
|
private boolean xmlStatisticExport(String ausgabeFormat) throws IOException { |
|
boolean done = true; |
|
String propertiesFileName = getParameter(request, "propertiesFileName"); |
|
String sdf = getParameter(request, "sdf"); |
|
String dir = getParameter(request, "statdir"); |
|
String lieferung = getParameter(request, "Lieferung"); |
|
String semester = getParameter(request, "berichtssemester"); |
|
String inspectionLevel = getParameter(request, "Prüfstufe"); |
|
String plausi = getParameter(request, "Plausibilisierung"); |
|
String stand = getParameter(request, "stand"); |
|
String sql = getParameter(request, "statsql"); |
|
String standort = getParameter(request, "Hochschulstandort"); |
|
String where = null; |
|
if (standort != null && !standort.isEmpty()) { |
|
// filter on Standort in statistik2016 |
|
where = "ef004='" + standort + "'"; |
|
} |
|
DistributionType distributionType; |
|
distributionType = DistributionType.COMPLETE1990; |
|
if (dir.contains("2016")) { |
|
distributionType = DistributionType.COMPLETE2016; |
|
} |
|
switch (lieferung.toLowerCase()) { |
|
case "2": |
|
distributionType = DistributionType.STUDENTS1990; |
|
if (dir.contains("2016")) { |
|
distributionType = DistributionType.STUDENTS2016; |
|
} |
|
break; |
|
case "3": |
|
distributionType = DistributionType.EXAMINATIONS1990; |
|
if (dir.contains("2016")) { |
|
distributionType = DistributionType.EXAMINATIONS2016; |
|
} |
|
break; |
|
case "4": |
|
distributionType = DistributionType.GUEST_LISTENERS; |
|
break; |
|
} |
|
logger.debug("Lieferungsart: " + lieferung); |
|
logger.debug("Plausi: " + plausi); |
|
ServletContext servletContext = request.getSession().getServletContext(); |
|
String contextPath = servletContext.getRealPath("/"); |
|
ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); |
|
StatisticExport statExport = new StatisticExport(distributionType, contextPath + File.separator + dir, sdf, propertiesFileName, sql, where); |
|
DataSource datasource = (DataSource) appContext.getBean("dataSource"); |
|
statExport.setDataSource(datasource); |
|
int offset = getOffset(); |
|
if ("2".equals(plausi) && offset == 0) { |
|
// only if we're not paging or at page 1 otherwise too expensive! |
|
statExport.doPlausi(); |
|
} |
|
//HTML! We're done here... |
|
if (ausgabeFormat.equals("text/html")) { |
|
return false; |
|
} |
|
ExportFormat exportFormat = ExportFormat.getForMimeType(ausgabeFormat); |
|
if (exportFormat == ExportFormat.UNKNOWN) { |
|
throw new RuntimeException("Unbekanntes Ausgabeformat: " + ausgabeFormat); |
|
} |
|
String fileName = distributionType.getDescription() + "_statistik_" + semester.replaceAll("\\/", "-") + "_" + stand + "."; |
|
fileName = fileName.replaceAll(" ", "_"); |
|
try (OutputStream responseOut = this.response.getOutputStream()) { |
|
// ZIP file with xml and core.inspector report |
|
if (exportFormat == ExportFormat.ZIP) { |
|
response.setHeader("Content-disposition", "attachment; filename=statistik.zip"); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
Path tmp = Files.createTempFile("stat", "stud", new FileAttribute[0]); |
|
try (OutputStream tmpOut = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) { |
|
statExport.generate(tmpOut); |
|
} |
|
try (ZipOutputStream zipOutputStream = new ZipOutputStream(responseOut)) { |
|
fileName += "xml"; |
|
ZipEntry entry = new ZipEntry(fileName); |
|
zipOutputStream.putNextEntry(entry); |
|
InputStream tmpIn = new BufferedInputStream(new FileInputStream(tmp.toFile())); |
|
ByteStreams.copy(tmpIn, zipOutputStream); |
|
if (inspectionLevel != null) { |
|
int inspectionLevelInt = Integer.parseInt(inspectionLevel); |
|
InspectionReport report = statExport.getInspectionReport(new BufferedInputStream(new FileInputStream(tmp.toFile())), inspectionLevelInt); |
|
entry = new ZipEntry("inspection_report.txt"); |
|
zipOutputStream.putNextEntry(entry); |
|
@SuppressWarnings("unchecked") |
|
List<InspectionProblem> problems = report.getProblemList(); |
|
for (InspectionProblem problem : problems) { |
|
ProblemPosition position = problem.getPosition(); |
|
String line = String.format("Problem: Zeile %d, Spalte %d: %s\n", Integer.valueOf(position.getLine()), Integer.valueOf(position.getColumn()), |
|
problem.getComment()); |
|
zipOutputStream.write(line.getBytes()); |
|
} |
|
|
|
} |
|
} |
|
} |
|
// ZIP file with astat plausi report |
|
else if ("2".equals(plausi)) { |
|
response.setHeader("Content-disposition", "attachment; filename=statistik.zip"); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
Path tmp = Files.createTempFile("stat", "stud", new FileAttribute[0]); |
|
try (OutputStream tmpOut = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) { |
|
statExport.getOutput(exportFormat.getMimeType(), tmpOut); |
|
} |
|
try (ZipOutputStream zipOutputStream = new ZipOutputStream(responseOut)) { |
|
// statistic export |
|
fileName += exportFormat.getExtension(); |
|
zipOutputStream.putNextEntry(new ZipEntry(fileName)); |
|
InputStream tmpIn = new BufferedInputStream(new FileInputStream(tmp.toFile())); |
|
ByteStreams.copy(tmpIn, zipOutputStream); |
|
// plausi log |
|
zipOutputStream.putNextEntry(new ZipEntry("plausi.log")); |
|
statExport.readPlausiFromDb(zipOutputStream); |
|
} |
|
} else { |
|
fileName += exportFormat.getExtension(); |
|
response.setHeader("Content-disposition", "attachment; filename=" + fileName); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
// response.setContentType(exportFormat.getContentType()); |
|
statExport.getOutput(exportFormat.getMimeType(), responseOut); |
|
} |
|
JdbcTemplate jt = new JdbcTemplate(datasource); |
|
switch (distributionType) { |
|
case STUDENTS2016: |
|
case EXAMINATIONS2016: |
|
case COMPLETE2016: |
|
String filenameUpdateSql = "update sos_stat_info set exportfile='" + fileName + "' where lieferungsart = 'statistik2016'"; |
|
jt.execute(filenameUpdateSql); |
|
break; |
|
case GUEST_LISTENERS: |
|
filenameUpdateSql = "update sos_stat_info set exportfile='" + fileName + "' where lieferungsart = 'gasthoerer'"; |
|
jt.execute(filenameUpdateSql); |
|
break; |
|
} |
|
return done; |
|
} |
|
} |
|
|
|
|
|
private int getOffset() { |
|
int offset; |
|
String offs = getParameter(request, "offset"); |
|
|
|
if (offs == null || offs.isEmpty()) { |
|
offset = 0; |
|
} else { |
|
offset = (Integer.parseInt(offs)); |
|
} |
|
return offset; |
|
} |
|
|
|
} |
|
|
|
private class CSVUploadHelper extends SuperXServletHelper { |
|
private List filterList = new LinkedList(); |
|
|
|
private String tabelle = ""; |
|
|
|
private String tid = ""; |
|
|
|
private String delim = "^"; |
|
|
|
private String encoding = ""; |
|
|
|
private boolean withHeader = false; |
|
|
|
private String hinzufuegenModus = ""; |
|
|
|
private boolean showMaskResult = false; |
|
|
|
private File csvfile; |
|
|
|
private SxUser sxuser; |
|
|
|
private Locale desiredLocale; |
|
|
|
private final Hashtable formular = new Hashtable(); |
|
|
|
private StringBuffer msgAboutEmptyFields; |
|
|
|
private HashMap params = new HashMap(); |
|
|
|
private Maske maske; |
|
|
|
private boolean navi = false; |
|
|
|
private boolean isZipped = false; |
|
|
|
private final boolean isXml = false; // nicht änderbar |
|
|
|
private final String insertMode = "false"; // nicht änderbar |
|
|
|
private List<FileItem> multipartData = new LinkedList<FileItem>(); |
|
|
|
public CSVUploadHelper(HttpServletRequest request, HttpServletResponse response, List<FileItem> multipartData) throws IOException { |
|
super(request, response); |
|
this.multipartData = multipartData; |
|
userid = request.getSession().getAttribute("UserID").toString(); |
|
filterList.add(".csv"); |
|
filterList.add(".txt"); |
|
filterList.add(".zip"); |
|
filterList.add(".unl"); |
|
|
|
} |
|
|
|
/** |
|
* Kopie von TableCreator loadMask |
|
* |
|
* @throws CloneNotSupportedException |
|
* @throws TemplateException |
|
* @throws KeyParentEqualException |
|
* @throws SichtException |
|
* @throws IOException |
|
* @throws SQLException |
|
* @throws DBServletException |
|
* @throws ParseException |
|
* @throws UngueltigeEingabeException |
|
* @throws TransformerException |
|
* @throws NumberFormatException |
|
* @throws NoMainEntryException |
|
* @throws InvalidDataTypeException |
|
*/ |
|
private void loadMask() throws CloneNotSupportedException, TemplateException, KeyParentEqualException, SichtException, IOException, SQLException, DBServletException, |
|
ParseException, UngueltigeEingabeException, TransformerException, NumberFormatException, NoMainEntryException, InvalidDataTypeException { |
|
String tidString = tid;// getTid(request); |
|
userid = request.getSession().getAttribute("UserID").toString(); |
|
SxUser user = (SxUser) request.getSession().getAttribute("user"); |
|
|
|
formular.put("UserID", userid); |
|
formular.put("locale", desiredLocale.getLanguage()); |
|
request.getSession().setAttribute(tidString + "-isSent", "false"); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
|
|
String cm = ServletHelper.getParameter(request, "cachingcontrol"); |
|
if (cm != null && cm.toLowerCase().equals("clearmask")) { |
|
mc.removeMaske(tidString); |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " removing cached mask " + tidString); |
|
} else { |
|
maske = mc.getMaske(tidString); |
|
} |
|
|
|
tutil.start(); |
|
|
|
if (maske == null) { |
|
|
|
if (SxPools.get(getMandantenID()).hasMaske(new Integer(tidString))) { |
|
maske = SxPools.get(getMandantenID()).getMaskenclone(new Integer(tidString)); |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.FINER, " using mask clone"); |
|
} else { |
|
maske = new Maske(getMandantenID(), user, new Integer(tidString), desiredLocale); |
|
} |
|
|
|
mc.addMaske(maske); |
|
} |
|
maske.setFieldDefaults(sxuser, request, this.params, true); |
|
} |
|
|
|
/** |
|
* vorher muss uploadFile gelaufen sein, damit Feldvariable tid gesetzt |
|
* ist |
|
*/ |
|
private void checkUserAndMaskAuthentification() { |
|
|
|
sxuser = (SxUser) request.getSession().getAttribute("user"); |
|
if (sxuser == null) { |
|
throw new IllegalStateException("Kein user in der Session gefunden - bitte Browser neu starten!"); |
|
} |
|
|
|
sxuser.checkAuthentificationForMask(tid); |
|
} |
|
|
|
/** |
|
* |
|
* |
|
* @param name |
|
* @return |
|
*/ |
|
private boolean isFileAllowed(String name) { |
|
boolean result = false; |
|
for (Iterator it = filterList.iterator(); it.hasNext();) { |
|
String afilter = (String) it.next(); |
|
if (afilter.indexOf("*") == -1) { |
|
if (name.toLowerCase().endsWith(afilter)) result = true; |
|
} else { |
|
afilter = StringUtils.replace(afilter, ".", "\\.").toLowerCase(); |
|
afilter = StringUtils.replace(afilter, "*", ".*"); |
|
Pattern p = Pattern.compile(afilter); |
|
Matcher m = p.matcher(name.toLowerCase()); |
|
if (m.matches()) result = true; |
|
} |
|
} |
|
return result; |
|
} |
|
|
|
/** |
|
* Also add all params to hashmap |
|
* |
|
* @throws IOException |
|
*/ |
|
private void uploadFile() throws IOException { |
|
csvfile = File.createTempFile("tmp", ".csv"); |
|
try { |
|
String mandantenID = getMandantenID(); |
|
Iterator iter = multipartData.iterator(); |
|
while (iter.hasNext()) { |
|
FileItem item = (FileItem) iter.next(); |
|
if (item.isFormField()) { |
|
String fieldName = item.getFieldName(); |
|
if (fieldName != null) { |
|
String itemValue = item.getString(); |
|
params.put(item.getFieldName(), itemValue); |
|
switch (fieldName) { |
|
case "tid": |
|
tid = itemValue; |
|
break; |
|
case "Tabelle": |
|
tabelle = itemValue; |
|
break; |
|
case "Trennzeichen": |
|
delim = itemValue; |
|
break; |
|
case "Kodierung": |
|
encoding = itemValue; |
|
break; |
|
case "zip-komprimiert": |
|
isZipped = itemValue.equals("1"); |
|
break; |
|
case "Feldnamen 1. Zeile": |
|
if (itemValue.equals("1")) withHeader = true; |
|
break; |
|
case "Modus": |
|
hinzufuegenModus = itemValue; |
|
break; |
|
case "showMaskResult": |
|
// show the mask directly after file upload and don't ask for ok? |
|
String showMaskResultStr = itemValue; |
|
showMaskResult = showMaskResultStr != null && !showMaskResultStr.isEmpty() ? Boolean.parseBoolean(showMaskResultStr) : false; |
|
break; |
|
case "navi": |
|
// show the mask with standard superx navi menu? |
|
String naviResultStr = itemValue; |
|
this.navi = naviResultStr != null && !naviResultStr.isEmpty() ? Boolean.parseBoolean(naviResultStr) : false; |
|
break; |
|
} |
|
} |
|
} else { |
|
if (item.getName().isEmpty()) { |
|
throw new IllegalArgumentException("Bitte geben Sie eine Upload-Datei an!"); |
|
} |
|
if (item.getSize() == 0) { |
|
throw new IllegalArgumentException("Upload-Datei darf nicht leer sein!"); |
|
} |
|
if (isFileAllowed(item.getName())) { |
|
try { |
|
item.write(csvfile); |
|
} catch (Exception e) { |
|
e.printStackTrace(); |
|
throw new IOException("Dateiupload fehlgeschlagen:" + e.getMessage()); |
|
} |
|
} else { |
|
throw new IOException("Nicht erlaubte Datei " + item.getName()); |
|
} |
|
} |
|
} |
|
} catch (IllegalArgumentException e) { |
|
writeResponse(e); |
|
} |
|
|
|
} |
|
|
|
protected void perform() throws SQLException, DBServletException, TransformerException, KeyParentEqualException, NichtAngemeldetException, IOException, ParseException, |
|
ParserConfigurationException, FactoryConfigurationError, SAXException, DocumentException, IllegalArgumentException, SecurityException, |
|
InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException, TemplateException, |
|
InvalidKeyException, SichtException, IOException, ServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { |
|
desiredLocale = getDesiredLocale(); |
|
if (FileUpload.isMultipartContent(request)) { |
|
uploadFile(); |
|
if (this.showMaskResult) { |
|
doUploadAndShowMask(); |
|
} else { |
|
uploadTest(); |
|
} |
|
} else { |
|
doImport(); |
|
} |
|
} |
|
|
|
private void uploadTest() throws IOException, SQLException, FileNotFoundException, TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, |
|
TransformerConfigurationException, ParseException, InvalidKeyException, TransformerException, DBServletException, UngueltigeEingabeException, |
|
NoMainEntryException, InvalidDataTypeException { |
|
checkUserAndMaskAuthentification(); |
|
if (!csvfile.exists()) throw new IllegalStateException("Datei " + csvfile + " nicht gefunden"); |
|
Connection con = SxPools.get(getMandantenID()).getConnection(); |
|
CSVUploader cu = new CSVUploader(userid, getMandantenID(), tabelle, csvfile.toString(), delim, encoding, withHeader, insertMode, isXml, "exclude-row", isZipped); |
|
|
|
cu.upload(true, true, con); |
|
|
|
try { |
|
runMask(true, cu.getResultReport(), con); |
|
dropTmpTabelle(con); |
|
|
|
CSVResultReport rr = cu.getResultReport(); |
|
for (Iterator it = rr.getMessages().iterator(); it.hasNext();) { |
|
System.out.println(it.next()); |
|
} |
|
if (rr.getErrorCount() > 0) { |
|
csvfile.delete(); |
|
sendBackHtml(rr.errorsToHtml()); |
|
} else { |
|
|
|
sendBackHtml(readyToImport(cu.getHtmlPreview())); |
|
} |
|
} catch (ObligatoryFieldEmptyException e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.WARNING, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
output.println("<html><head><LINK REL='stylesheet' type='text/css' href='../style/superx.css' /></LINK></head><body><p class='errmsg'>" + e.getMessage() |
|
+ "</p></body></html>"); |
|
|
|
} finally { |
|
if (!con.isClosed()) con.close(); |
|
} |
|
} |
|
|
|
private void doUploadAndShowMask() |
|
throws IOException, SQLException, TransformerConfigurationException, TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, |
|
ParseException, InvalidKeyException, TransformerException, DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { |
|
checkUserAndMaskAuthentification(); |
|
if (!csvfile.exists()) throw new IllegalStateException("Datei " + csvfile + " nicht gefunden"); |
|
Connection con = SxPools.get(getMandantenID()).getConnection(); |
|
isZipped = false;// wurde vorher schon gemacht |
|
CSVUploader cu = new CSVUploader(userid, getMandantenID(), tabelle, csvfile.toString(), delim, encoding, withHeader, insertMode, isXml, "exclude-row", isZipped); |
|
cu.upload(true, false, con); |
|
try { |
|
runMask(false, cu.getResultReport(), con); |
|
dropTmpTabelle(con); |
|
CSVResultReport rr = cu.getResultReport(); |
|
if (rr.getErrorCount() > 0) { |
|
csvfile.delete(); |
|
sendBackHtml(rr.errorsToHtml()); |
|
} else { |
|
XmlTransformer xmlTransformer = new XmlTransformer(getServletConfig(), request, response, getMandantenID(), getBrowser()); |
|
xmlTransformer.setMaske(maske); |
|
xmlTransformer.transform(maske.getName(), maske.getTmpFiles(), currentXml, desiredLocale, maske.getSelectedTableStylesheetFilename(), |
|
maske.getSelectedTableStylesheetContenttype(null), ServletHelper.getParameter(request, "encrypt")); |
|
} |
|
} catch (ObligatoryFieldEmptyException | NumberFormatException | FactoryConfigurationError | ParserConfigurationException e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.WARNING, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
output.println(de.superx.servlet.SuperXManager.htmlPageHead("Problem") + "<p class='errmsg'>" + e.getMessage() + "</p></body></html>"); |
|
|
|
} finally { |
|
if (!con.isClosed()) con.close(); |
|
if (csvfile.exists()) csvfile.delete(); |
|
} |
|
} |
|
|
|
private void dropTmpTabelle(Connection con) throws SQLException { |
|
Statement stm = con.createStatement(); |
|
stm.executeUpdate("drop table tmp_" + tabelle); |
|
stm.close(); |
|
} |
|
|
|
private void doImport() |
|
throws SQLException, IOException, TransformerConfigurationException, TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, |
|
ParseException, InvalidKeyException, TransformerException, DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException { |
|
readParams(); |
|
checkUserAndMaskAuthentification(); |
|
|
|
Connection con = SxPools.get(getMandantenID()).getConnection(); |
|
isZipped = false;// wurde vorher schon gemacht |
|
CSVUploader cu = new CSVUploader(userid, getMandantenID(), tabelle, csvfile.toString(), delim, encoding, withHeader, insertMode, isXml, "exclude-row", isZipped); |
|
cu.upload(true, false, con); |
|
try { |
|
runMask(false, cu.getResultReport(), con); |
|
dropTmpTabelle(con); |
|
|
|
CSVResultReport rr = cu.getResultReport(); |
|
if (rr.getErrorCount() > 0) { |
|
csvfile.delete(); |
|
sendBackHtml(rr.errorsToHtml()); |
|
} else { |
|
sendBackHtml(rr.resultToHtml()); |
|
} |
|
} catch (ObligatoryFieldEmptyException | NumberFormatException | FactoryConfigurationError e) { |
|
Logger.getLogger("superx_" + getMandantenID()).log(Level.WARNING, e.toString()); |
|
response.reset(); |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter output = response.getWriter(); |
|
output.println(de.superx.servlet.SuperXManager.htmlPageHead("Problem") + "<p class='errmsg'>" + e.getMessage() + "</p></body></html>"); |
|
|
|
} finally { |
|
if (!con.isClosed()) con.close(); |
|
if (csvfile.exists()) csvfile.delete(); |
|
} |
|
|
|
} |
|
|
|
private void readParams() { |
|
tid = ServletHelper.getParameter(request, "tid"); |
|
tabelle = ServletHelper.getParameter(request, "Tabelle"); |
|
delim = ServletHelper.getParameter(request, "Trennzeichen"); |
|
encoding = ServletHelper.getParameter(request, "Kodierung"); |
|
// String zip=ServletHelper.getParameter(request, |
|
// "zip-komprimiert"); |
|
// isZipped = zip.equals("1"); |
|
|
|
String feldnamen = ServletHelper.getParameter(request, "Feldnamen 1. Zeile"); |
|
|
|
withHeader = feldnamen.equals("1"); |
|
|
|
hinzufuegenModus = ServletHelper.getParameter(request, "Modus"); |
|
String file = ServletHelper.getParameter(request, "tmpfile"); |
|
csvfile = new File(file); |
|
if (!csvfile.exists()) throw new IllegalStateException("Datei " + csvfile + " nicht gefunden"); |
|
} |
|
|
|
private void runMask(boolean isTestMode, CSVResultReport resultReport, Connection dbCon) throws SQLException, TemplateException, IOException, KeyParentEqualException, |
|
CloneNotSupportedException, SichtException, TransformerConfigurationException, ParseException, InvalidKeyException, TransformerException, |
|
DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException, ObligatoryFieldEmptyException { |
|
loadMask(); |
|
desiredLocale = getDesiredLocale(); |
|
maske.setMaxOffset(10000000); |
|
maske.setReuseResult(false); |
|
maske.setNavi(this.navi); |
|
SuperXManager.clearLog(); |
|
Statement stm = null; |
|
if (isTestMode) { |
|
stm = dbCon.createStatement(); |
|
try { |
|
|
|
stm.executeUpdate("drop table tmp_errors"); |
|
} catch (Exception e) { |
|
} |
|
|
|
stm.executeUpdate("create temp table tmp_errors (tid integer,bezeichnung varchar(255))"); |
|
// durch Trick zur Basic Map ein Freemarker Feld testupload |
|
// setzen |
|
sxuser.getBasicMap().put("testupload", "1"); |
|
|
|
} else { |
|
sxuser.getBasicMap().put("testupload", "0"); |
|
sxuser.getBasicMap().put("colnames", resultReport.getColnames()); |
|
sxuser.getBasicMap().put("Modus", hinzufuegenModus); |
|
} |
|
|
|
try { |
|
if (isTestMode) |
|
currentXml = maske.runQuery(sxuser, new CSVServletRequest(request, params), dbCon, this.params).toString(); |
|
else |
|
currentXml = maske.runQuery(sxuser, request, dbCon, this.params).toString(); |
|
sxuser.getBasicMap().remove("testupload"); |
|
sxuser.getBasicMap().remove("colnames"); |
|
sxuser.getBasicMap().remove("Modus"); |
|
SuperXManager.setLastXml(currentXml); |
|
|
|
if (isTestMode) { |
|
ResultSet rs = stm.executeQuery("select distinct bezeichnung from tmp_errors "); |
|
while (rs.next()) { |
|
resultReport.incError("Error " + rs.getString(1)); |
|
} |
|
rs.close(); |
|
stm.executeUpdate("drop table tmp_errors"); |
|
} |
|
|
|
} catch (FileUploadException e) { |
|
throw new IOException(e.getMessage()); |
|
} |
|
|
|
} |
|
|
|
/** |
|
* @deprecated not in use |
|
*/ |
|
private void prepareActualImport() { |
|
String file = ServletHelper.getParameter(request, "tmpfile"); |
|
if (file == null) throw new IllegalArgumentException("tmpfile nicht angegeben"); |
|
csvfile = new File(file); |
|
tabelle = ServletHelper.getParameter(request, "Tabelle"); |
|
if (tabelle == null) throw new IllegalArgumentException("Tabelle nicht angegeben"); |
|
encoding = ServletHelper.getParameter(request, "Kodierung"); |
|
if (encoding == null) throw new IllegalArgumentException("Kodierung nicht angegeben"); |
|
String header = ServletHelper.getParameter(request, "Feldnamen 1. Zeile"); |
|
if (header == null) throw new IllegalArgumentException("Feldnamen 1. Zeile nicht angegeben"); |
|
withHeader = header.equals("1"); |
|
hinzufuegenModus = ServletHelper.getParameter(request, "Modus"); |
|
if (hinzufuegenModus == null) throw new IllegalArgumentException("Modus nicht angegeben"); |
|
} |
|
|
|
private String success() { |
|
String s = de.superx.servlet.SuperXManager.htmlPageHead("Erfolg") + "<p align='center'>Import erfolgreich</p></body></html>"; |
|
return s; |
|
} |
|
|
|
private String readyToImport(String htmlPreview) { |
|
StringBuffer buf = new StringBuffer(de.superx.servlet.SuperXManager.htmlPageHead("Erfolg") + "<center><p align='center'>Die Daten können importiert werden</p>"); |
|
buf.append("<p>Tabelle " + tabelle + "</p>"); |
|
buf.append(htmlPreview + "<br><br>"); |
|
buf.append("<form method='post' action='SuperXmlTabelle'>"); |
|
buf.append("<input type='hidden' name='csvupload' value='true'>\n"); |
|
buf.append("<input type='hidden' name='tid' value='" + tid + "'>\n"); |
|
buf.append("<input type='hidden' name='Tabelle' value='" + tabelle + "'>\n"); |
|
buf.append("<input type='hidden' name='Trennzeichen' value='" + delim + "'>\n"); |
|
buf.append("<input type='hidden' name='Kodierung' value='" + encoding + "'>\n"); |
|
buf.append("<input type='hidden' name='Feldnamen 1. Zeile' value='" + (withHeader ? "1" : "0") + "'>\n"); |
|
buf.append("<input type='hidden' name='Modus' value='" + hinzufuegenModus + "'>\n"); |
|
|
|
buf.append("<input type='hidden' name='tmpfile' value='" + csvfile.getAbsoluteFile() + "'>\n"); |
|
for (Iterator it = params.keySet().iterator(); it.hasNext();) { |
|
String name = (String) it.next(); |
|
if (name.equals("tid") || name.equals("Tabelle") || name.equals("Trennzeichen") || name.equals("Kodierung") || name.equals("Feldnamen 1. Zeile") |
|
|| name.equals("Modus")) continue; |
|
buf.append("<input type='hidden' name='" + name + "' value='" + params.get(name) + "'>\n"); |
|
} |
|
buf.append("<input type='submit' name='jetzt importieren' value='jetzt importieren'></center>\n"); |
|
buf.append("</form></body></html>"); |
|
return buf.toString(); |
|
} |
|
} |
|
|
|
private class KidRowsResponder extends SuperXServletHelper { |
|
private Maske maske; |
|
|
|
private final SxUser user; |
|
|
|
public KidRowsResponder(HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
super(request, response); |
|
user = (SxUser) request.getSession().getAttribute("user"); |
|
setAjaxResponder(true); |
|
} |
|
|
|
@Override |
|
protected void perform() throws SQLException, DBServletException, TransformerException, KeyParentEqualException, NichtAngemeldetException, IOException, ParseException, |
|
ParserConfigurationException, FactoryConfigurationError, SAXException, DocumentException, IllegalArgumentException, SecurityException, |
|
InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException, TemplateException, |
|
InvalidKeyException, SichtException, IOException, ServletException { |
|
if (user == null) { |
|
throw new IllegalStateException("Kein user in der Session gefunden - bitte Browser neu starten!"); |
|
} |
|
userid = request.getSession().getAttribute("UserID").toString(); |
|
|
|
String tidString = getTid(request); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
maske = mc.getMaske(tidString); |
|
if (maske == null) { |
|
throw new IllegalStateException("Es wurde versucht, per AJAX Daten nachzuladen, ohne, dass die Maske geladen wurde"); |
|
} |
|
|
|
String rowkids = ServletHelper.getParameter(request, "getKidRows"); |
|
String treetableid = ServletHelper.getParameter(request, "treetableid"); |
|
int row = Integer.parseInt(rowkids); |
|
StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"" + SqlStringUtils.getEncoding() + "\"?>\n<ergebnisse isMakro=\"false\">\n<sqlerg>"); |
|
|
|
xml.append(maske.getKidRows(treetableid, row)); |
|
xml.append("</sqlerg>\n</ergebnisse>"); |
|
Logger.getLogger("superx_" + getMandantenID() + "_xml").log(Level.FINE, " treetable rows\n" + xml); |
|
XmlTransformer xmlTransformer = new XmlTransformer(getServletConfig(), request, response, getMandantenID(), getBrowser()); |
|
String xsl = "tabelle_html_rows.xsl"; |
|
if (maske.getChartx() != null && maske.getChartx().endsWith(".xsl")) { |
|
xsl = maske.getChartx(); |
|
} |
|
xmlTransformer.transform(maske.getName(), null, xml.toString(), getDesiredLocale(), xsl, "", "false"); |
|
|
|
} |
|
|
|
/** |
|
* Anders als reguläre Servlets hier |
|
*/ |
|
public void sendNotAuthorized() throws IOException { |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter p = response.getWriter(); |
|
String msg = ServletUtils.getJSONErrorText(userid, getDesiredLocale()); |
|
System.out.println(msg); |
|
p.print(msg); |
|
|
|
// p.print("({type:\"error\",error:\"\"})"); |
|
|
|
p.close(); |
|
} |
|
} |
|
|
|
private class ChartResponder extends SuperXServletHelper { |
|
private Maske maske; |
|
|
|
private final SxUser user; |
|
|
|
public ChartResponder(HttpServletRequest request, HttpServletResponse response) throws IOException { |
|
super(request, response); |
|
user = (SxUser) request.getSession().getAttribute("user"); |
|
setAjaxResponder(true); |
|
} |
|
|
|
@Override |
|
protected void perform() throws SQLException { |
|
try { |
|
if (user == null) { |
|
throw new IllegalStateException("Kein user in der Session gefunden - bitte Browser neu starten!"); |
|
} |
|
userid = request.getSession().getAttribute("UserID").toString(); |
|
|
|
String tidString = getTid(request); |
|
MaskenContainer mc = MaskenContainer.getFromRequest(request); |
|
maske = mc.getMaske(tidString); |
|
if (maske == null) { |
|
throw new IllegalStateException("Es wurde versucht, per AJAX Daten nachzuladen, ohne, dass die Maske geladen wurde"); |
|
} |
|
|
|
GraphicFormat graphicformat = SxPools.get(getMandantenID()).getGraphicFormat2("1"); |
|
// int pos=sharedData.addImage(ChartCreator.create(tableXml,f)); |
|
|
|
StringBuffer tabXml = new StringBuffer(maske.getFullTableXml(getMandantenID(), user, request, getDesiredLocale())); |
|
File graphicFile = ChartCreator.createFile(tabXml, graphicformat); |
|
} catch (Exception e) { |
|
e.printStackTrace(); |
|
throw new SQLException("XML konnte nicht erzeugt werden " + e); |
|
} |
|
|
|
} |
|
|
|
/** |
|
* Anders als reguläre Servlets hier |
|
*/ |
|
|
|
public void sendNotAuthorized() throws IOException { |
|
response.setContentType("text/html; charset=" + SqlStringUtils.getEncoding()); |
|
PrintWriter p = response.getWriter(); |
|
String msg = ServletUtils.getJSONErrorText(userid, getDesiredLocale()); |
|
System.out.println(msg); |
|
p.print(msg); |
|
|
|
// p.print("({type:\"error\",error:\"\"})"); |
|
|
|
p.close(); |
|
} |
|
} |
|
|
|
public void transformToJrxmlAndExecute(String lastXml,String xslStylesheetFile,String params , |
|
HttpServletRequest request, HttpServletResponse response, Maske maske, |
|
String mandantenid) |
|
{ |
|
try { |
|
Locale desiredLocale = request.getLocale(); |
|
String currentXml = SxPools.get(mandantenid).localize(lastXml, desiredLocale); |
|
String reports_dir=getServletConfig().getServletContext().getRealPath("/")+"WEB-INF"+File.separator+"reports"+File.separator; |
|
String jrxmlFileName=xslStylesheetFile+".jrxml"; |
|
String jrxmlFilePath=reports_dir+jrxmlFileName; |
|
String xslFilePath=getServletConfig().getServletContext().getRealPath("/")+"xml"+File.separator+xslStylesheetFile; |
|
FileWriter myFilewriter=new FileWriter(jrxmlFilePath); |
|
PrintWriter myOutwriter = new PrintWriter(new BufferedWriter(myFilewriter)); |
|
|
|
Logger.getLogger("superx_" + mandantenid + "_xml").log(Level.INFO, |
|
|
|
" Translet für Ergebnisvorbereitung:" + xslFilePath); |
|
Transformer transformer = TransletCache.getTransformer(mandantenid, xslFilePath); |
|
|
|
|
|
StringReader s1 = new StringReader(currentXml); |
|
transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, SqlStringUtils.getEncoding()); |
|
transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "xml"); |
|
|
|
String result = null; |
|
if (params != null) |
|
{ |
|
if(!params.endsWith(",")) params += ","; |
|
|
|
StringTokenizer st = new StringTokenizer(params, ","); |
|
for (; st.hasMoreTokens();) { |
|
String param = st.nextToken(); |
|
if (!param.equals("")) { |
|
String paramname = param.substring(0, param.indexOf("=")); |
|
String paramvalue = param.substring(param.indexOf("=") + 1, param.length()); |
|
transformer.setParameter(paramname, paramvalue); |
|
} |
|
} |
|
} |
|
String rptContentype=request.getParameter("RPTContentype"); |
|
String rptPageFormat=request.getParameter("RPTPageFormat"); |
|
if(rptPageFormat!=null && rptPageFormat.equalsIgnoreCase("a4")) |
|
{ |
|
transformer.setParameter("seitenbreite", "842"); |
|
transformer.setParameter("seitenhoehe", "595"); |
|
} |
|
if(rptPageFormat!=null && rptPageFormat.equalsIgnoreCase("a3")) |
|
{ |
|
transformer.setParameter("seitenbreite", "1191"); |
|
transformer.setParameter("seitenhoehe", "842"); |
|
} |
|
transformer.transform(new javax.xml.transform.stream.StreamSource(s1), new javax.xml.transform.stream.StreamResult(myOutwriter)); |
|
if(rptContentype.equals("text/xml")) { |
|
//JRXML-Sourcecode |
|
String filename_extension=".jrxml"; |
|
OutputStream out = response.getOutputStream(); |
|
// open browser download dialogue |
|
response.setHeader("Content-disposition", "attachment; filename=" + FileUtils.removeProblemChars(maske.getName()) + filename_extension); |
|
response.setHeader("Cache-Control", "expires=0"); |
|
|
|
String jrxmlFileContent = de.memtext.util.FileUtils.getFileContentsWithEncoding(jrxmlFilePath, SqlStringUtils.getEncoding()); |
|
byte[] myBytes = jrxmlFileContent.getBytes(SqlStringUtils.getEncoding()); |
|
response.setContentLength(myBytes.length); |
|
out.write(myBytes); |
|
} |
|
|
|
else |
|
{ |
|
JasperCreator jc = new JasperCreator( |
|
request, |
|
response, |
|
(SxUser) request.getSession() |
|
.getAttribute("user"), |
|
maske, |
|
jrxmlFileName, |
|
rptContentype, //"application/pdf" TODO maske.getDesiredContenttype(), |
|
reports_dir); |
|
|
|
//lastXml = SxPools.get(getMandantenID()).localize(lastXml, desiredLocale); |
|
if(request.getParameter("irowno").isEmpty()) |
|
{ |
|
//complete Table -> use better performance of jasperDatasource |
|
jc.perform(mandantenid, maske,null); |
|
} |
|
else |
|
{ |
|
// only selected lines -> use XML datasource |
|
jc.perform(mandantenid, currentXml, null); |
|
} |
|
|
|
|
|
|
|
Logger.getLogger("superx_" + mandantenid).log( |
|
Level.FINER, |
|
" schicken des JasperReport an Client " |
|
+ tutil.getSinceStart()); |
|
|
|
|
|
} //Wenn kein JRXML-Quellcode |
|
} |
|
catch (JRException e) { |
|
System.err.println("Fehler bei JasperReport-Erzeugung "+ e.toString()); |
|
} |
|
|
|
catch (Exception e) { |
|
System.err.println("XSL-Transformation fehlgeschlagen: " + e.toString()); |
|
|
|
} |
|
} |
|
|
|
}
|
|
|