SuperX-Kernmodul
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.
 
 
 
 
 
 

2769 lines
125 KiB

package de.superx.common;
import static de.superx.servlet.SxSQL_Server.DEFAULT_MANDANTEN_ID;
import static de.superx.common.SxUser.USER_HISINONE_ORGUNIT_LID_PLACEHOLDER;
import static de.superx.common.SxUser.USER_ROLE_PLACEHOLDER;
import static de.superx.common.SxUser.USER_ROLE_ID_PLACEHOLDER;
import static de.superx.servlet.SuperXManager.QIS_CONTEXT;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
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.TreeSet;
import org.apache.log4j.*;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.fileupload.FileItem;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import de.memtext.baseobjects.NamedIdObject;
import de.memtext.baseobjects.coll.NamedIdObjectList;
import de.memtext.tree.KeyParentEqualException;
import de.memtext.tree.NoMainEntryException;
import de.memtext.util.DateUtils;
import de.memtext.util.EqualsUtil;
import de.memtext.util.ServletHelper;
import de.memtext.util.StringUtils;
import de.memtext.util.TimeUtils;
import de.memtext.util.XMLUtils;
import de.superx.bin.SxDBUtils;
import de.superx.common.Field.Art;
import de.superx.rest.model.Item;
import de.superx.rest.model.Legend;
import de.superx.servlet.ExternalPool;
import de.superx.servlet.RequestParameter;
import de.superx.servlet.ServletUtils;
import de.superx.servlet.SuperXManager;
import de.superx.servlet.SxPools;
import de.superx.util.SqlStringUtils;
import freemarker.template.TemplateException;
/**
* Eine Maske wie sie in der Tabelle maskeninfo hinterlegt, kann allerdings auch
* Untermasken enthalten
*/
public class Maske extends NamedIdObject {
private static final String PARAM_SICHT_PREFIX = "-Sicht";
private static final String PARAM_STAND_PREFIX = "-Stand";
/**
* SQL query for initializing new Maske from maskeninfo
*/
public static String QUERY_MASKENINFO = "select M.tid, M.name, M.select_stmt, M.xil_proplist, M.cleanup_stmt, "
+ "M.breite, M.hoehe, S.datum, M.chart_xtitel, M.chart_ytitel,M.erlaeuterung,M.hinweis,"
+ "(select max(P.update_time) from update_prot P where P.systeminfo_id=B.systeminfo_id) as update_time "
+ "FROM maskeninfo M, systeminfo S, maske_system_bez B "
+ "WHERE M.tid = %s and M.tid = B.maskeninfo_id and S.tid = B.systeminfo_id" + ";";
/**
* SQL query for stylesheets. Parameters are, in this order:
* mask_id, browser, mask_id
*/
public static String QUERY_STYLESHEETS = "SELECT S.filename, S.caption, S.description, S.contenttype, M.ord, S.is_generic, S.toolbar_icon_filepath,"
+ " S.jr_datasource, S.usage_resultset_data, S.stylesheet_type "
+"FROM sx_stylesheets S,sx_mask_style M"
+ " WHERE M.stylesheet_id=S.tid AND M.maskeninfo_id =%s AND S.relation ='table'"
+ " AND (S.useragent = '' OR S.useragent IS NULL OR S.useragent = '%s')"
+ " UNION"
// Default-Styleshets HTML :
+ " SELECT S.filename, S.caption, S.description, S.contenttype, 99999, S.is_generic, S.toolbar_icon_filepath,"
+ " S.jr_datasource, S.usage_resultset_data, S.stylesheet_type "
+ " FROM sx_stylesheets S"
+ " WHERE S.filename = 'tabelle_html.xsl' AND 0 = (SELECT COUNT(*) FROM sx_stylesheets S, sx_mask_style M WHERE M.stylesheet_id=S.tid"
+ " AND M.maskeninfo_id=%s AND S.relation='table' AND S.filename='tabelle_html.xsl')"
+ " UNION"
// Default-Styleshets die neben HTML immer aktiv sind:
+ " SELECT S.filename, S.caption, S.description, S.contenttype, 100000, S.is_generic, S.toolbar_icon_filepath,"
+ " S.jr_datasource, S.usage_resultset_data, S.stylesheet_type "
+ " FROM sx_stylesheets S "
+ " WHERE S.is_generic=1 and S.filename != 'tabelle_html.xsl' "
+ " AND S.filename != 'tabelle_html_datenblatt.xsl' ORDER BY 5,2;";
/**
* SQL query for stylesheets. Parameters are, in this order:
* mask_id, list of stylesheet filenames
*/
public static String QUERY_STYLESHEETS_BY_FILENAMES = "SELECT DISTINCT S.filename, S.caption, S.description, S.contenttype, M.ord, S.is_generic, S.toolbar_icon_filepath,"
+ " S.jr_datasource, S.usage_resultset_data, S.stylesheet_type "
+"FROM sx_stylesheets S,sx_mask_style M"
+ " WHERE M.stylesheet_id=S.tid AND M.maskeninfo_id =%s AND S.filename IN (%s) AND S.relation='table'";
/**
* SQL query to get sachgebiet tid
*/
public static String QUERY_SACHGEBIET_TID = "SELECT sachgebiete_id FROM sachgeb_maske_bez where maskeninfo_id = ? ;";
/**
* SQL query to get sachgebiet tid
*/
public static String QUERY_SACHGEBIET_NAME = "SELECT name FROM sachgebiete where tid = ?;";
/**
* SQL query to get felder from maske
*/
public static String QUERY_FELDER_OF_MASKE = "SELECT * FROM masken_felder_bez mf "
+ "LEFT JOIN felderinfo f ON f.tid = mf.felderinfo_id "
+ "WHERE maskeninfo_id = ? ;";
/**
* SQL query to get feld
*/
public static String QUERY_FELD = "SELECT * FROM felderinfo WHERE tid = ? ;";
// TODO: für Maskencachfunktion (s. Propadmin) erstmal auf default gesetzt
// für Mandanten müsste nach masken cloning MandantenID noch gesetzt werden
private static org.slf4j.Logger logger = LoggerFactory.getLogger(Maske.class);
private String mandantenID = DEFAULT_MANDANTEN_ID;
private boolean isResultReuseFeatureWanted = true;
private String schleifenrelation, schleifenfeldname, schleifenfstand, schleifenfsicht, aktion;
private String select_stmt = "";
private String cleanup_stmt = "";
private String xilString = "";
private String chartx = "";
private String charty = "";
private String standString = "";
private String standStringDT = "";
private String desiredContenttype = "";
private HashMap map = new HashMap();
private boolean navi = false;
private boolean isMakroSubMaske = false;
private String selectedMaskStylesheetFile = null;
private Stylesheet selectedTableStylesheet = null;
private SharedData sharedData = new SharedData();
private FieldContainer individualFields = new FieldContainer();
private List<Stylesheet> maskStylesheetList = new LinkedList<>();
private List<Stylesheet> tableStylesheetList = new LinkedList<>();
private SuperX_el result_el = new SuperX_el();
private String lastExecuted;
private String lastHeaderXml = "";
private int offset;
// welche Spalten sollen dargestellt werden
// wird bewußt nicht geclont!
private String colset;
private int maxOffset;
private static final long serialVersionUID = 1;
// browser erstmal abgeklemmt
private String browser = "";
private boolean isReuseResult = false;
private Integer sortNr;
private NamedIdObjectList submaskenListe = new NamedIdObjectList();
private Locale locale;
private String maskHtml;
// neu für Werte reuse
private StringBuffer lastXmlResult;
private static final int MACRO_MAX_OFFSET = 10000000;
private String explanation;
private String hinweis = "", hinweisCaption = "";
private String colsort = null;
private HeaderManager headerManager = new HeaderManager();
private String captionShort, captionLong;
private String lastsql;
private String desiredRows;
private List<FileItem> multipartData = null;
private static String KDSF_EXPORT_MASK_ID = "34040";
private Integer themenbaumParent;//vergl. #316289
/**
* Dieser Konstruktur wird nur zum Clonen gebraucht
*
*/
private Maske() {
locale = TranslationContainer.defaultLocale;
}
/**
* Dieser Konstruktor ist zum Aufbauen einer Maske
*
* @param locale
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws SQLException
* @throws DBServletException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
public Maske(String mandantenID, SxUser user, Integer tid, Locale locale) throws TemplateException, KeyParentEqualException,
CloneNotSupportedException, SichtException, IOException, SQLException, DBServletException, NoMainEntryException {
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, "Aufbau der Maske " + tid + " " + DateUtils.getNowString());
this.mandantenID = mandantenID;
setId(tid);
// TODO: Is this the correct position? Shouldn't this be called after initFromMaskenInfo()?
setLocale(locale);
initFromMaskeninfo();
NamedIdObjectList fields = readFelderFromDb(user);
individualFields.addAll(fields);
initMaskStylesheets();
initTableStylesheets();
initSubMasken(user);
}
/**
* Untermaske aufbauen Der Konstruktur ist private, kann also nur von einer
* Hauptmaske aus aufgerufen werden
*
* @param singleSubMask
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws SQLException
* @throws DBServletException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
private Maske(String mandantenID, SxUser user, SharedData sharedData, SxResultRow singleSubMaskRow, Locale locale) throws TemplateException, KeyParentEqualException,
CloneNotSupportedException, SichtException, IOException, SQLException, DBServletException, NoMainEntryException {
this.mandantenID = mandantenID;
this.locale = locale;
this.isResultReuseFeatureWanted = true; // bei Untermasken
setName(singleSubMaskRow.get(0).toString());
setId(singleSubMaskRow.get(1));
// wird in initsubmasken gemacht setMaxOffset(1000000);
setSchleifenrelation(singleSubMaskRow.get(2));
setSchleifenfeldname(singleSubMaskRow.get(3));
setSchleifenfstand((String) singleSubMaskRow.get(4));
setSchleifenfsicht((String) singleSubMaskRow.get(5));
if (getSchleifenrelation() != null && getSchleifenfeldname() == null) {
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Bei der Maske " + getId()
+ " ist in makro_masken_bez kein Schleifenfeldname für die Schleife angegeben");
}
if (getSchleifenrelation() == null && getSchleifenfeldname() != null) {
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Bei der Maske " + getId()
+ " ist in makro_masken_bez keine Schleifenrelation für die Schleife");
}
setAktion(singleSubMaskRow.get(6));
setSortNr(Integer.valueOf(singleSubMaskRow.get(7).toString()));
initFromMaskeninfo();
this.sharedData = sharedData;
individualFields.addAll(readFelderFromDb(user));
initSubMasken(user);
}
public void setThemenbaumParent(Integer themenbaumParent)
{
this.themenbaumParent=themenbaumParent;
}
private Integer getThemenbaumParent() {
return themenbaumParent;
}
public String getAktion() {
if (aktion == null || aktion.toString().trim().equals("")) this.aktion = "SHOWTABLE";
return aktion;
}
public void setAktion(Object aktion) {
if (aktion == null || aktion.toString().trim().equals(""))
this.aktion = "SHOWTABLE";
else
this.aktion = aktion.toString().toUpperCase();
}
/**
* Schleifenfeldname
*
* @return null wenn nicht in Benutzung
*/
private String getSchleifenfeldname() {
return schleifenfeldname;
}
private void setSchleifenfeldname(Object schleifenfeldname) {
if (schleifenfeldname == null || schleifenfeldname.toString().trim().equals(""))
this.schleifenfeldname = null;
else
this.schleifenfeldname = schleifenfeldname.toString();
}
/**
* schleifenrelation
*
* @return null wenn nicht in Benutzung
*/
private String getSchleifenrelation() {
return schleifenrelation;
}
public Collection getTmpFiles() {
return sharedData.getGraphicFiles();
}
private void setSchleifenrelation(Object schleifenrelation) {
if (schleifenrelation == null || schleifenrelation.toString().trim().equals(""))
this.schleifenrelation = null;
else
this.schleifenrelation = schleifenrelation.toString();
}
public String getDesiredContenttype() {
return desiredContenttype;
}
public void setDesiredContenttype(String desiredContenttype) {
this.desiredContenttype = desiredContenttype;
}
/**
* Die eigenen Felder einlesen und hinzufügen in initSubMasken werden ggfs.
* aus übergeordneten Masken Felder rübergeholt
*
* @return
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws SQLException
* @throws DBServletException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
public NamedIdObjectList readFelderFromDb(SxUser user) throws TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, IOException, SQLException,
DBServletException, NoMainEntryException {
if (getId() == null) throw new IllegalStateException("Kann keine Maske ohne tid vorbereiten");
NamedIdObjectList felder = new NamedIdObjectList();
String query = "select F.tid, F.name, F.nummer, F.x, F.y, F.buttonbreite, " + "F.feldbreite, F.zeilenanzahl, F.typ, F.laenge, "
+ "F.obligatorisch, F.art, F.relation, F.attribut, F.defaultwert, M.name as Maskenname " + "from felderinfo F, masken_felder_bez B, maskeninfo M "
+ "where F.art!=999 and B.maskeninfo_id = " + getId() + " and M.tid = " + getId() + " and F.tid = B.felderinfo_id " + "order by F.nummer;";
SxResultSet felderset = ServletUtils.execute("Einlesen der Felder für Maske " + getId(), query, mandantenID);
String sql = "select field_name,locale,contents_short, contents_long " + " from sx_captions " + " where table_name='felderinfo' "
+ " and field_name in (select name from felderinfo where tid in (select felderinfo_id from masken_felder_bez where maskeninfo_id=" + getId() + "))"
+ " and (record_no is null OR record_no in (select felderinfo_id from masken_felder_bez where maskeninfo_id=" + getId() + "))" + " and (locale ='"
+ locale.getLanguage() + "' or locale is null or locale='' or locale='de')" + " order by record_no DESC";
SxResultSet captionSet = ServletUtils.execute("Einlesen der Captions für Maske " + getId(), sql, mandantenID);
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
for (Iterator it = felderset.iterator(); it.hasNext();) {
SxResultRow feldRow = (SxResultRow) it.next();
// individualFields ist beim initialen erstellen des Feldes noch leer, weshalb z.B. keine Sichtgruppen erstellt werden
Field feld = new Field(mandantenID, user, ((Integer) this.getId()), feldRow, locale, individualFields.getFormular(), map, individualFields, captionSet);
logger.debug("ADD FIELD " + feld.getName());
felder.add(feld);
}
return felder;
}
private void loadFieldsFromRequest(HttpServletRequest request)
{
// nur für bekannte Felder #279826
for (Enumeration en = request.getParameterNames(); en != null && en.hasMoreElements();) {
String name = (String) en.nextElement();
if (individualFields.containsField(name)) {
ServletUtils.addParamToFormular(request, individualFields.getFormular(), name);
}
}
}
public void setFieldDefaults(SxUser user, HttpServletRequest request, boolean isCalledByTableServlet)
throws ParseException, SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException,
UngueltigeEingabeException, TransformerException, NoMainEntryException, InvalidDataTypeException {
this.setFieldDefaults(user, request, null, isCalledByTableServlet);
}
/**
* Wenn für Felder Defaults im Request hinterlegt sind, werden diese
* eingetragen, ansonsten wird der in der DB ggfs. hinterlegt Defaultwert
* genommen
* isCalledByTableServlet - wenn von TabellenServlet aufgerufen und Leerstring als Param
* (= von SuperXmlMaske kommend oder tid=123&abc= im Request ->
* Leerparam hat Vorrang vor DB-Defaultwerten)
* @param request
* @throws ParseException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws UngültigeEingabeException
* @throws TransformerException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*/
public void setFieldDefaults(SxUser user, HttpServletRequest request, Map params, boolean isCalledByTableServlet)
throws ParseException, SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException,
UngueltigeEingabeException, TransformerException, NoMainEntryException, InvalidDataTypeException {
// für ein Feld müsste auch über request parameter gewünschte Sicht &
// Stand einstellbar sein
// sichtParamSetzen(request, "Organigramm","10");
Hashtable formular = individualFields.getFormular();
// default, wird ggfs. von request überschrieben
formular.put("erlaubt", "0");
sharedData.getFormular().put("erlaubt", "0");
standParamSetzen("Organigramm", DateUtils.getTodayString());
formular.put("UserID", user.getId());
formular.put(USER_ROLE_PLACEHOLDER, user.getRole());
formular.put(USER_ROLE_ID_PLACEHOLDER, user.getRoleId());
// remove if 'null': behaves as if 'unset' in Freemarker and homebrew variable replacement
formular.remove(USER_HISINONE_ORGUNIT_LID_PLACEHOLDER);
formular.put(USER_HISINONE_ORGUNIT_LID_PLACEHOLDER, user.getHisInOneOrgUnitLidOfRole());
formular.put("system_version", "SuperX");
String h1version = System.getProperty(SuperXManager.SUPER_X_HISINONE_VERSION);
if (h1version != null) {
formular.put("system_version", h1version);
}
String his1_refapp = SuperXManager.his1_refapp;
if (his1_refapp != null) {
formular.put("his1_refapp", his1_refapp);
}
// Elemente aus dem request zum Formular hinzufügen
// wichtig für Querabhängigkeiten
if (request != null) {
loadFieldsFromRequest(request);
}
// Werte ggfs. trimmen
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field aField = (Field) it.next();
String fieldName = aField.getName();
String param = (String) formular.get(fieldName);
if (param != null && param.length() > 30 && param.length() > aField.getLaenge()) {
String shortparam = StringUtils.trimLength(param, Math.max(30, aField.getLaenge()));
Logger.getLogger("superx_" + mandantenID).log(Level.WARN,
"Parameter für Feld " + fieldName + " (" + aField.getId() + ") wird gekürzt auf angegebene Länge "
+ aField.getLaenge() + " Zeichen:" + shortparam + " \nwar:" + param);
formular.put(fieldName, shortparam);
}
//Hier soll vermutl. für jeden Aufruf FieldID hinterlegt werden, nicht nur bei Feldart0 und gesetztem Defaultwert
String fieldId = String.valueOf(aField.getId());
formular.put("FieldID", fieldId);
if (aField.getArt()== Art.id_0_nur_Text_direkte_Eingabe && aField.getDefaultwertString()!=null)
{
aField.updateDefaultValue(formular, map, individualFields, param, false, user);
formular.put(fieldName, aField.getDefaultValueEscaped());
}
// System.out.println("test:"+aField.getName());
if (aField.isOldOrganigrammArt() || aField.isSicht()) {
setFeldStand(fieldName, ServletHelper.getParameterString(request, fieldName + PARAM_STAND_PREFIX), user);
setSelectedFeldSicht(fieldName, ServletHelper.getParameterString(request, fieldName + PARAM_SICHT_PREFIX), user);
}
// MB ggfs. trennzeichen umformen
if (aField.getZeilenanzahl() > 1) {
// TODO: Definition für Startreihenfolge
if (param != null && (param.indexOf(",") > -1 || param.indexOf("|") > -1)) {
formular.put(fieldName, aField.getParamAdaptedEscaped(param));
}
}
}
logger.debug("*** ITERATING INDIVIDUALFIELDS ***");
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field aField = (Field) it.next();
logger.debug("FIELD: " + aField.getName());
// Um Werte von html-Listboxen und checkboxen einzulesen
String[] fw = request != null ? request.getParameterValues(aField.getName()) : null;
//wenn Parameter übergeben wurde per Maske ist param gefüllt mit Leerstring
//wenn URL übergeben wird ohne Parameter abc ist, param null
//
String param = "";
if (fw != null) {
for (int i = 0; i < fw.length; i++) {
if (StringUtils.containsTags(fw[i])) throw new IllegalArgumentException("Parameter für " + aField.getName() + " enthält unerlaubte Tags");
String nextParameterValue = fw[i] != null ? fw[i].trim() : "";
if (i < fw.length - 1)
param += nextParameterValue + ",";
else
param += nextParameterValue;
}
} else if (params != null && params.containsKey(aField.getName())) {
param = (String) params.get(aField.getName());
}
// Schutz vor Sql-Injection aber nur, wenn mehr param mehr als ";" enthält!
if (param.length() > 1) {
param = param.replace(';', '^');
}
// alt String param = request.getParameter(aField.getName());
// falls noch nötig werden auch selectionElements initialisiert
// Art 0 könnte neues Einlesen nötig machen
// Beispiel: Datumseingabe manuell Jahr geändert, Kapitel direkt
// eingegeben
if (aField.isDynamic() && this.hasArt0Fields()) {
for (Iterator itr = individualFields.iterator(); itr.hasNext();) {
Field f = (Field) itr.next();
if (f.getArt() == Art.id_0_nur_Text_direkte_Eingabe && aField.getRelation() != null && aField.getRelation().indexOf("<<" + f.getName() + ">>") > -1) {
aField.setInited(false);
break;
}
}
}
HashMap map = new HashMap();
String fieldId = String.valueOf(aField.getId());
formular.put("FieldID", fieldId);
map.putAll(user.getBasicMap());
boolean isTableServletAndEmptyStringParam = isCalledByTableServlet && request.getParameter(aField.getName()) != null
&& request.getParameter(aField.getName()).equals("");
aField.updateDefaultValue(formular, map, individualFields, param, isTableServletAndEmptyStringParam, user); // damit
// initSelectionTree
// auf jeden
// Fall gelaufen
// ist
// wenn maskenparameter angegeben sind, z.B. aus Lesezeichen,
// selectionbuffer ignorieren
int paramcount = params != null ? params.size() : 0;
Enumeration en = request != null ? request.getParameterNames() : null;
while (en != null && en.hasMoreElements()) {
String name = (String) en.nextElement();
if (name.equals("tid") || name.equals("cachingcontrol") || name.equals("navi") || name.equals("themenbaumparent")) continue;
paramcount++;
}
SelectionBuffer sb = user.getSelectionBuffer();
boolean isMehrfachAuswahl = aField.isMehrfachAuswahl(sb.getFieldDefault(aField.getName()));
// wenn ein Feldparameter z.B. aus Lesezeichen gefunden wird, hat
// der Vorrang
// wenn es einen Eintrag für das Feld gibt und der auch in der
// Auswahlliste des Felds vorkommt wird gearbeitet
if (paramcount == 0 && !aField.isHidden() && (request == null || request.getParameter(aField.getName()) == null) && sb.getFieldDefault(aField.getName()) != null
&& !sb.getFieldDefault(aField.getName()).equals("") && aField.hasKeys(isMehrfachAuswahl, sb.getFieldDefault(aField.getName()))) {
// bei Mehrfachauswahl nur wenn das Zielfeld auch zeilenzahl>1
// hat
if (!isMehrfachAuswahl || aField.getZeilenanzahl() > 1) {
{
aField.updateDefaultValue(formular, map, individualFields, sb.getFieldDefault(aField.getName()), false, user);
}
}
}
formular.put(aField.getName(), aField.getDefaultValueEscaped());
}
// MB 8/2011
setFieldsDefaultSichten(user, request);
}
/**
* Bei obligatorischen Kostenstellenfeldern bei denen keine Auswahl möglich
* ist, Fehlermeldung ausgeben
*
* @throws SQLException
*/
public void kostenstellenSichtAufAuswahlPruefen() throws SQLException {
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field aField = (Field) it.next();
if (aField.isObligatorisch() && aField.isSicht() && (aField.getSichtgruppe().getSelectedSicht().getArt().indexOf("Kostenstelle") > -1
|| aField.getSichtgruppe().getSelectedSicht().getArt().indexOf("Organigramm") > -1)) {
if (aField.getSichtgruppe().getSelectedSicht().isNoSelectionPossible())
throw new SQLException("Feld " + aField.getName() + " bei der Sicht " + aField.getSichtgruppe().getSelectedSicht().getName() + " (Art: "
+ aField.getSichtgruppe().getSelectedSicht().getArt() + ") enthält keine Elemente");
}
}
}
public void setLocale(Locale newlocale) throws SQLException, DBServletException {
if (locale == null || !(locale.equals(newlocale))) {
this.locale = newlocale;
individualFields.getFormular().put("locale", locale.getLanguage());
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
f.setLocale(locale);
}
for (Iterator it = sharedData.getFields().iterator(); it.hasNext();) {
Field f = (Field) it.next();
f.setLocale(locale);
}
}
}
/**
* Liest falls vorhanden Submasken ein.
*
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws SQLException
* @throws DBServletException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*
*/
private void initSubMasken(SxUser user) throws TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, IOException, SQLException,
DBServletException, NoMainEntryException {
String query = "select A.name,M.maskeninfo_id2, M.schleifenrelation,M.schleifenfeldname,M.schleifenfstand,M.schleifenfsicht,M.aktion,M.sortnr "
+ "from macro_masken_bez M, maskeninfo A " + "where M.active=1 and M.maskeninfo_id2 = A.tid and M.maskeninfo_id1 = " + getId() + " order by M.sortnr;";
SxResultSet submaskenrs = ServletUtils.execute("Suche möglicher Submasken in makro_masken_bez", query, mandantenID);
if (submaskenrs.size() > 0) {
sharedData.addUniqueFields(individualFields);
}
for (Iterator it = submaskenrs.iterator(); it.hasNext();) {
SxResultRow singleSubMaskRow = (SxResultRow) it.next();
Maske m = new Maske(mandantenID, user, sharedData, singleSubMaskRow, locale);
m.isMakroSubMaske = true;
if (SxPools.get(mandantenID).hasMakroFieldSelection(this.getId(), m.getSortNr())) {
SxPools.get(mandantenID).applyMacroFieldSelectionTo(this.getId(), m, sharedData.getFormular(), map, individualFields, user);
}
m.setMaxOffset(MACRO_MAX_OFFSET);
submaskenListe.add(m);
}
if (this.isMakro()) {
this.setMaxOffset(MACRO_MAX_OFFSET);
isResultReuseFeatureWanted = true;
}
}
public boolean isMakro() {
return submaskenListe.size() > 0;
}
private void initFromMaskeninfo() throws DBServletException, SQLException {
if (getId() == null) throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Kann keine Maske ohne tid vorbereiten");
SxResultSet masksRs = ServletUtils.execute("Lesen aus Maskeninfo für Maske " + getId(), String.format(QUERY_MASKENINFO, getId()), mandantenID);
if (masksRs.size() == 0) {
throw new SQLException("Die Maske ist derzeit nicht benutzbar. Fehlende Angaben in Tabellen maskeninfo,maske_system_bez oder systeminfo für Maske " + getId());
} else if (masksRs.size() > 1) {
throw new SQLException("Mehr als ein Eintrag für Maske " + getId() + " in Tabelle maskeninfo!");
}
SxResultRow maskRow = masksRs.first();
setName(SqlStringUtils.getValueAsString(maskRow.get(1)));
String tmp_select_stmt = "" + SqlStringUtils.getValueAsString(maskRow.get(2));
tmp_select_stmt=tmp_select_stmt.replaceAll("<<Maskennummer>>", this.getId().toString());
String tmp_xil = "" + SqlStringUtils.getValueAsString(maskRow.get(3));
tmp_xil=tmp_xil.replaceAll("<<Maskennummer>>", this.getId().toString());
String tmp_cleanup = "" + SqlStringUtils.getValueAsString(maskRow.get(4));
tmp_cleanup=tmp_cleanup.replaceAll("<<Maskennummer>>", this.getId().toString());
if (tmp_select_stmt.indexOf("<sximport type=\"select_stmt,cleanup,xil_proplist\">") > -1) {
int sourceMask = getTmpMaskNr(tmp_select_stmt);
tmp_select_stmt = "<sximport>select select_stmt from maskeninfo where tid=" + sourceMask+"</sximport>";
tmp_cleanup = "<sximport>select cleanup_stmt from maskeninfo where tid=" + sourceMask+"</sximport>";
tmp_xil = "<sximport>select xil_proplist from maskeninfo where tid=" + sourceMask+"</sximport>";
}
select_stmt = SxPools.get(mandantenID).checkImports(tmp_select_stmt);
xilString = SxPools.get(mandantenID).checkImports(tmp_xil);
cleanup_stmt = SxPools.get(mandantenID).checkImports(tmp_cleanup);
standString = SqlStringUtils.getValueAsString(maskRow.get(7));
standStringDT = SqlStringUtils.getValueAsString(maskRow.get(12));
if(!standStringDT.isEmpty()) {
standStringDT = findoutUpdate(maskRow.get(7),maskRow.get(12));
}
chartx = SqlStringUtils.getValueAsString(maskRow.get(8));
charty = SqlStringUtils.getValueAsString(maskRow.get(9));
explanation = SqlStringUtils.getValueAsString(maskRow.get(10));
setHinweis(SqlStringUtils.getValueAsString(maskRow.get(11)));
setHinweisCaption(getHinweis());
}
private int getTmpMaskNr(String input) {
int result = -1;
int posStart = input.indexOf("<sximport type=\"select_stmt,cleanup,xil_proplist\">");
int posEnde = input.indexOf("</sximport>");
if (posEnde == -1)
throw new IllegalArgumentException("Tag sximport nicht ordentlich geschlossen");
String part = input.substring(posStart + 50, posEnde - posStart);
try {
result = Integer.parseInt(part.trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Ungültige Maskennummer " + part + " bei sximport");
}
return result;
}
public String findoutUpdate(Object standHlr, Object standIncr) {
String f_wertHlr = "";
String f_wertIncr = "";
String f_wertIncrCut = "";
boolean comp = true;
if ((standHlr instanceof java.sql.Date) && (standIncr instanceof java.sql.Timestamp) ) {
f_wertHlr = "" + DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY).format(standHlr);
f_wertIncr = "" + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.GERMANY).format(standIncr);
// f_wertIncr - abschneiden:
int l1 = f_wertHlr.length();
f_wertIncrCut = f_wertIncr.substring(0, l1);
try {
comp = DateUtils.compareDates(f_wertHlr, f_wertIncrCut);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (comp==false) {f_wertIncr = "";
}
}
return f_wertIncr;
}
public String getCharty() {
return charty;
}
public void setCharty(String charty) {
this.charty = charty;
}
public String getChartx() {
return chartx;
}
public String getCleanup_stmt() {
return cleanup_stmt;
}
public String getSelect_stmt() {
return select_stmt;
}
public String getStandString() {
return standString;
}
public String getStandStringDT() {
return standStringDT;
}
public String getXilString() {
return xilString;
}
public String getHinweis() {
return hinweis;
}
public void setSelectedMaskStylesheetFile(String filename) {
this.selectedMaskStylesheetFile = filename;
}
public String getSelectedMaskStylesheetFile() {
return selectedMaskStylesheetFile;
}
private void initMaskStylesheets() throws SQLException, DBServletException {
String query = "select t1.filename, t1.caption, t1.description, " + " t1.contenttype, t0.ord, t1.is_generic,"
+" t1.toolbar_icon_filepath, t1.jr_datasource, t1.usage_resultset_data, t1.stylesheet_type from sx_mask_style t0, sx_stylesheets t1"
+ " where (t0.stylesheet_id=t1.tid) and (t1.relation ='mask') and" + " (t0.maskeninfo_id =" + getId() + ")"
+ " and (t1.useragent = '' or t1.useragent is null or t1.useragent = '" + browser + "')" + " order by t0.ord;";
SxResultSet stylesheetsRs = ServletUtils.execute("Einlesen der Stylesheets für die Maske " + getId(), query, mandantenID);
if (stylesheetsRs.size() > 0) {
SxResultRow stylesheetRow = (SxResultRow) stylesheetsRs.first();
// Wenn kein Stylesheet definiert ist, dann wird das
// erste als Default genommen
// hier müssten eigentlich alle stylesheets zur Liste
// hinzugefügt werden
Stylesheet s = new Stylesheet(stylesheetRow);
maskStylesheetList.add(s);
if (selectedMaskStylesheetFile == null) selectedMaskStylesheetFile = s.getFilename();
} else {
selectedMaskStylesheetFile = SuperXManager.defaultMaskXsl;
}
}
private void initTableStylesheets() throws SQLException, DBServletException {
String sql = getQueryTableStylesheets();
SxResultSet stylesheetsRs = ServletUtils.execute("Einlesen der Stylesheets für die Tabellen der Maske " + getId(), sql, mandantenID);
for( SxResultRow stylesheetRow : stylesheetsRs ) {
Stylesheet s = new Stylesheet(stylesheetRow);
tableStylesheetList.add(s);
}
// Wenn ein Stylesheet definiert ist, dann wird das
// erste als Default genommen
if (selectedTableStylesheet == null && tableStylesheetList.size() > 0) {
selectedTableStylesheet = tableStylesheetList.get(0);
}
}
public String getQueryTableStylesheets() {
return String.format(QUERY_STYLESHEETS, getId(), this.browser, getId());
}
/**
* selectedTableStheet zurücksetzen neu 5/06
*
*/
public void resetTableStylesheet() {
selectedTableStylesheet = null;
if (tableStylesheetList.size() > 0) {
Stylesheet s = (Stylesheet) tableStylesheetList.get(0);
selectedTableStylesheet = s;
}
}
public List<Stylesheet> getTableStyleSheets() {
return (List<Stylesheet>) this.tableStylesheetList;
}
private StringBuffer getStylesheetXml() {
StringBuffer result = new StringBuffer();
if (tableStylesheetList.size() > 0) {
result.append("<stylesheets>\n");
for (Iterator it = tableStylesheetList.iterator(); it.hasNext();) {
Stylesheet stylesheet = (Stylesheet) it.next();
result.append(stylesheet.toXml());
}
result.append("</stylesheets>\n");
}
return result;
}
public String getMaskHtml(SxUser user, boolean showNavigation) throws TransformerConfigurationException, TransformerException, DBServletException {
// wenn maske neue aufgebaut wird
resetTableStylesheet();
if (maskHtml == null)
prepareHtml(user, showNavigation);
else {
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, " " + getMaskInfo() + " benutze HTML-Vorlage (XSL-Transformation nicht nötig)");
}
String result = maskHtml;
result = result.replaceAll("_USERID_", user.getId().toString());
result = result.replaceAll("_USER_IS_ADMIN_", (user.isAdmin() ? "true" : "false"));
return result.replaceAll("_HISINONE_", SuperXManager.his1_refapp);
}
/**
* von SuperXmlMaske und Entwicklungsservlet aufgerufen, wenn Masken-XML
* angezeigt werden soll
*
* @param user
* @param showNavigation
* @return
* @throws TransformerConfigurationException
* @throws TransformerException
* @throws DBServletException
*/
public String getMaskXml(SxUser user, boolean showNavigation) throws TransformerConfigurationException, TransformerException, DBServletException {
// wenn maske neue aufgebaut wird
resetTableStylesheet();
String result = prepareXml(user, true, showNavigation).toString();
result = result.replaceAll("_USERID_", user.getId().toString());
result = result.replaceAll("_USER_IS_ADMIN_", (user.isAdmin() ? "true" : "false"));
if (!KDSF_EXPORT_MASK_ID.equals(getId().toString())) {
result = XMLUtils.removeTroublesomeCharacters(result);
}
return result;
}
private StringBuffer prepareXml(SxUser user, boolean isFullXMLRequired, boolean showNavigation) throws DBServletException {
int rownr = 0;
Logger.getLogger("superx_" + mandantenID + "_xml").log(Level.DEBUG, "baue XML auf für " + getMaskInfo() + " fullXMLRequired:" + isFullXMLRequired);
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, "baue XML auf für " + getMaskInfo() + " fullXMLRequired:" + isFullXMLRequired);
StringBuffer result = new StringBuffer("<?xml version=\"1.0\" encoding=\"" + SqlStringUtils.getEncoding() + "\" ?>\n" + "<maske tid=\"" + getId() + "\" name=\"" + getName()
+ "\" helpcontext=\"@@doku_url@@@@doku_" + getId() + "_mask_url@@\" sortnr=\"" + getSortNr() + "\"" + " datum=\""
+ DateUtils.getTodayString() + "\" MandantenID=\"" + mandantenID + "\" hisinone_active=\""
+ (SuperXManager.isHis1() ? "true" : "false") + "\" " + "hisinone_refapp=\"" + SuperXManager.his1_refapp + "\" showNavigation=\""
+ showNavigation + "\" >\n");
result.append("<user id=\"" + user.getId() + "\" admin=\"" + (user.isAdmin() ? "true" : "false") + "\"><![CDATA[" + user.getName() + "]]></user>\n");
// for historic reasons
result.append("<UserID admin=\"" + (user.isAdmin() ? "true" : "false") + "\">" + user.getId().toString() + "</UserID>\n");
result.append(addGeneralInfo());
if (user != null) {
result.append(user.getThemenbaum().getMenupath(this.getThemenbaumParent(),this.getId().toString()));
if (showNavigation) {
result.append(user.getThemenbaum().toXml(locale));
}
}
result.append("<felder>");
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field feld = (Field) it.next();
List<String> dependentOnFields=getDependentOnFields(feld);
if (feld.getY() == 0) rownr++;
result.append(FieldXmlEncoder.toXml(feld, isFullXMLRequired, rownr,dependentOnFields));
}
result.append("<rownr>" + rownr + "</rownr></felder>\n");
// derzeit wird nur das erste Stylesheet zur Liste hinzugefügt
for (Iterator it = maskStylesheetList.iterator(); it.hasNext();) {
Stylesheet aStylesheet = (Stylesheet) it.next();
result.append(aStylesheet.toXml());
}
result.append("</maske>\n");
Logger.getLogger("superx_" + mandantenID + "_xml").log(Level.DEBUG, result.toString());
SuperXManager.setLastXml(result.toString());
SuperXManager.setLastXmlMandantid(mandantenID);
return result;
}
/* Feldabhängigkeiten pro Maske abfragen, also ob ein Maskenfeld in der Spalte "relation"
* auf ein anderes Maskenfeld verweist.
* Wird nachher im XML-Strom im Element <dependentOn> abgelegt */
private List<String> getDependentOnFields(Field fld)
{
List<String> dependentOnFields = new ArrayList();
String relation=fld.getRelation();
if(relation !=null) {
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field feld = (Field) it.next();
if(relation.indexOf("<<"+feld.getName()+">>")>-1)
{
dependentOnFields.add(feld.getName());
}
}
}
return dependentOnFields;
}
/**
* Bereitet aus der Maske in XML-Format einen HTML-String vor, der
* zurückgeliefert werden kann. Oder aktualisiert diesen.
*
* @throws TransformerException
* @throws DBServletException
* @throws TransformerConfigurationException
*/
private void prepareHtml(SxUser user, boolean showNavigation) throws TransformerException, TransformerConfigurationException, DBServletException {
String stylesheet = "file:///" + ServletUtils.getPath() + File.separatorChar + selectedMaskStylesheetFile;
boolean isFullXMLRequired = TransletCache.isFullXMLRequired(stylesheet);
StringBuffer result = prepareXml(user, isFullXMLRequired, showNavigation);
TimeUtils t = new TimeUtils();
Transformer transformer = TransletCache.getTransformer(mandantenID, stylesheet);
transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "html");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "no");
StringWriter erg = new StringWriter();
transformer.transform(new StreamSource(new StringReader(result.toString())), new StreamResult(erg));
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, " " + getMaskInfo() + " XSL-Transformation der Maske (mittels Translet) dauerte " + t.getSinceStart());
maskHtml = erg.toString();
}
public String getMaskInfo() {
return getName() + " (" + getId() + (getSortNr() != null ? " sortnr=" + getSortNr() : "") + ")";
}
public String runQuery(SxUser user, HttpServletRequest request, Connection dbCon) throws TemplateException, IOException, SQLException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TransformerConfigurationException, ObligatoryFieldEmptyException, ParseException, InvalidKeyException,
TransformerException, DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException {
return this.runQuery(user, request, dbCon, null);
}
/**
* Parameter für colset/colsort werden in executeQuery ausgelesen und
* gesetzt
*
* @param user
* @param request
* @param dbCon - wohl nur von SuperXmlTabelle.CSVUploadHelper genutzt
* @return
* @throws TemplateException
* @throws IOException
* @throws SQLException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws TransformerConfigurationException
* @throws ObligatoryFieldEmptyException
* @throws ParseException
* @throws InvalidKeyException
* @throws TransformerException
* @throws DBServletException
* @throws UngültigeEingabeException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*/
public String runQuery(SxUser user, HttpServletRequest request, Connection dbCon, Map params) throws TemplateException, IOException, SQLException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TransformerConfigurationException, ObligatoryFieldEmptyException, ParseException, InvalidKeyException,
TransformerException, DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException {
if (isMakro() && isReuseResult()) {
SuperXManager.logActivity(Level.INFO, " Makro-Abfrage " + getMaskInfo() + " liefere gecachtes Ergebnis");
if (lastXmlResult == null || lastXmlResult.toString().trim().equals("")) {
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Parameter reuseresult wurde übergeben, es wurde aber kein gecachter XML im Maskenobjekt (runQuery,lastXmlResult) gefunden");
}
return lastXmlResult.toString();
}
// Parameter für colset/colsort werden in executeQuery ausgelesen und
// gesetzt
SuperXManager.logActivity(Level.INFO, "Anforderung: Abfrage " + getMaskInfo());
individualFields.getFormular().put("UserID", user.getId().toString());
sharedData.getFormular().put("UserID", user.getId());
sharedData.setErgebnisOrdNr(0);
sharedData.setErgebnisElementOrdNr(0);
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
if (!isReuseResult()) {
String keyfieldsused = ServletHelper.getParameter(request, RequestParameter.keyfieldsused);
if (EqualsUtil.areEqual(keyfieldsused, "true")) {
// ajax-log
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field aField = (Field) it.next();
if (aField.getArt() != Art.id_0_nur_Text_direkte_Eingabe && !aField.isSicht() && aField.isDynamic()) aField.setInited(false);
// für Sichten gibt's keine Querabhängigkeiten, müssen aber
// initialisiert sein
// Problem: bei Schlüsseleingabe für Kostenstellen klappte
// nicht
// auch Definition von kst_sql für Fin-Rechte klappte nicht,
// da Sichtfeld Kostenstelle nicht initialisiert
if (aField.isSicht()) {
aField.initIfNeeded(individualFields.getFormular(), map, individualFields, user);
setFeldStand(aField.getName(), ServletHelper.getParameterString(request, aField.getName() + PARAM_STAND_PREFIX), user);
setSelectedFeldSicht(aField.getName(), ServletHelper.getParameterString(request, aField.getName() + PARAM_SICHT_PREFIX), user);
}
}
}
setFieldDefaults(user, request, params, true);
// also sets tablestylesheets, desiredContenttype
setFieldSelections(user, request);
// MB 1/2016 dynamsische Sichten updaten
boolean dynamicSichtFound = false;
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
if (f.isSicht() && f.getSichtgruppe().hasDynamicSicht()) {
dynamicSichtFound = true;
updateDynamicSichten(f, user);
}
}
//muss nochmal gemacht werden, weil dynamische Sichten Baum neu aufbauen,
//dass selection gesetzt wird
if (dynamicSichtFound) setFieldSelections(user, request);
}
String naviParam = ServletHelper.getParameter(request, RequestParameter.navi);
if (naviParam == null && multipartData != null) {
naviParam = ServletUtils.getParamValue(multipartData, "navi");
}
boolean showNavigation = naviParam != null && !naviParam.isEmpty() ? Boolean.parseBoolean(naviParam) : this.navi;
boolean fixed_columns_aktiv=false;
if (SxPools.get(mandantenID).getRepository().containsKey("K_fixed_columns_aktiv")&&SxPools.get(mandantenID).getRepository().get("K_fixed_columns_aktiv").toString().equals("1"))
{
fixed_columns_aktiv=true;
}
StringBuffer result = new StringBuffer("<?xml version=\"1.0\" encoding=\"" + SqlStringUtils.getEncoding() + "\"?>\n<ergebnisse MandantenID=\"" + mandantenID
+ "\" datum=\"" + DateUtils.getTodayString() + "\" zeit=\""
+ DateUtils.getNowString() + "\" isMakro=\"" + (isMakro() ? "true" : "false") + "\" " + "hisinone_active=\""
+ (SuperXManager.isHis1() ? "true" : "false") + "\" " + "hisinone_refapp=\"" + SuperXManager.his1_refapp + "\" showNavigation=\""
+ showNavigation + "\" fixed_columns_aktiv=\""+(fixed_columns_aktiv?"true":"false")+"\" > \n");
if (isMakro()) result.append("<makro id=\"" + this.getId() + "\">\n<name>" + this.getName() + "</name>\n</makro>\n");
result.append("<user id=\"" + user.getId() + "\" admin=\"" + (user.isAdmin() ? "true" : "false") + "\"><![CDATA[" + user.getName() + "]]></user>\n");
// for historic reasons
result.append("<userID admin=\"" + (user.isAdmin() ? "true" : "false") + "\">" + user.getId() + "</userID>\n");
if (user != null) {
result.append(user.getThemenbaum().getMenupath(this.getThemenbaumParent(),this.getId().toString()));
if (showNavigation) {
result.append(user.getThemenbaum().toXml(locale));
}
}
// link back to home page
addBacklink(request, result);
result.append(addGeneralInfo());
result.append(getStylesheetXml());
result.append(getMaskResult(user, request, dbCon));
result.append("</ergebnisse>\n");
String resultstr;
if (KDSF_EXPORT_MASK_ID.equals(getId().toString())) {
resultstr = result.toString();
} else {
resultstr = XMLUtils.removeTroublesomeCharacters(result);
}
lastXmlResult = new StringBuffer(resultstr);
return resultstr;
}
// MB 17.8.2011 Defaultsicht setzen falls gewünscht
public void setFieldsDefaultSichten(SxUser user, HttpServletRequest request) throws SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException,
SichtException, TemplateException, IOException, NoMainEntryException {
Hashtable formular = individualFields.getFormular();
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field aField = (Field) it.next();
if (aField.isSicht() && aField.hasDynamicDefaultSicht()) aField.setDefaultSicht(formular, map, individualFields, user);
}
}
/**
* General info replaced by sxcaptions
*
* @return
*/
public static String addGeneralInfo() {
String info = "<generalinfo>\n" + "<REPORT_HEADING_INSTITUTION><![CDATA[@@REPORT_HEADING_INSTITUTION@@]]></REPORT_HEADING_INSTITUTION> \n"
+ "<REPORT_HEADING_URL><![CDATA[@@REPORT_HEADING_URL@@]]></REPORT_HEADING_URL> \n"
+ "<REPORT_LOGO_FILE><![CDATA[@@REPORT_LOGO_FILE@@]]></REPORT_LOGO_FILE> \n"
+ "<REPORT_HEADING_ADRESS><![CDATA[@@@REPORT_HEADING_ADRESS@@@]]></REPORT_HEADING_ADRESS> \n" + "<REPORT_EMAIL><![CDATA[@@REPORT_EMAIL@@]]></REPORT_EMAIL> \n"
+ "<REPORT_DOCUMENTATION_URL><![CDATA[@@REPORT_DOCUMENTATION_URL@@]]></REPORT_DOCUMENTATION_URL>" + "</generalinfo>\n";
return info;
}
private void setColsort(String colsort) {
if (colsort != null && !colsort.trim().equals("")) {
if (colsort.equalsIgnoreCase("restore")) colsort = null;
this.colsort = colsort;
result_el.setColsort(colsort);
}
}
public SuperX_el getResult_el() {
return result_el;
}
/**
* Interpretiert auch "restore" als zurücksetzen
*
* @param param
*/
private void setColset(String param) {
if (param != null && !param.trim().equals("")) {
if (this.isMakro())
throw new IllegalArgumentException("Die Maske ist derzeit nicht benutzbar." + getMaskInfo() + " ist ein Makro - definieren von colset " + param + " nicht möglich");
if (param.trim().equalsIgnoreCase("restore"))
colset = null;
else
colset = param;
}
}
public String getColset() {
return colset;
}
/**
* Returns the field selections in XML form.
*
* @param user
* @return
* @throws ParseException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
private String getXmlFieldSelection(SxUser user) throws ParseException, SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException,
TemplateException, IOException, NoMainEntryException {
StringBuffer result = new StringBuffer("<felder>\n");
StringBuffer completeFields = new StringBuffer("<completefields>\n");
HashMap map1 = new HashMap();
map1.putAll(user.getBasicMap());
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field feld = (Field) it.next();
if (feld.shouldBeAddedToLegend()) {
try {
result.append(feld.getSelectedKeyXml(individualFields.getFormular(), map1, individualFields, user));
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new RuntimeException("Maske " + getMaskInfo() + " hatte im Feld " + feld.getName() + " (" + feld.getId() + ") einen ungültigen key.\n" + e);
}
}
completeFields.append("<feld varname=\"" + feld.getName() + "\" art=\"" + feld.getArt().getIntValue() + "\">" + feld.getValueXml() + "<caption_short><![CDATA["
+ feld.getCaptionShort() + "]]></caption_short>" + "<caption_long><![CDATA[" + feld.getCaptionLong() + "]]></caption_long>" + "</feld>\n");
}
// TODO: caption_long etc. rein
result.append("</felder>\n");
completeFields.append("</completefields>");
result.append(completeFields);
return result.toString();
}
/**
* Setzt den selectedKey eintrag in den einzelnen feldern und fügt die
* ausgewählten Werte dem formular hinzu, das für generateSQL benutzt wird
* von runQuery also bei einem Makro der Hauptmaske aufgerufen
*
* @param request
* @throws ObligatoryFieldEmptyException
* @throws ParseException
* @throws InvalidKeyException
* @throws TransformerException
* @throws DBServletException
* @throws CloneNotSupportedException
* @throws KeyParentEqualException
* @throws SQLException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*/
private void setFieldSelections(SxUser user, HttpServletRequest request)
throws ObligatoryFieldEmptyException, ParseException, InvalidKeyException, TransformerException, SQLException, DBServletException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException, InvalidDataTypeException {
// default-Einträge
individualFields.getFormular().put("Organigramm-Sicht", "0");
sharedData.getFormular().put("Organigramm-Sicht", "0");
loadFieldsFromRequest(request);
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field feld = (Field) it.next();
if (feld.isOldOrganigrammArt() || feld.isSicht()) {
setFeldStand(feld.getName(), ServletHelper.getParameterString(request, feld.getName() + PARAM_STAND_PREFIX), user);
setSelectedFeldSicht(feld.getName(), ServletHelper.getParameterString(request, feld.getName() + PARAM_SICHT_PREFIX), user);
}
// Spezial "Felder" dynamisches Feld für das wichtig ist, dass neu
// gelesen wird in Abhängigkeit von tablestylesheet
if (feld.getName().equals("Felder")) {
feld.setInited(false);
feld.initIfNeeded(individualFields.getFormular(), map, individualFields, user);
}
String param = "";
String[] params = request.getParameterValues(feld.getName());
if (params == null && multipartData != null) {
params = new String[1];
params[0] = ServletUtils.getParamValue(multipartData, feld.getName());
if (params[0] == null) params = null;
}
if (params != null) {
for (int i = 0; i < params.length; i++) {
if (StringUtils.containsTags(params[i])) throw new IllegalArgumentException("Parameter für " + feld.getName() + " enthält unerlaubte Tags");
param += params[i] != null ? params[i].trim() : "";
if (i < params.length - 1) param += "|";
}
}
// 3.2.09 MB wenn kein Parameter übergeben, aber Defaultwert
// vorhanden, diesen nehmen
if (param.equals("")
&& feld.getDefaultValue() != null && feld.getDefaultValue().getId() != null) param = feld.getDefaultValue().getId().toString();
String selectedKey = new String(param);
selectedKey = selectedKey.trim();
if (!feld.isFileUpload() && feld.isObligatorisch() && selectedKey.equals(""))
throw new ObligatoryFieldEmptyException("Bitte füllen Sie das Feld " + feld.getName() + " aus.");
feld.setSelectedKey(selectedKey);
if (!feld.isHidden()) user.getSelectionBuffer().setFieldDefault(feld.getName(), selectedKey);
if (feld.isOldOrganigrammArt() || feld.isSicht()) {
sichtParamsInsFormular(feld);
}
String escapedKey = feld.getSelectedKeyEscaped();
// MB Stylesheet by field 6/2010
if (feld.getName().equals("tablestylesheet") && selectedKey != null && !selectedKey.equals("")) {
// also sets desired contenttype of that stylesheet!
setSelectedTableStylesheetFileAndContenttype(selectedKey);
}
if (feld.getName().equals("Ausgabeformat") && selectedKey != null && !selectedKey.equals("")) setDesiredContenttype(selectedKey);
// if contenttype is in request that has predominance
String c = ServletHelper.getParameter(request, RequestParameter.contenttype);
if (c != null && !c.equals("")) setDesiredContenttype(c);
individualFields.getFormular().put(feld.getName(), escapedKey);
// damit auch ggfs. Submasken die Parameter erhalten
sharedData.getFormular().put(feld.getName(), escapedKey);
}
}
public Hashtable getFormularCopy() {
Hashtable f = new Hashtable();
f.putAll(sharedData.getFormular());
f.putAll(individualFields.getFormular());
return f;
}
/**
* Sicht-Parameter wie Organigramm-Sicht und -Stand, erlaubt setzen.
* defaultOrgaSicht
*
* @param feld
* -
*
*/
private void sichtParamsInsFormular(Field feld) {
// konkreter Feldname z.B. Org-Einheit-Sicht/Stand
String feldname = feld.getName();
standParamSetzen(feldname, feld.getSichtgruppe().getSelectedSicht().getStand());
individualFields.getFormular().put(feldname + PARAM_SICHT_PREFIX, feld.getSichtgruppe().getSelectedSicht().getId().toString());
sharedData.getFormular().put(feldname + PARAM_SICHT_PREFIX, feld.getSichtgruppe().getSelectedSicht().getId().toString());
// das gleiche nochmal für Sichtart name:
// Auch Organigramm-Sicht/Stand setzen
String sichtart = feld.getSichtgruppe().getArt();
if (sichtart.endsWith(PARAM_SICHT_PREFIX)) sichtart = sichtart.substring(0, sichtart.length() - 6);
standParamSetzen(sichtart, feld.getSichtgruppe().getSelectedSicht().getStand());
individualFields.getFormular().put(sichtart + PARAM_SICHT_PREFIX, feld.getSichtgruppe().getSelectedSicht().getId().toString());
sharedData.getFormular().put(sichtart + PARAM_SICHT_PREFIX, feld.getSichtgruppe().getSelectedSicht().getId().toString());
// für Organigramm-Felder erlaubt Parameter setzen
if (feld.isOldOrganigrammArt() || feld.isOrganigrammSichtArt()) {
String erlaubt = "0";
if (feld.getSelectedKey() != null && !feld.getSelectedKey().equals("") && !feld.getSelectedKey().equals("null")
&& feld.getSichtgruppe().getSelectedSicht().getSelectionCount() > 0) {
SelectableItemNode selectedNode = (SelectableItemNode) feld.getSichtgruppe().getSelectedSicht().getSelectionPath().getLastPathComponent();
erlaubt = selectedNode.isAllowed() ? "1" : "0";
}
individualFields.getFormular().put("erlaubt", erlaubt);
// auch in SharedData eintragen sonst wird wieder überschrieben
sharedData.getFormular().put("erlaubt", erlaubt);
}
}
/**
* Stand Parameter in formular setzen
*
* @param name
* z.B. Organigramm
* @param value
*/
private void standParamSetzen(String name, String value) {
if (!name.endsWith(PARAM_STAND_PREFIX)) name = name + PARAM_STAND_PREFIX;
if (SxPools.get(mandantenID).getSqlDialect().equals("Postgres"))
value = "date_val('" + value.trim() + "')";
else
value = "date('" + value.trim() + "')";
individualFields.getFormular().put(name, value);
sharedData.getFormular().put(name, value);
}
/**
*
* @param user
* @param request
@param dbCon - wohl nur von SuperXmlTabelle.CSVUploadHelper genutzt
* @return
* @throws TemplateException
* @throws IOException
* @throws InvalidKeyException
* @throws ParseException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*/
private StringBuffer getMaskResult(SxUser user, HttpServletRequest request, Connection dbCon) throws TemplateException, IOException, InvalidKeyException, ParseException,
SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, NoMainEntryException, InvalidDataTypeException {
StringBuffer xmlBuffer = new StringBuffer("");
if (this.isMakro()) {
// / MAKRO MAKRO MAKRO
updateFormular(user);
NamedIdObjectList schleifenElemente = getSchleifenElemente();
// mindestens ein Durchlauf, wenn es schleifenElemente gibt
// öfter
int schleifendurchläufe = java.lang.Math.max(1, schleifenElemente.size());
// mindestens ein Durchlauf, falls schleifenrelation hinterlegt
// wurde öfter
for (int i = 0; i < schleifendurchläufe; i++) {
for (Iterator it = submaskenListe.iterator(); it.hasNext();) {
Maske eineMaske = (Maske) it.next();
// formularFelder aus dem sharedFields auch ins individuelle
// formular kopieren
updateFormular(user);
// wenn wir in einer Schleife sind, ein Element
// einsetzten
Field schleifenField = null;
if (schleifenElemente.size() > 0) {
NamedIdObject schleifenElement = (NamedIdObject) schleifenElemente.get(i);
SuperXManager.logActivity(Level.DEBUG, " Abfrage " + eineMaske.getMaskInfo() + " Schleife einsetzen:" + schleifenElement);
if (!eineMaske.getFields().containsField(getSchleifenfeldname()))
throw new IllegalArgumentException("Versuch einen Schleifenwert " + schleifenElement + " für das Feld " + getSchleifenfeldname() + " bei der Maske "
+ eineMaske.getMaskInfo() + " fehlgeschlagen, da in der Abfrage kein Feld " + getSchleifenfeldname()
+ " gefunden wurde");
schleifenField = (Field) eineMaske.getFields().getByName(getSchleifenfeldname());
fieldSichtStandSetzen(user, schleifenField);
// Es kann sein, dass Feld, das gewählte Element noch
// nicht
// in den selectionElements hat, dann als temporäres
// Feld hinzufügen
if (!schleifenField.getSelectableItemsTree().containsItemWithId((String) schleifenElement.getId())) {
SelectableItem item = new SelectableItem(schleifenElement);
item.setTemporary(true);
schleifenField.addTempSelectionElement(item);
}
schleifenField.setSelectedKey(schleifenElement.getId().toString());
schleifenField.setSpecialSelectionApplied(true);
eineMaske.getFields().getFormular().put(getSchleifenfeldname(), schleifenField.getSelectedKeyEscaped());
sharedData.getFormular().put(getSchleifenfeldname(), schleifenField.getSelectedKeyEscaped());
}
// merken, kann auch null sein
sharedData.setSchleifenField(schleifenField);
xmlBuffer.append(eineMaske.getMaskResult(user, request, dbCon));
}
}
}
// EINZELNE MASKE
else {
// formularFelder aus dem sharedFields auch ins individuelle
// formular kopieren
updateFormular(user);
NamedIdObjectList schleifenElemente = getSchleifenElemente();
// mindestens ein Durchlauf, wenn es schleifenElemente gibt öfter
int schleifendurchläufe = java.lang.Math.max(1, schleifenElemente.size());
SuperXManager.logActivity(Level.INFO, "Abfrage " + getMaskInfo() + " durchführen");
// mindestens ein Durchlauf, falls schleifenrelation hinterlegt
// wurde öfter
for (int i = 0; i < schleifendurchläufe; i++) {
// wenn wir in einer Schleife sind, ein Element
// einsetzten
NamedIdObject schleifenElement = null;
Field schleifenFeld = null;
if (schleifenElemente.size() > 0) {
schleifenElement = (NamedIdObject) schleifenElemente.get(i);
SuperXManager.logActivity(Level.DEBUG, " Abfrage " + getMaskInfo() + " Schleife einsetzen:" + schleifenElement);
schleifenFeld = (Field) individualFields.getByName(getSchleifenfeldname());
fieldSichtStandSetzen(user, schleifenFeld);
schleifenFeld.setSelectedKey(schleifenElement.getId().toString());
schleifenFeld.setSpecialSelectionApplied(true);
individualFields.getFormular().put(getSchleifenfeldname(), schleifenFeld.getSelectedKeyEscaped());
}
xmlBuffer.append("<ergebnis ordnr=\"" + sharedData.getErgebnisOrdNr() + "\">\n");
sharedData.incOrdnr();
if (sharedData.getSchleifenField() != null) {
xmlBuffer.append(sharedData.getSchleifenField().getSchleifenXml());
}
xmlBuffer.append("<maskenname id=\"" + getId() + "\" helpcontext=\"@@doku_url@@@@doku_" + getId() + "_table_url@@\" >" + getName() + "</maskenname>\n");
xmlBuffer.append("<explanation><![CDATA[" + getExplanation() + "]]></explanation>\n");
// in execute Query wird auch ggfs. Hinweis-SQL ausgeführt
// sowie setzen von colsort/colset
StringBuffer tableXml = executeQuery(user, request, dbCon);
hinweis = getHinweisCaption();
if (isMaxRowsReached()) {
if (hinweis != null && !hinweis.equals(""))
hinweis = SuperXManager.getMaxRowsHinweis() + ". " + hinweis;
else
hinweis += SuperXManager.getMaxRowsHinweis();
}
xmlBuffer.append("<hinweis><![CDATA[" + hinweis + "]]></hinweis>\n");
xmlBuffer.append("<stand>" + getStandString() + "</stand>\n");
xmlBuffer.append("<standdt>" + getStandStringDT() + "</standdt>\n");
xmlBuffer.append("<chartx>" + getChartx() + "</chartx>\n");
xmlBuffer.append("<charty>" + getCharty() + "</charty>\n");
xmlBuffer.append(getXmlFieldSelection(user));
StringTokenizer st = new StringTokenizer(getAktion(), "|");
while (st.hasMoreElements()) {
String anAktion = st.nextToken();
performAktion(anAktion, tableXml, xmlBuffer);
}
xmlBuffer.append("</ergebnis>\n");
}
}
return xmlBuffer;
}
/**
* Bei der Durchführung von Makros für Felder gewünschte Sicht/Stand setzen
* aufgerufen von getMaskResult
*
* @param f
* @throws ParseException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
*/
private void fieldSichtStandSetzen(SxUser user, Field f) throws ParseException, SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException,
SichtException, TemplateException, IOException, NoMainEntryException {
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
try {
// damit auf jeden Fall initialisiert
f.initIfNeeded(individualFields.getFormular(), map, individualFields, user);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Die Maske ist derzeit nicht benutzbar. Maske " + getMaskInfo() + " konnte Feld " + f.getName() + " (" + f.getId()
+ ") nicht initialisieren,\n um ggfs. Sicht oder Stand zu setzen.\n" + e);
}
if (f.isSicht() && f.getSichtgruppe().size() > 1) {
String sicht = getSchleifenfsicht();
if (sicht == null || sicht.trim().equals(""))
// sicht sollte gesetzt sein, welche Sicht aus erstes ausgewählt
// wird
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar.Für das Feld " + f.getName() + " (" + f.getId() + ") Maske " + this
.getMaskInfo() + " muss in macro_masken_bez eine Sicht hinterlegt sein (z.B. fest 13 oder dynamisch z.B. Kostenstellen-Sicht in doppelten Kleiner-/Größerzeichen = auf Hauptmaske ausgewaehlte Sicht)");
if (sicht.startsWith("<<SQL>>"))
throw new UnsupportedOperationException("Die Maske ist derzeit nicht benutzbar. Sql bei der Sichtenauswahl in macros wird noch nicht unterstützt Maske "
+ this.getId());
sicht = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), new String(sicht));
int sichttid = 0;
try {
sichttid = Integer.parseInt(sicht);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Die Maske ist derzeit nicht benutzbar. Konnte gewünschte Sicht für das Feld " + f.getName() + " (" + f.getId() + ") Maske "
+ this.getId() + "nicht ermitteln, " + sicht + " ist kein gültige Integerzahl.(tid)");
}
f.setSicht(individualFields.getFormular(), map, individualFields, Integer.valueOf(sichttid), user);
}
String stand = getSchleifenfstand();
if (stand == null || stand.trim().equals("")) {
if (f.isOldOrganigrammArt() || (f.isSicht() && f.getSichtgruppe().isStandButtonWanted()))
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Für das Feld " + f.getName() + " (" + f.getId() + ") Maske " + this.getId()
+ " muss in macro_masken_bez ein Stand hinterlegt sein (z.B. fest 01.01.2005 oder dynamisch <<Org. Einheit-Stand>>)");
} else {
if (stand.startsWith("<<SQL>>"))
throw new UnsupportedOperationException("Die Maske ist derzeit nicht benutzbar. Sql bei der Standauswahl in macros wird noch nicht unterstützt Maske "
+ this.getId() + "");
stand = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), new String(stand));
f.setStand(individualFields.getFormular(), map, individualFields, stand, user);
}
}
/**
* Removes temp selection items from all fields that may have been used
* during macro loop iteration
*
*/
public void removeTempFieldItems() {
this.getFields().removeTempFieldItems();
for (Iterator it = submaskenListe.iterator(); it.hasNext();) {
Maske m = (Maske) it.next();
m.removeTempFieldItems();
}
}
private FieldContainer getFields() {
return individualFields;
}
private void performAktion(String anAktion, StringBuffer tableXml, StringBuffer xmlBuffer) throws IOException {
if (anAktion.equals("SHOWTABLE")) {
xmlBuffer.append("<ergebniselement typ=\"tabelle\" id=\"" + getId() + "\" ordnr=\"" + sharedData.getErgebnisElementOrdNr() + "\">");
sharedData.incErgebnisElementOrdNr();
xmlBuffer.append(tableXml);
xmlBuffer.append("</ergebniselement>\n");
}
if (anAktion.startsWith("CREATECHART-")) {
GraphicFormat f = SxPools.get(mandantenID).getGraphicFormat(anAktion.substring(12));
File graphicFile;
try {
graphicFile = ChartCreator.createFile(tableXml, f);
} catch (IOException e) {
e.printStackTrace();
throw new IOException("Fehler bei Grafikerzeugung "+e);
} catch (SAXException e) {
e.printStackTrace();
throw new IOException("Fehler bei Grafikerzeugung, XML Problem "+e);
}
sharedData.addGraphicFile(graphicFile);
xmlBuffer.append("<ergebniselement typ=\"image\" localurl=\"file:///" + graphicFile.getAbsolutePath() + "\" url=\"../xml/" + graphicFile.getName() + "\" ordnr=\""
+ sharedData.getErgebnisOrdNr() + "\"/>\n");
sharedData.incErgebnisElementOrdNr();
}
}
public String getSql2() {
String select_string = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), getSelect_stmt() + "\n" + getCleanup_stmt());
return select_string;
}
public String getSql3(SxUser user) throws TemplateException, IOException, SQLException {
String select_string = SxPools.get(mandantenID).getTemplateProcessor().process(user.getBasicMap(), (Integer) getId(), getMaskInfo(), getSql2(), individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
return select_string;
}
public String getFormularValues() {
StringBuffer buf = new StringBuffer();
TreeSet set = new TreeSet(sharedData.getFormular().keySet());
set.addAll(individualFields.getFormular().keySet());
for (Iterator it = set.iterator(); it.hasNext();) {
Object key = it.next();
if (key.toString().equalsIgnoreCase("passwort")) continue;
Object val = sharedData.getFormular().get(key);
if (individualFields.getFormular().get(key) != null) val = individualFields.getFormular().get(key);
buf.append("<b>" + key + "</b> : " + val + "<br/>");
}
return buf.toString();
}
public String getLastsql() {
return lastsql;
}
/**
* Eine einzelne Abfrage durchführen und Ergebnis-XML zurücklieferen
*
* @param dbCon
* kann null sein, dann wird neue Connection geholt
* @param dbCon - wohl nur von SuperXmlTabelle.CSVUploadHelper genutzt
* @return
* @throws DBServletException
* @throws SQLException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws CloneNotSupportedException
* @throws KeyParentEqualException
* @throws NoMainEntryException
*/
private StringBuffer executeQuery(SxUser user, HttpServletRequest request, Connection dbCon) throws DBServletException, SQLException, TemplateException, IOException,
KeyParentEqualException, CloneNotSupportedException, SichtException, NoMainEntryException {
if (isResultReuseFeatureWanted && isReuseResult() && result_el == null) {
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar. Maske nicht mehr im Cache - bitte neu aufrufen DETAILS:Can't reuse result for Maske " + getId()
+ " because result_el is null");
}
desiredRows = null;
desiredRows = ServletHelper.getParameter(request, RequestParameter.irowno);
if (!isResultReuseFeatureWanted || (isResultReuseFeatureWanted && !isReuseResult())) {
map.clear();
map.putAll(user.getBasicMap());
individualFields.updateStandTags(map, user);
boolean isTemplate = getSelect_stmt().toUpperCase().indexOf("FREEMARKER TEMPLATE") > -1;
String select_string = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(),
getSelect_stmt() + "\n" + getCleanup_stmt());
if (isTemplate) {
SuperXManager.setLastFMMaskenSql("-- " + getMaskInfo() + " " + DateUtils.getNowString() + "\n" + select_string);
select_string = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), select_string, individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
// danach enthält map alle vars inkl. sqlvars
}
// MB 07/2010 macht Probleme bei Freemarker hashes
// generell deaktiviert, hier falls doch noch in alten Masken
// vorhanden
select_string = SqlStringUtils.removeComment(select_string, "{", "}");
lastsql = select_string;
lastExecuted = DateUtils.getNowString();
ExternalPool ep = ServletUtils.getExternalPoolIfSpecified(mandantenID, ((Integer) this.getId()), getSelect_stmt());
result_el = ServletUtils.executeALL_el(ep, dbCon, "Abfrage Maske " + getMaskInfo() + " durchführen", "--Abfrage\n" + select_string, mandantenID, true);
String errorstring = result_el.getError_String();
String errorselect = result_el.getAktuelleNachricht();
if (errorstring != null && !errorstring.equals("")) {
throw new SQLException("<h2>Fehler</h2><p class='errmsg'>Bei der Abfrage<br /> " + getMaskInfo() + "<br /> ist ein Fehler aufgetreten:<br />" + errorstring
+ "<br /> sql:" + errorselect + "</p>");
}
}
setColset(ServletHelper.getParameter(request, RequestParameter.colset));
setColsort(ServletHelper.getParameter(request, RequestParameter.colsort));
boolean isEbenenWanted = detectDrilldownTableMode(request);
if (hinweis != null) {
if (hinweis.startsWith("<<SQL>>")) {
setHinweisCaption("");
String sql = hinweis.substring(7, hinweis.length());
boolean isTemplate = sql.toUpperCase().indexOf("FREEMARKER TEMPLATE") > -1;
try {
sql = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), sql);
if (isTemplate) {
map.putAll(user.getBasicMap());
sql = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), sql, individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
// danach enthält map alle vars inkl. sqlvars
}
ExternalPool ep = ServletUtils.getExternalPoolIfSpecified(mandantenID, ((Integer) this.getId()), hinweis);
SuperX_el hinweis_el = ServletUtils.executeALL_el(ep, dbCon, "Hinweis holen ", sql, mandantenID, true);
SxResultSet rs = hinweis_el.getResultSet();
Iterator it = rs.iterator();
StringBuffer hinw = new StringBuffer();
int i = 0;
while (it.hasNext()) {
SxResultRow row = (SxResultRow) it.next();
if (i > 0) hinw.append("\n");
hinw.append(row.get(0));
i++;
}
setHinweisCaption(hinw.toString());
} catch (Exception e) {
System.out.println("Error beim Hinweis lesen:" + sql + " " + e);
}
}
}
// Wenn das ResultSet die Spalte "_runtimeMessage" enthält und diese
// nicht leer ist, wird der Inhalt nach <hinweis> geschrieben.
// nützlich z.B. für Datenblätter, deren max. Zeilenanzahl überschritten
// ist.
String meldung = result_el.getRuntimeMessage();
if (meldung != null && !meldung.equals("")) setHinweisCaption(meldung);
meldung = null;
return getXmlResultTable(user, desiredRows, isEbenenWanted);
}
private boolean detectDrilldownTableMode(HttpServletRequest request) {
String stylesheet = ServletHelper.getParameter(request, RequestParameter.stylesheet);
String usetreetable = ServletHelper.getParameter(request, RequestParameter.usetreetable);
if (usetreetable != null) usetreetable = usetreetable.toLowerCase();
boolean isEbenenWanted = false;
if (!isMakroSubMaske &&
(result_el != null && result_el.hasEbeneCol()) &&
!EqualsUtil.areEqual(usetreetable, "false") &&
colsort == null &&
!EqualsUtil.areEqual(stylesheet, "tabelle_html_p.xsl") &&
(stylesheet == null || stylesheet.indexOf(".jrxml") == -1) &&
(desiredContenttype == null || desiredContenttype.trim().equals("") || desiredContenttype.toLowerCase().indexOf("htm") > -1)
) isEbenenWanted = true;
return isEbenenWanted;
}
public String getLastExecuted() {
return lastExecuted;
}
public String getSelectString() {
boolean isTemplate = getSelect_stmt().toUpperCase().indexOf("FREEMARKER TEMPLATE") > -1;
String select_string = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), getSelect_stmt() + "\n" + getCleanup_stmt());
if (isTemplate) {
SuperXManager.setLastFMMaskenSql("-- " + getMaskInfo() + " " + DateUtils.getNowString() + "\n" + select_string);
try {
select_string = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), select_string, individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
} catch (TemplateException | IOException | SQLException e) {
logger.error("Couldn't get select string!", e);
throw new RuntimeException(e);
}
}
return select_string;
}
/**
* new 2/2015
* bei export von nur bestimmten Zeilen oder Makro alten Export nutzen
* @return
*/
public boolean isNewExcelExport()
{
return getSelect_stmt().toUpperCase().indexOf("RAM EXCELEXPORT") > -1 && (desiredRows == null || desiredRows.equals("")) && !isMakro() && !isMakroSubMaske;
}
/**
* Bei Submasken von Makros müssen die Formularparameter der Hauptmaske in
* das Formular der Untermasken übernommen werden.
*
* @throws InvalidKeyException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*
*/
private void updateFormular(SxUser user) throws InvalidKeyException, SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException,
TemplateException, IOException, NoMainEntryException, InvalidDataTypeException {
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
for (Enumeration it = sharedData.getFormular().keys(); it.hasMoreElements();) {
String keyname = (String) it.nextElement();
// erstmal sicherheitshalber aus sharedData alle
// Felderinfo ins individuelle Formular kopieren
Object wertInSuperMaske = sharedData.getFormular().get(keyname);
individualFields.getFormular().put(keyname, wertInSuperMaske.toString());
}
// aus übergeordneter Maske Werte eintragen
for (Iterator it = sharedData.getFields().iterator(); it.hasNext();) {
Field superField = (Field) it.next();
if (individualFields.containsItemWithName(superField.getName())) {
Field f = (Field) individualFields.getByName(superField.getName());
f.initIfNeeded(individualFields.getFormular(), map, individualFields, user);
if (superField.isOldOrganigrammArt() || superField.isSicht()) {
f.setStand(individualFields.getFormular(), map, individualFields, superField.getSichtgruppe().getStand(), user);
if (f.isSicht() && !f.isMacroMaskenSichtSet())
f.setSicht(individualFields.getFormular(), map, individualFields, (Integer) superField.getSichtgruppe().getSelectedSicht().getId(), user);
}
// wenn kein Spezialwert hinterlegt wurde
// Schlüssel vom superField eintragen.
if (!f.isSpecialSelectionApplied()) {
f.setSelectedKey(superField.getSelectedKey());
}
}
}
// individuelle Felder durchgehen, ggfs. special selection aus
// makro_feld_wert ins Formular eintragen
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
if (f.isSpecialSelectionApplied()) individualFields.getFormular().put(f.getName(), f.getSelectedKeyEscaped());
}
if (maxOffset == 0)
individualFields.getFormular().put("MAXOFFSET", "" + "ALL");
else
individualFields.getFormular().put("MAXOFFSET", "" + maxOffset);
individualFields.getFormular().put("OFFSET", "" + getOffset());
}
/**
*
* @param schleifenrelation
* @return
* @throws DBServletException
* @throws SQLException
*/
private NamedIdObjectList getSchleifenElemente() throws DBServletException, SQLException {
NamedIdObjectList result = new NamedIdObjectList();
if (getSchleifenrelation() != null) {
String stmt = "";
if (getSchleifenrelation().startsWith("sp_")) {
if (SxPools.get(mandantenID).getSqlDialect().equals("Postgres"))
stmt = "select " + schleifenrelation;
else
stmt = "execute procedure " + schleifenrelation;
}
if (getSchleifenrelation().startsWith("<<SQL>>")) stmt = getSchleifenrelation().substring(7);
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), stmt);
Logger.getLogger("superx_" + mandantenID).log(Level.INFO, "Hole Schleifenelemente : " + stmt);
SxResultSet rs = ServletUtils.execute("Hole Schleifenelemente aus makro_maske_bez maske:" + getId(), stmt, mandantenID);
for (Iterator it = rs.iterator(); it.hasNext();) {
SxResultRow row = (SxResultRow) it.next();
result.add(new NamedIdObject(row.get(0), (String) row.get(1)));
}
}
return result;
}
/**
* Nur den Ergebnisteil <sqlerg> incl. Header
*
* @return
* @throws SQLException
* @throws DBServletException
* @throws NoMainEntryException
* @throws KeyParentEqualException
*/
private StringBuffer getXmlResultTable(SxUser user, String desiredRows, boolean isEbenenWanted)
throws SQLException, DBServletException, IOException, TemplateException, KeyParentEqualException, NoMainEntryException {
StringBuffer result = new StringBuffer();
result.append("\n<sqlerg max=\"" + result_el.getResultSet().size() + "\" maxOffset= \"" + maxOffset + "\" offset=\"" + offset + "\" istreetable=");
if (result_el != null && result_el.hasEbeneCol())
result.append("\"true\"");
else
result.append("\"false\"");
result.append(">\n");
result.append(getXmlHeader(user));
// wichtig
if (headerManager.hasTreeFunction()) setColset(headerManager.getColset());
XMLResultCreator rc = new XMLResultCreator(result_el, maxOffset, offset, mandantenID);
if (desiredRows != null && !desiredRows.equals("")) rc.setDesiredRows(desiredRows);
rc.addXML(result, getColset(), isEbenenWanted, "table0", -1);
result.append("</sqlerg>\n");
addCustomXmlAdditions(user, result);
return result;
}
private void addCustomXmlAdditions(SxUser user, StringBuffer result) throws TemplateException, IOException, SQLException {
Iterator it = SxPools.get(mandantenID).getRepository().keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if (key.startsWith("CUSTOMXMLADD")) {
String customadd = ((RepositoryItemCollection) SxPools.get(mandantenID).getRepository().get(key)).get("content").toString();
Logger.getLogger("superx_" + mandantenID + "_xml").log(Level.DEBUG, "Hinzufügen von " + key + ":\n " + customadd + DateUtils.getNowString());
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
customadd = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), customadd, individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
Logger.getLogger("superx_" + mandantenID + "_xml").log(Level.DEBUG, "Hinzufügen von " + key + ":\n " + customadd + DateUtils.getNowString());
result.append(customadd);
}
}
}
/**
*
* @return
* @throws SQLException
* @throws DBServletException
* @throws NoMainEntryException
* @throws KeyParentEqualException
*/
private String getXmlHeader(SxUser user) throws SQLException, DBServletException, IOException, TemplateException, KeyParentEqualException, NoMainEntryException {
StringBuffer preresult = null;
// TODO: hier BasicHashmap übergeben damit auch Repositoryvars zur
// Verfügung stehen
// TODO: todo noch besser: Map der Maske (damit sqlvars nicht doppelt
// gepflegt werden müssen)
if (isReuseResult) {
// bei aggregationHeadern wird colset überlagert
preresult = headerManager.getHeaders(null, getColset(), getColsort(), result_el, individualFields.getFormular(), mandantenID);
} else {
String tmpxil = getXilString();
// freemaker parsing der XIL Liste
tmpxil = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), tmpxil);
map.putAll(user.getBasicMap());
tmpxil = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), tmpxil, individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
headerManager.setXilString(tmpxil);
preresult = headerManager.getHeaders(tmpxil, getColset(), getColsort(), result_el, individualFields.getFormular(), mandantenID);
}
lastHeaderXml = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), "xil_proplist" + getId(), preresult.toString(), individualFields,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
return lastHeaderXml;
}
private String getColsort() {
return colsort;
}
public int getMaxOffset() {
return maxOffset;
}
/**
* Gilt auch für alle Submasken eines Makros Wieviele Zeilen sollen maximal
* angezeigt werden, bevor nächste Seite kommt
*
* @param maxOffset
*/
public void setMaxOffset(int maxOffset) {
this.maxOffset = maxOffset;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getSelectedTableStylesheetFilename() {
String result = "";
if (selectedTableStylesheet != null) result = selectedTableStylesheet.getFilename();
return result;
}
/**
* selected Stylesheet object
*
* @param none
*
* @return Stylesheet selectedTableStylesheet
*/
public Stylesheet getSelectedTableStylesheet() {
return this.selectedTableStylesheet;
}
/**
* determine contenttype, Default is derived from request, if null, then
* sx_stylesheets.contenttype is read
*
* @param requestContenttype
* Contenttype according to request
* @return String contenttype
*/
public String getSelectedTableStylesheetContenttype(String requestContenttype) {
String result = requestContenttype;
if (requestContenttype == null && selectedTableStylesheet != null) result = selectedTableStylesheet.getContenttype();
return result;
}
/**
* also sets desiredContenttype of Stylesheet
*
* @param desiredTableStylesheet
*/
public void setSelectedTableStylesheetFileAndContenttype(String desiredTableStylesheet) {
this.selectedTableStylesheet = null;
for (Iterator it = tableStylesheetList.iterator(); it.hasNext();) {
Stylesheet s = (Stylesheet) it.next();
if (s.getFilename().equals(desiredTableStylesheet) || (desiredTableStylesheet.equals("") && s.getFilename().equals("tabelle_html.xsl"))) {
selectedTableStylesheet = s;
setDesiredContenttype(s.getContenttype());
if (desiredTableStylesheet != null && desiredTableStylesheet.endsWith(".jrxml")) this.maxOffset = 100000000;
}
}
}
public Integer getSortNr() {
return sortNr;
}
public void setSortNr(Integer sortNr) {
this.sortNr = sortNr;
}
/**
* Legt einen bestimmten Wert fest, der bei einem Feld ausgewählt sein soll.
* Aufgerufen von Object.Cache.applyMakroFieldSelection
*
* @param fieldname
* @param selectedKey
* @throws InvalidKeyException
* @throws InvalidDataTypeException
*/
public void setSpecialFieldSelection(String fieldname, String selectedKey) throws InvalidKeyException, InvalidDataTypeException {
if (!individualFields.containsItemWithName(fieldname)) throw new IllegalArgumentException("Kein Feld mit Namen " + fieldname + " gefunden in Maske " + getMaskInfo());
Field f = (Field) individualFields.getByName(fieldname);
f.setSelectedKey(selectedKey);
f.setSpecialSelectionApplied(true);
// bringt hier nichts, weil von sharedData.standardmäßig übergebügelt
// individualFields.getFormular().put(fieldname,
// f.getSelectedKeyEscaped());
// see updateFormular();
}
public Field getField(String fieldname) {
if (!individualFields.containsItemWithName(fieldname))
throw new IllegalArgumentException("Kein Feld mit Name " + fieldname + " in der Maske " + getMaskInfo() + " (" + selectedTableStylesheet + ") vorhanden. ");
return getFieldOrNull(fieldname);
}
public Field getFieldOrNull(String fieldname) {
if (!individualFields.containsItemWithName(fieldname)) {
return null;
}
return (Field) individualFields.getByName(fieldname);
}
public boolean isReuseResult() {
return isReuseResult;
}
/**
* Wird auch für Submasken eingetragen
*
* @param isReuseResult
*/
public void setReuseResult(boolean isReuseResult) {
this.isReuseResult = isReuseResult;
for (Iterator it = submaskenListe.iterator(); it.hasNext();) {
Maske aMask = (Maske) it.next();
aMask.setReuseResult(isReuseResult);
}
}
public Object clone() throws CloneNotSupportedException {
Maske cl = new Maske();
cl.setId(this.getId());
cl.setName(this.getName());
// result_el wird einfach neues Result_el Objekt
cl.locale = this.locale;
cl.schleifenrelation = schleifenrelation;
cl.schleifenfeldname = schleifenfeldname;
cl.aktion = aktion;
cl.select_stmt = select_stmt;
cl.cleanup_stmt = cleanup_stmt;
cl.xilString = xilString;
cl.chartx = chartx;
cl.charty = charty;
cl.standString = standString;
cl.standStringDT = standStringDT;
cl.selectedMaskStylesheetFile = selectedMaskStylesheetFile;
cl.selectedTableStylesheet = selectedTableStylesheet;
cl.sharedData = (SharedData) this.sharedData.clone();
cl.individualFields = (FieldContainer) this.individualFields.clone();
LinkedList l = new LinkedList();
l.addAll(maskStylesheetList);
cl.maskStylesheetList = l;
l = new LinkedList();
l.addAll(tableStylesheetList);
cl.tableStylesheetList = l;
cl.sortNr = this.sortNr;
NamedIdObjectList tmpList = new NamedIdObjectList();
for (Iterator it = submaskenListe.iterator(); it.hasNext();) {
Maske m = (Maske) it.next();
tmpList.add((Maske) m.clone());
}
cl.submaskenListe = tmpList;
cl.maskHtml = this.maskHtml;
return cl;
}
/**
* Ändert den Stand eines Felds Setzt die Membervariable maskHtml auf null,
* so dass bei Anforderung in getMaskHtml klar ist, dass neu transformiert
* werden muss
*
* @param feldname
* @param String
* neuerStand
* @throws TransformerException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
* @throws IllegalArgumentException
* wenn kein Feld mit dem Namen gefunden
*/
public void setFeldStand(String feldname, String neuerStand, SxUser user) throws TransformerException, SQLException, DBServletException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (neuerStand == null) return;
if (!individualFields.containsItemWithName(feldname))
throw new IllegalArgumentException("Es wurde versucht, den Stand des Feldes " + feldname + " zu ändern, aber in der Maske wurde kein Feld mit dem Namen gefunden");
if (!SuperXManager.isZukuenftigerStandErlaubt && DateUtils.isValidDate(neuerStand)) {
try {
neuerStand = neuerStand.replaceAll("'", "");
// Klammern löschen, \\ ist java.util.regex.Pattern escaping
neuerStand = neuerStand.replaceAll("\\(", "");
neuerStand = neuerStand.replaceAll("\\)", "");
if (DateUtils.isDateInFuture(DateUtils.parse(neuerStand))) throw new IllegalArgumentException("Datum in der Zukunft nicht erlaubt");
} catch (ParseException e) {
// um Fehler kümmert sich schon setFeldStand-Methode
}
}
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
Field f = (Field) individualFields.getByName(feldname);
f.setStand(individualFields.getFormular(), map, individualFields, neuerStand, user);
// eventuell gecachten HTML löschen
maskHtml = null;
}
/**
* Ändert die ausgewählte Sicht für ein Feld. Setzt die Membervariable
* maskHtml auf null, so dass bei Anforderung in getMaskHtml klar ist, dass
* neu transformiert werden muss
*
* @param feldname
* @param sichttid
* @throws TransformerException
* @throws DBServletException
* @throws TransformerConfigurationException
* @throws CloneNotSupportedException
* @throws KeyParentEqualException
* @throws SQLException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
* @throws IllegalArgumentException
* wenn kein Feld mit dem Namen gefunden
*/
public void setSelectedFeldSicht(String feldname, String sichtStr, SxUser user) throws TransformerConfigurationException, TransformerException, DBServletException,
SQLException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (!individualFields.containsItemWithName(feldname)) throw new IllegalArgumentException("Es wurde versucht, eine andere Sicht für das Feld " + feldname
+ " auszuwählen, aber in der Maske wurde kein Feld mit dem Namen gefunden");
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
Field f = (Field) individualFields.getByName(feldname);
f.initIfNeeded(individualFields.getFormular(), map, individualFields, user);
if (sichtStr != null) {
int sichtint = 0;
try {
sichtint = Integer.parseInt(sichtStr);
f.setSicht(individualFields.getFormular(), map, individualFields, Integer.valueOf(sichtint), user);
if (!f.isHidden()) user.getSelectionBuffer().setFieldSicht(feldname, sichtStr);
} catch (NumberFormatException e) {
boolean found = false;
StringBuffer buf = new StringBuffer();
for (Iterator it2 = f.getSichtgruppe().iterator(); it2.hasNext();) {
AbstractSicht sicht = (AbstractSicht) it2.next();
buf.append(sicht.getName_intern() + " ");
if (sicht.getName_intern().equals(sichtStr)) {
f.setSicht(individualFields.getFormular(), map, individualFields, (Integer) sicht.getId(), user);
found = true;
}
}
if (!found) throw new IllegalArgumentException("Feld " + f.getName() + " konnte nicht aktualisiert werden DETAILS: da Parameter " + f.getName()
+ "-Sicht, keine gültige tid oder name_intern einer Sicht lieferte (" + sichtStr + ")" + " möglich wären " + buf
+ " gewesen");
}
}
// eventuell gecachten HTML löschen
maskHtml = null;
}
private String getSchleifenfstand() {
return schleifenfstand;
}
private void setSchleifenfstand(String schleifenfstand) {
this.schleifenfstand = schleifenfstand;
}
private String getSchleifenfsicht() {
return schleifenfsicht;
}
private void setSchleifenfsicht(String schleifenfsicht) {
this.schleifenfsicht = schleifenfsicht;
}
/**
* @return Returns the explanation.
*/
public String getExplanation() {
return explanation;
}
/**
* @param explanation
* The explanation to set.
*/
public void setExplanation(String explanation) {
this.explanation = explanation;
}
public void setHinweis(String hinweis) {
this.hinweis = hinweis;
if (hinweis != null) {
if (hinweis.startsWith("<<SQL>>")) {
hinweis = ""; // DQ muss noch gemacht werden wie im Applet:
}
}
}
public String getHinweisCaption() {
return hinweisCaption;
}
public void setHinweisCaption(String hinweisCaption) {
this.hinweisCaption = hinweisCaption;
}
public String getKidRows(String treetableid, int row) {
if (result_el == null)
throw new IllegalStateException("Die Maske ist derzeit nicht benutzbar.Nachladen per Ajax fehlgeschlagen DETAILS:result-objekt ist null, kann keine Kinder per Ajax nachladen");
XMLResultCreator rc = new XMLResultCreator(result_el, maxOffset, offset, mandantenID);
StringBuffer xml = new StringBuffer();
rc.addXML(xml, colset, true, treetableid, row);
return xml.toString();
}
/**
* set to uninited damit wieder eingelesen werden
*/
public void markDynamicFields() {
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
if (f.isDynamic()) f.setInited(false);
}
}
public boolean hasDynamicFields() {
boolean result = false;
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
if (f.isDynamic()) result = true;
}
return result;
}
public boolean hasArt0Fields() {
boolean result = false;
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field f = (Field) it.next();
if (f.getArt() == Art.id_0_nur_Text_direkte_Eingabe) result = true;
}
return result;
}
public void openHeader(String key) {
headerManager.openHeader(key);
setReuseResult(true);
}
public void closeHeader(String key) {
headerManager.closeHeader(key);
setReuseResult(true);
}
public boolean isMaxRowsReached() {
boolean result = false;
if (result_el != null && result_el.getResultSet() != null
&& (result_el.getResultSet().size() == SuperXManager.maxRows
|| (result_el.getRuntimeMessage() != null && result_el.getRuntimeMessage().indexOf("Zeilen liegen über max. Grenze") >= 1)))
result = true;
return result;
}
public List<String> getHeaderCaptionList(String mandantenID, boolean removeNewline) {
int pos = lastHeaderXml.indexOf("<headersconcated>");
if (pos == -1) throw new IllegalStateException("Kein Knoten headersconcated im Masken-Xml gefunden)");
int pos2 = lastHeaderXml.indexOf("]>\n</headersconcated>", pos) - 1;
String concated = lastHeaderXml.substring(pos + 26, pos2);
concated = SxPools.get(mandantenID).localize(concated, new Locale("de"));
List<String> result = new ArrayList();
StringTokenizer st = new StringTokenizer(concated, "\t");
while (st.hasMoreTokens()) {
String h = st.nextToken();
if (removeNewline) {
h = h.replaceAll( "\r\n", " ");
h = h.replaceAll( "\r", " ");
h = StringUtils.replace(h, "\n", " ");
h = StringUtils.replace(h, "\\n", " ");
h = StringUtils.replace(h, "\\000", " ");
}
result.add(h);
}
return result;
}
public String getLegendText(SxUser user) throws ParseException {
return this.getLegendList(user.getName()).stream()
.map(item -> item.label + ": " + item.value)
.collect(Collectors.joining(", ", "", ""));
}
public Legend getSplitLegend(String userName) throws ParseException {
Legend result = new Legend();
ArrayList<Item> legendList = this.getLegendList(userName);
for (Item item : legendList) {
if( item.label.equals("Benutzerkennung") || item.label.equals("Letztes Daten-Update") ) {
result.systemParams.add(item);
} else if (item.value.contains(" (Sicht:")) {
result.viewParams.add(item);
} else {
result.standardParams.add(item);
}
}
if (this.hinweis != null && !this.hinweis.isEmpty()) {
result.hint = new Item("Hinweis", this.hinweis);
}
return result;
}
public ArrayList<Item> getLegendList(String userName) throws ParseException{
ArrayList<Item> result = new ArrayList<Item>();
for (Iterator it = individualFields.iterator(); it.hasNext();) {
Field feld = (Field) it.next();
if ( feld.shouldBeAddedToLegend() ) {
String label = feld.getLegendName();
String valueCaption = feld.getValueCaptionForLegend();
result.add(new Item(label, valueCaption));
}
}
result.add(new Item("Benutzerkennung", userName));
result.add(new Item("Letztes Daten-Update", this.getStand()));
return result;
}
private String getStand() {
String timestamp = this.getStandStringDT();
return timestamp.isEmpty() ? this.getStandString() : timestamp;
}
public String fmProcess(SxUser user, String vorlage) throws TemplateException, IOException, SQLException {
String result = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), individualFields.getFormular(), vorlage);
map.clear();
map.putAll(user.getBasicMap());
result = SxPools.get(mandantenID).getTemplateProcessor().process(map, (Integer) getId(), getMaskInfo(), result, individualFields, SxPools.get(mandantenID).getRepository(),
SxPools.get(mandantenID).getSqlDialect());
return result;
}
/**
* Normalerweise Maskenname nur bei JasperReports der Stylesheetname
*
* @return
*/
public String getExportName() {
String result = getName();
if (selectedTableStylesheet != null && selectedTableStylesheet.getFilename().indexOf(".jrxml") > -1) result = selectedTableStylesheet.getCaption();
if (map.containsKey("exportfilename"))
{
if (map.get("exportfilename")==null||map.get("exportfilename").toString().trim().equals(""))
{
throw new IllegalStateException("Die Maske definiert exportfilename, dieser ist aber leer. Masken-SQL prüfen");
}
result=map.get("exportfilename").toString();
}
return result;
}
public String getFullTableXml(String mandantenId, SxUser sxuser, HttpServletRequest request, Locale locale) throws TransformerConfigurationException, TemplateException,
IOException, SQLException, KeyParentEqualException, CloneNotSupportedException, SichtException, ObligatoryFieldEmptyException, ParseException,
InvalidKeyException, TransformerException, DBServletException, UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException {
boolean isReuse = this.isReuseResult();
int offset = this.getOffset();
int maxoffset = this.getMaxOffset();
this.setOffset(0);
this.setMaxOffset(100000000);
this.setReuseResult(true);
String returnText = this.runQuery(sxuser, request, null).toString();
returnText = SxPools.get(mandantenId).localize(returnText, locale);
this.setReuseResult(isReuse);
this.setOffset(offset);
this.setMaxOffset(maxoffset);
return returnText;
}
private StringBuffer addBacklink(HttpServletRequest request, StringBuffer buf) {
String backlink = ServletHelper.getParameter(request, RequestParameter.backlink);
if (backlink != null) {
buf.append("\n<backlink>");
if (backlink.equalsIgnoreCase("his1")) {
buf.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append("/")
.append(System.getProperty(QIS_CONTEXT)).append("/pages/cs/sys/portal/hisinoneStartPage.faces");
} else {
buf.append(backlink);
}
buf.append("</backlink>\n");
}
return buf;
}
public FieldContainer getIndividualFields() {
return individualFields;
}
public StringBuffer getCSV(String mandantenID) throws IOException {
String fld_delim1 = "";
String fld_delim2 = "^";
boolean isCSV_Excel_ISO=false;
if (SxPools.get(mandantenID).getRepository().containsKey("K_CSV_Excel_ISO")&&SxPools.get(mandantenID).getRepository().get("K_CSV_Excel_ISO").toString().equals("1"))
{
fld_delim2 = ";";
isCSV_Excel_ISO=true;
}
String row_delim1 = "";
String row_delim2 = "\n";// we only user unix newline, even under DOS
String outFormat = "txt";
StringBuffer result = new StringBuffer();
StringBuffer line = new StringBuffer("");
int cols = this.getResult_el().getColumnCount();
// header
List headerlist = getHeaderCaptionList(mandantenID, true);
for (Iterator it = headerlist.iterator(); it.hasNext();) {
String headername = it.next() + fld_delim2;
headername = headername.replaceAll(" ", " ");
headername = headername.replaceAll(" ", " ");
line.append(headername);
}
line.append("\n");
result.append(line);
// data
Iterator it = this.getResult_el().getResultSet().iterator();
while (it.hasNext()) {
SxResultRow row = (SxResultRow) it.next();
line.setLength(0);
for (int i = 1; i <= cols; i++) {
Object o = row.get(i - 1);
// aus SxTransformer.printResult
String f_wert = SxDBUtils.field_value(o);
// MB spezifisch statt . ein , als Decimaltrenner
if (o instanceof Float || o instanceof Double || o instanceof BigDecimal) f_wert = o.toString().replace('.', ',');
// MB Spezifisch Ende
if (outFormat.equals("xml") && (f_wert.indexOf("&") > -1 || f_wert.indexOf("<") > -1 || f_wert.indexOf(">") > -1)) f_wert = "<![CDATA[" + f_wert + "]]>";
//wenn der Feldwert einen Zeilenumbruch oder Trennzeichen enthält wird der Test in "" gesetzt -> für CSV Import
if (outFormat.equals("txt") && f_wert != null && !f_wert.trim().equals("") && (f_wert.indexOf("\n") > -1 || isCSV_Excel_ISO || f_wert.indexOf(fld_delim2) > -1)) {
//CSV-Mode, d.h. Text-Trennzeichen wird drum herum gesetzt, und " im Text verdoppelt:
f_wert = "\""+de.memtext.util.StringUtils.replace(f_wert,"\"","\"\"")+"\"";
}
if (outFormat.equals("txt") && f_wert != null && (f_wert.indexOf("\\n") > -1)) {
f_wert = de.memtext.util.StringUtils.replace(f_wert, "\\n", "\\\\n");
}
if (i < cols)
line.append(fld_delim1 + f_wert + fld_delim2);
else {
line.append(fld_delim1 + f_wert + fld_delim2);
line.append(row_delim2);
}
// aus SxTransformer.printResult
}
result.append(line);
}
return result;
}
public void updateDynamicSichten(Field f, SxUser user)
throws SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, NoMainEntryException, TemplateException, IOException {
HashMap map = new HashMap();
map.putAll(user.getBasicMap());
f.getSichtgruppe().updateDynamicSichten(individualFields.getFormular(), map, individualFields);
}
public void setNavi(boolean navi) {
this.navi = navi;
}
/**
* Wenn eine Maske mit multipart-Data aufgerufen wird, dieses Ablegen.
* in individualFields reinschreiben
* wird von setSelection gelesen
* @param multipartData
*/
public void setMultipartData(List<FileItem> multipartData) {
this.multipartData = multipartData;
Iterator iter = multipartData.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String paramName = item.getFieldName();
String paramValue = item.getString();
individualFields.getFormular().put(paramName, paramValue);
}
}
}
/**
* Stylesheet handling for Angular:
* Fehlerbehandlung: Datenblättern die ein "Generisches Standardlayout Datenblätter"
* und ein "Generisches Standardlayout" besitzen wird "Generisches Standardlayout" rausgefiltert,
* dies führt sonst zu einem Validierungsfehler beim Export.
*/
public List<Stylesheet> getFilteredStylesheets(){
List<Stylesheet> filteredStylesheets = tableStylesheetList.stream()
.filter(e -> e.getFilename().startsWith("tabelle_html_") || e.getFilename().endsWith(".jrxml")).collect(Collectors.toList());
if (filteredStylesheets.stream().anyMatch(e -> e.getFilename().equals("tabelle_html_datenblatt.xsl"))) {
filteredStylesheets.removeIf(e -> e.getCaption().equals("tabelle_html.xsl"));
}
return filteredStylesheets;
}
public List<Stylesheet> getTableStylesheetsForNg() {
Field stylesheetField = getFieldOrNull("tablestylesheet");
Field ausgabeformatField = getFieldOrNull("Ausgabeformat");
if (stylesheetField != null) {
// report has field "tablestylesheets
// return its entries, even if there are none!
// (i.e. a dependant field yields no stylesheets)
Collection<SelectableItemNode> stylesheetItems = stylesheetField.getSelectableItemsTree().getAllElements();
List<Stylesheet> tableStylesheets = new ArrayList<>();
// Gibt es nur ein Stylesheet? (size() == 2, weil immer ein leerer Eintrag an erster Stelle ist!)
// UND gibt es das Feld "Ausgabeformat", dann wird das Stylesheet aus den Feldinhalten
// erstellt:
if (stylesheetItems.size() == 2 && ausgabeformatField != null) {
String defaultStylesheetKey = ausgabeformatField.getDefaultValueKey();
Collection<SelectableItemNode> ausgabeformatItems = ausgabeformatField.getSelectableItemsTree().getAllElements();
SelectableItemNode[] itemArr = stylesheetItems.toArray(new SelectableItemNode[0]);
SelectableItemNode[] ausgabeArr = ausgabeformatItems.toArray(new SelectableItemNode[0]);
Stylesheet s = new Stylesheet((String) itemArr[1].getId());
s.setCaption(itemArr[1].getName());
s.setContenttype(defaultStylesheetKey == null || defaultStylesheetKey.isEmpty() ? (String) ausgabeArr[1].getId() : defaultStylesheetKey);
tableStylesheets.add(s);
// ansonsten wird aus der DB ausgelesen
} else if (stylesheetField.hasEntries()) {
StringBuffer listBuffer = new StringBuffer();
for (SelectableItemNode item : stylesheetItems) {
String fileName = (String) item.getId();
if (!fileName.isEmpty()) {
listBuffer
.append('\'')
.append(fileName)
.append('\'')
.append(',');
}
}
listBuffer.deleteCharAt(listBuffer.length() - 1);
String list = listBuffer.toString();
logger.debug(list);
String sql = String.format(QUERY_STYLESHEETS_BY_FILENAMES, this.getId().toString(), list);
try {
SxResultSet res = ServletUtils.execute("Get Stylesheet infos for angular", sql, this.mandantenID);
Iterator<SxResultRow> it = res.iterator();
while(it.hasNext()) {
SxResultRow row = it.next();
Stylesheet s = new Stylesheet(row);
tableStylesheets.add(s);
}
} catch (Exception e) {
logger.error("Couldn't read stylesheets", e);
}
}
return tableStylesheets;
}
// default: report has no field "tablestylesheets", return
// the default set
return getFilteredStylesheets();
}
public String getDefaultStylesheetForNg() {
Field aField = getFieldOrNull("tablestylesheet");
if (aField != null) {
return aField.getDefaultValueKey();
}
return this.selectedTableStylesheet.getFilename();
}
public String getMandantenId() {
return this.mandantenID;
}
}
// Created on 23.09.2004 at 14:11:07