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.
 
 
 
 
 
 

2075 lines
87 KiB

package de.superx.common;
import static de.superx.servlet.SxSQL_Server.DEFAULT_MANDANTEN_ID;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
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 org.apache.log4j.*;
import org.slf4j.LoggerFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import de.memtext.baseobjects.NamedIdObject;
import de.memtext.tree.KeyParentEqualException;
import de.memtext.tree.NoMainEntryException;
import de.memtext.util.CryptUtils;
import de.memtext.util.DateUtils;
import de.memtext.util.NumberUtils;
import de.memtext.util.StringUtils;
import de.superx.rest.model.FieldType;
import de.superx.sec.CheckExecution;
import de.superx.servlet.ExternalPool;
import de.superx.servlet.ServletUtils;
import de.superx.servlet.SxPools;
import de.superx.util.SqlStringUtils;
import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.SimpleSequence;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
/**
* Ein Feld wie es in der Tabelle felderinfo hinterlegt ist. Zusätzlich merkt es
* sich das Objekt, alle Auswahlmöglichkeiten bei Feldern wie dem Organigramm
* oder Kostenartenauswahl
*
*/
public class Field extends NamedIdObject implements TemplateHashModel, TemplateMethodModel {
public enum Art {
id_0_nur_Text_direkte_Eingabe(0), // Freitextfeld
id_1_Nummer_Text_nur_mit_Dialog(1), // aka drop down list
id_2_wie_1_aber_mit_stored_Procedure(2), // in keinem Standardbericht
id_3_Dateiauswahl_nur_mit_Dialog(3), // in keinem Standardbericht
id_4_Institutionsdialog(4), // in keinem Standardbericht
id_5_nur_Text_nur_Dialog(5), // hier wird nur eine statische Beschriftung angezeigt, es gibt kein Eingabefeld
id_6_Institutionsdialog_fuer_Lehreinheiten(6), // in keinem Standardbericht
id_7_Institutionsdialog_fuer_Lehreinheiten_ohne_Einschr_Userrechte(7), // in keinem Standardbericht
id_8_Erlaeuterungsfeld_ohne_Mausaktion(8), // u.a.(?) die Trennlinie
id_9_Treeview(9), // in keinem Standardbericht
id_10_Checkbox(10), // in keinem Standardbericht
id_11_Passwort(11), // Passwortfeld
id_12_Sicht(12), // Sichtenauswahl
id_13_Verstecktes_Feld(13), // Hidden field
id_15_Hyperlink_Feld(15), // in keinem Standardbericht
id_17_Radio(17), // Radiobutton
id_18_Link_auf_weitere_Einstellungen(18), // diese Elementart dient nicht der Dateneingabe, sondern bietet die Möglichkeit, einen Link zu konfgurieren
id_19_Datei_Upload(19),
id_21_Datum_von_bis(21),
id_999_Inaktives_Feld(999);
private int value;
private static Map<Integer, Art> map = new HashMap<Integer, Art>();
static {
for (Art art : Art.values()) {
map.put(Integer.valueOf(art.value), art);
}
}
public static Art valueOf(int key) {
return map.get(Integer.valueOf(key));
}
public int getIntValue() {
return value;
}
private Art(int value) {
this.value = value;
}
}
public enum Typ {
typ_sql("sql"),
typ_date("date"),
typ_integer("integer"),
typ_char("char"),
typ_decimal("decimal"),
typ_timestamp("timestamp"),
typ_time("time");
private String value;
private Typ(String value) {
this.value = value;
}
public String getStringValue() {
return value;
}
}
private boolean isMacroMaskenSichtSet = false;
private static org.slf4j.Logger logger = LoggerFactory.getLogger(Field.class);
public boolean isMacroMaskenSichtSet() {
return isMacroMaskenSichtSet;
}
public void setMacroMaskenSichtSet(boolean isMacroMaskenSichtSet) {
this.isMacroMaskenSichtSet = isMacroMaskenSichtSet;
}
String mandantenID = DEFAULT_MANDANTEN_ID;
private int nummer, x, y, buttonbreite, feldbreite, zeilenanzahl, laenge, obligatorisch, startpos;
Art art;
Typ typ = null;
private Integer maskennummer;
private String relation, attribut;
private String defaultwertString;
private String selectedKey;
private Locale locale;
private String captionShort, captionLong;
private SxResultSet captionSet;
private Sichtgruppe sichtgruppe;
// Verweis auf individualFields einer Maske wird für etwaige
// Querabhänigkeiten
// insbesondere bei Benutzung von Freemarker in relations-sqls benötigt
private FieldContainer fieldContainer;
// von apply makro feld wert hinterlegte WErt
// private NamedIdObjectWithParentCollection tempElements=new
// NamedIdObjectWithParentCollection();
// Sammlung der Elemente, die als Auswahl möglich sind
private SelectableItemTree selectableItemsTree = new SelectableItemTree();
private SelectableItem defaultValue, originalDefaultValue;
// wenn für eine Submasken eines Makros ein spezieller Auswahlwert
// hinterlegt wurde
private boolean isSpecialSelectionApplied = false;
private static final long serialVersionUID = 1;
private boolean isDynamic, isInited;
private FieldType fieldType;
// can be set to true for testing code
public static boolean isTest = false;
public Field() {
}
/**
* just for cloning
*
* @param namedIdObject
*/
private Field(NamedIdObject namedIdObject, Integer maskennummer, SxResultSet captionSet) {
this.setId(namedIdObject.getId());
this.setName(namedIdObject.getName());
this.captionSet = captionSet;
this.maskennummer = maskennummer;
if (getId() == null) throw new IllegalArgumentException("Kann kein Feld mit tid=null aufbauen " + namedIdObject);
}
public Field(String mandantenID, SxUser user, Integer maskennummer, SxResultRow feldRow, Locale locale, Hashtable formular, HashMap map, FieldContainer individualFields,
SxResultSet captionSet) throws TemplateException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException,
SQLException, DBServletException, NoMainEntryException {
this.mandantenID = mandantenID;
this.maskennummer = maskennummer;
this.captionSet = captionSet;
this.setFieldContainer(individualFields);
setId(checkValueForNull(feldRow.get(0), "Kann kein Feld mit tid=null aufbauen"));
setName(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(1), "Feld ohne Name in felderinfo")).replaceFirst("^@@@", ""));
setNummer(Integer.parseInt(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(2), "Feld ohne Nummer in felderinfo"))));
//x,y koennen in DB Null sein, hier aber Zahl erwartet #284469
String x="0", y="0";
if (feldRow.get(3)!=null) x=feldRow.get(3).toString();
if (feldRow.get(4)!=null) y=feldRow.get(4).toString();
setX(Integer.parseInt(x));
setY(Integer.parseInt(y));
setButtonbreite(feldRow.get(5) != null ? Integer.parseInt(SqlStringUtils.getValueAsString(feldRow.get(5))) : 0);
setFeldbreite(feldRow.get(5) != null ? Integer.parseInt(SqlStringUtils.getValueAsString(feldRow.get(6))) : 0);
setZeilenanzahl(feldRow.get(5) != null ? Integer.parseInt(SqlStringUtils.getValueAsString(feldRow.get(7))) : 0);
setTyp(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(8), "Feld ohne typ in felderinfo")));
setLaenge(Integer.parseInt(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(9), "Feld ohne laenge in felderinfo"))));
setObligatorisch(Integer.parseInt(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(10), "Feld ohne obligatorisch in felderinfo"))));
setArt(Art.valueOf(Integer.parseInt(SqlStringUtils.getValueAsString(checkValueForNull(feldRow.get(11), "Feld ohne art in felderinfo")))));
setRelation(SqlStringUtils.getValueAsString(feldRow.get(12)));
setAttribut(SqlStringUtils.getValueAsString(feldRow.get(13)));
if (user.isFieldHidingWanted(this.getId())) setAttribut("hidden");
setFieldType();
// Organigramm-Felder, Sichten-Felder und andere Felder mit <<SQL
// sind dynamisch, d.h. werden nicht automatisch
// initalisiert, sondern durch initSelectionElements()
startpos = 0;
if (getRelation() != null && getRelation().startsWith("<<SQL>>")) startpos = 7;
if (isOldOrganigrammArt() || isSicht() || (getRelation() != null && getRelation().indexOf(">>", startpos) > -1)) isDynamic = true;
if (!isDynamic && getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isFileUpload())// direkte Eingabe
initSelectableItemsTree(formular, map, individualFields, user);
setDefaultwertString(SqlStringUtils.getValueAsString(feldRow.get(14)));
setLocale(locale);
// initCaptions(); wird in setLocale gemacht
}
private Object checkValueForNull(Object field, String message) throws IllegalStateException {
Object result = field;
if (result == null) {
throw new IllegalStateException(message + ": " + getId());
}
return result;
}
public void setFieldContainer(FieldContainer fc) {
this.fieldContainer = fc;
}
/**
* Vergleichbare Methode im Applet ist in addButtonField
*
* @param user
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws NoMainEntryException
*/
private void initSichtengruppe(Hashtable formular, HashMap map, FieldContainer individualFields, SxUser user)
throws SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, NoMainEntryException {
List<Integer> sichtentids = new LinkedList<>();
// Falls Datenbankzugriff nötig hier schon machen
if (isSicht() && relation != null && relation.startsWith("<<SQL>>")) {
String stmt = relation.substring(7);
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), formular, stmt);
SuperX_el el = ServletUtils.executeALL_el(null, null, "Sichten für Feld " + getName() + "(" + getId() + ") lesen", stmt, mandantenID, true);
StringBuffer msg = new StringBuffer(" Gefundene Sichtentids für Feld " + getFeldInfo() + " ");
for (Iterator it = el.getResultSet().iterator(); it.hasNext();) {
SxResultRow aRow = (SxResultRow) it.next();
Integer eineSichtTid = (Integer) aRow.get(0);
sichtentids.add(eineSichtTid);
msg.append(eineSichtTid + " ");
}
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, msg.toString());
}
try {
String neuerStand = de.memtext.util.DateUtils.getTodayString();
// MB 11/13
if (!isHidden() && user.getSelectionBuffer().hasFieldStand(getName())) neuerStand = user.getSelectionBuffer().getFieldStand(getName());
sichtgruppe = user.getSichten().getGruppe(formular, map, individualFields, getFeldInfo(), art, sichtentids, relation, getZeilenanzahl(), neuerStand, mandantenID);
} catch (Exception e) {
e.printStackTrace();
throw new SichtException("Initalisieren von Sichten für " + getFeldInfo() + " fehlgeschlagen. DETAILS:" + e.getMessage());
}
}
/**
* MB Neu 8/2011
*
* @param formular
* @param user
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws TemplateException
* @throws IOException
* @throws NoMainEntryException
*/
protected void setDefaultSicht(Hashtable formular, HashMap map, FieldContainer individualFields, SxUser user) throws SQLException, DBServletException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (!isSicht() || !hasDynamicDefaultSicht()) throw new IllegalArgumentException("Kann keine Defaultsicht für Feld " + getName() + "(" + getId() + ") setzen");
String stmt = getAttribut().replace("hidden", "");
stmt = stmt.replace("<<Sicht>>", "");
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), formular, stmt);
SuperX_el el = ServletUtils.executeALL_el(null, null, "Defaultsicht für Feld " + getName() + "(" + getId() + ") lesen", stmt, mandantenID, true);
Integer sichtTid = null;
for (Iterator it = el.getResultSet().iterator(); it.hasNext();) {
SxResultRow aRow = (SxResultRow) it.next();
sichtTid = (Integer) aRow.get(0);
}
if (sichtTid == null) throw new IllegalArgumentException("Keine Defaultsicht für Feld " + getName() + "(" + getId() + ") gefunden DETAILS: per sql:" + stmt
+ " - Attributspalte: " + getAttribut() + " prüfen");
setSicht(formular, map, individualFields, sichtTid, user);
}
/**
* MB Neu 8/2011
*
* @return
*/
protected boolean hasDynamicDefaultSicht() {
return getAttribut() != null && getAttribut().indexOf("<<Sicht>>") > -1;
}
private String getFeldInfo() {
return "Feld " + this.getName() + " (" + this.getId() + ")";
}
private void initCaptions() throws SQLException, DBServletException {
String capShort = "", capLong = "";
boolean capIsSet=false;
/*
* Wenn ein Feld mehrere Captions hat wird nach der Prio
* vorgegangen: Zuerst mit record_no=aktuelles Feld,
* dann mit record_no=null. Das Resultset kommt entsprechend sortiert
* in diese Methode, und hier wird nur noch die locale geprüft:
*
*/
for (Iterator it = captionSet.iterator(); it.hasNext();) {
SxResultRow row = (SxResultRow) it.next();
// Feldname kontrollieren
if (row.get(0) == null || !row.get(0).equals(getName()) || capIsSet)
continue;
// falls vorhanden gewünschte Locale bevorzugen
String availableLocale=(String) row.get(1);
if(availableLocale==null || availableLocale.equals("") || availableLocale.equals(locale.getLanguage().toString()))
{
capShort= row.get(2) != null ? row.get(2).toString():"";
capLong= row.get(3) != null ? row.get(3).toString():"";
capIsSet=true;
}
// wenn immer noch nix Deutsche locale
if(!capIsSet)
{
if(availableLocale!=null && availableLocale.equals("de"))
capShort= row.get(2) != null ? row.get(2).toString():"";
capLong= row.get(3) != null ? row.get(3).toString():"";
capIsSet=true;
}
}
if (capShort != null && !capShort.equals(""))
setCaptionShort(capShort);
if (capLong != null && !capLong.equals(""))
setCaptionLong(capLong);
}
private SxResultRow readCaptionsFromDb(String select_string) throws SQLException, DBServletException {
SxResultRow ret = new SxResultRow(0, 1);
SuperX_el field_el = ServletUtils.executeALL_el(null, null, "Caption SQL durchführen", select_string, mandantenID, true);
String errorstring = field_el.getError_String();
// String errorselect = field_el.getAktuelleNachricht();
if (errorstring != null && !errorstring.equals("")) {
ret.add(0, "SQL-Fehler:" + errorstring + "<br />sql: " + field_el);
ret.add(1, "");
return ret;
} else {
SxResultSet rs = field_el.getResultSet();
if (!rs.isEmpty()) {
ret = (SxResultRow) rs.first();
if (ret.size() == 1) ret.add(1, "");
// ServletUtils.logger.log("sql","Header return: "
// +ret.get(0).toString());
}
}
return ret;
}
public Art getArt() {
return art;
}
public void setArt(Art art) {
this.art = art;
}
public FieldType getFieldType() {
return this.fieldType;
}
public void setFieldType() {
this.fieldType = FieldType.getCorrectedFieldType(this);
}
public SelectableItemTree getSelectableItemsTree() {
return selectableItemsTree;
}
public String getAttribut() {
return attribut;
}
public void setAttribut(String attribut) {
this.attribut = attribut;
}
/**
* hidden Felder werden nicht in sessionbasierten Feldercache gespeichert
*
* @return
*/
public boolean isHidden() {
boolean result = fieldType == FieldType.HiddenField
|| getAttribut().equals("hidden")
|| getName().equals("User-tid")
|| getName().equals("Gruppen-tid")
|| getName().equals("Benutzerkennung");
return result;
}
public boolean isFileUpload() {
return fieldType == FieldType.FileUpload;
}
public int getButtonbreite() {
return buttonbreite;
}
public void setButtonbreite(int buttonbreite) {
this.buttonbreite = buttonbreite;
}
public String getDefaultwertString() {
return defaultwertString;
}
private void setDefaultwertString(String df) throws SQLException {
this.defaultwertString = SxPools.get(mandantenID).checkImports(df);
}
/**
* nicht für sql/direkt eingabe
*
* @param param
* @return result enthält keine Kommas nur |
*/
private String paramAdaptCommaWildcard(String param) {
if (getZeilenanzahl() < 2 || getTyp() == Typ.typ_sql || getArt() == Art.id_0_nur_Text_direkte_Eingabe || isFileUpload() || this.isHidden()) return param;
String result = "";
if (param != null) {
param = param.replace('|', ',');
if (param.indexOf(",") > -1) {
boolean isFirst = true;
for (StringTokenizer st = new StringTokenizer(param, ","); st.hasMoreElements();) {
String aparam = st.nextToken();
if (aparam.indexOf("*") > -1) aparam = paramAdaptCommaWildcard(aparam);
if (!isFirst)
result += "|";
else
isFirst = false;
result += aparam;
}
} else
result = param;
if (result.indexOf("*") > -1) {
if (this.isOldOrganigrammArt() || this.isSicht()) this.getSichtgruppe().getSelectedSicht().setSubelementsinForEach(false);
result = this.selectableItemsTree.getSuitingKeyString(result);
}
}
return result;
}
/**
* Prüft ob ein key (wird getrimmt) auswaehlbar ist Können auch mehrere mit
* oder , | getrennt sein
*
* @param key
* @return
*/
public boolean hasKeys(boolean isMehrfachAuswahl, String key) {
boolean result = true;
// if (getName().equals("Köpfe oder Fälle ?"))
// System.out.println(selectableItemsTree.getAllKeys());
if (!isMehrfachAuswahl) {
result = selectableItemsTree.getById(key) != null;
} else {
String token = ",";
boolean pipe = key.indexOf('|') > -1;
if (pipe) token = "|";
StringTokenizer st = new StringTokenizer(key, token);
if (getArt() != Art.id_0_nur_Text_direkte_Eingabe) // bei Felderart 0 Eingabefeld Wert akzeptieren
{
while (st.hasMoreElements()) {
if (selectableItemsTree.getById(st.nextToken()) == null) result = false;
}
}
}
if (getArt() == Art.id_0_nur_Text_direkte_Eingabe) result = true;
if (isFileUpload()) result = false;
return result;
}
/**
* Wird von Maske.setFieldDefaults aufgerufen
*
* @param request
* @param df
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws UngültigeEingabeException
* @throws NoMainEntryException
* @throws InvalidDataTypeException
*/
public void updateDefaultValue(Hashtable formular, HashMap map, FieldContainer individualFields, String param, boolean isTableServletAndEmptyStringParam, SxUser user)
throws SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException,
UngueltigeEingabeException, NoMainEntryException, InvalidDataTypeException {
// 3/16 MB
logger.debug("*** Set defaultvalue for field " + this.getName());
defaultValue = null;
boolean resetWanted = false;
if (param != null && param.equals("--leer--")) {
resetWanted = true;
param = "";
// MB 8/2015
this.selectableItemsTree.clearSelection();
}
if (getTyp() == Typ.typ_date) {
param = xDateParamOhneApostrophes(param);
//HTML5 input type=date always delivers US-format yyyy-MM-dd
if(param !=null && param.indexOf("-")>-1)
{
param=de.superx.util.SqlStringUtils.formatDateUStoDE(param); //Transform to dd.MM.yyyy
}
}
if (param != null && !param.equals("")) {
checkDataType(param);
}
if ( param != null && !param.equals("") && this.art == Art.id_0_nur_Text_direkte_Eingabe ) {
CheckExecution check = new CheckExecution(this);
if (!check.run(param)) {
System.err.println("Ungültige Eingabe Feld "+ getFeldInfo()+ ": "+param);
throw new UngueltigeEingabeException("Ungültige Eingabe");
}
}
// bei User spezifischen Feldern, müssen die selectionElements evtl.
// noch gefüllt werden
if (art != Art.id_0_nur_Text_direkte_Eingabe && !isFileUpload() && !isInited()) {
initSelectableItemsTree(formular, map, individualFields, user);
}
if (this.isOldOrganigrammArt() || this.isSicht()) {
this.getSichtgruppe().getSelectedSicht().setSubelementsinForEach(true);
}
if (getZeilenanzahl() > 1 && getTyp() != Typ.typ_sql) {
param = paramAdaptCommaWildcard(param);
}
check(param);
// es kann sein, dass der defaultwert aus der DB gelesen werden muss
// dann ist stmt gefüllt
String stmt = SqlStringUtils.adaptSql(SxPools.get(mandantenID).getSqlDialect(), defaultwertString, null);
if (stmt != null && !stmt.equals("")) {
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), formular, stmt);
stmt = stmt.replace("@@TID@@", "" + this.getId());
logger.debug("*** Update default SQL: " + stmt);
defaultValue = readDefaultwertFromDb(user, stmt, formular);
if (originalDefaultValue == null) {
originalDefaultValue = (SelectableItem) defaultValue.clone();
}
} else { // nicht aus DB
if (art == Art.id_0_nur_Text_direkte_Eingabe ||
art == Art.id_13_Verstecktes_Feld ||
art == Art.id_19_Datei_Upload) {
defaultValue = new SelectableItem(defaultwertString, defaultwertString);
} else {
if ((param == null || param.equals("")) && defaultwertString != null) {
param = new String(defaultwertString);
}
// verarbeitung s.u.
}
}
// Wenn ein Parameter übergeben wurde, diesen als Wert nehmen
//wird unten ggfs noch mal überschrieben, wenn Leerstring als Parameter übergeben wurde
if (param != null && !(param.equals(""))) {
if (art == Art.id_1_Nummer_Text_nur_mit_Dialog && typ == Typ.typ_date) {
if (!param.startsWith("'")) {
param = "'" + param;
}
if (!param.endsWith("'")) {
param = param + "'";
}
}
if (art == Art.id_0_nur_Text_direkte_Eingabe ||
art == Art.id_10_Checkbox ||
art == Art.id_11_Passwort ||
art == Art.id_13_Verstecktes_Feld ||
art == Art.id_19_Datei_Upload ||
art == Art.id_18_Link_auf_weitere_Einstellungen) {
if (art == Art.id_10_Checkbox && param.isEmpty()) {
param = "false";
}
defaultValue = new SelectableItem(param, param);
} else {
try {
if (param.indexOf("|") > -1) {
defaultValue = new SelectableItem(param, getMultiNames(param));
defaultValue.setTemporary(true);
selectableItemsTree.setSelectedKeys(param);
} else {
SelectableItemNode node = selectableItemsTree.getById(param);
if (node == null) {
throw new UngueltigeEingabeException(getName() + " ungültige Eingabe");
}
defaultValue = (SelectableItem) node.getUserObject();
selectableItemsTree.setSelectedKey(param);
}
} catch (IllegalArgumentException e) {
System.err.println(getFeldInfo() + " ungültiger Defaultwert:" + param + " auswählbar gewesen wäre:");
StringBuffer buf = new StringBuffer();
for (Enumeration en = ((DefaultMutableTreeNode) selectableItemsTree.getModel().getRoot()).breadthFirstEnumeration(); en.hasMoreElements();) {
SelectableItemNode n = (SelectableItemNode) en.nextElement();
if (n.isRoot()) {
continue;
}
buf.append(n + " " + n.getId().toString() +"\n");
}
System.out.println(buf);
// Zendas Wunsch nix näheres angeben
throw new UngueltigeEingabeException(getName() + " ungültige Eingabe");
}
}
}
if (isTableServletAndEmptyStringParam) {
defaultValue = null;
}
if (defaultValue == null || resetWanted) {
defaultValue = new SelectableItem("", "");
}
logger.debug("*** Defaultvalue set to: " + this.defaultValue.getId());
}
/**
* Der erste Eintrag der ggfs. aus der Datenbank gelesen wurde
* @return
*/
public SelectableItem getOriginalDefaultValue() {
return originalDefaultValue;
}
public String getDefaultValueKey() {
String result = "";
if (defaultValue != null) result = defaultValue.getId().toString();
return result;
}
/**
* 07/2010 - auch Freemarker Transformation
*
* @param user
* @param stmt
* @param formular
* @return
* @throws DBServletException
* @throws SQLException
* @throws TemplateException
* @throws IOException
*/
SelectableItem readDefaultwertFromDb(SxUser user, String stmt, Hashtable formular) throws DBServletException, SQLException, TemplateException, IOException {
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), formular, stmt);
HashMap map = new HashMap();
if (user != null) map.putAll(user.getBasicMap());
stmt = SxPools.get(mandantenID).getTemplateProcessor().process(map, maskennummer, "Felddefault " + getId(), stmt, fieldContainer,
SxPools.get(mandantenID).getRepository(), SxPools.get(mandantenID).getSqlDialect());
ExternalPool ep = ServletUtils.getExternalPoolIfSpecified(mandantenID, maskennummer, defaultwertString);
SuperX_el el = ServletUtils.executeALL_el(ep, null, "Defaultwert für Feld " + getName() + " (" + getId() + ") ermitteln", stmt, mandantenID, true);
String key;
String name;
SxResultSet result = el.getResultSet();
if (result.size() == 0) {
return new SelectableItem("", "");
}
SxResultRow defaultrow = (SxResultRow) result.first();
if (result.size() > 1) {
System.out.println(getFeldInfo() + " default-sql " + stmt + " lieferte mehrere Werte, Mehrfachauswahl wird aber nicht unterstützt, nur 1. Wert wird genommen");
}
key = SqlStringUtils.getValueAsString(defaultrow.get(0));
if (key == null)
return new SelectableItem("", "");
if (defaultrow.size() > 1) {
name = formatName(SqlStringUtils.getValueAsString(defaultrow.get(1)));
} else {
// Prüfen ob im SelectableItemTree Item vorkommt
SelectableItemNode node = null;
if (selectableItemsTree != null) node = selectableItemsTree.getById(key);
if (node != null) {
name = node.getName();
} else {
name = formatName(key);
}
}
return new SelectableItem(key, name);
}
public int getFeldbreite() {
return feldbreite;
}
public void setFeldbreite(int feldbreite) {
this.feldbreite = feldbreite;
}
public int getLaenge() {
return laenge;
}
public void setLaenge(int laenge) {
this.laenge = laenge;
}
public int getNummer() {
return nummer;
}
public void setNummer(int nummer) {
this.nummer = nummer;
}
public void setObligatorisch(int obligatorisch) {
this.obligatorisch = obligatorisch;
}
public boolean isObligatorisch() {
return obligatorisch == 1;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) throws SQLException {
if (relation != null && relation.trim().equals("")) relation = null;
this.relation = SxPools.get(mandantenID).checkImports(relation);
}
public Typ getTyp() {
return typ;
}
public void setTyp(String typ) {
for (Typ t : Typ.values())
{
if(t.getStringValue().equals(typ.toLowerCase().trim()))
this.typ = t;
}
if (this.typ == null) throw new IllegalArgumentException("Ungültiger Typ: " + typ + " für Feld " + getId());
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZeilenanzahl() {
return zeilenanzahl;
}
public void setZeilenanzahl(int zeilenanzahl) {
this.zeilenanzahl = zeilenanzahl;
}
public Locale getLocale() {
return locale;
}
/** Macht auch Captions lesen **/
public void setLocale(Locale newlocale) throws SQLException, DBServletException {
if (locale == null || !(locale.equals(newlocale))) {
this.locale = newlocale;
initCaptions();
}
}
public String getCaptionShort() {
return captionShort;
}
public void setCaptionShort(String cap) {
this.captionShort = cap;
}
public String getCaptionLong() {
return captionLong;
}
public void setCaptionLong(String cap) {
this.captionLong = cap;
}
/**
* initialisiert die auswählbaren Elemente. Es kann sich um eine Feldart
* handeln, bei der das Organigramm gelesen wird oder auch um einen explizit
* hinterlegten relations-sql
*
* @param user
* - wenn null können keine user-spezifischen Felder
* initialisiert werden
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
private void initSelectableItemsTree(Hashtable formular, HashMap map, FieldContainer individualFields, SxUser user) throws SQLException, DBServletException,
KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
// TODO: Achtung! Hiermit wird auch sichtgruppe geleert, selbe Objektreferenz?!
if (sichtgruppe == null) {
((DefaultMutableTreeNode) selectableItemsTree.getModel().getRoot()).removeAllChildren();
}
isInited = true;
String stmt = SqlStringUtils.createRelationString(SxPools.get(mandantenID).getSqlDialect(), "" + getArt().getIntValue(), getRelation(), getAttribut());
if (stmt.equals("")) return;
if (isOldOrganigrammArt() || isSicht()) {
if (user == null) throw new IllegalStateException("Da der Parameter user an Field.initSelectableItemTree null war, kann kein Organigramm bzw Sicht eingelesen werden");
// MB 1/2016 TEST wenn dynamisch komplett neu aufbauen
if (sichtgruppe == null) {
initSichtengruppe(formular, map, individualFields, user);
}
// if (this.getSichtgruppe().hasDynamicSicht())
// this.getSichtgruppe().updateDynamicSichten(formular, map,
// individualFields);
// MB 11/13
if (!isHidden() && user.getSelectionBuffer().hasFieldSicht(getName())
&& sichtgruppe.containsItemWithId(Integer.valueOf(user.getSelectionBuffer().getFieldSicht(getName())))) {
sichtgruppe.setSelectedSicht(Integer.valueOf(user.getSelectionBuffer().getFieldSicht(getName())));
// nur durch setzen von Stand, wird selectableItemsTree
// aktualisiert
if (!isHidden() && user.getSelectionBuffer().hasFieldStand(getName()))
sichtgruppe.setStand(formular, map, individualFields, user.getSelectionBuffer().getFieldStand(getName()));
}
selectableItemsTree = (SelectableItemTree) sichtgruppe.getSelectedSicht();
updateSichtenInFormular(formular);
} else // bei nicht-Organigramm/Sichten
{
if (formular != null) {
stmt = SqlStringUtils.generateSQL(SxPools.get(mandantenID).getDatabaseAbbr(), formular, stmt);
}
// MB 1/16 map wird schon übergeben
// HashMap map = new HashMap();
// if (user != null)
// map.putAll(user.getBasicMap());
stmt = SxPools.get(mandantenID).getTemplateProcessor().process(map,maskennummer, "Feld " + getId(), stmt, fieldContainer, SxPools.get(mandantenID).getRepository(),
SxPools.get(mandantenID).getSqlDialect());
String msg = "Ausführen des relations-Sqls für Feld " + getName() + " (" + getId() + ")";
int startSuchPos = 0;
if (relation.startsWith("<<SQL>>")) startSuchPos = 7;
if (relation.indexOf("<<", startSuchPos) > -1)
msg += " Es sind Tags wie << Semester >> enthalten, alle benötigten Felder müssen eine kleinere Felderinfo-tid haben\nund einen Defaultwert ausgewählt haben ";
SxResultSet rohform;
if (SxPools.get(mandantenID).getFieldElementCache().containsEntry(stmt)) {
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, " hole aus Cache: SQL für Feld " + getName() + " (" + getId() + "): " + stmt);
rohform = SxPools.get(mandantenID).getFieldElementCache().get(stmt);
} else {
Logger.getLogger("superx_" + mandantenID).log(Level.DEBUG, "SQL für Feld " + getName() + " (" + getId() + "): " + stmt);
ExternalPool ep = ServletUtils.getExternalPoolIfSpecified(mandantenID, maskennummer, getRelation());
rohform = ServletUtils.executeALL_el(ep, null, msg, stmt, mandantenID, true).getResultSet();
}
String id;
String name;
// Organigramm ist jetzt in Sichten, wird eigentlich nicht mehr
// gebraucht
// normalerweise kommt id bzw key als erstes und dann der Name
int idPos = 0;
int namePos = 1;
// bei Organigramm-Abfragen / Treeviews ist es aber dummerweise
// genau
// anders herum
// herum
if (isOldOrganigrammArt() || isTreeView()) {
idPos = 1;
namePos = 0;
}
// dieses leer-Item wird gewählt, wenn in der Combobox keine
// Einschränkung vorgenommen wurde
selectableItemsTree.add(new SelectableItemNode(new SelectableItem("", "")));
for (Iterator it = rohform.iterator(); it.hasNext();) {
SxResultRow element = (SxResultRow) it.next();
id = SqlStringUtils.getValueAsString(element.get(idPos));
if (element.size() > 1)
name = formatName(SqlStringUtils.getValueAsString(element.get(namePos)));
else
name = id;
SelectableItem item = new SelectableItem(id, name);
if (element.size() > 2 && rohform.getColumnName(2).equals("nodeattrib")) item.setNodeAttrib(element.get(2));
// Organigramm ist jetzt in Sichten, wird eigentlich nicht mehr
// gebraucht
if (isOldOrganigrammArt()) {
item.setOrganigrammItem(true);
item.setParentKey(element.get(2));
item.setAllowed(element.get(3) != null && element.get(3).toString().equals("1"));
}
if (isTreeView()) {
item.setTreeView(true);
item.setParentKey(element.get(2));
}
SelectableItemNode newnode = new SelectableItemNode(item);
newnode.setAllowed(true);
selectableItemsTree.add(newnode);
}
}
if (!isDynamic() && getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isFileUpload() && isObligatorisch() && !hasEntries()) {
throw new IllegalStateException("Das Feld " + getName() + " ist obligatorisch, enthält aber keine Werte zur Auswahl - wahrscheinlich keine Daten vorhanden");
}
}
public boolean hasEntries() {
boolean result = false;
DefaultMutableTreeNode root = (DefaultMutableTreeNode) selectableItemsTree.getModel().getRoot();
for (Enumeration en = root.children(); en.hasMoreElements();) {
SelectableItemNode child = (SelectableItemNode) en.nextElement();
if (!child.getName().equals("")) result = true;
}
return result;
}
private void updateSichtenInFormular(Hashtable formular) {
formular.put(sichtgruppe.getArt(), sichtgruppe.getSelectedSicht().getId().toString());
formular.put(this.getName() + "-Sicht", sichtgruppe.getSelectedSicht().getId().toString());
formular.put(sichtgruppe.getArt() + "-Stand", " date_val('" + sichtgruppe.getStand() + "')");
if (sichtgruppe.getArt().endsWith("-Sicht"))
formular.put(StringUtils.removeFromEnd(sichtgruppe.getArt(), "Sicht", true) + "Stand", " date_val('" + sichtgruppe.getStand() + "')");
formular.put(this.getName() + "-Stand", " date_val('" + sichtgruppe.getStand() + "')");
}
/**
* Formatiert ein Objekt zur schönen Ansicht - insb. Datum
*
* @param o
* @return
*/
private String formatName(Object o) {
String result = "";
if (o != null) // throw new IllegalArgumentException("Can't format null
// ");
{
result = o.toString();
if (o instanceof java.util.Date) {
result = de.memtext.util.DateUtils.format((java.sql.Date) o);
}
}
return result;
}
/**
* Liefert, ob ein Feld eine alte Organigramm-Sicht (Art 4,6 oder 7)
* darstellt
*
* @return
*/
public boolean isOldOrganigrammArt() {
return fieldType == FieldType.TreeSelect_Institution_Person;
}
public boolean isTreeView() {
return fieldType == FieldType.TreeView;
}
public boolean isSicht() {
return fieldType == FieldType.TreeSelect;
}
/**
* Lieftert true, wenn ein Sichtfeld eine Sichtgruppe der Art Organigramm
* hat
*
* @return
*/
public boolean isOrganigrammSichtArt() {
boolean result = false;
if (isSicht() && sichtgruppe.getArt().startsWith("Organigramm")) result = true;
return result;
}
public String getSelectedKeyEscaped() {
String escaped = "";
if (selectedKey == null) {
escaped = getEscaped(selectedKey);
} else {
if (selectedKey.indexOf("|") == -1)
escaped = getEscaped(selectedKey);
else {
StringTokenizer st = new StringTokenizer(selectedKey, "|");
while (st.hasMoreTokens()) {
escaped += getEscaped(st.nextToken()) + ",";
}
if (escaped.endsWith(",")) escaped = StringUtils.deleteLastChar(escaped);
}
}
return escaped;
}
/**
* Achtung wird von getselectedKeyEscaped aufgerufen gibt aber ähnliche
* Methode getKeyEscaped(Object)
*
* @param key
* @return
*/
private String getEscaped(String key) {
Art feldart = this.getArt();
String escapedKey = "";
if (key != null) escapedKey = new String(key);
// dirty escaping, we should have a proper specification and unit
// tests
// widerlich - datumsfelder können schon ein ' als Umgebung haben
if (getTyp() == Typ.typ_date && !escapedKey.equals("") && !escapedKey.startsWith("'")) {
escapedKey = "'" + escapedKey + "'";
}
if (feldart == Art.id_11_Passwort) escapedKey = CryptUtils.encodeSHA(escapedKey + CryptUtils.geheimnis1);
if (getTyp() == Typ.typ_char || getTyp() == Typ.typ_time) {
String charcode1 = "'";
String charcode2 = "'";
escapedKey = SqlStringUtils.escapeString(escapedKey);
if (escapedKey.length() > 0) {
if (SqlStringUtils.unescapeString(escapedKey).equals("--leer--"))
escapedKey = charcode1 + charcode2;
else
escapedKey = charcode1 + escapedKey + charcode2;
}
}
if (this.isOldOrganigrammArt() || isOrganigrammSichtArt()) {
// Organigramm kommt mit "" nicht klar, muss 'null' sein
if (escapedKey.equals("")) escapedKey = "'null'";
}
if (getTyp() == Typ.typ_sql) {
escapedKey = escapedKey.replace(';', '^');
}
return escapedKey;
}
// when field constructor ist called initSelectableItemsTree could not initSelectableItemsTree because of missing individualFields in Mask
public void initIfNeeded(Hashtable formular, HashMap map, FieldContainer individualFields, SxUser user) throws SQLException, DBServletException, KeyParentEqualException,
CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isFileUpload() && !isInited) {
initSelectableItemsTree(formular, map, individualFields, user);
// initCaptions();
}
}
/**
* Holt eine xml-Darstellung des Feldes mit ausgewähltem Wert bei einem
* Makrofeld, für das ein spezieller Wert hinterlegt wurde kann es sein,
* dass die selectionElemente noch nicht initialisiert wurden, Für die ggfs.
* nötige Initalisierung werden formular und user durchgereicht
*
* Wenn nichts ausgewählt wurde (null,"" oder "null") kommt ein Leerstring
* zurück
*
* @param formular
* @param user
* @return String xml Darstellung
* @throws ParseException
* @throws InvalidKeyException
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws SichtException
* @throws IOException
* @throws TemplateException
* @throws NoMainEntryException
*/
public String getSelectedKeyXml(Hashtable formular, HashMap map, FieldContainer individualFields, SxUser user) throws ParseException, InvalidKeyException, SQLException,
DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
// bei einfachen Feldern wie Jahreszahl ist key und name gleich
// bei kompleren Feldern mit Auswahl wie Organigramm sind die
// möglichen Elemente in der Liste selectionElements hinterlegt
// und das ausgewählte Element kann anhand des Keys gefunden werden
StringBuffer result = null;
initIfNeeded(formular, map, individualFields, user);
if (isSelectedKeyEmpty() && !isSicht()) {
result = new StringBuffer("");
} else {
// System.out.println(getId()+" "+ getName());
result = new StringBuffer("<feld varname=\"" + getName() + "\" art=\"" + getArt().getIntValue() + "\" typ=\"" + getTyp().getStringValue() + "\"" + " tid=\"" + getId().toString() + "\"");
if (isOldOrganigrammArt() || (isSicht() && sichtgruppe.getSelectedSicht().isStandbuttonWanted())) {
result.append(" stand=\"" + sichtgruppe.getSelectedSicht().getStand() + "\"");
result.append(" isstandtoday=\"" + (DateUtils.isToday(sichtgruppe.getSelectedSicht().getStand()) ? "true" : "false") + "\"");
}
if (isSicht()) result.append(" sichtenzahl=\"" + sichtgruppe.size() + "\" ");
result.append(">" + "<caption_short><![CDATA[" + getCaptionShort() + "]]></caption_short>" + "<caption_long><![CDATA[" + getCaptionLong() + "]]></caption_long>"
+ getValueXml());
if (isSicht()) {
result.append("<sicht name_intern=\"" + sichtgruppe.getSelectedSicht().getName_intern() + "\" tid=\"" + sichtgruppe.getSelectedSicht().getId()
+ "\" isFirstInGroup=\"" + (sichtgruppe.getSelectedSicht().isFirstInGroup() ? "true" : "false") + "\"");
// if (sichtgruppe.isStandButtonWanted())
// result.append(" stand=\""+sichtgruppe.getStand()+"\"");
result.append("><![CDATA[" + sichtgruppe.getSelectedSicht().getName() + "]]></sicht>");
}
result.append("</feld>\n");
}
return result.toString();
}
public String getValueXml() throws ParseException {
String valueCaption = getSelectedKeyValueCaption();
if (isSicht() && isSelectedKeyEmpty()) valueCaption = "keine Einschränkung";
return "<value><![CDATA[" + getKeyEscaped(selectedKey) + "]]></value><value_caption><![CDATA[" + SqlStringUtils.unescapeString(valueCaption) + "]]></value_caption>";
}
public String getSelectedKeyValueCaption() throws ParseException {
String valueCaption = "";
if (!isSelectedKeyEmpty()) {
valueCaption = getKeyEscaped(selectedKey);
if (getArt() == Art.id_0_nur_Text_direkte_Eingabe || isFileUpload()) // bei direkter Eingabe
{
valueCaption = "";
if (selectedKey != null) valueCaption = selectedKey.toString();
}
if (!isSelectedKeyEmpty() && selectableItemsTree.getRoot().getChildCount() > 0) {
if (selectedKey.indexOf("|") > -1) {
valueCaption = getMultiNames(selectedKey);
} else {
SelectableItemNode item = (SelectableItemNode) selectableItemsTree.getById(selectedKey);
valueCaption = item.getName();
}
}
}
return valueCaption;
}
public boolean shouldBeAddedToLegend() throws ParseException {
String value = this.getSelectedKey();
if ( this.fieldType == FieldType.Anchor ) return false;
if ( value == null || value.isEmpty() ) return false;
if ( this.fieldType == FieldType.HLine ) return false;
if ( this.isHidden() ) return false;
if ( this.isLabel() ) return false;
if ( !value.equals("") ) return true;
if ( this.isOrganigrammSichtArt() &&
( !this.getSichtgruppe().getSelectedSicht().isFirstInGroup() ||
DateUtils.isToday(this.getSichtgruppe().getSelectedSicht().getStand()))
) {
return true;
}
// TODO: Return default true for debug purposes, so that uncaught cases are shown in frontend.
// Set default to false once all cases are identified.
return true;
}
public boolean isLabel() {
return this.fieldType == FieldType.Label;
}
public String getLegendName() {
String feldname = this.getCaptionShort();
if (feldname == null || feldname.equals("")) feldname = this.getName();
return feldname;
}
public String getValueCaptionForLegend() throws ParseException {
String result = this.getSelectedKeyValueCaption() + this.addSichtAndStand();
if (this.isSicht() && this.isSelectedKeyEmpty()) result = "keine Einschränkung";
return SqlStringUtils.unescapeString(result);
}
private String addSichtAndStand() {
return this.isSicht()
? " (Sicht: " + this.getSichtgruppe().getSelectedSicht().getName() + " Stand: " + this.getSichtgruppe().getStand() + ")"
: "" ;
}
boolean isSelectedKeyEmpty() {
return (selectedKey == null || selectedKey.equals("null") || selectedKey.equals(""));
}
private void throwInvalidKey() throws InvalidKeyException {
StringBuffer msg = new StringBuffer("Ungültiger Schlüssel:\"" + selectedKey + "\" für das Feld " + getName() + " DETAILS:" + " (tid " + getId()
+ ").\nDer Wert kommt nicht in den auswählbaren Werten des Felds vor.\n");
if (isSicht()) {
msg.append(" Die möglichen Auswahlwerte werden durch die Sicht (vergl. Spalte relation in Felderinfo) definiert.\n");
AbstractSicht sicht = sichtgruppe.getSelectedSicht();
if (sicht == null)
msg.append(" Es war keine Sicht ausgewählt.\n");
else
msg.append("Ausgewählt war Sicht " + sicht.getName() + "(" + sicht.getId() + ") Stand:" + sicht.getStand() + "\n");
} else if (isOldOrganigrammArt()) {
msg.append(" Die möglichen Auswahlwerte werden durch das Organigramm, Feldart " + getArt() + " definiert.\n");
AbstractSicht sicht = sichtgruppe.getSelectedSicht();
if (sicht == null)
msg.append(" Es war intern keine Sicht für diese Feldart ausgewählt.\n");
else
msg.append("Gewählter Stand:" + sicht.getStand() + "\n");
} else {
if (getRelation() != null && getRelation().startsWith("<<SQL>>"))
msg.append(" Die möglichen Auswahlwerte werden durch das in der Spalte relation hinterlegte SQL-Statement definiert:\n " + getRelation());
else
msg.append(" Die möglichen Auswahlwerte werden durch die Spalte relation (und ggfs.attribut) definiert.\n");
}
msg.append("\n");
if (getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isFileUpload() && selectableItemsTree != null && selectableItemsTree.getRoot() != null) {
msg.append("Auswählbar wären die folgenden Schlüssel gewesen:\n");
SelectableItemNode sin = null;
for (Enumeration en = selectableItemsTree.getRoot().preorderEnumeration(); en.hasMoreElements();) {
sin = (SelectableItemNode) en.nextElement();
msg.append(sin.getKey() + " : Bezeichnung: " + sin.getName() + "\n");
}
}
throw new InvalidKeyException(msg.toString());
}
public Sichtgruppe getSichtgruppe() {
return sichtgruppe;
}
/**
* initIfNeeded muss vorher aufgerufen worden, sein, weil der gewählte key
* jetzt im Baum markiert wird Als temporärer Trick wird für art 1-Felder
* akzeptiert dass eine Mehrfachauswahl mit | codiert übergeben wird. Für
* diese wird ein temp. Knoten in den Baum eingefügt
*
* @param selectedKey
* @throws InvalidKeyException
* @throws InvalidDataTypeException
*/
public void setSelectedKey(String selectedKey) throws InvalidKeyException, InvalidDataTypeException {
if (selectedKey != null && selectedKey.equals("--leer--")) selectedKey = "";
if (getZeilenanzahl() > 1) {
if (this.isOldOrganigrammArt() || this.isSicht()) this.getSichtgruppe().getSelectedSicht().setSubelementsinForEach(true);
selectedKey = paramAdaptCommaWildcard(selectedKey);
}
check(selectedKey);
this.selectedKey = selectedKey;
if (this.selectedKey != null && !this.selectedKey.equals("") & getTyp() == Typ.typ_date) {
xSelectedKeyDatePrüfen();
}
if (this.selectedKey != null && !this.selectedKey.equals("") && !(getArt() == Art.id_1_Nummer_Text_nur_mit_Dialog && this.selectedKey.indexOf("|") > -1)) checkDataType(this.selectedKey);
xDirekteingabeSQLoderCharLängePrüfen();
if (this.isOldOrganigrammArt() || this.isSicht() || (selectableItemsTree.getRoot().getChildCount() > 0)) {
if (isSelectedKeyEmpty()) {
selectableItemsTree.clearSelection();
defaultValue = new SelectableItem("", "");
} else {
try {
if (this.selectedKey.indexOf("|") == -1 || getTyp() == Typ.typ_sql)
selectableItemsTree.setSelectedKey(this.selectedKey);
else {
selectableItemsTree.setSelectedKeys(this.selectedKey);
}
} catch (IllegalArgumentException e) {
throwInvalidKey();
}
}
}
// if (this.selectedKey != null && this.selectedKey.indexOf("|") > -1)
// addTempMultiSelectionElement(this.selectedKey);
}
/**
* // bei sql/char und direkteingabe kein Parameter der länger als Länge //
* ist akzeptieren
*/
private void xDirekteingabeSQLoderCharLängePrüfen() {
if (this.selectedKey != null && (getArt() == Art.id_0_nur_Text_direkte_Eingabe || this.isHidden() || isFileUpload())// direkteingabe
&& (getTyp() == Typ.typ_sql || getTyp() == Typ.typ_char)) {
if (this.laenge == 0) throw new IllegalStateException("In felderinfo ist 0 für laenge hinterlegt " + getFeldInfo());
if (this.selectedKey.trim().length() > this.laenge) {
throw new IllegalArgumentException("Eingabe war länger als die vorgesehene maximale Zahl von " + laenge + " Zeichen - " + getFeldInfo());
}
}
}
// sicherheitshalber in DateObjekt verwandeln und
// dann in Datumsstring formatieren, parsen von
// "1.1.2000;drop table test;" liefert sonst keine Exception
private void xSelectedKeyDatePrüfen() throws InvalidKeyException {
this.selectedKey = xDateParamOhneApostrophes(this.selectedKey);
//HTML5 input type=date always delivers US-format yyyy-MM-dd
if(this.selectedKey !=null && this.selectedKey.indexOf("-")>-1)
{
this.selectedKey=de.superx.util.SqlStringUtils.formatDateUStoDE(this.selectedKey); //Transform to dd.MM.yyyy
}
java.sql.Date d;
try {
d = DateUtils.parse(this.selectedKey);
} catch (ParseException e) {
throw new InvalidKeyException("Ungültige Eingabe für Feld " + getName());
}
this.selectedKey = DateUtils.formatGerman(d);
if (!this.selectedKey.startsWith("'")) this.selectedKey = "'" + this.selectedKey;
if (!this.selectedKey.endsWith("'")) this.selectedKey = this.selectedKey + "'";
}
private void check(String key) {
if (getZeilenanzahl() > 1 && getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isHidden() && !isFileUpload() && key != null && (key.indexOf("|") > -1 || key.indexOf(",") > -1)) {
if (getArt() != Art.id_1_Nummer_Text_nur_mit_Dialog && getArt() != Art.id_12_Sicht)
throw new IllegalArgumentException("Trennzeichen | oder , für Mehrfachauswahl gefunden - diese wird aber nur von Feldart 1 und 12 unterstützt");
if (this.getTyp() != Typ.typ_sql && this.getZeilenanzahl() < 2) {
System.out.println(getFeldInfo() + " falsches Trennzeichen:" + key);
throw new IllegalArgumentException("Trennzeichen | oder , für Mehrfachauswahl gefunden - wird von " + getFeldInfo() + " nicht unterstützt");
}
}
if (getArt() == Art.id_0_nur_Text_direkte_Eingabe && key != null && key.length() > getLaenge()) {
throw new IllegalArgumentException("Eingegebene Daten länger als erlaubt (" + getLaenge() + " Zeichen)");
}
}
private String xDateParamOhneApostrophes(String key) {
String result = key;
if (getTyp() == Typ.typ_date && key != null) {
if (key.startsWith("'")) result = result.substring(1);
if (key.endsWith("'")) result = result.substring(0, key.length() - 2);
}
return result;
}
private void checkDataType(String key) throws InvalidDataTypeException {
//bei mehrfachauswahl von integer wird statt | ein , übergeben
if (getTyp() != Typ.typ_sql && getArt() != Art.id_0_nur_Text_direkte_Eingabe && !isHidden() && !isFileUpload() && (key.indexOf("|")>-1||key.indexOf(",") > -1)) {
String tmpkey=key.replace(',', '|');
for (StringTokenizer st = new StringTokenizer(tmpkey, "|"); st.hasMoreElements();) {
String akey = st.nextToken();
checkDataType(akey);
}
} else {
if (getTyp() == Typ.typ_integer) {
try {
Integer.parseInt(key);
} catch (NumberFormatException e) {
throw new InvalidDataTypeException("Ungültige Eingabe für Feld " + getName() + "<br> (erwarteter Datentyp ist " + getTyp() + ")");
}
}
if (getTyp() == Typ.typ_decimal) {
try {
NumberUtils.parse(key);
} catch (ParseException e) {
throw new InvalidDataTypeException("Ungültige Eingabe für Feld " + getName() + "<br> (erwarteter Datentyp ist " + getTyp() + ")");
}
}
if (getTyp() == Typ.typ_date && key != null && !key.equals("")) {
String test = StringUtils.replace(key, "'", "");
if (!DateUtils.isValidDate(test)) throw new InvalidDataTypeException("Ungültige Eingabe für Feld " + getName() + "<br> (erwarteter Datentyp ist " + getTyp() + ")");
}
if ((getTyp() == Typ.typ_decimal || getTyp() == Typ.typ_time || getTyp() == Typ.typ_timestamp)) {
if (key.indexOf("'") > -1 || key.indexOf(';') > -1 || key.indexOf("\"") > -1 || key.indexOf("--") > -1)
throw new InvalidDataTypeException("Ungültige Eingabe für Feld " + getName() + "<br> (erwarteter Datentyp ist " + getTyp() + ")");
}
/*
* geht schief wegen ' im Key, vorher schon in
* xSelectedKeyDatePrüfen gemacht if (getTyp().equals("date") &&
* key.indexOf("|") == -1 && !DateUtils.isValidDate(key)) throw new
* IllegalArgumentException( "Ungültige Eingabe für Feld " +
* getName() + " (" + getId() + ") Datentyp ist " + getTyp());
*/
}
}
/**
* @deprecated
* @param selectedKeys
*/
@Deprecated
private void addTempMultiSelectionElement(String selectedKeys) {
StringTokenizer st = new StringTokenizer(selectedKeys, "|");
String tmpname = "";
while (st.hasMoreTokens()) {
String akey = st.nextToken();
SelectableItemNode node = selectableItemsTree.getById(akey);
if (node == null) {
System.out.println("Feld " + getName() + " (" + getId() + ") ungültiges Element in Mehrfachauswahl: " + akey);
throw new IllegalArgumentException("Feld " + getName() + " (" + getId() + ") ungültiges Element in Mehrfachauswahl (s.catalina.out)");
}
tmpname += node.getName() + ",";
}
tmpname = StringUtils.deleteLastChar(tmpname);
SelectableItem item = new SelectableItem(selectedKeys, tmpname);
item.setTemporary(true);
addTempSelectionElement(item);
}
/**
* expects | in selectedKey, gets name of all elements
*
* @return
*/
private String getMultiNames(String keys) {
StringTokenizer st = new StringTokenizer(keys, "|");
String tmpname = "";
while (st.hasMoreTokens()) {
String akey = st.nextToken();
SelectableItemNode node = selectableItemsTree.getById(akey);
if (node == null) {
System.out.println("Feld " + getName() + " (" + getId() + ") ungültiges Element in Mehrfachauswahl: " + akey);
throw new IllegalArgumentException(getFeldInfo() + ") ungültiges Element in Mehrfachauswahl (s.catalina.out)");
}
tmpname += node.getName() + ", ";
}
tmpname = StringUtils.deleteLastChar(tmpname);
tmpname = StringUtils.deleteLastChar(tmpname);
return tmpname;
}
public String getSelectedKeyUnescaped() throws ParseException {
return SqlStringUtils.unescapeString(getKeyEscaped(selectedKey));
}
/**
* Returns a key in escaped format Achtung gibt ähnlich Methode getEscaped
*
* @param key
* @return String key in escaped format
* @throws ParseException
*/
private String getKeyEscaped(Object key) throws ParseException {
String result = "";
if (key != null) result = new String(key.toString());
String feldart = getArt().getIntValue() + "";
if (feldart.equals("11")) {
result = CryptUtils.encodeSHA(result + CryptUtils.geheimnis1);
}
if (getTyp() == Typ.typ_char) {
result = ServletUtils.escapeCharFeld(result);
}
if (getTyp() == Typ.typ_date && result.length() > 0) {
// result =
// result.substring(1,result.length()-1);//ServletUtils.escapeDateFeld
// (result);
result = ServletUtils.escapeDateFeld(result);
}
if (getTyp() == Typ.typ_timestamp && result.length() > 0) {
result = ServletUtils.escapeTimestampFeld(result);
}
if (getTyp() == Typ.typ_time && result.length() > 0) {
result = ServletUtils.escapeTimeFeld(result);
}
if (isOldOrganigrammArt() || (isOrganigrammSichtArt())) {
if (result.equals("")) result = "null";
}
if (key != null && getTyp() == Typ.typ_sql) {
result = key.toString().replace(';', '^');
}
if (result == null)
{
throw new IllegalStateException("null nicht erlaubt");
}
return result;
}
/**
* @deprecated not in use
* @throws DBServletException
* @throws SQLException
* @throws ParseException
*/
@Deprecated
public void createTmpInformixTable() throws DBServletException, SQLException, ParseException {
/*
* String tablename = "tmp_" + this.getName(); String sql = "create temp
* table " + tablename + " (value blob)"; //falls das nicht zusammen mit
* preparedstatement geht //ServletUtils.execute("Erstelle tmp_table für
* Feld "+getName(),sql); sql += "update " + tablename + " set value=?";
*
* long callerId = IDGenerator.getInstance().getID();
*
* SuperX_el result_el = new SuperX_el(); try { Connection dbConnection
* = OldConnectionPool.getInstance() .getConnection(callerId, this);
* PreparedStatement pst = dbConnection.prepareStatement(sql);
* pst.setObject(1, this.getKeyEscaped(selectedKey)); pst.execute(); }
* //finally damit Connection auf jeden Fall zurückgegeben wird finally
* { OldConnectionPool.getInstance().returnConnection(callerId, this); }
*/
}
@Override
public Object clone() throws CloneNotSupportedException {
Field cl = new Field((NamedIdObject) super.clone(), this.maskennummer, this.captionSet);
cl.setNummer(this.getNummer());
cl.setX(this.x);
cl.setY(this.y);
cl.mandantenID = this.mandantenID;
cl.setButtonbreite(this.buttonbreite);
cl.setFeldbreite(this.feldbreite);
cl.setZeilenanzahl(this.zeilenanzahl);
cl.setLaenge(this.laenge);
cl.setObligatorisch(this.obligatorisch);
cl.setArt(this.art);
cl.setTyp(typ.getStringValue());
try {
cl.setRelation(relation);
cl.setAttribut(attribut);
cl.setDefaultwertString(defaultwertString);
cl.setSelectedKey(selectedKey);
cl.setLocale(locale);
} catch (Exception e) {
throw new CloneNotSupportedException("Cloning of field " + this.getName() + " (" + this.getNummer() + ") failed: " + e);
}
cl.selectableItemsTree = (SelectableItemTree) selectableItemsTree.clone();
cl.setCaptionShort(captionShort);
cl.setCaptionLong(captionLong);
cl.defaultValue = defaultValue;
cl.isDynamic = isDynamic;
cl.isInited = isInited;
// wird wegen Endlosschleife nicht mitgeclont,sondern in
// FieldContainer.clone() nachgetragen
// cl.individualFields = (FieldContainer) individualFields.clone();
return cl;
}
public boolean isInited() {
return isInited;
}
public void setInited(boolean isInited) {
this.isInited = isInited;
}
public boolean isDynamic() {
return isDynamic;
}
public void setDynamic(boolean isUserSpecific) {
this.isDynamic = isUserSpecific;
}
/**
* wird derzeit nur von FieldXmlEncoder und getJSON gebraucht
*
* @return
*/
SelectableItem getDefaultValue() {
return defaultValue;
}
/**
* erwartet:if (param!=null&&(param.indexOf(",")>-1||param.indexOf("|")>-1))
*
* @param param
* @return
* @throws ParseException
*/
String getParamAdaptedEscaped(String param) throws ParseException {
String result = "";
param = paramAdaptCommaWildcard(param);
if (param.indexOf("|") > -1) {
boolean isFirst = true;
for (StringTokenizer st = new StringTokenizer(param, "|"); st.hasMoreElements();) {
String akey = st.nextToken();
if (!isFirst)
result += ",";
else
isFirst = false;
result += getEscaped(akey);
}
}
return result;
}
String getDefaultValueEscaped() throws ParseException {
String result = "";
if (defaultValue != null)
// result = getKeyEscaped(defaultValue.getId());
{
if (defaultValue.isTemporary() && defaultValue.getId().toString().indexOf("|") > -1) {
boolean isFirst = true;
for (StringTokenizer st = new StringTokenizer(defaultValue.getId().toString(), "|"); st.hasMoreElements();) {
String akey = st.nextToken();
if (!isFirst)
result += ",";
else
isFirst = false;
result += getEscaped(akey);
}
} else
result = getEscaped(defaultValue.getId().toString());
}
return result;
}
/**
* Adds a temporary item to the selectionElements which is needed during a
* makro loop or by multiple selection trick
*
* @param item
*/
void addTempSelectionElement(SelectableItem item) {
item.setTemporary(true);
// tempElements.add(item);
selectableItemsTree.add(new SelectableItemNode(item));
}
/**
* Only called by FMTester momentarily
*
* @param item
*/
public void addSelectionElement(SelectableItem item) {
// tempElements.add(item);
selectableItemsTree.add(new SelectableItemNode(item));
}
void removeTempSelectionElements() {
selectableItemsTree.removeTempElements();
}
public String getSelectedKey() {
return selectedKey;
}
/**
* Ändert den Stand eines Feldes
*
* @param neuerStand
* @throws SQLException
* @throws DBServletException
* @throws KeyParentEqualException
* @throws CloneNotSupportedException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
* @throws IllegalStateException
* - wenn Feldart nicht 4,6,7 oder 12 ist
*/
public void setStand(Hashtable formular, HashMap map, FieldContainer individualFields, String neuerStand, SxUser user) throws SQLException, DBServletException,
KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (neuerStand == null) throw new IllegalArgumentException("Der Stand kann nicht auf null gesetzt werden - Feld " + getName() + " (" + getId() + ")");
neuerStand = neuerStand.replaceAll("'", "");
// Klammern löschen, \\ ist java.util.regex.Pattern escaping
neuerStand = neuerStand.replaceAll("\\(", "");
neuerStand = neuerStand.replaceAll("\\)", "");
neuerStand = neuerStand.replaceAll("date", "");
neuerStand = neuerStand.replaceAll("date_val", "").trim();
if (neuerStand.trim().equalsIgnoreCase("today") || neuerStand.trim().equalsIgnoreCase("<<today>>")) neuerStand = DateUtils.getTodayString();
if (!DateUtils.isValidDate(neuerStand)) {
throw new IllegalArgumentException("Konnte neuen Stand für Feld " + getName() + " (" + getId() + ") nicht setzen. '() date wurden entfernt, aber " + neuerStand
+ " ist kein gültiges dd.mm.yyyy-Datum");
}
if (!isOldOrganigrammArt() && !isSicht()) throw new IllegalStateException("Nur Felder mit Sichtenfunktionalität (Art 4,6,7,12) können den Stand ändern");
initIfNeeded(formular, map, individualFields, user);
sichtgruppe.setStand(formular, map, individualFields, neuerStand);
selectableItemsTree = sichtgruppe.getSelectedSicht();
updateSichtenInFormular(formular);
// MB 11/13
if (!isHidden()) user.getSelectionBuffer().setFieldStand(getName(), neuerStand);
}
/**
* Ändert die Sicht auf ein Feld
*
* @param sichttid
* @throws CloneNotSupportedException
* @throws KeyParentEqualException
* @throws DBServletException
* @throws SQLException
* @throws SQLException
* @throws DBServletException
* @throws IOException
* @throws TemplateException
* @throws SichtException
* @throws NoMainEntryException
* @throws IllegalStateException
* - wenn Feldart nicht 4,6,7 oder 12 ist
*/
public void setSicht(Hashtable formular, HashMap map, FieldContainer individualFields, Integer sichttid, SxUser user) throws SQLException, DBServletException,
KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException, NoMainEntryException {
if (!isSicht()) throw new IllegalStateException("Nur Felder mit Sichtenfunktionalität (art=12) können die Sicht ändern");
initIfNeeded(formular, map, individualFields, user);
sichtgruppe.setSelectedSicht(sichttid);
sichtgruppe.makeSureSelectedSichtIsOK(formular, map, individualFields);
selectableItemsTree = sichtgruppe.getSelectedSicht();
updateSichtenInFormular(formular);
if (!isHidden()) user.getSelectionBuffer().setFieldSicht(getName(), sichttid.toString());
}
public String getSchleifenXml() throws InvalidKeyException, ParseException {
String caption = getKeyEscaped(selectedKey);
if (!caption.equals("") && selectableItemsTree.getRoot().getChildCount() > 0) {
if (getArt() == Art.id_0_nur_Text_direkte_Eingabe || isFileUpload()) // bei direkter Eingabe
{
caption = "";
if (selectedKey != null) caption = selectedKey.toString();
} else {
if (!selectableItemsTree.containsItemWithId(selectedKey)) throwInvalidKey();
SelectableItemNode item = (SelectableItemNode) selectableItemsTree.getById(selectedKey);
caption = item.getName();
}
}
return "<schleifenelement><value><![CDATA[" + getSelectedKeyEscaped() + "]]></value><value_caption><![CDATA[" + SqlStringUtils.unescapeString(caption)
+ "]]></value_caption></schleifenelement>\n";
}
/**
* True wenn für eine Submasken eines Makros ein spezieller Auswahlwert
* hinterlegt wurde
*/
boolean isSpecialSelectionApplied() {
return isSpecialSelectionApplied;
}
void setSpecialSelectionApplied(boolean isSpecialSelectionApplied) {
this.isSpecialSelectionApplied = isSpecialSelectionApplied;
}
/**
* ACHTUNG !!!!!!!!!!!!!!!!!!!!!!!!! Im Applet wird analoge Methode
* AbstractSicht.get aufgerufen,weil SichtObjekt direkt in das Datenmodell
* kommt.
*
*/
@Override
public TemplateModel get(String key) throws TemplateModelException {
if (key == null) return null;
if (this.isSicht() || this.isOldOrganigrammArt()) {
sichtgruppe.getSelectedSicht().updateLevelFromSelection();
}
TemplateModel result = null;
if (key.equalsIgnoreCase("sichtart")) {
result = new SimpleScalar(sichtgruppe.getSelectedSicht().getArt());
}
if (key.equalsIgnoreCase("sichtname_intern")) {
result = new SimpleScalar(sichtgruppe.getSelectedSicht().getName_intern());
}
if (key.equalsIgnoreCase("sichtname")) {
result = new SimpleScalar(sichtgruppe.getSelectedSicht().getName());
}
if (key.equalsIgnoreCase("id") || key.equalsIgnoreCase("key")) {
if (getId() == null)
result = new SimpleScalar(null);
else
result = new SimpleScalar(getId().toString());
}
if (key.equalsIgnoreCase("allNeededKeys") || key.equalsIgnoreCase("allNeededKeysList")) {
if (isSicht() || isOldOrganigrammArt())
result = new SimpleScalar(sichtgruppe.getSelectedSicht().getAllNeededKeysList());
else if (getArt() == Art.id_1_Nummer_Text_nur_mit_Dialog) {
result = new SimpleScalar(selectableItemsTree.getAllNeededKeysList());
} else
throw new UnsupportedOperationException("wird nur von Feldart 1 und Sicht-Feldern unterstützt");
}
if (key.equalsIgnoreCase("allKeys")) {
if (this.getArt() != Art.id_1_Nummer_Text_nur_mit_Dialog) throw new UnsupportedOperationException("wird nur von Art1-Feldern unterstützt");
result = new SimpleScalar(selectableItemsTree.getAllKeys());
}
if (key.equalsIgnoreCase("keysToRoot")) result = new SimpleScalar(sichtgruppe.getSelectedSicht().getOwnAndParentsKeyList());
// für <#foreach
if (key.equalsIgnoreCase("elementsMinEbene")) result = new SimpleNumber(sichtgruppe.getSelectedSicht().getElementsMinEbene(SelectableItemTree.PREORDER_ENUM));
if (key.equalsIgnoreCase("elementsMaxEbene")) result = new SimpleNumber(sichtgruppe.getSelectedSicht().getElementsMaxEbene(SelectableItemTree.PREORDER_ENUM));
if (key.equalsIgnoreCase("allElements")) result = new SimpleSequence(selectableItemsTree.getAllElements());
if (key.equalsIgnoreCase("elements")) result = new SimpleSequence(selectableItemsTree.getElements(SelectableItemTree.PREORDER_ENUM,false));
if (key.equalsIgnoreCase("breadthFirstElements")) result = new SimpleSequence(selectableItemsTree.getElements(SelectableItemTree.BREADTHFIRST_ENUM,false));
if (key.equalsIgnoreCase("depthFirstElements")) result = new SimpleSequence(selectableItemsTree.getElements(selectableItemsTree.DEPTHFIRST_ENUM,false));
if (key.equalsIgnoreCase("elements_incl_hidden")) result = new SimpleSequence(selectableItemsTree.getElements(SelectableItemTree.PREORDER_ENUM,true));
if (key.equalsIgnoreCase("breadthFirstElements_incl_hidden")) result = new SimpleSequence(selectableItemsTree.getElements(SelectableItemTree.BREADTHFIRST_ENUM,true));
if (key.equalsIgnoreCase("depthFirstElements_incl_hidden")) result = new SimpleSequence(selectableItemsTree.getElements(selectableItemsTree.DEPTHFIRST_ENUM,true));
if (key.equalsIgnoreCase("selectedElementsOnly")) {
Collection list = new LinkedList();
for (int i = 0; i < selectableItemsTree.getSelectionCount(); i++) {
list.add(selectableItemsTree.getSelectionPaths()[i].getLastPathComponent());
}
result = new SimpleSequence(list);
}
if (key.equalsIgnoreCase("hasValue") || key.equalsIgnoreCase("hasSelection")) {
if (selectableItemsTree.getSelectionCount() == 0)
result = TemplateBooleanModel.FALSE;
else
result = TemplateBooleanModel.TRUE;
}
if (key.equals("containsElements")) {
if (selectableItemsTree.containsElements())
result = TemplateBooleanModel.TRUE;
else
result = TemplateBooleanModel.FALSE;
}
if (key.equalsIgnoreCase("selectionCount")) result = new SimpleNumber(Integer.valueOf(sichtgruppe.getSelectedSicht().getSelectionCount()));
// für Applet kopieren
if (key.equalsIgnoreCase("selectedKeyEscaped")) result = new SimpleScalar(this.getSelectedKeyEscaped());
if (key.equalsIgnoreCase("selectedKey")) {
String selkey = this.getSelectedKeyEscaped();
if (selkey != null && selkey.startsWith("'")) selkey = selkey.substring(1);
if (selkey != null && selkey.endsWith("'")) selkey = selkey.substring(0, selkey.length() - 1);
result = new SimpleScalar(selkey);
}
if (key.equalsIgnoreCase("selectedItems")) result = new SimpleSequence(selectableItemsTree.getSelectedItems());
if (key.equalsIgnoreCase("selectedItemsSortByKey")) result = new SimpleSequence(selectableItemsTree.getSelectedItemsSortByKey());
if (key.equalsIgnoreCase("selectedItemsSortByName")) result = new SimpleSequence(selectableItemsTree.getSelectedItemsSortByName());
if (key.equalsIgnoreCase("selectedItemsSortByStrukturInt")) result = new SimpleSequence(selectableItemsTree.getSelectedItemsSortByStrukturInt());
if (key.equalsIgnoreCase("selectedItemsSortByStrukturStr")) result = new SimpleSequence(selectableItemsTree.getSelectedItemsSortByStrukturStr());
return result;
}
public boolean isEmpty() throws TemplateModelException {
return false;
}
public StringBuffer getJSON(String param)
throws SQLException, DBServletException, KeyParentEqualException, CloneNotSupportedException, SichtException, TemplateException, IOException {
// System.out.println("defaultvaluestring:"+this.defaultwertString+"
// defaultvalue *"+getDefaultValue().getId()+"*");
if (!isInited()) throw new IllegalStateException("JSON holen aber nicht initialisiert");
// initIfNeeded(formular,user);
StringBuffer result = new StringBuffer();
if (art == Art.id_0_nur_Text_direkte_Eingabe) throw new IllegalArgumentException("Für Feldart 0 kann kein JSON angefordert werden");
if (param == null) throw new IllegalArgumentException("param darf nicht null sein");
result.append("(");
if (param.startsWith("search:"))
addSearchJSON(param, result);
else
addRegularJSON(param, result);
result.append(")");
return result;
}
private void addSearchJSON(String param, StringBuffer result) {
boolean isFirstItem = true;
String search = param.substring(7).toLowerCase();
result.append("[");
int dummy = 1;
DefaultMutableTreeNode root = (DefaultMutableTreeNode) selectableItemsTree.getModel().getRoot();
for (Enumeration en = root.breadthFirstEnumeration(); en.hasMoreElements();) {
SelectableItemNode node = (SelectableItemNode) en.nextElement();
if (node.isHidden()) continue;
if (node.getName() != null && node.getName().toLowerCase().indexOf(search) > -1) {
if (!isFirstItem)
result.append(",");
else
isFirstItem = false;
result.append(node.toJSON(this.getDefaultValue().getId(), false));
}
}
result.append("]");
}
private void addRegularJSON(String param, StringBuffer result) {
if (!this.getSelectableItemsTree().containsItemWithId(param))
throw new IllegalArgumentException("Im Feld " + getName() + " (" + getId() + ") gibt es kein Element " + param);
SelectableItemNode startnode = getSelectableItemsTree().getById(param);
boolean isSingleRoot = startnode.getChildCount() < 2;
if (param.equals("xxxxxx-xxxxxx@")) {
result.append("{");
if (isOldOrganigrammArt() || isSicht()) {
result.append(getSichtgruppe().getJSONInfo());
} else {
result.append("sichten:{count:0},zeilenanzahl:" + this.getZeilenanzahl());
}
result.append(",nodes:");
// {sichten:{count:3,stand:"1.6.2007",selected:{name:"reguläre
// Sicht",name_intern:"Hauptsicht
// Kosten-/Erlösarten",stand:true},
// other:[{name:"Fachbereichsansicht",name_intern:"FB",stand:false},{
// name:"Alt
// hier2",name_intern:"alt_hier2",stand:false}]},
// data: [{objectId:"4",title:"FB
// Architektur-Bauing.wesen-Versorg.technik"},{objectId:"2",title:"FB
// Bio-,Chemie-,Verfahrenstechnik"},{objectId:"1",title:"FB
// Informatik-Elektrotechnik-Maschinenbau"},{objectId:"5",title:"FB
// Musikpädagogik"},{objectId:"3",title:"FB
// Wirtschaftswissenschaften"}]
// };
}
result.append("[");
boolean isFirstItem = true;
for (Enumeration en = startnode.children(); en.hasMoreElements();) {
SelectableItemNode node = (SelectableItemNode) en.nextElement();
if (node.isHidden()) continue;
if (!isFirstItem)
result.append(",");
else
isFirstItem = false;
result.append(node.toJSON(this.getDefaultValue().getId(), isSingleRoot));
}
result.append("]");
if (param.equals("xxxxxx-xxxxxx@")) result.append("}");
}
/**
* z.B. für Kostenarten("getSubkeys","21") von XML-Frontend aufgerufen, von
* Applet direkt AbstractSicht.exec
*/
public Object exec(List l) throws TemplateModelException {
String function = l.get(0).toString();
Object result = null;
if (function.equalsIgnoreCase("getSubkeys")) {
if (!this.isSicht() && this.getArt() != Art.id_1_Nummer_Text_nur_mit_Dialog) throw new IllegalArgumentException("getSubkeys,Schlüssel nur für Sichten und Feldart 1 implementiert");
if (this.isSicht())
result = this.getSichtgruppe().getSelectedSicht().exec(l);
else {
// Sichtart 1 einfach nur den Schlüssel selbst wieder
// zurückliefern
String surround = "";
if (getTyp() == Typ.typ_char) surround = "'";
result = "(" + surround + l.get(1).toString() + surround + ")";
}
}
if (function.equalsIgnoreCase("containselementwithid")) {
String id = l.get(1).toString();
if (selectableItemsTree.containsItemWithId(id))
result = TemplateBooleanModel.TRUE;
else
result = TemplateBooleanModel.FALSE;
}
return result;
}
/**
* prüft ob ein keystring Mehrfachauswahl enthält, mit Komma oder |
* getrennt, wenn alle Teilkeys auswaehlbar sind ist Mehrfachauswahl
*
* @param keystring
* @return
*/
public boolean isMehrfachAuswahl(String keystring) {
boolean result = false;
if (this.getZeilenanzahl() > 1) {
if (keystring != null) {
if (keystring.indexOf(',') > -1) {
result = true;
StringTokenizer st = new StringTokenizer(keystring, ",");
while (st.hasMoreTokens()) {
if (selectableItemsTree.getById(st.nextToken()) == null) result = false;
}
}
if (keystring.indexOf('|') > -1) {
result = true;
StringTokenizer st = new StringTokenizer(keystring, "|");
while (st.hasMoreTokens()) {
if (selectableItemsTree.getById(st.nextToken()) == null) result = false;
}
}
}
}
return result;
}
public String getDefaultValueStatement(){
String statement = this.getDefaultwertString().substring(this.startpos);
return statement;
}
}
// Created on 30.09.2004 at 09:45:50