From 5bf2a1fa11c1529a731ab6b4521b8254c1fa100f Mon Sep 17 00:00:00 2001 From: rk Date: Wed, 29 Aug 2001 01:47:14 +0000 Subject: [PATCH] Initial revision --- source/mir/entity/AbstractEntity.java | 218 +++++ source/mir/entity/Entity.java | 139 +++ source/mir/entity/EntityList.java | 199 ++++ source/mir/entity/EntityRelation.java | 128 +++ source/mir/entity/GenericEntity.java | 18 + source/mir/misc/Configuration.java | 170 ++++ source/mir/misc/HTMLParseException.java | 20 + source/mir/misc/HTMLTemplateProcessor.java | 343 +++++++ source/mir/misc/Helper.java | 35 + source/mir/misc/InputSourceResolver.java | 76 ++ source/mir/misc/LineFilterWriter.java | 62 ++ source/mir/misc/Logfile.java | 192 ++++ source/mir/misc/StringUtil.java | 899 +++++++++++++++++ source/mir/misc/WebdbImage.java | 155 +++ source/mir/misc/WebdbMultipartRequest.java | 70 ++ source/mir/misc/XmlSaxonStyler.java | 43 + source/mir/misc/XmlStyler.java | 21 + source/mir/misc/XslStyleCache.java | 93 ++ source/mir/module/AbstractModule.java | 191 ++++ source/mir/module/ModuleException.java | 20 + source/mir/servlet/AbstractServlet.java | 75 ++ source/mir/servlet/ServletModule.java | 345 +++++++ source/mir/servlet/ServletModuleDispatch.java | 75 ++ source/mir/servlet/ServletModuleException.java | 20 + source/mir/servlet/ServletModuleMonitor.java | 97 ++ source/mir/servlet/ServletModuleShow.java | 76 ++ source/mir/storage/Database.java | 1082 +++++++++++++++++++++ source/mir/storage/DatabaseAdaptor.java | 76 ++ source/mir/storage/DatabaseAdaptorMySQL.java | 40 + source/mir/storage/DatabaseAdaptorOracle.java | 83 ++ source/mir/storage/DatabaseAdaptorPostgresql.java | 40 + source/mir/storage/DatabaseAdaptorSybase.java | 85 ++ source/mir/storage/StorageObject.java | 224 +++++ source/mir/storage/StorageObjectException.java | 40 + 34 files changed, 5450 insertions(+) create mode 100755 source/mir/entity/AbstractEntity.java create mode 100755 source/mir/entity/Entity.java create mode 100755 source/mir/entity/EntityList.java create mode 100755 source/mir/entity/EntityRelation.java create mode 100755 source/mir/entity/GenericEntity.java create mode 100755 source/mir/misc/Configuration.java create mode 100755 source/mir/misc/HTMLParseException.java create mode 100755 source/mir/misc/HTMLTemplateProcessor.java create mode 100755 source/mir/misc/Helper.java create mode 100755 source/mir/misc/InputSourceResolver.java create mode 100755 source/mir/misc/LineFilterWriter.java create mode 100755 source/mir/misc/Logfile.java create mode 100755 source/mir/misc/StringUtil.java create mode 100755 source/mir/misc/WebdbImage.java create mode 100755 source/mir/misc/WebdbMultipartRequest.java create mode 100755 source/mir/misc/XmlSaxonStyler.java create mode 100755 source/mir/misc/XmlStyler.java create mode 100755 source/mir/misc/XslStyleCache.java create mode 100755 source/mir/module/AbstractModule.java create mode 100755 source/mir/module/ModuleException.java create mode 100755 source/mir/servlet/AbstractServlet.java create mode 100755 source/mir/servlet/ServletModule.java create mode 100755 source/mir/servlet/ServletModuleDispatch.java create mode 100755 source/mir/servlet/ServletModuleException.java create mode 100755 source/mir/servlet/ServletModuleMonitor.java create mode 100755 source/mir/servlet/ServletModuleShow.java create mode 100755 source/mir/storage/Database.java create mode 100755 source/mir/storage/DatabaseAdaptor.java create mode 100755 source/mir/storage/DatabaseAdaptorMySQL.java create mode 100755 source/mir/storage/DatabaseAdaptorOracle.java create mode 100755 source/mir/storage/DatabaseAdaptorPostgresql.java create mode 100755 source/mir/storage/DatabaseAdaptorSybase.java create mode 100755 source/mir/storage/StorageObject.java create mode 100755 source/mir/storage/StorageObjectException.java diff --git a/source/mir/entity/AbstractEntity.java b/source/mir/entity/AbstractEntity.java new file mode 100755 index 00000000..3f2c0db4 --- /dev/null +++ b/source/mir/entity/AbstractEntity.java @@ -0,0 +1,218 @@ +/** + * abstrakte Basisklasse der Entity-Klassen

+ */ + + +package mir.entity; + +import java.lang.*; +import java.io.*; +import java.util.*; +import java.sql.*; + +import mir.storage.*; +import mir.misc.*; + +/** + * abstrakte Basisklasse der Entity-Klassen + * + * @author RK + * @version 29.6.1999 + * + */ + +public class AbstractEntity implements Entity +{ + private boolean changed; + protected HashMap theValuesHash; // tablekey / value + protected StorageObject theStorageObject; + protected static Logfile theLog; + protected ArrayList streamedInput=null; + private static int instances = 0; + static { + theLog = Logfile.getInstance(Configuration.getProperty("Home") + Configuration.getProperty("Entity.Logfile")); + } + + public AbstractEntity() { + this.changed = false; + instances++; + } + + /** + * Konstruktor + */ + public AbstractEntity (StorageObject StorageObject) { + this(); + setStorage(StorageObject); + } + + /* + * Setzt das StorageObject der Entity. + */ + public void setStorage (StorageObject storage) { + this.theStorageObject = storage; + } + + /** + * Setzt die Werte der Entity + * @param theStringValues + */ + + public void setValues(HashMap theStringValues) + { + /** @todo should be synchronized */ + theValuesHash = new HashMap(); + String aKey; + Set set = theStringValues.keySet(); + Iterator it = set.iterator(); + int size = set.size(); + for (int i = 0; i < size; i++) { + aKey = (String)it.next(); + theValuesHash.put(aKey, (String)theStringValues.get(aKey)); + } + } + + /** + * Liefert boolschen Wert, ob sich der Inhalt der Entity geändert hat. + * @return true wenn ja, sonst false + */ + public boolean changed () { + return changed; + } + + /** + * Liefert den Primärschluessel der Entity zurueck + * @return String Id + */ + public String getId () { + return (String)getValue(theStorageObject.getIdName()); + } + + /** + * Setzt den Primaerschluessel der Entity + * @param id + */ + public void setId (String id) { + theValuesHash.put(theStorageObject.getIdName(), id); + } + + /** + * Liefert den Wert für einen Feldnamen zurueck + * @param theFieldString + * @return Wert für Feld + */ + public String getValue (String theFieldString) { + return (String)theValuesHash.get(theFieldString); + } + + /** + * Fügt Entity via StorageObject in Datenbank ein. + * @return Primary Key der Entity + * @exception StorageObjectException + */ + public String insert () throws StorageObjectException { + theLog.printDebugInfo("Entity: trying to insert ..."); + if (theStorageObject != null) { + return theStorageObject.insert((Entity)this); + } + else + throw new StorageObjectException("Kein StorageObject gesetzt!"); + } + + /** + * Aktualisiert Aenderungen an der Entity in der Datenbank + * @exception StorageObjectException + */ + public void update () throws StorageObjectException { + theStorageObject.update((Entity)this); + } + + /** + * Setzt den Wert fuer ein Feld + * @param theProp + * @param theValue + * @exception StorageObjectException + */ + public void setValueForProperty (String theProp, String theValue) throws StorageObjectException { + this.changed = true; + if (isField(theProp)) + theValuesHash.put(theProp, theValue); + else + theLog.printWarning("Property not found: " + theProp); + } + + /** + * Gibt die Feldnamen der Entity als ArrayList zurueck + * @return ArrayList mit Feldnamen + * @exception StorageObjectException wird geworfen, wenn kein Zugriff auf die Datenbank + * möglich. + */ + public ArrayList getFields () throws StorageObjectException { + return theStorageObject.getFields(); + } + + /** + * Liefert ein int[] mit den Typen der Felder zurueck + * @return int[] mit den Feldtypen + * @exception StorageObjectException + */ + public int[] getTypes () throws StorageObjectException { + return theStorageObject.getTypes(); + } + + /** + * Liefert ArrayListe mit Feldnamen zurueck. + * @return Liste mit Feldnamen + * @exception StorageObjectException + */ + public ArrayList getLabels () throws StorageObjectException { + return theStorageObject.getLabels(); + } + + /** + * Liefert eine Hashmap mit allen Werten der Entity zurueck + * @return HashMap mit Feldname/Wert + */ + public HashMap getValues() { + return theValuesHash; + } + + /** + * Liefert einen ArrayList mit allen Datenbankfeldern, die + * als streamedInput ausgelesen werden muessen. + * Waere automatisierbar ueber die types (blob, etc.) + * Bisher manuell anzulegen in der erbenden Klasse + */ + + public ArrayList streamedInput() { + return streamedInput; + } + + /* Fragt ab, ob fieldName einem Feld entspricht + * @param fieldName + * @return true, wennn ja, sonst false + * @exception StorageObjectException + */ + public boolean isField (String fieldName) throws StorageObjectException { + return theStorageObject.getFields().contains(fieldName); + } + + /** Liefert Anzahl der Instanzen zurück + * @return int + */ + public int getInstances() { + return instances; + } + /** + * Gibt eine Instanz frei + */ + public void finalize () { + instances--; + try { + super.finalize(); + } catch (Throwable t) { + System.err.println(t.toString()); + } + } +} + diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java new file mode 100755 index 00000000..bff5eb22 --- /dev/null +++ b/source/mir/entity/Entity.java @@ -0,0 +1,139 @@ +/* + * put your module comment here + */ + + +package mir.entity; + +import java.lang.*; +import java.util.*; +import mir.storage.*; + +/** + * Interface-Definition für Entities + */ + +public interface Entity { + + /** + * Eine Entity muss setStorage implementieren, mit der eine Entity mit einem + * StorageObject assoziiert wird. + * + * @param st + */ + public abstract void setStorage (StorageObject st); + + + + /** + * Eine Entity muss setValues implementieren, mit der die Werte der Entity gesetzt werden + * können. + * + * @param ht + */ + public abstract void setValues(HashMap ht); + + + + /** + * Eine Entity muss getValues implementieren, mit der die Werte der Entity + * als HashMap zurueckgeliefert werden + * @return Werte der Entity + */ + public abstract HashMap getValues(); + + + + /** + * Eine Entity muss getFields implementieren, mit der die Feldnamen der + * Entity zurueckgegeben werden. + * @return ArrayList der Feldnamen + * @exception StorageObjectException + */ + public abstract ArrayList getFields () throws StorageObjectException; + + + + /** + * Eine Entity muss getTypes implementieren, mit der die Feldtype der + * Entity zurueckgegeben werden. + * @return int[] der Feldtypen + * @exception StorageObjectException + */ + public abstract int[] getTypes () throws StorageObjectException; + + + + /** + * Eine Entity muss getLabels implementieren, mit der die Feldnamen der + * Entity zurueckgegeben werden. + * @return ArrayList der Feldnamen + * @exception StorageObjectException + */ + public abstract ArrayList getLabels () throws StorageObjectException; + + + + /** + * Eine Entity muss getId implementieren, um den Primaerschuessel der + * Entity zurueckgeliefert zu bekommen. + * + * @return Primary-Key der Entity + */ + public abstract String getId(); + + + + /** + * Eine Entity muss setId implementieren, um den Primaerschuessel der + * Entity zu setzen + * + * @param str + */ + public abstract void setId(String str); + + + /** + * Eine Entity muss getValue implementieren, um den Wert eines + * Feldes zurueckzugeben + * + * @param field + * @return Wert von Feld field + */ + public abstract String getValue (String field); + + + + /** + * Einfügen der Entity in StorageObject + * + * @return Primary-Key der eingefügten Entity + * @exception StorageObjectException + */ + public abstract String insert () throws StorageObjectException; + + + + /** + * Aktualisieren der Entity via StorageObject + * @exception StorageObjectException + */ + public abstract void update () throws StorageObjectException; + + + + /** + * ArrayListe mit Feldern, die einer Sonderbehandlung bedürfen (blobs) + * @return Liste der Feldnamen + */ + public abstract ArrayList streamedInput (); + + + public abstract void setValueForProperty (String theProp, String theValue) throws StorageObjectException; + + +} + + + + diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java new file mode 100755 index 00000000..98883c82 --- /dev/null +++ b/source/mir/entity/EntityList.java @@ -0,0 +1,199 @@ +/* + * put your module comment here + */ + + +package mir.entity; + +import java.lang.*; +import java.util.*; +import mir.misc.*; + + +/** + * + * abstrakte Containerklasse für Listen von Entities. + * + * @author + * @version 27.6.1999 + */ +public class EntityList { + private static Logfile theLog; + private ArrayList theEntityArrayList; + private String whereClause; + private String orderClause; + private int count; + private int offset; + private int offsetnext = -1; + private int offsetprev = -1; + + /** + * Konstruktor für leere Liste von Entities + */ + public EntityList(){ + this.theEntityArrayList = new ArrayList(); + if (theLog == null) + this.theLog = Logfile.getInstance(Configuration.getProperty("Home") + Configuration.getProperty("Entity.Logfile")); + } + + /** + * Setzt die WhereClause, mit der die Entitis dieser Liste geholt wurden. + * @param wc + */ + public void setWhere(String wc) { + this.whereClause = wc; + } + + /** + * Liefert die WhereClause zurueck, mit der die Entities geholt wurden. + * @return whereClause + */ + public String getWhere() { + return whereClause; + } + + /** + * Setzt das Sortierkriterium fest, mit der die Entities in die Liste + * gestellt wurden. + * + * @param oc + */ + public void setOrder(String oc) { + this.orderClause = oc; + } + + /** + * Liefert das Sortierkriterium der Liste zurueck. + * @return orderClause + */ + public String getOrder() { + return orderClause; + } + + /** + * Setzt die Anzahl der Datensätze fest, die WhereClause erfüllen. + * @param i + */ + public void setCount(int i) { + this.count = i; + } + + /** + * Liefert Anzahle der Datensätze, die WhereClause erfüllen. + * @return + */ + public int getCount() { + return count; + } + + /** + * Setzt den Offset fest. + * @param i + */ + public void setOffset(int i) { + offset = i; + } + + /** + * Liefert den Offset zurueck + * @return offset + */ + public int getOffset() { + return offset; + } + + /** + * Setzt den offset für das naechste Batch von Entities fest. + * @param i + */ + public void setNextBatch(int i) { + offsetnext = i; + } + + /** + * Liefert den offset für das naechste Batch von Entities + * @return offset für naechstes Batch + */ + public int getNextBatch() { + return offsetnext; + } + + /** + * Fragt ab, ob es noch nachfolgendes Batch innerhalb der WhereClause gibt + * @return + */ + public boolean hasNextBatch() { + return (offsetnext >= 0); + } + + /** + * Setzt offset des vorhergehenden Batches fest. + * @param i + */ + public void setPrevBatch(int i) { + offsetprev = i; + } + + /** + * Liefert offset des vorhergehenden Batches zurueck. + * @return offset des vorhergehenden Batches. + */ + public int getPrevBatch() { + return offsetprev; + } + + /** + * Fragt ab, ob es ein vorhergehendes Batch gibt + * @return true wenn ja, sont false + */ + public boolean hasPrevBatch() { + return (offsetprev >= 0); + } + + /** + * Liefert den Startindex des Batches zurueck. + * @return + */ + public int getFrom() { + return offset+1; + } + + /** + * Liefert den Endindex des Batches zurueck. + * @return + */ + public int getTo() { + if (hasNextBatch()) + return offsetnext; + else + return count; + } + + /** + * Fügt eine Entity in die Liste ein + * @param anEntity + */ + public void add (Entity anEntity) { + if (anEntity!=null) + theEntityArrayList.add(anEntity); + else + theLog.printWarning("add (EntityList) mit leerer Entity"); + } + + /** + * @return Anzahl der Entities in der Liste + */ + public int size() { + return theEntityArrayList.size(); + } + + + + + + + public Entity elementAt(int i) { + return (Entity)theEntityArrayList.get(i); + } + +} diff --git a/source/mir/entity/EntityRelation.java b/source/mir/entity/EntityRelation.java new file mode 100755 index 00000000..8f44ac32 --- /dev/null +++ b/source/mir/entity/EntityRelation.java @@ -0,0 +1,128 @@ +package mir.entity; + +import mir.storage.*; +import mir.misc.*; +import freemarker.template.*; + +public class EntityRelation { + + public String fromId; + public String toId; + public StorageObject storage; + public int type; + + public final static int TO_ONE = 1; + public final static int TO_MANY = 2; + + + /** + * Kontruktor fuer EntityRelation + * @param fromId ist der Feldname in der ausgehenden Tabelle fuer die Relation + * @param toId ist der Feldname in der Zieltablle + * @param storage ist das StorageObject, ueber das der Zugriff auf die abhaengige + * Tabelle erfolgt. + * @param type ist der Typ der EntityRelation (TO_ONE oder TO_MANY) + */ + + public EntityRelation(String fromId, String toId, StorageObject storage, int type) { + this.fromId = fromId; + this.toId = toId; + this.storage = storage; + this.type = type; + } + + /** + * @return Liefert eine abhaengige Entity mit den verknuepften + * Entities, wenn es sich um eine TO_ONE Beziehung handelt, ansonsten + * null. + */ + + public Entity getOne(Entity entity) throws StorageObjectException { + if (type==TO_ONE) { + return storage.selectById(entity.getValue(fromId)); + } + else return null; + } + + /** + * @return Liefert ein freemarker.template.SimpleHash mit den verknuepften + * Entities, wenn es sich um eine TO_ONE Beziehung handelt, ansonsten + * null. + */ + + public SimpleHash getOneAsSimpleHash(Entity entity) throws StorageObjectException { + if (type==TO_ONE) { + Entity returnEntity = getOne(entity); + if (returnEntity!=null) return HTMLTemplateProcessor.makeSimpleHash(returnEntity); + } + return null; + } + + /** + * @return Liefert eine freemarker.template.SimpleList mit den verknuepften + * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten + * null. + */ + + public EntityList getMany(Entity entity) throws StorageObjectException{ + if (type==TO_MANY) { + return storage.selectByFieldValue(toId, entity.getValue(fromId)); + } + else return null; + } + + /** + * @return Liefert eine freemarker.template.SimpleList mit den verknuepften + * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten + * null. + */ + + public EntityList getMany(Entity entity, String order) throws StorageObjectException{ + if (type==TO_MANY) { + return storage.selectByWhereClause(toId+"="+entity.getValue(fromId), order,-1); + } + else return null; + } + + /** + * @return Liefert eine freemarker.template.SimpleList mit den verknuepften + * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten + * null. + */ + + public SimpleList getManyAsSimpleList(Entity entity) + throws StorageObjectException { + + if (type==TO_MANY) { + EntityList returnList = getMany(entity); + if (returnList!=null) return HTMLTemplateProcessor.makeSimpleList(returnList); + } + return null; + } + + /** + * @return Liefert eine freemarker.template.SimpleList mit den verknuepften + * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten + * null. + */ + + public SimpleList getManyAsSimpleList(Entity entity, String order) + throws StorageObjectException { + + if (type==TO_MANY) { + EntityList returnList = getMany(entity, order); + if (returnList!=null) return HTMLTemplateProcessor.makeSimpleList(returnList); + } + return null; + } + + /** + * @return Liefert den Referenznamen der abhaengigen Tabelle + */ + + public String getName() { + return "to" + storage.getTableName(); + } + + +} \ No newline at end of file diff --git a/source/mir/entity/GenericEntity.java b/source/mir/entity/GenericEntity.java new file mode 100755 index 00000000..12f3d562 --- /dev/null +++ b/source/mir/entity/GenericEntity.java @@ -0,0 +1,18 @@ +/* + * GenericEntity + */ +package mir.entity; + +/** + * Standard-Entity-Container. Wenn keine Zusatzfunktionalitaeten für die Kapselung einer + * Datenbankzeile nötig sind, d.h. zu einem Database-Objekt keine eigene Entity-Klasse + * implementiert wird, so wird dieser Standard-Container verwendet. + * + * @author /rk + * @version 1.2 + */ +public class GenericEntity extends AbstractEntity + implements Entity {} + + + diff --git a/source/mir/misc/Configuration.java b/source/mir/misc/Configuration.java new file mode 100755 index 00000000..1155bf06 --- /dev/null +++ b/source/mir/misc/Configuration.java @@ -0,0 +1,170 @@ +/* + * put your module comment here + */ + + +package mir.misc; + +import java.net.*; +import java.io.*; +import java.util.*; +import java.lang.*; +import com.javaexchange.dbConnectionBroker.*; + + +/** + * Diese Klasse realisert den Zugriff auf die Konfiguration. + * + */ +public class Configuration { + + private static HashMap confs = new HashMap(); // key: conffilename, confHash + private static HashMap c = new HashMap(); + private String confFilename; + private static String defaultconfFilename; + private static int instances=0; + //static ResourceBundle conf = ResourceBundle.getBundle("config"); + static ResourceBundle conf; + + public static void initConfig(String confName) { + conf = ResourceBundle.getBundle(confName); + confs.put("confname",confName); + } + + public static void addBroker(String driver, String URL){ + + System.err.println("--trying to add broker"); + String username,passwd,min,max,log,reset; + + if(!c.containsKey("Pool.broker")){ + username=conf.getString("Database.Username"); + passwd=conf.getString("Database.Password"); + min=conf.getString("Database.poolMin"); + max=conf.getString("Database.poolMax"); + log=conf.getString("Home") + conf.getString("Database.PoolLog"); + reset=conf.getString("Database.poolResetTime"); + + try{ + System.err.println("-- making Broker for -" + +driver+" - " +URL + + " log " + log + " user " + + username + " pass: " + passwd); + + DbConnectionBroker br = new DbConnectionBroker(driver,URL,username,passwd,(new Integer(min)).intValue(), + (new Integer(max)).intValue(),log,(new Float(reset)).floatValue()); + if (br!=null){ + instances++; + c.put("Pool.broker",br); + } else { + throw new Exception(); + } + } catch(Exception e){ + System.err.println("Der ConnectionBroker konnte nicht initializiert werden"+ e.toString());e.printStackTrace(); + } + } // end if + } + + + /** + * Fragt ab, ob das Betriebssystem Windows ist. + * @return true wenn ja, sonst false. + */ + public static boolean isWindows() { + return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0; + } + + /** + * Liefert Wert einer Property zurueck + * @param propName + * @return Wert der Property + */ + public static String getProperty(String propName) { // default + return conf.getString(propName); + } + + /** + * Liest eine Property eines Modules aus der Konfiguration + * @param filename + * @param theModule + * @param propName + * @return Wert der Property + */ + public String getProperty(String filename ,String theModule, String propName) { + return getProperty(filename, theModule + "." + propName); + } + + /** + * Liest eine Property aus der Konfiguration + * @param filename + * @param propName + * @return Wert der Property + */ + public static String getProperty(String filename, String propName) { + if (filename != null) { + String prop = null; + HashMap conf = ((HashMap)confs.get("confname")); + + if (conf == null) { + System.err.println("Keine Konfiguration fuer " + filename); + } else { + prop = (String)conf.get(propName); + } + + if (prop == null) { + System.err.println("Keine Konfiguration fuer " + filename + " " + propName); + } + + return prop; + + } else { + System.err.println("--- filename null!"); + } + + return null; + } + + /** + * Liefert DBConnectionBroker einer Configuration zurueck + * @param confFilename + * @return DBConnectionBroker + */ + public static DbConnectionBroker getBroker() { + DbConnectionBroker broker=null; + broker=(DbConnectionBroker)c.get("Pool.broker"); + if (broker==null) { + System.err.println("Konnte kein ConnectionPoolBroker initialisiert werden"); + } + return broker; + } + + /** + * Liefert Hashtabel mit den Konfigurationen + * @return + */ + public static HashMap getConfs(){ + return confs; + } + + public static DbConnectionBroker getBrokerInfo(){ + return (DbConnectionBroker)c.get("Pool.broker"); + } + + + /** + * Finalize Methode + */ + public void finalize(){ + instances --; + try { + super.finalize(); + } catch (Throwable t) {} + } + + /** + * Liefert Anzahl der Instantiierten DBConnectionBroker zurueck + * @return + */ + public static int getBrokerInstances() { + return instances; + } +} //end of class diff --git a/source/mir/misc/HTMLParseException.java b/source/mir/misc/HTMLParseException.java new file mode 100755 index 00000000..f82aa738 --- /dev/null +++ b/source/mir/misc/HTMLParseException.java @@ -0,0 +1,20 @@ +package mir.misc; + +import java.lang.*; + +/* + * HTMLParseException - + * wird vom HTMLProcessor geschmissen + * + * + * @version 30.6.199 + * @author RK + */ + +public class HTMLParseException extends Exception +{ + HTMLParseException(String msg) { + super(msg); + } +} + diff --git a/source/mir/misc/HTMLTemplateProcessor.java b/source/mir/misc/HTMLTemplateProcessor.java new file mode 100755 index 00000000..70ec150d --- /dev/null +++ b/source/mir/misc/HTMLTemplateProcessor.java @@ -0,0 +1,343 @@ +/* + * put your module comment here + */ + + +package mir.misc; + +import java.lang.*; +import java.util.*; +import java.io.*; +import java.net.*; +import freemarker.template.*; +import mir.entity.*; +import mir.storage.*; + + +/** + * Hilfsklasse zum Mergen von Template und Daten + */ +public final class HTMLTemplateProcessor { + + public static String templateDir; + private static FileTemplateCache templateCache; + private static Logfile theLog; + private static String docRoot; + private static String actionRoot; + private static String productionHost; + private static String audioHost; + private static String videoHost; + private static String imageHost; + private static String openAction; + protected static String producerDocRoot = Configuration.getProperty("Producer.DocRoot"); + protected static String producerStorageRoot = Configuration.getProperty("Producer.StorageRoot"); + + + // + // Initialisierung + + static { + templateDir = Configuration.getProperty("Home") + Configuration.getProperty("HTMLTemplateProcessor.Dir"); + templateCache = new FileTemplateCache(templateDir); + templateCache.setLoadingPolicy(templateCache.LOAD_ON_DEMAND); + //templateCache.startAutoUpdate(); + theLog = Logfile.getInstance(Configuration.getProperty("Home") + Configuration.getProperty("HTMLTemplateProcessor.Logfile")); + docRoot = Configuration.getProperty("HTMLTemplateProcessor.DocRoot"); + actionRoot = Configuration.getProperty("HTMLTemplateProcessor.ActionRoot"); + openAction = Configuration.getProperty("Producer.OpenAction"); + productionHost = Configuration.getProperty("Producer.ProductionHost"); + videoHost = Configuration.getProperty("Producer.VideoHost"); + audioHost = Configuration.getProperty("Producer.AudioHost"); + imageHost = Configuration.getProperty("Producer.Image.Host"); + producerDocRoot = Configuration.getProperty("Producer.DocRoot"); + producerStorageRoot = Configuration.getProperty("Producer.StorageRoot"); + + + } + + /** + * Privater Konstruktor, um versehentliche Instantiierung zu verhindern + */ + private HTMLTemplateProcessor () { + } + + + // + // process-Methoden zum Mischen verschiedener Datenstrukturen mit HTML-Templates + + + /** + * Wandelt anEntity in freemarker-Struktur um, mischt die Daten mit + * Template templateFilename und gibt das Ergebnis an den PrintWriter + * out + * + * @param templateFilename + * @param anEntity + * @param out + * @exception HTMLParseException + */ + + public static void process(String templateFilename, Entity anEntity, PrintWriter out) + throws HTMLParseException { + if (anEntity == null) throw new HTMLParseException("Entity leer!"); + else process(templateFilename, anEntity, out); + } + + + /** + * Wandelt Liste mit Entities entList in freemarker-Struktur um, mischt die Daten mit + * Template templateFilename und gibt das Ergebnis an den PrintWriter + * out + * + * @param templateFilename + * @param entList + * @param out + * @exception HTMLParseException + */ + public static void process(String templateFilename, EntityList entList, PrintWriter out) + throws HTMLParseException { + process( templateFilename, entList, (String)null, (TemplateModelRoot)null, out); + } + + /** + * Wandelt Entitylist in freemarker-Struktur um, fügt additionalModel + * unter dem Namen additionalModelName ein und mischt die Daten mit + * Template templateFilename und gibt das Ergebnis an den PrintWriter + * out + * + * @param templateFilename + * @param entList + * @param additionalModelName + * @param additionalModel + * @param out + * @exception HTMLParseException + */ + public static void process(String templateFilename, EntityList entList, String additionalModelName, + TemplateModelRoot additionalModel, PrintWriter out) + throws HTMLParseException { + + SimpleHash modelRoot = new SimpleHash(); + + if (entList == null) { + //theLog.printInfo("Keine Daten! Suche erfolglos."); + process(templateFilename, modelRoot, out); + } else { + try { + modelRoot = makeSimpleHashWithEntitylistInfos(entList); + // + // Hilfskruecke um mal ein Popup mit reinzunhemen .. + if (additionalModelName != null && additionalModel != null) + modelRoot.put(additionalModelName, additionalModel); + + process(templateFilename, modelRoot, out); + } catch (StorageObjectException e) { + throw new HTMLParseException(e.toString()); + } + } + } + + /** + * Wandelt HashMap mergeData in freemarker-Struktur und mischt diese mit + * Template templateFilename und gibt das Ergebnis an den PrintWriter + * out + * + * @param templateFilename + * @param mergeData + * @param out + * @exception HTMLParseException + */ + public static void process(String templateFilename, HashMap mergeData, PrintWriter out) + throws HTMLParseException { + process(templateFilename, makeSimpleHash(mergeData), out); + } + + /** + * Gibt Template templateFilename an den PrintWriter + * out + * + * @param templateFilename + * @param mergeData + * @param out + * @exception HTMLParseException + */ + public static void process(String templateFilename, PrintWriter out) + throws HTMLParseException { + process(templateFilename, (TemplateModelRoot)null, out); + } + + + /** + * Mischt die freemarker-Struktur tmr mit + * Template templateFilename und gibt das Ergebnis an den PrintWriter + * out + * + * @param templateFilename + * @param mergeData + * @param out + * @exception HTMLParseException + */ + public static void process(String templateFilename, TemplateModelRoot tmr, PrintWriter out) + throws HTMLParseException { + if (out==null) throw new HTMLParseException("KEIN OUTPUTSTREAM"); + Template tmpl = getTemplateFor(templateFilename); + if (tmpl == null) throw new HTMLParseException("KEIN TEMPLATE: " + templateFilename); + if (tmr==null) tmr = new SimpleHash(); + + //some utilities + SimpleHash utilityHash = new SimpleHash(); + utilityHash.put("htmlEscape",new freemarker.template.utility.HtmlEscape()); + + // put standard configuration into tempalteRootmodel + SimpleHash configHash = new SimpleHash(); + configHash.put("docroot", new SimpleScalar(producerDocRoot)); + configHash.put("storageroot", new SimpleScalar(producerStorageRoot)); + configHash.put("productionhost", new SimpleScalar(productionHost)); + configHash.put("openaction", new SimpleScalar(openAction)); + + + tmr.put("docRoot", new SimpleScalar(docRoot)); + tmr.put("now", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); + tmr.put("actionRoot", new SimpleScalar(actionRoot)); + tmr.put("openAction", new SimpleScalar(openAction)); + tmr.put("productionHost", new SimpleScalar(productionHost)); + tmr.put("videoHost", new SimpleScalar(videoHost)); + tmr.put("audioHost", new SimpleScalar(audioHost)); + tmr.put("imageHost", new SimpleScalar(imageHost)); + + tmr.put("config", configHash); + tmr.put("utility",utilityHash); + tmpl.process(tmr, out); + + } + + + /** + * Wandelt eine Entity-Liste in eine SimpleList von SimpleHashes um. + * @param aList ist eine Liste von Entity + * @return eine freemarker.template.SimpleList von SimpleHashes. + */ + public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException + { + SimpleList simpleList = new SimpleList(); + if (aList != null) { + for(int i=0;i"); + return null; + } + } + + /** + * Konvertiert ein Hashtable mit den keys und values als String + * in ein freemarker.template.SimpleHash-Modell + * @param mergeData der HashMap mit den String / String Daten + * @return SimpleHash mit den entsprechenden freemarker Daten + * + */ + public static SimpleHash makeSimpleHash(HashMap mergeData) + { + SimpleHash modelRoot = new SimpleHash(); + String aField; + if (mergeData != null) { + Set set = mergeData.keySet(); + Iterator it = set.iterator(); + for (int i=0; i not found" ); + } + + return is; + } + + + /** + * This method was created in VisualAge. + * @return org.xml.sax.InputSource + * @param key java.lang.String + */ + public static InputSource resolve( String key ) + throws IOException { + + InputSource is = new InputSource( single.getFileInputStream( key ) ); + if ( key.indexOf( ':' ) >= 0 ) { + is.setSystemId( "file:///" + key ); // special for win (file:///c:/xxx) + } else { + is.setSystemId( "file://" + key ); + } + + return is; + } +} \ No newline at end of file diff --git a/source/mir/misc/LineFilterWriter.java b/source/mir/misc/LineFilterWriter.java new file mode 100755 index 00000000..960c29b2 --- /dev/null +++ b/source/mir/misc/LineFilterWriter.java @@ -0,0 +1,62 @@ +package mir.misc; +import java.io.*; + +/** + * LineFilterWriter schneidet unsinnige \t \r \n ` ` raus + * + **/ +public final class LineFilterWriter extends PrintWriter{//extends java.io.FilterWriter{ + + + public LineFilterWriter(Writer out) { + super(out); + } + + public final void write(String str){ + int i,j,len; + boolean state=true; + char c; + len=str.length(); + if (len==1) {try{out.write(str);}catch(IOException e){}return;} + StringBuffer sbuf = new StringBuffer(); + + for(i=0;ifileName wird eine Instanz der Logfileklassen + * angelegt. + * + * @param fileName + * @return Logfile + */ + public static Logfile getInstance(String fileName) { + Logfile returnLogfile = null; + System.err.println(fileName); + if (fileName != null) { + if (instanceRepository.containsKey(fileName)) { + returnLogfile = (Logfile) instanceRepository.get(fileName); + } else { + returnLogfile = new Logfile(fileName); + instanceRepository.put(fileName, returnLogfile); + } + } else { + System.err.println("Fehler bei Instantiierung von Logfile"); + } + return returnLogfile; + } + + /** + * Privater Konstruktor + * @param String fileName + */ + private Logfile(String fileName){ + this.fileName = fileName; + try { + File f = new File(fileName); + File dir = new File(f.getParent()); + dir.mkdirs(); + raf = new RandomAccessFile(fileName, "rw"); + } catch (IOException e) { + System.err.println("Could not open logfile '"+fileName+"'"); + } + } + + /** + * Private Methode, um eine Zeile auszugeben + * + * @param type Typ der Logfilezeile (INFO, WARNING, ERROR, DEBUG) + * @param text Lognachricht + * @todo an dieser Stelle koennte statt in das File in die Datenbank geloggt werden. + */ + private void print(int type, String text) { + if (text == null) text = "null"; + text = text.replace('\n', ' '); + + String typeText = + type == LOG_DEBINFO ? "DEBINFO " : + type == LOG_INFO ? "INFO " : + type == LOG_WARNING ? "WARNING " : + type == LOG_ERROR ? "ERROR " : + "? "; + + String sectionText = text; + GregorianCalendar date = new GregorianCalendar(); + + String line = StringUtil.pad2(date.get(Calendar.DATE))+"-"+ + StringUtil.pad2(date.get(Calendar.MONTH)+1)+"-"+ + StringUtil.pad2(date.get(Calendar.YEAR) % 100)+" "; + int hour = date.get(Calendar.HOUR); + if (date.get(Calendar.AM_PM) == Calendar.PM) hour+=12; + line += StringUtil.pad2(hour)+":"+ + StringUtil.pad2(date.get(Calendar.MINUTE))+":"+ + StringUtil.pad2(date.get(Calendar.SECOND))+" "+ + typeText+sectionText; + + print(line); + } + + /** + * Interne Ausgabeprozedur. + * Erfordert etwas Handarbeit, da PrintStream nicht mit RandomAcccessFile + * kooperiert. Und ein RandomAccessFile brauchen wir, weil FileOutputStream + * kein "append" zuläßt. + * + */ + private void print(String line) { + if (raf == null) return; + line += lineSeparator; + // byte[] buf = new byte[line.length()]; + //line.getBytes(0, line.length(), buf, 0); + + byte[] buf = line.getBytes(); + + try { + raf.seek(raf.length()); + raf.write(buf, 0, line.length()); + } catch (IOException e) { + System.err.print("Could not write logfile line: "+line); + } + } + + /** + * Schreibt Information text ins Logfil. + * @param text + */ + public void printInfo (String text) { + print(LOG_INFO, text); + } + + /** + * Schreibt Warnung text ins Logfile. + * @param text + */ + public void printWarning (String text) { + print(LOG_WARNING, text); + } + + /** + * Schreibt Fehlermeldung text ins Logfile. + * @param text + */ + public void printError (String text) { + print(LOG_ERROR, text); + } + + /** + * Schreibt Debuginformation text ins Logfile. + * @param text + */ + public void printDebugInfo (String text) { + print(LOG_DEBINFO, text); + } + + /** + * Finalize-Methode, die alle offenen Dateien schliesst. + */ + public void finalize () { + if (raf != null) { + try { + raf.close(); + } catch (IOException e) {} + raf = null; + } + staticFinalize(fileName); + try { + super.finalize(); + } catch (Throwable t) { + ; + } + } + + /** + * Static-Finalizer + * @param fileName + */ + private static synchronized void staticFinalize (String fileName) { + instanceRepository.remove(fileName); + } +} + + + diff --git a/source/mir/misc/StringUtil.java b/source/mir/misc/StringUtil.java new file mode 100755 index 00000000..d5685fe2 --- /dev/null +++ b/source/mir/misc/StringUtil.java @@ -0,0 +1,899 @@ +/* + * put your module comment here + */ + + +package mir.misc; + +import java.io.*; +import java.lang.*; +import java.util.*; +import gnu.regexp.*; + +/** + * Statische Hilfsmethoden zur Stringbehandlung + * + * @version 29.6.99 + * @author RK + */ +public final class StringUtil { + + /** + * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd) + * @param theDate + * @return 8-ziffriger String (yyyymmdd) + */ + + public static final String date2webdbDate (GregorianCalendar theDate) { + StringBuffer webdbDate = new StringBuffer(); + webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR))); + webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1)); + webdbDate.append(pad2(theDate.get(Calendar.DATE))); + return webdbDate.toString(); + } + + /** + * wandelt Calendar in dd.mm.yyyy / hh.mm um + * @param theDate + * @return String mit (dd.mm.yyyy / hh.mm um) + */ + public static String date2readableDateTime (GregorianCalendar theDate) { + String readable = ""; + int hour; + readable += pad2(theDate.get(Calendar.DATE)); + readable += "." + pad2(theDate.get(Calendar.MONTH) + 1); + readable += "." + String.valueOf(theDate.get(Calendar.YEAR)); + hour = theDate.get(Calendar.HOUR); + if (theDate.get(Calendar.AM_PM) == Calendar.PM) + hour += 12; + readable += " / " + pad2(hour); + readable += ":" + pad2(theDate.get(Calendar.MINUTE)); + return readable; + } + + /** + * wandelt eine Datum in einen 8-buchstabigen String, der durch / + * getrennt ist. + * + * @param webdbDate + * @return String mit /yyyy/mm/dd + */ + public static final String webdbDate2path (String webdbDate) { + StringBuffer path = new StringBuffer(); + path.append("/").append(webdbDate.substring(0, 4)); + path.append("/").append(webdbDate.substring(4, 6)); + path.append("/").append(webdbDate.substring(6, 8)); + return path.toString(); + } + + /** + * wandelt Calendar in dd.mm.yyyy um + * + * @param theDate + * @return String mit dd.mm.yyyy + */ + public static final String webdbDate2readableDate (String webdbDate) { + String date = ""; + date += webdbDate.substring(6, 8); + date += "." + webdbDate.substring(4, 6); + date += "." + webdbDate.substring(0, 4); + return date; + } + + + /** + * converts string from format: yyyy-mm-dd__hh:mm:ss.d + * to dd.mm.yyyy hh:mm + */ + public static String dateToReadableDate(String date) { + StringBuffer returnDate = new StringBuffer(); + if (date!=null) { + + returnDate.append(date.substring(8,10)).append('.'); + returnDate.append(date.substring(5,7)).append('.'); + returnDate.append(date.substring(0,4)).append(' '); + returnDate.append(date.substring(11,16)); + } + return returnDate.toString(); + } + + + /** + * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält + * + * @return gequoteter String + */ + public static String quoteIfNecessary(String s) { + for (int i = 0; i < s.length(); i++) + if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.')) + return quote(s, '"'); + return s; + } + + /** + * schließt s in ' ein und setzt Backslashes vor + * "gefährliche" Zeichen innerhalb des Strings + * Quotes special SQL-characters in s + * + * @return geqoteter String + */ + public static String quote(String s) + { + //String s2 = quote(s, '\''); + + //Quickhack + //Because of '?-Bug in Postgresql-JDBC-Driver + StringBuffer temp = new StringBuffer(); + for(int i=0;is in ' ein und setzt Backslashes vor + * "gefährliche" Zeichen innerhalb des Strings + * + * @param s String, der gequoted werden soll + * @param quoteChar zu quotendes Zeichen + * @return gequoteter String + */ + public static String quote(String s, char quoteChar) + { + StringBuffer buf = new StringBuffer(s.length()); + int pos = 0; + while (pos < s.length()) { + int i = s.indexOf(quoteChar, pos); + if (i < 0) i = s.length(); + buf.append(s.substring(pos, i)); + pos = i; + if (pos < s.length()) { + buf.append('\\'); + buf.append(quoteChar); + pos++; + } + } + return buf.toString(); + } + + /** + * ersetzt gefährliche zeichen in s + * + */ + + public static String unquote(String s) + { + char quoteChar='\''; + StringBuffer buf = new StringBuffer(s.length()); + int pos = 0; + String searchString = "\\"+quoteChar; + while (pos < s.length()) { + int i = s.indexOf(searchString, pos); + if (i < 0) i = s.length(); + buf.append(s.substring(pos, i)); + pos = i+1; + } + return buf.toString(); + } + + /** + * Wandelet String in byte[] um. + * @param s + * @return byte[] des String + */ + + public static byte[] stringToBytes(String s) { + String crlf = System.getProperty("line.separator"); + if (!crlf.equals("\n")) + s = replace(s, "\n", crlf); + // byte[] buf = new byte[s.length()]; + byte[] buf = s.getBytes(); + return buf; + } + + /** + * Ersetzt in String s das pattern durch substitute + * @param s + * @param pattern + * @param substitute + * @return String mit den Ersetzungen + */ + public static String replace(String s, String pattern, String substitute) { + int i = 0, pLen = pattern.length(), sLen = substitute.length(); + StringBuffer buf = new StringBuffer(s.length()); + while (true) { + int j = s.indexOf(pattern, i); + if (j < 0) { + buf.append(s.substring(i)); + break; + } else { + buf.append(s.substring(i, j)); + buf.append(substitute); + i = j+pLen; + } + } + return buf.toString(); + } + + + /** + * Fügt einen Separator an den Pfad an + * @param path + * @return Pfad mit Separator am Ende + */ + public static final String addSeparator (String path) { + return path.length() == 0 || path.endsWith(File.separator) ? path : path + + File.separatorChar; + } + + /** + * Fügt ein / ans ende des Strings and + * @param path + * @return Pfad mit / am Ende + */ + public static final String addSlash (String path) { + return path.length() == 0 || path.endsWith("/") ? path : path + '/'; + } + + /** + * Löscht / am Ende des Strings, falls vorhanden + * @param path + * @return String ohne / am Ende + */ + public static final String removeSlash (String path) { + return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() + - 1) : path; + } + + /** + * Löscht Slash am Anfang des Strings + * @param path + * @return + */ + public static String removeFirstSlash (String path) { + return path.startsWith("/") ? path.substring(1) : path; + } + + /** + * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05) + * @return zwistellige Zahl + */ + public static String pad2 (int number) { + return number < 10 ? "0" + number : String.valueOf(number); + } + + /** + * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007) + * + * @return 3-stellige Zahl + */ + public static String pad3 (int number) { + return number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number); + } + + /** + * Konvertiert Unix-Linefeeds in Win-Linefeeds + * @param s + * @return Konvertierter String + */ + public static String unixLineFeedsToWin(String s) { + int i = -1; + while (true) { + i = s.indexOf('\n', i+1); + if (i < 0) break; + if ((i == 0 || s.charAt(i-1) != '\r') && + (i == s.length()-1 || s.charAt(i+1) != '\r')) { + s = s.substring(0, i)+'\r'+s.substring(i); + i++; + } + } + return s; + } + + + /** + * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen + * und Spaces werden zu Underscores + * + * @return gültige Url + */ + public static String convert2url(String s) { + s = toLowerCase(s); + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < s.length(); i++ ) { + switch( s.charAt( i ) ) { + case 'ö': + buf.append( "oe" ); break; + case 'ä': + buf.append( "ae" ); break; + case 'ü': + buf.append( "ue" ); break; + case 'ã': + buf.append( "a" ); break; + case '´': + case '.': + buf.append( "_" ); break; + case ' ': + if( buf.charAt( buf.length() - 1 ) != '_' ) { + buf.append( "_" ); + } + break; + default: + buf.append( s.charAt( i ) ); + } + } + return buf.toString(); + } + + /** + * wandelt Sonderzeichen in Quotes um + * + * @return Kovertierter String + */ + public static String encodeHtml(String s) { + StringBuffer buf = new StringBuffer(); + for(int i=0;i < s.length(); i++ ) { + + /** @todo looks inefficient */ + if (s.charAt(i)=='&') { + // convert html to xml-parsable representation + if( s.indexOf( "ö", i ) == i ) { + buf.append( "ö" ); i += 5; + continue; + } + if( s.indexOf( "ä", i ) == i ) { + buf.append( "ä" ); i += 5; + continue; + } + if( s.indexOf( "ü", i ) == i ) { + buf.append( "ü" ); i += 5; + continue; + } + if( s.indexOf( "Ö", i ) == i ) { + buf.append( "Ö" ); i += 5; + continue; + } + if( s.indexOf( "Ä", i ) == i ) { + buf.append( "Ä" ); i += 5; + continue; + } + if( s.indexOf( "Ü", i ) == i ) { + buf.append( "Ü" ); i += 5; + continue; + } + if( s.indexOf( "ß", i ) == i ) { + buf.append( "ß" ); i += 6; + continue; + } + + /** @todo should only escape outside of tags */ + + if( s.indexOf( """, i ) == i ) { + buf.append( "ß" ); i += 5; + continue; + } + if( s.indexOf( "–", i ) == i ) { + buf.append( "–" ); i += 6; + continue; + } + if( s.indexOf( "—", i ) == i ) { + buf.append( "—" ); i += 6; + continue; + } + if( s.indexOf( "“", i ) == i ) { + buf.append( "“" ); i += 6; + continue; + } + if( s.indexOf( "”", i ) == i ) { + buf.append( "”" ); i += 6; + continue; + } + if( s.indexOf( "„", i ) == i ) { + buf.append( "„" ); i += 6; + continue; + } + + //looks pretty stupid + if( s.indexOf( "<", i ) == i ) { + buf.append( "<" ); i += 3; + continue; + } + if( s.indexOf( ">", i ) == i ) { + buf.append( ">" ); i += 3; + continue; + } + if( s.indexOf( "´", i ) == i ) { + buf.append( "´" ); i += 6; + continue; + } + if( s.indexOf( " ", i ) == i ) { + buf.append( " " ); i += 5; + continue; + } + //has to be the last + if( s.indexOf( "&", i ) == i ) { + buf.append( "&" ); i += 0; + continue; + } + } + // convert umlauts an other special charakters + switch( s.charAt(i) ) { + case 'ö': buf.append( "ö" ); break; + case 'ä': buf.append( "ä" ); break; + case 'ü': buf.append( "ü" ); break; + case 'Ö': buf.append( "Ö" ); break; + case 'Ä': buf.append( "Ä" ); break; + case 'Ü': buf.append( "Ü" ); break; + case 'ß': buf.append( "ß" ); break; + case 'é': buf.append( "é" ); break; + case 'è': buf.append( "è" ); break; + case 'á': buf.append( "á" ); break; + case 'à': buf.append( "à" ); break; + case 'â': buf.append( "â" ); break; + case 'ã': buf.append( "ã" ); break; + case '¬': buf.append( "¬" ); break; + case '¹': buf.append( "¹" ); break; + case '²': buf.append( "²" ); break; + case '³': buf.append( "³" ); break; + case '¼': buf.append( "¼" ); break; + case '½': buf.append( "½" ); break; + case '¾': buf.append( "¾" ); break; + case '¶': buf.append( "¶" ); break; + case 'æ': buf.append( "æ" ); break; + case 'ð': buf.append( "ð" ); break; + case '|': buf.append( "¦" ); break; + case '·': buf.append( "·" ); break; + case '°': buf.append( "°" ); break; + case '§': buf.append( "§" ); break; + case 'ø': buf.append( "ø" ); break; + case 'ç': buf.append( "ç" ); break; + case '¤': buf.append( "¤" ); break; + case 'ª': buf.append( "ª" ); break; + case 'Ç': buf.append( "Ç" ); break; + case 'Ã': buf.append( "Ã" ); break; + case 'Â': buf.append( "Â" ); break; + case 'Æ': buf.append( "Æ" ); break; + case '©': buf.append( "©" ); break; + case '®': buf.append( "®" ); break; + case '¥': buf.append( "¥" ); break; + case 'Þ': buf.append( "þ" ); break; + case '¯': buf.append( "¯" ); break; + case 'Ð': buf.append( "Ð" ); break; + case 'º': buf.append( "º" ); break; + case '¡': buf.append( "¡" ); break; + case '£': buf.append( "£" ); break; + case '±': buf.append( "±" ); break; + case '¿': buf.append( "¿" ); break; + case 'Ø': buf.append( "Ø" ); break; + case 'Á': buf.append( "À" ); break; + case 'À': buf.append( "Á" ); break; + case 'É': buf.append( "È" ); break; + case 'È': buf.append( "É" ); break; + case 'ù': buf.append( "ú" ); break; + case 'ñ': buf.append( "ñ" ); break; + case 'Ñ': buf.append( "Ñ" ); break; + case 'µ': buf.append( "µ" ); break; + case 'Í': buf.append( "Ì" ); break; + case 'Ì': buf.append( "Í" ); break; + case 'í': buf.append( "ì" ); break; + case 'ì': buf.append( "í" ); break; + case 'î': buf.append( "î" ); break; + case 'Î': buf.append( "Î" ); break; + case 'ó': buf.append( "ó" ); break; + case 'Ó': buf.append( "Ò" ); break; + case 'ò': buf.append( "Î" ); break; + case 'Ò': buf.append( "Ó" ); break; + case 'ô': buf.append( "ô" ); break; + case 'Ô': buf.append( "Ô" ); break; + case 'õ': buf.append( "õ" ); break; + case 'Õ': buf.append( "Õ" ); break; + case 'ý': buf.append( "ý" ); break; + case 'Ý': buf.append( "Ý" ); break; + case 'û': buf.append( "û" ); break; + case 'Û': buf.append( "Û" ); break; + case 'ú': buf.append( "ù" ); break; + case 'Ú': buf.append( "Ù" ); break; + case 'Ù': buf.append( "Ú" ); break; + case 'Ê': buf.append( "Ê" ); break; + case 'ê': buf.append( "ê" ); break; + case 'å': buf.append( "å" ); break; + case 'Å': buf.append( "Å" ); break; + case 'ë': buf.append( "ë" ); break; + case 'Ë': buf.append( "Ë" ); break; + case 'ÿ': buf.append( "ÿ" ); break; + case 'ï': buf.append( "ï" ); break; + case 'Ï': buf.append( "Ï" ); break; + case '«': buf.append( "«" ); break; + case '»': buf.append( "»" ); break; + case '\'': buf.append( "´" ); break; + case '\"': buf.append( """ ); break; + //case '\u8211': buf.append( "–" ); break; + //case '\u8212': buf.append( "—" ); break; + //case '\u8220': buf.append( "“" ); break; + //case '\u8221': buf.append( "”" ); break; + //case '\u8222': buf.append( "„" ); break; + //case '\"': buf.append( """ ); break; + default: buf.append( s.charAt(i) ); + } + + } + return buf.toString(); + } + + + public static String decodeHTMLinTags(String s){ + StringBuffer buffer = new StringBuffer(); + boolean start = false; + boolean stop = false; + int startIndex = 0; + int stopIndex = 0; + int temp = 0; + + for(int i=0;i'){ + stop = true; + stopIndex = i; + + if(start && stop){ + buffer.append(s.substring(temp,startIndex)); + buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1))); + i= temp= stopIndex+1; + start= stop= false; + } + } + } + buffer.append(s.substring(stopIndex+1)); + return buffer.toString(); + } + + public static String replaceQuot(String s) { + StringBuffer buffer = new StringBuffer(); + for(int j = 0; j < s.length();j++){ + if(s.charAt(j)=='&'){ + if(s.indexOf( """,j) == j) { + buffer.append( "\"" ); + j += 5; + }//if + } else { + buffer.append(s.charAt(j)); + }//else + }//for + return buffer.toString(); + } + + /** wandelt Quotes in Sonderzeichen um + */ + public static String decodeHtml(String s) { + StringBuffer buf = new StringBuffer(); + for(int i=0;i < s.length(); i++ ) { + if( s.indexOf( "ö", i ) == i ) { + buf.append( "ö" ); i += 5; + continue; + } + if( s.indexOf( "ä", i ) == i ) { + buf.append( "ä" ); i += 5; + continue; + } + if( s.indexOf( "ü", i ) == i ) { + buf.append( "ü" ); i += 5; + continue; + } + if( s.indexOf( "Ö", i ) == i ) { + buf.append( "Ö" ); i += 5; + continue; + } + if( s.indexOf( "Ä", i ) == i ) { + buf.append( "Ä" ); i += 5; + continue; + } + if( s.indexOf( "Ü", i ) == i ) { + buf.append( "Ü" ); i += 5; + continue; + } + if( s.indexOf( "ß", i ) == i ) { + buf.append( "ß" ); i += 6; + continue; + } + if( s.indexOf( """, i ) == i ) { + buf.append( "\"" ); i += 5; + continue; + } + buf.append( s.charAt(i) ); + } + return buf.toString(); + } + + + /** + * schnellere Variante der String.toLowerCase()-Routine + * + * @return String in Kleinbuchsten + */ + public static String toLowerCase(String s) { + int l = s.length(); + char[] a = new char[l]; + for (int i = 0; i < l; i++) + a[i] = Character.toLowerCase(s.charAt(i)); + return new String(a); + } + + /** + * Findet element im String-Array array + * @param array + * @param element + * @return Fundstelle als int oder -1 + */ + public static int indexOf(String[] array, String element) { + if (array != null) + for (int i = 0; i < array.length; i++) + if (array[i].equals(element)) + return i; + return -1; + } + + /** + * Testet auf Vorkommen von element in array + * @param array String-Array + * @param element + * @return true wenn element vorkommt, sonst false + */ + public static boolean contains(String[] array, String element) { + return indexOf(array, element) >= 0; + } + + /** + * Ermittelt CRC-Prüfsumme von String s + * @param s + * @return CRC-Prüfsumme + */ + public static int getCRC(String s) { + int h = 0; + char val[] = s.toCharArray(); + int len = val.length; + + for (int i = 0 ; i < len; i++) { + h &= 0x7fffffff; + h = (((h >> 30) | (h << 1)) ^ (val[i]+i)); + } + + return (h << 8) | (len & 0xff); + } + + /** + * Liefert Default-Wert def zurück, wenn String s + * kein Integer ist. + * + * @param s + * @param def + * @return geparster int aus s oder def + */ + public static int parseInt(String s, int def) { + if (s == null) return def; + try { + return Integer.parseInt(s); + } catch (NumberFormatException e) { + return def; + } + } + + /** + * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann. + * @param s + * @param def + * @return geparster float oder def + */ + public static float parseFloat(String s, float def) { + if (s == null) return def; + try { + return new Float(s).floatValue(); + } catch (NumberFormatException e) { + return def; + } + } + + /** + * Findet Ende eines Satzes in String text + * @param text + * @param startIndex + * @return index des Satzendes, oder -1 + */ + public static int findEndOfSentence(String text, int startIndex) { + while (true) { + int i = text.indexOf('.', startIndex); + if (i < 0) return -1; + if (i > 0 && !Character.isDigit(text.charAt(i-1)) && + (i+1 >= text.length() + || text.charAt(i+1) == ' ' + || text.charAt(i+1) == '\n' + || text.charAt(i+1) == '\t')) + return i+1; + startIndex = i+1; + } + } + + /** + * Findet Wortende in String text ab startIndex + * @param text + * @param startIndex + * @return Index des Wortendes, oder -1 + */ + public static int findEndOfWord(String text, int startIndex) { + int i = text.indexOf(' ', startIndex), + j = text.indexOf('\n', startIndex); + if (i < 0) i = text.length(); + if (j < 0) j = text.length(); + return Math.min(i, j); + } + + /** + * Diese Routine macht aus links in reinem text browsbare links + * @param text + * @return Konvertierter String + */ + public static String makeLinks(String text) { + int i = 0; + StringBuffer buf = new StringBuffer(text.length()); + while (true) { + int j = text.indexOf("http://", i); + if (j < 0) { + buf.append(text.substring(i)); + break; + } else { + buf.append(text.substring(i, j)); + int k = findEndOfWord(text,j+7); + String url=""; + if (k<0) url = text.substring(j); + else url = text.substring(j,k); + + buf.append(""+url+""); + //System.out.println("url mark: " + url); + i = j+url.length(); + } + } + return buf.toString(); + + } + + + /** + * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n) + * in den html-tag

+ * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String convertNewline2P(String haystack) { + try { + RE regex = new RE("(
\r?\n
){1,}"); + return regex.substituteAll(haystack,"\n

"); + } catch(REException ex){ + return null; + } + } + + /** + * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n) + * in den html-tag
+ * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String convertNewline2Break(String haystack) { + try { + RE regex = new RE("(\r?\n){1}"); + return regex.substituteAll(haystack,"$0
"); + } catch(REException ex){ + return null; + } + } + + /** + * createMailLinks wandelt text im email-adressenformat + * in einen klickbaren link um + * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String createMailLinks(String haystack) { + try { + RE regex = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)"); + return regex.substituteAll(haystack,"$0"); + } catch(REException ex){ + return null; + } + } + + + /** + * createMailLinks wandelt text im email-adressenformat + * in einen klickbaren link um + * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String createMailLinks(String haystack, String imageRoot, String mailImage) { + try { + RE regex = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)"); + return regex.substituteAll(haystack," $0"); + } catch(REException ex){ + return null; + } + } + + + /** + * createURLLinks wandelt text im url-format + * in einen klickbaren link um + * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String createURLLinks(String haystack) { + try { + //dieser Ausdruck brauch dringend fachliche Beratung + RE regex = new RE("((https://)|(http://)|(ftp://))+([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/([^ \t\r\n<>]+[^ \t\r\n.,<>])"); + return regex.substituteAll(haystack,"$0"); + } catch(REException ex){ + return null; + } + } + + /** + * createURLLinks wandelt text im url-format + * in einen klickbaren link um + * nur sinnvoll, wenn text nicht im html-format eingegeben + */ + public static String createURLLinks(String haystack,String imageRoot,String extImage,String intImage) { + try { + //dieser Ausdruck brauch dringend fachliche Beratung + RE regex = new RE("((https://)|(http://)|(ftp://))+([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>]+[^ \t\r\n.,<>])"); + return regex.substituteAll(haystack," $0"); + } catch(REException ex){ + return null; + } + } + + /** + * deleteForbiddenTags + * this method deletes all