diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..f27a281 --- /dev/null +++ b/.classpath @@ -0,0 +1,922 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dfa868e --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +# ignore all log files +*.log +*.err +*.log.* + + +# ignore all CVS + sub dirs +*CVS/ + +# ignore java classes +*classes/ + +# ignore files in directory rohdaten +superx/WEB-INF/conf/edustore/db/module/*/rohdaten/unl/*.unl +superx/WEB-INF/conf/edustore/db/install/rohdaten/unl/*.unl + +# ignore temporary files +*.tmp +*.tmp.sql +temp.xml +tmp.fo + +# ignore auto generated files +db.properties +dbforms-config.xml +superx/WEB-INF/dbforms-config.old +superx.datum + +# ignore iReport Designer +*.jasper + +# ignore /dist/* +*dist/ + +# ignore swap files +superx/WEB-INF/reports/swap_* + +src/edustore/edustore_*.xml + +# ignore eclipse settings +.settings/org.eclipse.ltk.core.refactoring.prefs +/WEB-INF/ diff --git a/.project b/.project new file mode 100644 index 0000000..c89aa55 --- /dev/null +++ b/.project @@ -0,0 +1,36 @@ + + + eduStore_superX + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.babel.editor.rbeBuilder + + + + + + org.eclipse.jdt.groovy.core.groovyNature + org.eclipse.jdt.core.javanature + com.sysdeo.eclipse.tomcat.tomcatnature + com.jaspersoft.studio.babel.editor.rbeNature + + + + 1459344926910 + + 10 + + org.eclipse.ui.ide.multiFilter + 1.0-name-matches-false-false-dist + + + + diff --git a/README b/README new file mode 100644 index 0000000..8ea328c --- /dev/null +++ b/README @@ -0,0 +1,21 @@ +---------------------------------------------------------------------------- +Wissenswertes zum + +SuperX-Modul kern Version 4.9 für POSTGRES + +15.08.2022 + + + +---------------------------------------------------------------------------- +Dieses Archiv erweitert das Data Warehouse System SuperX um das Modul "kern" + +Installationsanleitung im Verzeichnis doc/kern_modul/admin/index.htm (Dort auch Link zu PDF-Version) + +---------------------------------------------------------------------------- +Diese Software nutzt Anwendungen der Apache-Software-Foundation (APACHE_LICENSE). +Lizenzbedingungen zu SuperX finden Sie in der Datei lizenz.txt +---------------------------------------------------------------------------- + +(c) 15.08.2022 Daniel Quathamer danielq@memtext.de +www.superx-projekt.de diff --git a/README.md b/README.md deleted file mode 100644 index 98fcc20..0000000 --- a/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# kern - -SuperX-Kernmodul \ No newline at end of file diff --git a/lizenz.txt b/lizenz.txt new file mode 100644 index 0000000..87cbe97 --- /dev/null +++ b/lizenz.txt @@ -0,0 +1,248 @@ +CampusSource · AGB und Lizenz + + + + + +Allgemeine Geschäftsbedingungen (AGB) und Lizenz + + + + +Mit CampusSource wird die Nutzung universitärer Entwicklungen durch Dritte zu +den Bedingungen der General GNU Public Licence (GPL) ermöglicht, die eine der +bekanntesten Opensource-Lizenzen ist. +Die GPL ist eine Lizenz, die dem amerikanischen Recht, nicht jedoch dem +deutschen Recht genügt. So sind einige Passagen der GPL nach dem deutschen Recht +nicht wirksam. CampusSource hat aus diesem Grunde Allgemeine +Geschäftsbedingungen formuliert, die die Interpretation der GPL unter deutschem +Recht vornimmt und ergänzt. + + + +Allgemeine Geschäftsbedingungen für die +Nutzung der Software der Initiative CampusSource + + +1. Vorbemerkung +Diese Allgemeinen Geschäftsbedingungen regeln die Rechtsbeziehungen zwischen dem +Land Nordrhein-Westfalen, vertreten durch die FernUniversität Hagen, diese +wiederum vertreten durch die Geschäftsstelle der Initiative CampusSource bei der +FernUniversität Hagen, Universitätsstraße 11, D-58097 Hagen (im Folgenden +»Lizenzgeber« genannt) und dem Nutzer (im Folgenden »Lizenznehmer« genannt) der +CampusSource-Software. Sie sind ebenso wie die GNU General Public License (siehe +dazu Abschnitt 4 »Lizenz«) Bestandteil des zwischen dem Lizenzgeber und dem +Lizenznehmer geschlossenen Vertrages. +Die GNU General Public License (im Folgenden GPL genannt) finden Sie im Internet +unter www.gnu.org/copyleft/gpl.html, eine deutsche Übersetzung unter +www.gnu.de/gpl-ger.html. + + + +2. Vertragsgegenstand +Gegenstand des Vertragsangebotes des Lizenzgebers ist die auf diesem Server +befindliche Software des CampusSource-Projektes (im Folgenden »Software« +genannt) und dazugehöriges Begleitmaterial. +Der Lizenzgeber bietet dem Lizenznehmer nach erfolgter Registrierung die +folgenden Leistungen an: + Der Lizenzgeber verschafft dem Lizenznehmer die Möglichkeit, auf + elektronischem Weg Zugang zur Software, deren Dokumentation und zu + Erfahrungsberichten zu erhalten und sich einen Überblick über das + Softwareangebot zu verschaffen. + + + Der Lizenzgeber gestattet dem Lizenznehmer, die Software physikalisch + downzuloaden. + + + Der Lizenzgeber überträgt die in Abschnitt 4 »Lizenz« näher bezeichneten + Nutzungsrechte auf den Lizenznehmer. + + +Lizenzgeber und Lizenznehmer sind sich einig darüber, dass die Inanspruchnahme +der unter 1.) bis 3.) angebotenen Leistungen unentgeltlich, schenkungsweise +erfolgen soll. Dies bedeutet jedoch nicht, dass der Lizenzgeber irgendwelche +durch die Nutzung des Angebots entstandenen Kosten übernimmt. +Sofern der Lizenznehmer die Software bearbeitet und diese Bearbeitung Dritten +zugänglich macht, ist er verpflichtet, dem Lizenzgeber auch eine Kopie der +Bearbeitung kostenlos zukommen zu lassen, oder, sofern die Bearbeitung +öffentlich und kostenlos zugänglich ist, dem Lizenzgeber die Quelle mitzuteilen. +Die in diesen Allgemeinen Geschäftsbedingungen festgelegten Nebenpflichten +stellen keine Gegenleistung im Sinne des Bürgerlichen Rechts dar und sind für +den Lizenznehmer verbindlich. Nicht Gegenstand des Vertrages sind irgendeine +Form von Softwareinstallation, Softwarepflege oder Beratung im Zusammenhang mit +der Software. Insbesondere wird durch die mit der Software beigefügte oder für +die Software bereitgestellte Information oder Dokumentation kein +Beratungsvertrag angeboten. Wenn Sie solche Dienstleistungen wünschen, wenden +Sie sich an die Geschäftsstelle der Initiative CampusSource. +Der Lizenzgeber behält sich vor, das Leistungsangebot jederzeit einzustellen. +Bezüglich bereits empfangener Leistungen bleiben die Verpflichtungen beider +Parteien hiervon unberührt, insbesondere entfallen dadurch nicht die in diesen +Allgemeinen Geschäftsbedingungen festgelegten Nebenpflichten des Lizenznehmers. +Diese Allgemeinen Geschäftsbedingungen gelten auch dann, wenn der Lizenznehmer +das oben genannte Leistungspaket nur teilweise in Anspruch nimmt. + + + +3. Sorgfaltspflichten des Lizenznehmers +Der Lizenznehmer ist verpflichtet, sein Passwort sorgfältig aufzubewahren und +Dritten nicht zugänglich zu machen. Der Lizenznehmer haftet für alle Schäden, +die aus der Verletzung dieser Sorgfaltspflicht entstehen. + + + +4. Lizenz +Die Nutzungsrechte, welche der Lizenznehmer erhält, ergeben sich aus der GNU +General Public License. Diese Nutzungsrechte sind dinglich - im Sinne des +Urheberrechts - mit der Software verknüpft und gelten auch dann, wenn der +Lizenznehmer keine Kenntnis davon nimmt. Die GNU General Public License (im +Folgenden GPL genannt) finden Sie im Internet unter +www.gnu.org/copyleft/gpl.html, eine deutsche Übersetzung unter +www.gnu.de/gpl-ger.html. +Die GPL ist zu dem Zweck entworfen worden, dass Sie die unter diese Lizenz +gestellte Software weitergeben und verändern dürfen. Wenn Sie die Software +verändern und weitergeben, müssen Sie den Quellcode der bearbeiteten Software +wieder unter die GPL stellen und den Quellcode zugänglich machen, so dass auch +andere von Ihrem Werk profitieren, wie auch Sie von der erhaltenen Software +profitiert haben. Auf diese Art und Weise soll ein System von jedermann frei +zugänglicher Software geschaffen werden. +Der Lizenzgeber weist den Lizenznehmer darauf hin, dass die GPL in den USA +entworfen wurde und daher einige Bestimmungen nach deutschem Recht nicht wirksam +sind oder in Deutschland rechtlich anders beurteilt werden als in den USA: + Die Formulierung »You may charge a fee for the physical act of transferring a + copy« in Abschnitt 1 der GPL ist nach deutschem Recht so zu verstehen, dass + nur eine angemessene, marktübliche Gegenleistung für die Anfertigung einer + Kopie verlangt werden darf. Sofern eine das marktübliche überschreitende + Gegenleistung für das Anfertigen von Kopien verlangt werden würde, hätte dies + neben einer möglichen Lizenzverletzung zur Folge, dass die durch die + kostenlose Weitergabe bestehende Haftungsprivilegierung wegfallen könnte und + der Lizenznehmer wie ein Verkäufer oder Unternehmer (Werkvertrag) bei Mängeln + auf Schadensersatz haftet. + + + Abschnitt 11 und 12 der GPL (Haftungsausschluss) verstoßen gegen das »Gesetz + zur Regelung des Rechts der Allgemeinen Geschäftsbedingungen« (AGBG) und sind + nach deutschem Recht unwirksam. An ihre Stelle treten die entsprechenden + Bestimmungen des Bürgerlichen Rechts §§ 521ff. (Haftung des Schenkers). + + +Es folgt eine kurze unvollständige Zusammenfassung der GPL. Der Lizenznehmer ist +verpflichtet, die weiterführenden und präziseren Bestimmungen der GPL zu +beachten. Der Lizenznehmer wird darauf hingewiesen, dass die GPL einige +(auflösende) Bedingungen enthält, bei deren Verletzung die dem Lizenznehmer +übertragenen Nutzungsrechte automatisch ohne jeden Widerruf erlöschen und eine +weitere Nutzung des Programms zu einer (strafbaren) Urheberrechtsverletzung +wird. + Die Lizenz erlaubt dem Lizenznehmer das Ausführen der Programme zu jedem + Zweck. Gesetzliche Einschränkungen werden hiervon nicht berührt. + + + Der Lizenznehmer darf unveränderte Kopien des Quellcodes anfertigen und + weiterverbreiten, unter der Bedingung, dass mit der Kopie ein entsprechender + Urheberrechtsvermerk sowie ein Haftungsausschluß veröffentlicht wird und dass + alle die GPL betreffenden Hinweise unverändert weitergegeben werden. Ein + Entgelt darf nur für die Anfertigung von Kopien oder für das Anbieten einer + Garantie genommen werden. Näheres enthält § 1 GPL. + + + Der Lizenznehmer darf das Programm verändern und die so entstandene + Bearbeitung unter der Bedingung vervielfältigen und verbreiten, dass er einen + auffälligen Vermerk über die vorgenommenen Modifizierungen anbringt, die + Kopien der Bearbeitung ohne Lizenzgebühren unter den Bedingungen der GPL + verbreitet und dafür sorgt, dass das Programm bei interaktiver Nutzung einen + Urheberrechtsvermerk ausgibt. Näheres regelt § 2 GPL. + + + Der Lizenznehmer darf das Programm oder eine Bearbeitung als Objectcode oder + in ausführbarer Form unter Berücksichtigung der letzten beiden Abschnitte + unter der Bedingung vervielfältigen und verbreiten, dass er den Quelltext + beifügt oder eine der in § 3 GPL genannten Alternativen erfüllt. Näheres + regelt § 3 GPL. + + + Sollte dem Lizenznehmer infolge eines Gerichtsurteils oder durch einen + gerichtlichen Vergleich Bedingungen auferlegt werden, die der GPL + widersprechen, so entbindet dies den Lizenznehmer nicht von der Einhaltung der + GPL. Näheres regelt § 7 GPL. + + + Wenn die Verbreitung oder die Benutzung des Programms in bestimmten Staaten + durch Patent- oder Urheberrecht eingeschränkt ist, kann der Lizenznehmer bei + der Verbreitung des Programms durch einen entsprechenden Vermerk bestimmen, + dass die Verbreitung des Programms in bestimmten Staaten ausgeschlossen ist. + Näheres regelt § 8 GPL. + + + + + +5. Schutzrechte Dritter +Der Lizenzgeber geht davon aus, dass der Besitz und der vertragsgemäße Gebrauch +der Software keine Schutzrechte Dritter für den Bereich der BRD beeinträchtigt. +Im Zusammenhang mit einer möglichen Beeinträchtigung der Schutzrechte Dritter +werden die folgenden Nebenpflichten vereinbart: + Der Lizenznehmer verpflichtet sich, dass er weder für sich noch im Auftrag + eines Dritten die Software zu dem Zweck verwendet, diese nach + Schutzrechtsverletzungen zu untersuchen oder untersuchen zu lassen. + + + Der Lizenznehmer verpflichtet sich, den Lizenzgeber unverzüglich zu + benachrichtigen, wenn Dritte Schutzrechtsverletzungen geltend machen. + + + Hat der Lizenznehmer den Eindruck, dass die Software Patente oder andere + Schutzrechte Dritter verletzt, so ist er verpflichtet, den Lizenzgeber + unverzüglich schriftlich unter Beifügung einer genauen Beschreibung der + Verletzungshandlung zu unterrichten. Es ist dem Lizenznehmer untersagt, andere + natürliche oder juristische Personen ohne schriftliches Einverständnis des + Lizenzgebers zu informieren. + + +Bei Verletzung einer der obigen Nebenpflichten verpflichtet sich der +Lizenznehmer, dem Lizenzgeber Schadensersatz für alle durch die Verletzung +entstandenen Schäden (einschließlich der Prozeßkosten) zu leisten. Ist die +Verletzung einer solchen Nebenpflicht festgestellt, so genügt es, wenn der +Lizenzgeber plausibel darlegt, dass der Schaden durch die Verletzung entstanden +ist. Den Lizenznehmer trifft die volle Beweislast für das Gegenteil. Der +Lizenznehmer verpflichtet sich, dem Lizenzgeber alle Auskünfte im Zusammenhang +mit der Verletzung einer der obigen Nebenpflichten zu erteilen. +Der Lizenzgeber weist darauf hin, dass zur CampusSource-Software nicht die +Software anderer Hersteller gehört, mit der die CampusSource-Software +zusammenarbeiten kann oder die für den Betrieb der CampusSource-Software +notwendigerweise vorhanden sein muss, wie z. B. WWW-Server, +Funktionsbibliotheken, Werkzeugsysteme und Datenbankmanagementsysteme. Die +Lizenzen für diese Software müssen vom jeweiligen Hersteller separat erworben +werden. Die GPL gilt für diese Software in der Regel nicht. + + + +6. Datenschutz +Der Lizenzgeber verpflichtet sich, bezüglich der bei der Registrierung +angegebenen Daten die einschlägigen landes- und bundesrechtlichen +Datenschutzbestimmungen einzuhalten. Alle Verbindungen zu diesem Server im +Download- und Registrierbereich werden in einem LOG-File aufgezeichnet. + + + +7. Schriftform +Alle Nebenabreden, die zwischen dem Lizenzgeber und dem Lizenznehmer +abgeschlossen werden, bedürfen der Schriftform. Eine Abänderung oder Aufhebung +dieser Klausel bedarf ebenfalls der Schriftform. + + + +8. Gerichtsstand +Gerichtsstand für alle Streitigkeiten aus diesem Vertrag ist Hagen, sofern der +Lizenznehmer Kaufmann, eine juristische Person des öffentlichen Rechts oder ein +öffentlich-rechtliches Sondervermögen ist. +Die Parteien vereinbaren die Anwendung deutschen Rechts. Sollte nach +Internationalem Verfahrensrecht die Zuständigkeit eines deutschen Gerichts +möglich sein, so vereinbaren die Parteien die Zuständigkeit der deutschen +Gerichtsbarkeit und innerhalb Deutschlands die Zuständigkeit des Amtsgerichtes +bzw. Landgerichtes Hagen. Bezüglich der in Abschnitt 5 »Schutzrechte Dritter« +festgelegten Nebenpflichten des Lizenznehmers kann der Lizenzgeber abweichend +von Satz 3 ein beliebiges international zuständiges Gericht anrufen. +© 2000 CampusSource Alle Rechte vorbehalten + + + diff --git a/src/ApplicationResources.properties b/src/ApplicationResources.properties new file mode 100644 index 0000000..df9d66d --- /dev/null +++ b/src/ApplicationResources.properties @@ -0,0 +1,65 @@ + +# Buttons +button.cancel=Cancel +button.confirm=Confirm +button.reset=Reset +button.save=Save +button.delete=Delete +button.delete.confirm=Do you really want to remove this entry? +button.update=Update +button.nav.new=New +button.nav.copy=Copy +button.addnew=Add a new entry +button.edit=Edit +button.nav.first=<< First +button.nav.last= Last >> +button.nav.next= Next > +button.nav.previous=< Previous +button.submit=Submit + + +# Messages +msg.yes=Yes +msg.no=No +msg.null=[Null] + +# Menus +menu.list.displayname=List +menu.list.readonly.displayname=List read-only +menu.login.displayname=Login +menu.logout.displayname=Logout +menu.admin.displayname=Administration + + +# DBforms use +dbforms.select.sort.ascending=Ascending +dbforms.select.sort.descending=Descending +dbforms.select.sort.none=None + + +# Errors +errors.footer= +errors.header=

Validation Error

You must correct the following error(s) before proceeding: +errors.ioException=I/O exception rendering error messages: {0} +error.database.missing=
  • User database is missing, cannot validate logon credentials
  • +errors.required={0} is required. +errors.minlength={0} can not be less than {1} characters. +errors.maxlength={0} can not be greater than {1} characters. +errors.invalid={0} is invalid. + +errors.byte={0} must be an byte. +errors.short={0} must be an short. +errors.integer={0} must be an integer. +errors.long={0} must be an long. +errors.float={0} must be an float. +errors.double={0} must be an double. + +errors.date={0} is not a date. +errors.test.date={0} is not a test date. + +errors.range={0} is not in the range {1} through {2}. +errors.creditcard={0} is not a valid credit card number. +errors.phone={0} is not a valid phone number ({1}). +errors.email={0} is an invalid e-mail address. + + diff --git a/src/ApplicationResources_de.properties b/src/ApplicationResources_de.properties new file mode 100644 index 0000000..e62b970 --- /dev/null +++ b/src/ApplicationResources_de.properties @@ -0,0 +1,74 @@ + +# Buttons +button.cancel=Abbrechen +button.confirm=Bestätigen +button.reset=Zurücksetzen +button.save=Sichern +button.update=Speichern +button.delete=Löschen +button.delete.confirm=Wollen Sie den Eintrag wirklich löschen? +button.submit=Abschicken +button.addnew=Einfügen + +button.nav.new=Neu +button.nav.copy=Kopieren +button.edit=Bearbeiten +button.nav.first=<< Erster +button.nav.last= Letzter >> +button.nav.next= Nächster > +button.nav.previous=< Vorheriger + + +# DBforms use +dbforms.select.sort.ascending=Ascendant +dbforms.select.sort.descending=Descendant +dbforms.select.sort.none=Aucun + +# Messages +msg.yes=Ja +msg.no=Nein +msg.null=--leer-- + +# Menus +menu.list.displayname=List +menu.list.readonly.displayname=List read-only +menu.login.displayname=Login +menu.logout.displayname=Logout +menu.admin.displayname=Administration + + +# DBforms use +dbforms.select.sort.ascending=Ascending +dbforms.select.sort.descending=Descending +dbforms.select.sort.none=None + + +# Errors +errors.footer= +errors.header=

    Validation Error

    You must correct the following error(s) before proceeding: +errors.ioException=I/O exception rendering error messages: {0} +error.database.missing=
  • User database is missing, cannot validate logon credentials
  • +errors.required={0} ist ein Pflichtfeld. +errors.minlength={0} can not be less than {1} characters. +errors.maxlength={0} can not be greater than {1} characters. +errors.invalid={0} is invalid. + +errors.byte={0} must be an byte. +errors.short={0} must be an short. +errors.integer={0} must be an integer. +errors.long={0} must be an long. +errors.float={0} must be an float. +errors.double={0} must be an double. + +errors.date={0} is not a date. +errors.test.date={0} is not a test date. + +errors.range={0} is not in the range {1} through {2}. +errors.creditcard={0} is not a valid credit card number. +errors.phone={0} is not a valid phone number ({1}). +errors.email={0} is an invalid e-mail address. + + +#HRK +studium.heading1=ee + diff --git a/src/LocalStrings.properties b/src/LocalStrings.properties new file mode 100644 index 0000000..ecf4f46 --- /dev/null +++ b/src/LocalStrings.properties @@ -0,0 +1,11 @@ +# $Id: LocalStrings_en.properties,v 1.1 2000/08/17 00:57:52 horwat Exp $ + +# Default localized resources for SuperX servlets +# This locale is en_US + +superx.login=SuperX Login +superx.welcome=Welcome +superx.denied=Session timeout reached, or no valid authorization for +superx.logintext=Please login again +superx.cookietext=Please make sure your Browser accepts Cookies from this site. + diff --git a/src/LocalStrings_de.properties b/src/LocalStrings_de.properties new file mode 100644 index 0000000..f208c9e --- /dev/null +++ b/src/LocalStrings_de.properties @@ -0,0 +1,11 @@ +# $Id: LocalStrings_de.properties,v 1.1 2000/08/17 00:57:52 horwat Exp $ + +# Default localized resources for SuperX servlets +# This locale is de_DE + +superx.login=SuperX Login +superx.welcome=Willkommen +superx.denied=Session-Timeout erreicht, oder keine gültige Authentifizierung für +superx.logintext=Bitte melden Sie sich neu an. +superx.cookietext=Bitte stellen Sie sicher, dass Ihr Browser Cookies von diesem Server erlaubt. +superx.deniednouser=Sie sind nicht mehr am System angemeldet. \ No newline at end of file diff --git a/src/LocalStrings_en.properties b/src/LocalStrings_en.properties new file mode 100644 index 0000000..bc75044 --- /dev/null +++ b/src/LocalStrings_en.properties @@ -0,0 +1,11 @@ +# $Id: LocalStrings_en.properties,v 1.1 2000/08/17 00:57:52 horwat Exp $ + +# Default localized resources for SuperX servlets +# This locale is en_US + +superx.login=SuperX Login +superx.welcome=Welcome +superx.denied=Session timeout reached, or no valid authorization for +superx.logintext=Please login again. +superx.cookietext=Please make sure your Browser accepts Cookies from this site. +superx.deniednouser=You are not logged in any more. diff --git a/src/commons-logging.properties b/src/commons-logging.properties new file mode 100644 index 0000000..2929256 --- /dev/null +++ b/src/commons-logging.properties @@ -0,0 +1 @@ +org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger diff --git a/src/de/memtext/baseobjects/ActivatableItem.java b/src/de/memtext/baseobjects/ActivatableItem.java new file mode 100644 index 0000000..7954996 --- /dev/null +++ b/src/de/memtext/baseobjects/ActivatableItem.java @@ -0,0 +1,31 @@ +package de.memtext.baseobjects; + +/** + * + * @author MB + * */ +public class ActivatableItem implements ActivatableItemI { + private static final long serialVersionUID = 1; +private boolean isActive; + /** + * + */ + public ActivatableItem() { + super(); + } + + /* (non-Javadoc) + * @see de.memtext.baseobjects.ActivatableItemI#isActive() + */ + public boolean isActive() { + return isActive; + } + + /* (non-Javadoc) + * @see de.memtext.baseobjects.ActivatableItemI#setActive(boolean) + */ + public void setActive(boolean isActive) { + this.isActive=isActive; + } + +} diff --git a/src/de/memtext/baseobjects/ActivatableItemI.java b/src/de/memtext/baseobjects/ActivatableItemI.java new file mode 100644 index 0000000..549a591 --- /dev/null +++ b/src/de/memtext/baseobjects/ActivatableItemI.java @@ -0,0 +1,10 @@ +package de.memtext.baseobjects; + +/** + * + * @author MB + * */ +public interface ActivatableItemI { +boolean isActive(); +void setActive(boolean isActive); +} diff --git a/src/de/memtext/baseobjects/ComparableObject.java b/src/de/memtext/baseobjects/ComparableObject.java new file mode 100644 index 0000000..31f73f2 --- /dev/null +++ b/src/de/memtext/baseobjects/ComparableObject.java @@ -0,0 +1,40 @@ +package de.memtext.baseobjects; + +public class ComparableObject extends NamedObject implements Comparable { + private int sortNr; + private static final long serialVersionUID = 1; + + public ComparableObject(String name, int sortNr) { + super(name); + this.sortNr = sortNr; + } + + public int compareTo(Object o) { + int result = 0; + if (getSortNr() < ((ComparableObject) o).getSortNr()) + result = -1; + if (getSortNr() > ((ComparableObject) o).getSortNr()) + result = 1; + return result; + } + + public int getSortNr() { + return sortNr; + } + + public boolean equals(Object o) { + boolean result = false; + ComparableObject comp = (ComparableObject) o; + if (this.getName().equals(comp.getName()) + && this.getSortNr() == comp.getSortNr()) + result = true; + + return result; + } + + public void setSortNr(int sortNr) { + this.sortNr = sortNr; + } +} + +//Created on 22.10.2004 at 16:20:48 diff --git a/src/de/memtext/baseobjects/DataList.java b/src/de/memtext/baseobjects/DataList.java new file mode 100644 index 0000000..ae25f08 --- /dev/null +++ b/src/de/memtext/baseobjects/DataList.java @@ -0,0 +1,50 @@ +package de.memtext.baseobjects; + +import java.util.Collection; +import java.util.LinkedList; + +/** + * + * @author MB + * List with different behaviour when setting items, + * when index higher than count of elements doesn't throw + * Exception, but adds as many nulls as necessary up to the + * right count of elements and then sets the indicated position to + * the new value + * + * * If for example a value for column 5 is to be stored, but the data List only + * contains values for column 1 and 2, for column 3 and 4 null values are stored. + + * */ +public class DataList extends LinkedList { + private static final long serialVersionUID = 1; + + /** + * + */ + public DataList() { + super(); + } + + /** + * @param c + */ + public DataList(Collection c) { + super(c); + + } + /** + * If for example a value for column 5 is to be stored, but the data List only + * contains values for column 1 and 2, for column 3 and 4 null values are stored. + + */ + public Object set(int index, Object o) { + while (index > this.size() - 1) { + this.add(null); + } + Object previous = this.get(index); + super.set(index, o); + return previous; + } + +} diff --git a/src/de/memtext/baseobjects/DoubleClickMouseListener.java b/src/de/memtext/baseobjects/DoubleClickMouseListener.java new file mode 100644 index 0000000..d35fea2 --- /dev/null +++ b/src/de/memtext/baseobjects/DoubleClickMouseListener.java @@ -0,0 +1,18 @@ +package de.memtext.baseobjects; + +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +public abstract class DoubleClickMouseListener extends MouseAdapter { + + public DoubleClickMouseListener() { + super(); + } + public final void mousePressed(MouseEvent e) { + if (e.getClickCount() == 2) doubleClickOccured(); +} + protected abstract void doubleClickOccured() ; + + +} +//Created on 16.03.2004 at 15:51:43 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/IdObject.java b/src/de/memtext/baseobjects/IdObject.java new file mode 100644 index 0000000..66c8713 --- /dev/null +++ b/src/de/memtext/baseobjects/IdObject.java @@ -0,0 +1,50 @@ +package de.memtext.baseobjects; + +import java.io.Serializable; + +/** + * + * @author MB + * */ +public class IdObject implements IdObjectI,Serializable { + private Object id; + private static final long serialVersionUID = 1; + public IdObject() { + + } + public IdObject(Object id) { + setId(id); + + } + + /** + * @return + */ + public Object getId() { + return id; + } + + + + /** + * @param object + */ + public void setId(Object object) { + id = object; + } + + public String toString() + { + return "id:"+getId(); + } + /** + * Provides a deep copy + */ + public Object clone() throws CloneNotSupportedException { + if (id!=null&&!(id instanceof String)&&!(id instanceof Integer)) + throw new CloneNotSupportedException(" You have to check in IdObject.clone if deep copying is necessary for class "+id.getClass()); + + IdObject cl=new IdObject(this.getId()); + return cl; + } +} diff --git a/src/de/memtext/baseobjects/IdObjectI.java b/src/de/memtext/baseobjects/IdObjectI.java new file mode 100644 index 0000000..c072890 --- /dev/null +++ b/src/de/memtext/baseobjects/IdObjectI.java @@ -0,0 +1,11 @@ +package de.memtext.baseobjects; +/** + * @see de.memtext.util.TreeUtils for a method creating key list (1,2,4) from nodes + */ +public interface IdObjectI { + public Object getId(); + public void setId(Object id); + +} + +//Created on 30.01.2004 at 13:03:06 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/NameDecorator.java b/src/de/memtext/baseobjects/NameDecorator.java new file mode 100644 index 0000000..4ef5efa --- /dev/null +++ b/src/de/memtext/baseobjects/NameDecorator.java @@ -0,0 +1,28 @@ +package de.memtext.baseobjects; + + +/** + * For classes up in the hierarchy which need a name in some context + * but shouldn't pass it on to inheriting classes + */ +public final class NameDecorator implements NamedObjectI{ +private Object object; +private String name; + public NameDecorator(String name,Object object) { + this.name=name; + this.object=object; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name=name; + } + + public Object getObject() + { + return object; + } +} + +//Created on 25.11.2003 at 14:49:50 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/NamedIdObject.java b/src/de/memtext/baseobjects/NamedIdObject.java new file mode 100644 index 0000000..9a4e381 --- /dev/null +++ b/src/de/memtext/baseobjects/NamedIdObject.java @@ -0,0 +1,83 @@ +package de.memtext.baseobjects; + +import java.io.Serializable; + +import de.memtext.util.EqualsUtil; +import de.memtext.util.HashCodeUtil; + +/** + * + * @author MB + */ +public class NamedIdObject extends NamedObject implements NamedIdObjectI, + Serializable { + private Object id; + private static final long serialVersionUID = 1; + public NamedIdObject() { + } + + public NamedIdObject(NamedObjectI namedObject) { + setName(namedObject.getName()); + } + + public NamedIdObject(Object id, String name) { + setId(id); + setName(name); + } + + /** + * @return + */ + public Object getId() { + return id; + } + + /** + * @param object + */ + public void setId(Object id) { + this.id = id; + } + + public String toString() { + return getId() + " - " + getName(); + } +public boolean equals(Object o) +{ + boolean result=false; + if (o instanceof NamedIdObject) + { + NamedIdObject o2=(NamedIdObject)o; + result=EqualsUtil.areEqual(this.getId(),o2.getId())&&EqualsUtil.areEqual(this.getName(),o2.getName()); + + + } + return result; +} +public int hashCode(){ + int result = HashCodeUtil.SEED; + //collect the contributions of various fields + result = HashCodeUtil.hash(result, getId()); + result = HashCodeUtil.hash(result, getName()); + + return result; + } + /** + * Provides a deep copy + */ + public Object clone() throws CloneNotSupportedException { + + NamedIdObject cl = new NamedIdObject((NamedObject) super.clone()); + + if (id != null && !(id instanceof String) && !(id instanceof Integer)) + throw new CloneNotSupportedException( + " You have to check in NamedIdObject.clone if deep copying is necessary for class " + + id.getClass()); + + if (this.id != null) + cl.setId(id); + return cl; + } + + +} \ No newline at end of file diff --git a/src/de/memtext/baseobjects/NamedIdObjectI.java b/src/de/memtext/baseobjects/NamedIdObjectI.java new file mode 100644 index 0000000..7ed3b62 --- /dev/null +++ b/src/de/memtext/baseobjects/NamedIdObjectI.java @@ -0,0 +1,10 @@ +package de.memtext.baseobjects; + +/** + * + * @author MB + * */ +public interface NamedIdObjectI extends NamedObjectI, IdObjectI{ + + +} \ No newline at end of file diff --git a/src/de/memtext/baseobjects/NamedIdObjectWithParent.java b/src/de/memtext/baseobjects/NamedIdObjectWithParent.java new file mode 100644 index 0000000..4b6998e --- /dev/null +++ b/src/de/memtext/baseobjects/NamedIdObjectWithParent.java @@ -0,0 +1,91 @@ +package de.memtext.baseobjects; + +import java.io.Serializable; + +import de.memtext.tree.KeyParentEqualException; +import de.memtext.util.EqualsUtil; +import de.memtext.util.HashCodeUtil; + +public class NamedIdObjectWithParent extends NamedIdObject implements + NamedIdObjectWithParentI, Serializable { + private Object parentKey; + private static final long serialVersionUID = 1; + public NamedIdObjectWithParent() { + super(); + } + + public NamedIdObjectWithParent(NamedIdObjectI namedIdObject) { + setId(namedIdObject.getId()); + setName(namedIdObject.getName()); + } + + public NamedIdObjectWithParent(Object id, String name) { + super(id, name); + } + + public NamedIdObjectWithParent(Object id, String name, Object parentKey) + throws KeyParentEqualException { + super(id, name); + setParentKey(parentKey); + } + + public Object getParentKey() { + return parentKey; + } + + public void setParentKey(Object parentKey) throws KeyParentEqualException { + this.parentKey = parentKey; + if ((getId() == null && getParentKey() == null) + || (getId() != null && getId().equals(getParentKey()))) + throw new KeyParentEqualException((NamedIdObjectWithParentI) this); + } +//TODO aufteilen auf übergeordnete Objekte + public boolean equals(Object obj) { + + if ( this == obj ) return true; + if ( obj == null || obj.getClass() != this.getClass() ) return false; + + NamedIdObjectWithParent i2=(NamedIdObjectWithParent)obj; + return + EqualsUtil.areEqual(this.getId(), i2.getId()) && + EqualsUtil.areEqual(this.getName(), i2.getName()) && + EqualsUtil.areEqual(this.getParentKey(), i2.getParentKey()); + + + } + + /* + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + int result = HashCodeUtil.SEED; + result = HashCodeUtil.hash(result, getId()); + result = HashCodeUtil.hash(result, getName()); + result = HashCodeUtil.hash(result, getParentKey()); + return result ; + } + /** + * Provides a deep copy + */ + public Object clone() throws CloneNotSupportedException { + + NamedIdObjectWithParent cl = new NamedIdObjectWithParent( + (NamedIdObject) super.clone()); + + if (parentKey != null && !(parentKey instanceof String) + && !(parentKey instanceof Integer)) + throw new CloneNotSupportedException( + " You have to check in NamedIdObjectWithParent.clone if deep copying is necessary for class " + + parentKey.getClass()); + + if (this.parentKey != null) + try { + cl.setParentKey(this.parentKey); + } catch (KeyParentEqualException e) { + throw new CloneNotSupportedException("Cloning didn't work" + e); + } + return cl; + } +} + +//Created on 18.11.2003 diff --git a/src/de/memtext/baseobjects/NamedIdObjectWithParentI.java b/src/de/memtext/baseobjects/NamedIdObjectWithParentI.java new file mode 100644 index 0000000..5f57048 --- /dev/null +++ b/src/de/memtext/baseobjects/NamedIdObjectWithParentI.java @@ -0,0 +1,9 @@ +package de.memtext.baseobjects; + +import de.memtext.tree.KeyParentEqualException; + +public interface NamedIdObjectWithParentI extends NamedIdObjectI { + public Object getParentKey(); + public void setParentKey(Object parentKey) throws KeyParentEqualException; +} +//Created on 18.11.2003 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/NamedObject.java b/src/de/memtext/baseobjects/NamedObject.java new file mode 100644 index 0000000..ecdf2a6 --- /dev/null +++ b/src/de/memtext/baseobjects/NamedObject.java @@ -0,0 +1,49 @@ +package de.memtext.baseobjects; + +import java.io.Serializable; + +/** + * + * @author MB + * */ +public class NamedObject implements NamedObjectI,Serializable { + private String name; + private static final long serialVersionUID = 1; + /** + * + */ + + public NamedObject() { + + } + public NamedObject(String name) { + setName(name); + } + + + /** + * @return + */ + public String getName() { + return name; + } + + + + /** + * @param string + */ + public void setName(String string) { + name = string; + } + public String toString() { + return name; + } + + /** + * Provides a deep copy + */ + protected Object clone() throws CloneNotSupportedException { + return new NamedObject(this.getName()); + } +} diff --git a/src/de/memtext/baseobjects/NamedObjectI.java b/src/de/memtext/baseobjects/NamedObjectI.java new file mode 100644 index 0000000..0cf8132 --- /dev/null +++ b/src/de/memtext/baseobjects/NamedObjectI.java @@ -0,0 +1,13 @@ +package de.memtext.baseobjects; + +/** + * + * @author MB + * */ +public interface NamedObjectI { + + public String getName(); + + public void setName(String name); + public String toString(); +} \ No newline at end of file diff --git a/src/de/memtext/baseobjects/SearchReplaceTextHolder.java b/src/de/memtext/baseobjects/SearchReplaceTextHolder.java new file mode 100644 index 0000000..d413003 --- /dev/null +++ b/src/de/memtext/baseobjects/SearchReplaceTextHolder.java @@ -0,0 +1,32 @@ +package de.memtext.baseobjects; +/** + * This class holds information about a string that is to be + * searched for and another string that the former is to be + * replaced with. + * By default both are empty strings. + */ +public class SearchReplaceTextHolder { + private String searchText="", replaceText=""; + public SearchReplaceTextHolder() { + super(); + } + + public String getReplaceText() { + return replaceText; + } + + public String getSearchText() { + return searchText; + } + + public void setReplaceText(String string) { + replaceText = string; + } + + public void setSearchText(String string) { + searchText = string; + } + +} + +//Created on 04.02.2004 at 11:40:47 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/User.java b/src/de/memtext/baseobjects/User.java new file mode 100644 index 0000000..8642d91 --- /dev/null +++ b/src/de/memtext/baseobjects/User.java @@ -0,0 +1,86 @@ +package de.memtext.baseobjects; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import de.memtext.rights.Rights; + +/** + * stellt einen User dar, könnte sicherer gemacht werden mit + * defensive Copying + * @author MB + * */ +public class User extends NamedIdObject implements Serializable { + private List groupMembershipIds = new ArrayList(5); + private String passwd; + + private Rights rights; + private boolean isAdmin=false; + private static final long serialVersionUID = 1; + public User() { + setName(""); + setPasswd(""); + } + public User(String username, String passwd) { + setName(username); + setPasswd(passwd); + + } + + public User(String username, Integer userid) { + super(userid,username); + if (userid == null) + throw new IllegalArgumentException("No user without userid allowed"); + } + public User(String username) { + setName(username); + } + /** + * @param groupmemberships + */ + public void addAllGroupmembershipsById(List groupmemberships) { + groupMembershipIds.addAll(groupmemberships); + } + public void addGroupMembershipById(Integer groupid) { + groupMembershipIds.add(groupid); + } + + public String getPasswd() { + return passwd; + } + + + + public Iterator groupmembershipIdIterator() { + return groupMembershipIds.iterator(); + } + public void removeGroupMembershipById(Integer groupid) { + groupMembershipIds.remove(groupid); + } + + public void setPasswd(String pwd) { + passwd = pwd; + } + + + public String toString() + { + + return getName(); + } + public Rights getRights() { + return rights; + } + public void setRights(Rights rights) { + this.rights = rights; + } + public boolean isAdmin() { + return isAdmin; + } + public void setAdmin(boolean isAdmin) { + this.isAdmin = isAdmin; + } + +} diff --git a/src/de/memtext/baseobjects/coll/ActivatableItemList.java b/src/de/memtext/baseobjects/coll/ActivatableItemList.java new file mode 100644 index 0000000..d23d6eb --- /dev/null +++ b/src/de/memtext/baseobjects/coll/ActivatableItemList.java @@ -0,0 +1,321 @@ +package de.memtext.baseobjects.coll; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import de.memtext.baseobjects.ActivatableItemI; + +/** + * + * @author MB + * */ +public class ActivatableItemList implements List,Serializable { + private List collect = new LinkedList(); + private static final long serialVersionUID = 1; + /** + * + */ + public ActivatableItemList() { + super(); + } + + public Iterator activeItemIterator() { + return getActiveItems().iterator(); + } + + public Collection getActiveItems() { + Collection result = new LinkedList(); + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (element.isActive()) + result.add(element); + } + return result; + } + public void setAllActive(boolean active) { + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + element.setActive(active); + } + } + public boolean isAllActive() { + boolean result = true; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (!element.isActive()) { + result = false; + break; + } + } + return result; + } + public boolean isAllDeactivated() { + boolean result = true; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (element.isActive()) { + result = false; + break; + } + } + return result; + } + public int activeCount() { + int count = 0; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (element.isActive()) + count++; + } + return count; + } + public int deactivatedCount() { + + int count = 0; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (!element.isActive()) + count++; + } + return count; + + } + public ActivatableItemI getActiveItem(int pos) { + ActivatableItemI result = null; + int i = 0; + + for (Iterator it = activeItemIterator(); it.hasNext();) { + ActivatableItemI element = (ActivatableItemI) it.next(); + if (i == pos) { + result = element; + break; + } + i++; + } + if (result == null) + throw new RuntimeException("not found"); + + return result; + } + /** + * + * @return null if all deactivated + */ + public ActivatableItemI getFirstActive() { + ActivatableItemI result = null; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (element.isActive()) { + result = element; + break; + } + } + return result; + } + /** + * + * @return null if all active + */ + public ActivatableItemI getFirstDeactivated() { + ActivatableItemI result = null; + for (Iterator iter = this.iterator(); iter.hasNext();) { + ActivatableItemI element = (ActivatableItemI) iter.next(); + if (!element.isActive()) { + result = element; + break; + } + } + return result; + } + /* (non-Javadoc) + * @see java.util.Collection#size() + */ + public int size() { + return collect.size(); + } + + /* (non-Javadoc) + * @see java.util.Collection#isEmpty() + */ + public boolean isEmpty() { + return collect.isEmpty(); + } + + /* (non-Javadoc) + * @see java.util.Collection#contains(java.lang.Object) + */ + public boolean contains(Object o) { + return collect.contains(o); + } + + /* (non-Javadoc) + * @see java.util.Collection#iterator() + */ + public Iterator iterator() { + return collect.iterator(); + } + + /* (non-Javadoc) + * @see java.util.Collection#toArray() + */ + public Object[] toArray() { + return collect.toArray(); + } + + /* (non-Javadoc) + * @see java.util.Collection#toArray(java.lang.Object[]) + */ + public Object[] toArray(Object[] a) { + return collect.toArray(a); + } + + /* (non-Javadoc) + * @see java.util.Collection#containsAll(java.util.Collection) + */ + public boolean containsAll(Collection c) { + return collect.containsAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#addAll(java.util.Collection) + */ + public boolean addAll(Collection c) { + for (Iterator iter = c.iterator(); iter.hasNext();) { + Object element = iter.next(); + if (!(element instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + + } + return collect.addAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#removeAll(java.util.Collection) + */ + public boolean removeAll(Collection c) { + return collect.removeAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#retainAll(java.util.Collection) + */ + public boolean retainAll(Collection c) { + for (Iterator iter = c.iterator(); iter.hasNext();) { + Object element = iter.next(); + if (!(element instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + + } + return collect.retainAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#clear() + */ + public void clear() { + collect.clear(); + } + + /* (non-Javadoc) + * @see java.util.Collection#add(java.lang.Object) + */ + public boolean add(Object o) { + if (!(o instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + return collect.add(o); + } + + /* (non-Javadoc) + * @see java.util.Collection#remove(java.lang.Object) + */ + public boolean remove(Object o) { + return collect.remove(o); + } + + /* (non-Javadoc) + * @see java.util.List#addAll(int, java.util.Collection) + */ + public boolean addAll(int index, Collection c) { + for (Iterator iter = c.iterator(); iter.hasNext();) { + Object element = iter.next(); + if (!(element instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + + } + return collect.addAll(c); + } + + /* (non-Javadoc) + * @see java.util.List#get(int) + */ + public Object get(int index) { + return collect.get(index); + } + + /* (non-Javadoc) + * @see java.util.List#set(int, java.lang.Object) + */ + public Object set(int index, Object element) { + if (!(element instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + return collect.set(index, element); + } + + /* (non-Javadoc) + * @see java.util.List#add(int, java.lang.Object) + */ + public void add(int index, Object element) { + if (!(element instanceof ActivatableItemI)) + throw new IllegalArgumentException("only Activatable items"); + collect.add(index, element); + } + + /* (non-Javadoc) + * @see java.util.List#remove(int) + */ + public Object remove(int index) { + return collect.remove(index); + } + + /* (non-Javadoc) + * @see java.util.List#indexOf(java.lang.Object) + */ + public int indexOf(Object o) { + return collect.indexOf(o); + } + + /* (non-Javadoc) + * @see java.util.List#lastIndexOf(java.lang.Object) + */ + public int lastIndexOf(Object o) { + return collect.lastIndexOf(o); + } + + /* (non-Javadoc) + * @see java.util.List#listIterator() + */ + public ListIterator listIterator() { + return collect.listIterator(); + } + + /* (non-Javadoc) + * @see java.util.List#listIterator(int) + */ + public ListIterator listIterator(int index) { + return collect.listIterator(index); + } + + /* (non-Javadoc) + * @see java.util.List#subList(int, int) + */ + public List subList(int fromIndex, int toIndex) { + return collect.subList(fromIndex, toIndex); + } + public String toString() { + return "ActivatableItemsList " + size() + " items"; + } +} diff --git a/src/de/memtext/baseobjects/coll/BaseObjectCollection.java b/src/de/memtext/baseobjects/coll/BaseObjectCollection.java new file mode 100644 index 0000000..57d9610 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/BaseObjectCollection.java @@ -0,0 +1,125 @@ +package de.memtext.baseobjects.coll; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; + +/** + * Basis for the collections, but default the used collection is a + * linkedList, subclasses may change to use a list or set + * @author MB + * */ +public class BaseObjectCollection implements Collection,Serializable { + protected Collection collect; + private static final long serialVersionUID = 1; + public BaseObjectCollection() { + super(); + collect = new LinkedList(); + } + + + + public int size() { + return collect.size(); + } + + /* (non-Javadoc) + * @see java.util.Collection#isEmpty() + */ + public boolean isEmpty() { + return collect.isEmpty(); + } + + /* (non-Javadoc) + * @see java.util.Collection#contains(java.lang.Object) + */ + public boolean contains(Object o) { + return collect.contains(o); + } + + /* (non-Javadoc) + * @see java.util.Collection#iterator() + */ + public Iterator iterator() { + return collect.iterator(); + } + + /* (non-Javadoc) + * @see java.util.Collection#toArray() + */ + public Object[] toArray() { + return collect.toArray(); + } + + /* (non-Javadoc) + * @see java.util.Collection#toArray(java.lang.Object[]) + */ + public Object[] toArray(Object[] a) { + return collect.toArray(a); + } + + + + + /* (non-Javadoc) + * @see java.util.Collection#containsAll(java.util.Collection) + */ + public boolean containsAll(Collection c) { + return collect.containsAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#addAll(java.util.Collection) + */ + public boolean addAll(Collection c) { + return collect.addAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#removeAll(java.util.Collection) + */ + public boolean removeAll(Collection c) { + return collect.removeAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#retainAll(java.util.Collection) + */ + public boolean retainAll(Collection c) { + return collect.retainAll(c); + } + + /* (non-Javadoc) + * @see java.util.Collection#clear() + */ + public void clear() { + collect.clear(); + } + + /* (non-Javadoc) + * @see java.util.Collection#add(java.lang.Object) + */ + public boolean add(Object o) { + if (o==null) throw new IllegalArgumentException("can't add null value"); + return collect.add(o); + } + + /* (non-Javadoc) + * @see java.util.Collection#remove(java.lang.Object) + */ + public boolean remove(Object o) { + return collect.remove(o); + } + + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + BaseObjectCollection c=new BaseObjectCollection(); + c.addAll(this); + return c; + } +} +//Created on 30.1.2004 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/IdObjectCollection.java b/src/de/memtext/baseobjects/coll/IdObjectCollection.java new file mode 100644 index 0000000..578dcd0 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/IdObjectCollection.java @@ -0,0 +1,108 @@ +package de.memtext.baseobjects.coll; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; + +import de.memtext.baseobjects.IdObjectI; +import de.memtext.util.StringUtils; + +/** + * + * @author MB + * */ +public class IdObjectCollection + extends BaseObjectCollection + implements Collection ,Serializable{ + private static final long serialVersionUID = 1; + public IdObjectCollection() { + super(); + } + /** + * + * @param id + * @return object + * @throws IllegalArgumentException if nothing found + */ + public IdObjectI getById(Object id) { + IdObjectI test, result = null; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (IdObjectI) it.next(); + if ((id == null && test.getId() == null) + || (test.getId() != null && test.getId().equals(id))) { + result = test; + break; + } + } + if (result == null) + throw new IllegalArgumentException( + "No element with id " + id + " found!"); + return result; + } + /** + * like '12','34','343' + * useful for creating sqls like where x in (...) + * @return + */ + public String getIdsApostropheString() { + StringBuffer result = new StringBuffer(); + IdObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (IdObjectI) it.next(); + result.append("'" + test.getId() + "',"); + } + StringUtils.deleteLastChar(result); + return result.toString(); + } + public boolean containsItemWithId(Object id) { + boolean result = false; + IdObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (IdObjectI) it.next(); + if (test.getId().equals(id)) { + result = true; + break; + } + } + return result; + } + /** + * Checks if the collection contains only the ids given in the param collection ids + * @param Collection ids + * @return + */ + public boolean consistsOfIds(Collection ids) { + + if (this.size() != ids.size()) + return false; + boolean result = true; + for (Iterator it = ids.iterator(); it.hasNext();) { + Object id = it.next(); + try { + Object dummy = getById(id); + } catch (IllegalArgumentException e) { + result = false; + break; + } + } + return result; + } + + public boolean add(Object o) { + if (o == null) + throw new IllegalArgumentException("can't add null value"); + if (!(o instanceof IdObjectI)) + throw new IllegalArgumentException("only named IdObjects allowed"); + return collect.add(o); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + IdObjectCollection c=new IdObjectCollection(); + c.addAll(this); + return c; + } +} +//Created on 30.1.2004 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/IdObjectList.java b/src/de/memtext/baseobjects/coll/IdObjectList.java new file mode 100644 index 0000000..c9a8967 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/IdObjectList.java @@ -0,0 +1,84 @@ +package de.memtext.baseobjects.coll; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import de.memtext.baseobjects.IdObjectI; +import de.memtext.util.StringUtils; + +/** + * + * @author MB + * */ +public class IdObjectList extends IdObjectCollection implements List { + private static final long serialVersionUID = 1; + public IdObjectList() { + super(); + collect=new LinkedList(); + } + + + public Object get(int pos) + { + return ((List)collect).get(pos); + } + + public boolean addAll(int arg0, Collection arg1) { + return ((List)collect).addAll(arg0,arg1); + } + + public Object set(int arg0, Object arg1) { + return ((List)collect).set(arg0,arg1); + } + + public void add(int pos, Object arg1) { + ((List)collect).add(pos,arg1); + } + + public Object remove(int arg0) { + return ((List)collect).remove(arg0); + } + + + public ListIterator listIterator(int arg0) { + return ((List)collect).listIterator(arg0); + } + + public List subList(int arg0, int arg1) { + return ((List)collect).subList(arg0,arg1); + } + + public int indexOf(Object arg0) { + return ((List)collect).indexOf(arg0); + } + + public int lastIndexOf(Object arg0) { + return ((List)collect).lastIndexOf(arg0); + } + + public ListIterator listIterator() { + return ((List)collect).listIterator(); + } + public String toString() + { + StringBuffer result=new StringBuffer("idobject list:"); + for (Iterator it = this.iterator(); it.hasNext();) { + IdObjectI element = (IdObjectI) it.next(); + result.append(element.toString()+","); + } + StringUtils.getLastChar(result); + return result.toString(); + } + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + IdObjectList c=new IdObjectList(); + c.addAll(this); + return c; + } +} +//Created on 30.1.2004 diff --git a/src/de/memtext/baseobjects/coll/IdObjectSet.java b/src/de/memtext/baseobjects/coll/IdObjectSet.java new file mode 100644 index 0000000..6228070 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/IdObjectSet.java @@ -0,0 +1,24 @@ +package de.memtext.baseobjects.coll; + +import java.util.HashSet; +import java.util.Set; + +public class IdObjectSet extends IdObjectCollection implements Set { + private static final long serialVersionUID = 1; + public IdObjectSet() { + super(); + collect=new HashSet(); + } + + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + IdObjectSet c=new IdObjectSet(); + c.addAll(this); + return c; + } +} + +//Created on 30.1.2004 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectCollection.java b/src/de/memtext/baseobjects/coll/NamedIdObjectCollection.java new file mode 100644 index 0000000..9074efe --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectCollection.java @@ -0,0 +1,138 @@ +package de.memtext.baseobjects.coll; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; + +import de.memtext.baseobjects.NamedIdObject; +import de.memtext.baseobjects.NamedIdObjectI; +import de.memtext.util.EqualsUtil; +import de.memtext.util.StringUtils; + +/** + * + * @author MB + */ +public class NamedIdObjectCollection extends NamedObjectCollection implements + Collection, Serializable { + private static final long serialVersionUID = 1; + public NamedIdObjectCollection() { + super(); + } + + /** + * + * @param id + * @return object + * @throws IllegalArgumentException + * if nothing found + */ + public NamedIdObjectI getById(Object id) { + NamedIdObjectI test, result = null; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedIdObjectI) it.next(); + if ((id == null && test.getId() == null) + || (test.getId() != null && test.getId().equals(id))) { + result = test; + break; + } + } + if (result == null) + throw new IllegalArgumentException("No element with id " + id + + " found!"); + return result; + } + + /** + * like '12','34','343' useful for creating sqls like where x in (...) + * + * @return + */ + public String getIdsApostropheString() { + StringBuffer result = new StringBuffer(); + NamedIdObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedIdObjectI) it.next(); + result.append("'" + test.getId() + "',"); + } + StringUtils.deleteLastChar(result); + return result.toString(); + } + + public boolean containsItemWithName(String name) { + boolean result = false; + NamedIdObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedIdObjectI) it.next(); + if (test.getName().equals(name)) { + result = true; + break; + } + } + return result; + } + + public boolean containsItemWithId(Object id) { + boolean result = false; + NamedIdObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedIdObjectI) it.next(); + if (EqualsUtil.areEqual(test.getId(),id)) { + result = true; + break; + } + } + return result; + } + + /** + * Checks if the collection contains only the ids given in the param + * collection ids + * + * @param Collection + * ids + * @return + */ + public boolean consistsOfIds(Collection ids) { + + if (this.size() != ids.size()) + return false; + boolean result = true; + for (Iterator it = ids.iterator(); it.hasNext();) { + Object id = it.next(); + try { + Object dummy = getById(id); + } catch (IllegalArgumentException e) { + result = false; + break; + } + } + return result; + } + + public boolean add(Object o) { + if (o == null) + throw new IllegalArgumentException("can't add null value"); + if (!(o instanceof NamedIdObjectI)) + throw new IllegalArgumentException("only named IdObjects allowed"); + return collect.add(o); + } + + public String toString() { + StringBuffer result = new StringBuffer(size() + " NamedIdObjects: "); + for (Iterator it = this.iterator(); it.hasNext();) { + NamedIdObjectI element = (NamedIdObjectI) it.next(); + result.append(element + " - "); + } + return result.toString(); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectCollection c=new NamedIdObjectCollection(); + c.addAll(this); + return c; + } +} \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectList.java b/src/de/memtext/baseobjects/coll/NamedIdObjectList.java new file mode 100644 index 0000000..81420ac --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectList.java @@ -0,0 +1,71 @@ +package de.memtext.baseobjects.coll; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +/** + * + * @author MB + * */ +public class NamedIdObjectList extends NamedIdObjectCollection implements List { + private static final long serialVersionUID = 1; + public NamedIdObjectList() { + super(); + collect=new LinkedList(); + } + + + public Object get(int pos) + { + return ((List)collect).get(pos); + } + + public boolean addAll(int arg0, Collection arg1) { + return ((List)collect).addAll(arg0,arg1); + } + + public Object set(int arg0, Object arg1) { + return ((List)collect).set(arg0,arg1); + } + + public void add(int pos, Object arg1) { + ((List)collect).add(pos,arg1); + } + + public Object remove(int arg0) { + return ((List)collect).remove(arg0); + } + + + public ListIterator listIterator(int arg0) { + return ((List)collect).listIterator(arg0); + } + + public List subList(int arg0, int arg1) { + return ((List)collect).subList(arg0,arg1); + } + + public int indexOf(Object arg0) { + return ((List)collect).indexOf(arg0); + } + + public int lastIndexOf(Object arg0) { + return ((List)collect).lastIndexOf(arg0); + } + + public ListIterator listIterator() { + return ((List)collect).listIterator(); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectList c=new NamedIdObjectList(); + c.addAll(this); + return c; + } + +} diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectSet.java b/src/de/memtext/baseobjects/coll/NamedIdObjectSet.java new file mode 100644 index 0000000..17d5005 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectSet.java @@ -0,0 +1,35 @@ +package de.memtext.baseobjects.coll; + +import java.util.HashSet; +import java.util.Set; + +public class NamedIdObjectSet extends NamedIdObjectCollection implements Set { + private static final long serialVersionUID = 1; + /** + * Default uses a HashSet internally; + * + */ + public NamedIdObjectSet() { + super(); + collect=new HashSet(); + } + /** + * + * @param set the implementation of Set interface to use internally + */ + public NamedIdObjectSet(Set set) { + super(); + collect=set; + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectSet c=new NamedIdObjectSet(); + c.addAll(this); + return c; + } +} + +//Created on 03.12.2003 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentCollection.java b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentCollection.java new file mode 100644 index 0000000..cfcd276 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentCollection.java @@ -0,0 +1,82 @@ +package de.memtext.baseobjects.coll; + +import java.util.Collection; +import java.util.Iterator; + +import de.memtext.baseobjects.NamedIdObject; +import de.memtext.baseobjects.NamedIdObjectI; +import de.memtext.baseobjects.NamedIdObjectWithParent; +import de.memtext.baseobjects.NamedIdObjectWithParentI; +import de.memtext.util.EqualsUtil; + +public class NamedIdObjectWithParentCollection + extends NamedIdObjectCollection + implements Collection { + private static final long serialVersionUID = 1; + public NamedIdObjectWithParentCollection() { + super(); + } + + public boolean containsItemWithParent(Object parent) { + boolean result = false; + NamedIdObjectWithParentI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedIdObjectWithParentI) it.next(); + if (EqualsUtil.areEqual(test.getParentKey(),parent)) { + result = true; + break; + } + } + return result; + } + /** + * get a collection with all objects in the collection that have a + * given parentKey + * @param parentKey + * @return collection if concrete object is a NamedIdObjectWithParentList also + * returns a NamedIdObjectWithParentList, same for NamedIdObjectWithParentSet + * makes casting possible + */ + public NamedIdObjectWithParentCollection getByParent(Object parentKey) { + NamedIdObjectWithParentCollection result = + new NamedIdObjectWithParentCollection(); + if (this instanceof NamedIdObjectWithParentList) + result = new NamedIdObjectWithParentList(); + if (this instanceof NamedIdObjectWithParentSet) + result = new NamedIdObjectWithParentSet(); + + for (Iterator it = this.iterator(); it.hasNext();) { + NamedIdObjectWithParentI element = + (NamedIdObjectWithParentI) it.next(); + if (EqualsUtil.areEqual(element.getParentKey(),parentKey)) + result.add(element); + } + return result; + } + + public int countItemsWithParent(Object parent) + { + return getByParent(parent).size(); + + } + public String toString() + { + StringBuffer result=new StringBuffer(size()+" NamedIdObjectsWithParent: "); + for (Iterator it = this.iterator(); it.hasNext();) { + NamedIdObjectWithParentI element = (NamedIdObjectWithParentI) it.next(); + result.append(element+" - "); + } + return result.toString(); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectWithParentCollection c=new NamedIdObjectWithParentCollection(); + c.addAll(this); + return c; + } +} + +//Created on 18.11.2003 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentList.java b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentList.java new file mode 100644 index 0000000..aa437f2 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentList.java @@ -0,0 +1,66 @@ +package de.memtext.baseobjects.coll; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +public class NamedIdObjectWithParentList extends NamedIdObjectWithParentCollection implements List { + private static final long serialVersionUID = 1; + public NamedIdObjectWithParentList() { + super(); + collect=new LinkedList(); + } + public Object get(int pos) + { + return ((List)collect).get(pos); + } + + public boolean addAll(int arg0, Collection arg1) { + return ((List)collect).addAll(arg0,arg1); + } + + public Object set(int arg0, Object arg1) { + return ((List)collect).set(arg0,arg1); + } + + public void add(int pos, Object arg1) { + ((List)collect).add(pos,arg1); + } + + public Object remove(int arg0) { + return ((List)collect).remove(arg0); + } + + + public ListIterator listIterator(int arg0) { + return ((List)collect).listIterator(arg0); + } + + public List subList(int arg0, int arg1) { + return ((List)collect).subList(arg0,arg1); + } + + public int indexOf(Object arg0) { + return ((List)collect).indexOf(arg0); + } + + public int lastIndexOf(Object arg0) { + return ((List)collect).lastIndexOf(arg0); + } + + public ListIterator listIterator() { + return ((List)collect).listIterator(); + } + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectWithParentList c=new NamedIdObjectWithParentList(); + c.addAll(this); + return c; + } +} + + +//Created on 18.11.2003 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentSet.java b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentSet.java new file mode 100644 index 0000000..25e4fcc --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedIdObjectWithParentSet.java @@ -0,0 +1,25 @@ +package de.memtext.baseobjects.coll; + +import java.util.HashSet; +import java.util.Set; + +public class NamedIdObjectWithParentSet extends NamedIdObjectWithParentCollection implements Set { + private static final long serialVersionUID = 1; + public NamedIdObjectWithParentSet() { + super(); + collect=new HashSet(); + } + + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedIdObjectWithParentCollection c=new NamedIdObjectWithParentSet(); + c.addAll(this); + return c; + } +} + + +//Created on 03.12.2003 \ No newline at end of file diff --git a/src/de/memtext/baseobjects/coll/NamedObjectCollection.java b/src/de/memtext/baseobjects/coll/NamedObjectCollection.java new file mode 100644 index 0000000..5ea158d --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedObjectCollection.java @@ -0,0 +1,102 @@ +package de.memtext.baseobjects.coll; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; + +import de.memtext.baseobjects.NamedObjectI; +import de.memtext.util.EqualsUtil; +import de.memtext.util.StringUtils; + +/** + * + * @author MB + * */ +public class NamedObjectCollection + extends BaseObjectCollection + implements Collection,Serializable { + private static final long serialVersionUID = 1; + + public NamedObjectCollection() { + super(); + } + + + /** + * Tries to find an element with the given name + * @param name + * @return first element with given name + * @throws IllegalArgumentException if nothing found + */public NamedObjectI getByName(String name) { + NamedObjectI test, result = null; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedObjectI) it.next(); + if (test.getName().equals(name)) { + result = test; + break; + } + } + if (result == null) + throw new IllegalArgumentException( + "No element with name " + name + " found."); + return result; + } + /** + * like '12','34','343' + * useful for creating sqls like where x in (...) + * @return '' if collection is empty + */ + + public String getNamesApostropheString() { + StringBuffer result = new StringBuffer(); + NamedObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedObjectI) it.next(); + result.append("'" + test.getName() + "',"); + } + StringUtils.deleteLastChar(result); + if (result.length() == 0) + result.append("''"); + return result.toString(); + } + + public boolean containsItemWithName(String name) { + boolean result = false; + NamedObjectI test; + for (Iterator it = collect.iterator(); it.hasNext();) { + test = (NamedObjectI) it.next(); + if (EqualsUtil.areEqual(test.getName(),name)) + { + result = true; + break; + } + } + return result; + } + + public boolean add(Object o) { + if (o == null) + throw new IllegalArgumentException("can't add null value"); + if (!(o instanceof NamedObjectI)) + throw new IllegalArgumentException("only named Objects allowed"); + return collect.add(o); + } + public String toString() + { + StringBuffer result=new StringBuffer(size()+" NamedObjects: "); + for (Iterator it = this.iterator(); it.hasNext();) { + NamedObjectI element = (NamedObjectI) it.next(); + result.append(element+" - "); + } + return result.toString(); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedObjectCollection c=new NamedObjectCollection(); + c.addAll(this); + return c; + } +} diff --git a/src/de/memtext/baseobjects/coll/NamedObjectList.java b/src/de/memtext/baseobjects/coll/NamedObjectList.java new file mode 100644 index 0000000..1e17771 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedObjectList.java @@ -0,0 +1,70 @@ +package de.memtext.baseobjects.coll; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + + +/** + * + * @author MB + * */ +public class NamedObjectList extends NamedObjectCollection implements List { + private static final long serialVersionUID = 1; + public NamedObjectList() { + super(); + collect = new LinkedList(); + } + + public Object get(int pos) + { + return ((List)collect).get(pos); + } + + public boolean addAll(int arg0, Collection arg1) { + return ((List)collect).addAll(arg0,arg1); + } + + public Object set(int arg0, Object arg1) { + return ((List)collect).set(arg0,arg1); + } + + public void add(int pos, Object arg1) { + ((List)collect).add(pos,arg1); + } + + public Object remove(int arg0) { + return ((List)collect).remove(arg0); + } + + + public ListIterator listIterator(int arg0) { + return ((List)collect).listIterator(arg0); + } + + public List subList(int arg0, int arg1) { + return ((List)collect).subList(arg0,arg1); + } + + public int indexOf(Object arg0) { + return ((List)collect).indexOf(arg0); + } + + public int lastIndexOf(Object arg0) { + return ((List)collect).lastIndexOf(arg0); + } + + public ListIterator listIterator() { + return ((List)collect).listIterator(); + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedObjectCollection c=new NamedObjectList(); + c.addAll(this); + return c; + } +} diff --git a/src/de/memtext/baseobjects/coll/NamedObjectSet.java b/src/de/memtext/baseobjects/coll/NamedObjectSet.java new file mode 100644 index 0000000..81371c3 --- /dev/null +++ b/src/de/memtext/baseobjects/coll/NamedObjectSet.java @@ -0,0 +1,29 @@ +package de.memtext.baseobjects.coll; + +import java.util.HashSet; +import java.util.Set; + +public class NamedObjectSet extends NamedObjectCollection implements Set { + private static final long serialVersionUID = 1; + public NamedObjectSet() { + super(); + collect=new HashSet(); + } + + public NamedObjectSet(Set set) { + super(); + if (set==null)throw new IllegalArgumentException("set must not be null"); + collect=set; + } + + /** + * Only shallow copy + */ + protected Object clone() throws CloneNotSupportedException { + NamedObjectCollection c=new NamedObjectSet(); + c.addAll(this); + return c; + } +} + +//Created on 02.12.2003 at 19:08:30 \ No newline at end of file diff --git a/src/de/memtext/buttons/ButtonGroupPanel.java b/src/de/memtext/buttons/ButtonGroupPanel.java new file mode 100644 index 0000000..5078f32 --- /dev/null +++ b/src/de/memtext/buttons/ButtonGroupPanel.java @@ -0,0 +1,89 @@ +package de.memtext.buttons; + +import java.util.Enumeration; + +import javax.swing.ButtonGroup; +import javax.swing.ButtonModel; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; + +public class ButtonGroupPanel extends JPanel { + ButtonGroup group = new ButtonGroup(); + ButtonWithValue hiddenNoSelectionButton = new ButtonWithValue("", null); + + public ButtonGroupPanel() { + this(null); + } + public ButtonGroupPanel(String header) { + super(); + if (header != null) + this.add(new JLabel(header)); + + hiddenNoSelectionButton.setVisible(false); + hiddenNoSelectionButton.setSelected(true); + group.add(hiddenNoSelectionButton); + } + public void addCategory(String label, Object value,boolean isSelected) { + ButtonWithValue b = new ButtonWithValue(label, value); + this.add(b); + group.add(b); + b.setSelected(isSelected); + } + public void addCategory(String label, Object value) { + addCategory(label, value,false); + } + + public void addCategory(String label, int i) { + addCategory(label, new Integer(i)); + } + public void addCategory(String label, int i,boolean isSelected) { + addCategory(label, new Integer(i),isSelected); + } + /** + * If you pass null as an argument no element will be selected + * @param label + */ + public void setSelected(String label) { + if (label == null) + hiddenNoSelectionButton.setSelected(true); + else + for (Enumeration en = group.getElements(); + en.hasMoreElements(); + ) { + ButtonWithValue b = (ButtonWithValue) en.nextElement(); + if (b.getText().equals(label)) { + b.doClick(); + break; + } + } + } + + public Object getSelectedValue() { + ButtonWithValue selectedButton=null; + for (Enumeration en = group.getElements(); + en.hasMoreElements(); + ) { + ButtonWithValue b = (ButtonWithValue) en.nextElement(); + if (b.isSelected()) { + selectedButton=b; + break; + } + } + return selectedButton.getValue(); + } + class ButtonWithValue extends JRadioButton { + private Object value; + ButtonWithValue(String label, Object value) { + super(label); + this.value = value; + } + Object getValue() { + return value; + } + + } + +} + +//Created on 17.02.2004 at 13:40:06 \ No newline at end of file diff --git a/src/de/memtext/buttons/Standard.java b/src/de/memtext/buttons/Standard.java new file mode 100644 index 0000000..f810202 --- /dev/null +++ b/src/de/memtext/buttons/Standard.java @@ -0,0 +1,39 @@ +package de.memtext.buttons; + +import javax.swing.JButton; + +/** + * @author MB + * + * JButtons not as static variables, because can be used in different + * places in one application, setting one be invisible would make all invisible + */ +public class Standard { + + /** + * Constructor for Standard. + */ + private Standard() { + super(); + } + + public static JButton getCopy() + { + + JButton copy=new JButton(de.memtext.icons.MBStandardIcons.getCopy()); + copy.setToolTipText("Kopieren"); + copy.setActionCommand("copy"); + return copy; + + } + public static JButton getCopyWithText() + { + + JButton copy=new JButton("Kopieren",de.memtext.icons.MBStandardIcons.getCopy()); + copy.setToolTipText("Kopieren"); + copy.setActionCommand("copy"); + return copy; + + } + +} diff --git a/src/de/memtext/db/AbstractHsqlStandaloneMgrResources.java b/src/de/memtext/db/AbstractHsqlStandaloneMgrResources.java new file mode 100644 index 0000000..de41e85 --- /dev/null +++ b/src/de/memtext/db/AbstractHsqlStandaloneMgrResources.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001-2004, The HSQL Development Group All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the HSQL Development Group nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package de.memtext.db; + +import java.util.ListResourceBundle; +/** + * Resources for HsqlStandaloneMgr. + * For other locales extend AbstractHsqlStandloneMgrResources, i.e. + * by copying HsqlStandaloneMgrResources_de to your locale + */ +public abstract class AbstractHsqlStandaloneMgrResources extends ListResourceBundle { + + public abstract String getDbInUseBy(String dbname,String user); +} + diff --git a/src/de/memtext/db/AddProc.java b/src/de/memtext/db/AddProc.java new file mode 100644 index 0000000..06498a3 --- /dev/null +++ b/src/de/memtext/db/AddProc.java @@ -0,0 +1,174 @@ +package de.memtext.db; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +/** + * Additional procedures for HSQLDB + * make sure that this class in the classpath. + * To constantly add it to hsql. + * Go to the directory where your hsqldb.jar is located + * Call jar -xf hsqlAddOn.jar + * jar -uf hsqldb.jar org/hsqldb/Library2.class + * Delete the directory org. + * + * Open your Database in Database Manager and execute + * the following commands once: + * GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC and + * CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom" + + + */ +public class AddProc { + private static DateFormat dfUS = new SimpleDateFormat("yyyy-MM-dd"); + + private AddProc() { + super(); + } + /** + * Fills regular tables with values from a CSV-file. + * Similar to Postgres COPY FROM command. + * + * If you want to fill your table TEST with data from test.csv + * make sure that this class in the classpath and that
    + * GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC;
    + CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom"
    + * has been called in your database at some point. +
    + * Then execute
    + * CALL COPYFROM('TEST','test.csv',null)
    + *
    + * if your not using , but | as a field separator
    + CALL COPYFROM('TEST','test.csv','fs=|')
    +
    + * + * @param con - Connection is automatically handed over by HSQL + * @param table - the name of the table that is to be filled + * if you created your table with "", e.g. create table "myData"
    + * also pass the inverted commans like this CALL COPYFROM('\"myData\"','test.csv',null); + * + * @param file - the filename of the CSV-file + * @param options - you can specify options separated by ; + * which are described in the text table documentation e.g.
    + * fs=| to use pipe instead of default comma as field separator or
    + * + * fs=|;vs=.;lvs=~" varchar separator, longvarchar separator
    + * ignore_first=true; ignore first line
    + * all_quoted=true or
    + * encoding=UTF-8 if you don't have ASCII
    + * @throws SQLException + */ + public static String copyFrom( + Connection con, + String table, + String file, + String options) + throws SQLException { + if (table == null || table.equals("")) + throw new IllegalArgumentException("Table must not be null or empty"); + if (file == null || file.equals("")) + throw new IllegalArgumentException("File must not be null or empty"); + File f = new File(file); + if (!f.exists()) + throw new IllegalArgumentException( + "source file " + file + " doesn't exist"); + + //normally created tables are in UPPERCASE in the metadata, + //but tables in inverted commas (create table "myData") + //are stored case sensitive + String tableNameInMetaData; + if (table.startsWith("\"")) + tableNameInMetaData = table.substring(1, table.length() - 1); + else + tableNameInMetaData = table.toUpperCase(); + StringBuffer buf = + new StringBuffer("create temp text table TMP_COPYFROM("); + + ResultSet rs = + con.getMetaData().getColumns(null, null, tableNameInMetaData, null); + String colname, coltype; + boolean tableFound = false; + while (rs.next()) { + tableFound = true; + colname = rs.getObject(4).toString(); + coltype = rs.getObject(6).toString(); + buf.append(colname + " " + coltype + ","); + } + rs.close(); + if (!tableFound) + throw new SQLException( + "Copy from failed - table " + + table + + " not found"); + buf.deleteCharAt(buf.lastIndexOf(",")); + buf.append("); SET TABLE TMP_COPYFROM SOURCE \"" + file); + if (options != null) + buf.append(";" + options); + buf.append("\";"); + buf.append("insert into " + table + " select * from TMP_COPYFROM"); + System.out.println(buf); + Statement stmt = con.createStatement(); + try { + stmt.execute(buf.toString()); + return "success"; + } + //finally is executed before returning whether an exception occurs or not + finally { + stmt.execute("drop table TMP_COPYFROM IF EXISTS"); + } + + } + + + public static String toDate(String year, String month, String day) + throws ParseException { + String result; + Date d = + dfUS.parse(year.trim() + "-" + month.trim() + "-" + day.trim()); + result = dfUS.format(d); + return result; + } + public static String toDate(String year, int month, int day) + throws ParseException { + return toDate(year + "", month + "", day + ""); + } + public static String toDate(int year, int month, int day) + throws ParseException { + return toDate(year + "", month + "", day + ""); + + } + public static void main(String a[]) { + Connection conn = null; + try { + Class.forName("org.hsqldb.jdbcDriver"); + conn = DriverManager.getConnection("jdbc:hsqldb:test", "sa", ""); + java.sql.Statement stmt = conn.createStatement(); + stmt.execute( + "drop table \"test\" if exists;create table \"test\" (col1 integer,col2 varchar, col3 double,col4 date)"); + copyFrom(conn, "\"test\"", "test.csv", "fs=;"); + System.out.println("2"); + copyFrom(conn, "\"test\"", "test.csv", "fs=;"); + stmt.close(); + + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + try { + conn.close(); + } catch (SQLException e1) { + e1.printStackTrace(); + } + } + } +} + +//Created on 08.03.2004 at 13:48:03 \ No newline at end of file diff --git a/src/de/memtext/db/Comparison.java b/src/de/memtext/db/Comparison.java new file mode 100644 index 0000000..71cd285 --- /dev/null +++ b/src/de/memtext/db/Comparison.java @@ -0,0 +1,43 @@ +/* + * Created on 23.07.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; + +/** + * @author Gast + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class Comparison { + private String name; + private Collection units = new LinkedList(); + public Comparison(String name) { + this.name = name; + } + public void addUnit(ComparisonUnit unit) { + units.add(unit); + + } + public Iterator iterator() + { + return units.iterator(); + } + public int getUnitCount() + { + return units.size(); + } + public void removeUnit(ComparisonUnit unit) { + units.remove(unit); + } + public String toString() { + return name; + } +} diff --git a/src/de/memtext/db/ComparisonUnit.java b/src/de/memtext/db/ComparisonUnit.java new file mode 100644 index 0000000..d4c8141 --- /dev/null +++ b/src/de/memtext/db/ComparisonUnit.java @@ -0,0 +1,50 @@ +/* + * Created on 23.07.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +/** + * @author Gast + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class ComparisonUnit { +private String name,sql; +public ComparisonUnit(String name,String sql) +{ + this.name=name; + this.sql=sql; +} +/** + * @return + */ +public String getName() { + return name; +} + +/** + * @return + */ +public String getSql() { + return sql; +} + +/** + * @param string + */ +public void setName(String string) { + name = string; +} + +/** + * @param string + */ +public void setSql(String string) { + sql = string; +} + +} diff --git a/src/de/memtext/db/ConnectionCreator.java b/src/de/memtext/db/ConnectionCreator.java new file mode 100644 index 0000000..f6b9b1e --- /dev/null +++ b/src/de/memtext/db/ConnectionCreator.java @@ -0,0 +1,127 @@ +package de.memtext.db; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +import de.memtext.util.CryptUtils; +import de.memtext.util.PropUtils; +/** + * This class is a utility that makes the creation of database connections + * easier. If necessary, one can use loadClass("jdbdcDriver-class") and then + * use one of the static getConnection(..) methods + * @author MB + * + + */ +public class ConnectionCreator { + public static void loadClass(String className) { + try { + Class.forName(className); + + } catch (Exception e) { + System.out.println(e.toString()); + System.exit(0); + } + } + public static Connection getConnection( + String url, + String username, + String passwd) throws SQLException + { + + return DriverManager.getConnection(url, username, passwd); + } + public static Connection getConnection( + String driver, + String url, + String username, + String passwd) + throws SQLException, ClassNotFoundException { + Class.forName(driver); + return getConnection(url, username, passwd); + } + + public static Connection getConnectionQuitOnException( + String driver, + String url, + String username, + String passwd) { + Connection con = null; + try { + con = getConnection(driver, url, username, passwd); + } catch (Exception e) { + System.out.println( + "Couldn't create connection to database " + + url + + "\n" + + e.toString()); + System.exit(-1); + } + return con; + } + public static Connection getConnection( + String propfilename, + String driverkey, + String urlkey, + String usernamekey, + String passwordkey) throws IOException, SQLException, ClassNotFoundException + { + Properties props = PropUtils.getProps(propfilename); + String driver = PropUtils.getProperty(props, driverkey); + String url = PropUtils.getProperty(props, urlkey); + String username = PropUtils.getProperty(props, usernamekey); + String passwd = PropUtils.getProperty(props, passwordkey); + return getConnection(driver, url, username, passwd); + + } + public static Connection getConnection(String propfilename) throws IOException, SQLException, ClassNotFoundException + { + return getConnection( + propfilename, + "driver", + "url", + "username", + "password"); + } + + /** + * Method getConnectionCryptPassword. + * 28.10.08 EInfache Verschlüsselungsmethode wird nicht mehr unterstützt + * @param propfilename + * @param string + * @param string1 + * @param string11 + * @param string111 + * @return Connection + * @throws IOException + * @throws ClassNotFoundException + * @throws SQLException + */ + public static Connection getConnectionCryptPassword( + String propfilename, + String driverkey, + String urlkey, + String usernamekey, + String passwordkey) throws IOException, SQLException, ClassNotFoundException + { + Properties props = PropUtils.getProps(propfilename); + String driver = PropUtils.getProperty(props, driverkey); + String url = PropUtils.getProperty(props, urlkey); + String username = PropUtils.getProperty(props, usernamekey); + String passwd =PropUtils.getProperty(props, passwordkey); + if (passwd.startsWith("sx_des")) { + try { + passwd = CryptUtils.decryptStringDES(passwd.substring(6)); + } catch (Exception e) { + e.printStackTrace(); + throw new SQLException("DES-Passwort konnte nicht entschlüsselt werden"); + } + } + // else + // passwd=de.memtext.util.CryptUtils.decryptSimple(passwd ); + return getConnection(driver, url, username, passwd); + } + +} diff --git a/src/de/memtext/db/DB.java b/src/de/memtext/db/DB.java new file mode 100644 index 0000000..28b12b7 --- /dev/null +++ b/src/de/memtext/db/DB.java @@ -0,0 +1,37 @@ +package de.memtext.db; + +import de.memtext.baseobjects.NamedObject; +/** + * This class represents a Database system like Informix or Postgres + */ +public class DB extends NamedObject { + private String version; + static public final DB INFORMIX = new DB("Informix", "7.3"); + static public final DB POSTGRES = new DB("Postgres", "7.3"); + static public final DB ACCESS = new DB("Access", "2000"); + /** + * The public constructors are needed because the DB class is + * a java bean which is cool for XMLEncoding + * + */ + public DB() { + this("Unbekannte Datenbank",""); + } + public DB(String name) { + this(name, ""); + } + + public DB(String name, String version) { + super(name); + this.version = version; + } + + public boolean equals(Object o) { + if (!(o instanceof DB)) + return false; + DB db = (DB) o; + return this.getName().equals(db.getName()); + } +} + +//Created on 03.12.2003 at 15:54:27 \ No newline at end of file diff --git a/src/de/memtext/db/DBAccess.java b/src/de/memtext/db/DBAccess.java new file mode 100644 index 0000000..2d19e6e --- /dev/null +++ b/src/de/memtext/db/DBAccess.java @@ -0,0 +1,1191 @@ +package de.memtext.db; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; + +import de.memtext.baseobjects.NamedIdObject; +import de.memtext.baseobjects.NamedIdObjectWithParent; +import de.memtext.baseobjects.coll.NamedIdObjectList; +import de.memtext.baseobjects.coll.NamedIdObjectWithParentList; +import de.memtext.tree.KeyParentEqualException; +import de.memtext.util.ExceptionHandler; +import de.memtext.util.StringUtils; +import de.memtext.widgets.WarningMessage; + +/** + * This class faciliates access to databases. It offers easy standardized + * access. To start with one has to call the create method with an existing + * Connection to the database and a name for this connection. In other parts of + * your programme database access is possible using + * DBAccess.get("connectionname").function + * + * The classes uses a de.superx.util.ExceptionHandler as default, which calls + * system.exit after any error. See ExceptionHandler + * + * You can also add / remove standard java.util.Loggers. Queries are logged at + * fine level, execute statements at info level. + * + * + * @author: MB + */ +public class DBAccess { + private String name; + private Connection con = null; + private Statement stmt = null; + private boolean isInJar = false; + private int updateCount; + private List loggerList = new LinkedList(); + private static IllegalStateException illegalStateEx = new IllegalStateException( + "DBAccess not inited - connection is null"); + private boolean isThrowRuntimeExceptionsActive; + private static Map entries = new HashMap(); + private ExceptionHandler exceptionHandler = new ExceptionHandler(true); + + public static DBAccess get(String name) { + DBAccess one = entries.get(name); + if (one != null) { + Connection con = one.getConnection(); + try { + if (con.isClosed()) { + throw new RuntimeException("DBAccess: Connection already closed!"); + } + } catch (SQLException e) { + throw new RuntimeException("DBAccess: Cannot check for closed connection.", e); + } + } + return one; + } + + public Connection getConn() + { + return con; + } + public static boolean hasConnection(String name) { + return entries.containsKey(name); + } + + /** + * + * when adding an hsqldb connection also notices from the url if the db is + * inside a jar, can be questioned by isInJar() + * + * @param name + * @param con + * @throws SQLException + + */ + public static void addConnection(String name, Connection con) throws SQLException { + DBAccess dba = DBAccess.get(name); + if (dba != null && !dba.getConnection().isClosed()) { + // System.out.println("There is already an entry with the name " + name); + } else { + entries.put(name, new DBAccess(name, con)); + } + } + + public static void removeConnection(String name) throws SQLException { + DBAccess dba = DBAccess.get(name); + if (dba != null && !dba.getConnection().isClosed()){ + dba.closeConnection(); + entries.remove(name); + } + } + + private DBAccess(String name, Connection con) throws SQLException { + this.name = name; + this.con = con; + + if (con.getMetaData().getDriverName().equals( + "HSQL Database Engine Driver") + && con.getMetaData().getURL().indexOf("res:") > 0) + isInJar = true; + + stmt = con.createStatement(); + } + + /** + * Returns the java.sql.Connection with the given name. Normally get(name) + * returns a DBAccess object this method is only used when the very + * Connection is needed. + * + * @param name + * @return + */ + + public Connection getConnection() { + return con; + } + + public boolean isInJar() { + return isInJar; + } + + public String getName() { + return name; + } + + public void setDatabase(String datenbank) { + throw new UnsupportedOperationException(); + /* + * try { + * + * if (con != null) { stmt.close(); con.close(); } + * logger.info("establishing connection to " + datenbank); con = + * DriverManager.getConnection(datenbank, "sa", ""); stmt = + * con.createStatement(); logger.info("done."); + * logger.info(listTables()); } catch (Exception e) { + * System.out.println(e.toString()); System.exit(0); } + */ + } + + static public void closeConnection(String name) { + DBAccess.get(name).closeConnection(); + } + + public void closeConnection() { + try { + stmt.close(); + con.close(); + con = null; + } catch (Exception e) { + handle("Couldn't close database connection", e); + } + entries.remove(this); + } + + public String getTableNames() { + StringBuffer result = new StringBuffer("Tabellen in der Datenbank:"); + try { + DatabaseMetaData meta = con.getMetaData(); + ResultSet rs = null; + + rs = meta.getTables(null, null, null, null); + while (rs.next()) { + result.append(rs.getObject(3) + " "); + + } + rs.close(); + + } catch (Exception e) { + handle("", e); + } + return result.toString(); + } + + public boolean hasTable(String tablename) { + boolean result = false; + try { + ResultSet rs = con.getMetaData().getTables(null, null, null, null); + while (rs.next()) { + if (tablename.equalsIgnoreCase(rs.getObject(3).toString())) { + result = true; + break; + } + } + rs.close(); + } catch (Exception e) { + handle("", e); + } + return result; + } + + /** + * select key from blueprint; _> "1,2,3,4,5,6,7" + * + * @param sql + * separator is comma null is ignored + */ + public StringBuffer getSeperatedString(String sql) { + return getSeperatedString(sql, ","); + } + + /** + * select key from blueprint; _> "'1','2','3','4','5','6','7'" + * + * @param sql + * @param separator + * null is ignored + */ + public StringBuffer getSeperatedString(String sql, String separator) { + StringBuffer erg = new StringBuffer(); + try { + ResultSet result = stmt.executeQuery(sql); + logFine(sql); + Object value; + while (result.next()) { + + // Print the first column of the result + // could use also getString("Path") + value = result.getObject(1); + if (value == null) + erg.append("null" + separator); + else + erg.append("'" + value + "'" + separator); + } + result.close(); + } catch (Exception e) { + handle("", e); + } + if (erg.length() > 0) + StringUtils.deleteLastChar(erg); + return erg; + } + + public String getString(String pstSql, Object ... args) { + String erg = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = this.con.prepareStatement(pstSql); + int paramPos = 1; + for (Object arg : args) { + pst.setObject(paramPos, arg); + paramPos++; + } + rs = pst.executeQuery(); + logFine(pstSql); + while (rs.next()) { + erg = rs.getString(1); + break; + } + } catch (Exception e) { + handle("sql:" + pstSql, e); + } + finally { + try { + if (rs != null) { + rs.close(); + } + if (pst != null) { + pst.close(); + } + } catch (SQLException sex) { + handle("sql:" + pstSql, sex); + } + } + return erg; + } + + /** + * @param sql + */ + private void logFine(String txt) { + for (Iterator it = loggerList.iterator(); it.hasNext();) { + Logger logger = (Logger) it.next(); + logger.fine(txt); + } + } + + /** + * Method log. + * + * @param sql + */ + private void logInfo(String txt) { + for (Iterator it = loggerList.iterator(); it.hasNext();) { + Logger logger = (Logger) it.next(); + logger.info(txt); + } + } + + /** + * @deprecated + * @param sql + * @return + */ + + public Vector getStringVector(String sql) { + Vector v = new Vector(); + ResultSet rs = null; + String item; + try { + rs = stmt.executeQuery(sql); + logFine(sql); + while (rs.next()) { + item = rs.getString(1); + v.add(item); + } + rs.close(); + } catch (Exception e) { + handle("", e); + } + return v; + + } + + public int execute(String sql) { + try { + + if (con == null) + throw illegalStateEx; + logInfo(sql); + updateCount = stmt.executeUpdate(sql); + //System.out.println(sql); + } catch (Exception e) { + handle("", e); + } + return updateCount; + + } + + public int executeFineLog(String sql) { + try { + + if (con == null) + throw illegalStateEx; + logFine(sql); + updateCount = stmt.executeUpdate(sql); + } catch (Exception e) { + handle("", e); + } + return updateCount; + + } + + public void log(Level level, String text) { + for (Iterator it = loggerList.iterator(); it.hasNext();) { + Logger logger = (Logger) it.next(); + logger.log(level, text); + } + } + + public void checkIfOneRowWasUpdated() { + if (getUpdateCount() != 1) { + handle("", new Exception(getUpdateCount() + + " row(s) changed, 1 expected")); + + } + } + + /** + * Method getUpdateCount. + * + * @return int + */ + private int getUpdateCount() { + return updateCount; + } + + /** + * @deprecated + * @param sql + * @param o1 + */ + public void insert(String sql, Object o1) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + /** + * @deprecated + * @param sql + * @param o1 + * @param o2 + */ + public void insert(String sql, Object o1, Object o2) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + insertAppend(sqlbuf, o2); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + /** + * @deprecated + * @param sql + * @param o1 + * @param o2 + * @param o3 + */ + public void insert(String sql, Object o1, Object o2, Object o3) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + insertAppend(sqlbuf, o2); + insertAppend(sqlbuf, o3); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + + /** + * @deprecated + * @param sql + * @param o1 + * @param o2 + * @param o3 + * @param o4 + */ + public void insert(String sql, Object o1, Object o2, Object o3, Object o4) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + insertAppend(sqlbuf, o2); + insertAppend(sqlbuf, o3); + insertAppend(sqlbuf, o4); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + /** + * @deprecated + * @param sql + * @param o1 + * @param o2 + * @param o3 + * @param o4 + * @param o5 + */ + public void insert(String sql, Object o1, Object o2, Object o3, Object o4, + Object o5) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + insertAppend(sqlbuf, o2); + insertAppend(sqlbuf, o3); + insertAppend(sqlbuf, o4); + insertAppend(sqlbuf, o5); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + /** + * @deprecated + * @param sql + * @param o1 + * @param o2 + * @param o3 + * @param o4 + * @param o5 + * @param o6 + */ + + public void insert(String sql, Object o1, Object o2, Object o3, Object o4, + Object o5, Object o6) { + StringBuffer sqlbuf = new StringBuffer(sql); + insertAppend(sqlbuf, o1); + insertAppend(sqlbuf, o2); + insertAppend(sqlbuf, o3); + insertAppend(sqlbuf, o4); + insertAppend(sqlbuf, o5); + insertAppend(sqlbuf, o6); + StringUtils.deleteLastChar(sqlbuf); + sqlbuf.append(")"); + execute(sqlbuf.toString()); + } + + private void insertAppend(StringBuffer buf, Object x) { + if (x != null) { + if (x instanceof String) { + String txt = x.toString(); + int len = txt.length(); + //make sure string starts with ' also if empty + if (len == 0 || txt.charAt(0) != '\'') + buf.append("'"); + buf.append(x); + if (len == 0 || txt.charAt(txt.length() - 1) != '\'') + buf.append("'"); + int i = 1242; + } else + buf.append(x); + } else { + buf.append("null"); + } + buf.append(","); + + } + + { + + } + + public ResultSet executeQuery(String sql) throws SQLException { + if (con == null) + throw illegalStateEx; + logFine(sql); + + stmt.close(); + stmt = con.createStatement(); + + ResultSet rs = stmt.executeQuery(sql); + return rs; + + } + + public void executeIgnoreExceptions(String sql) { + try { + logInfo(sql); + stmt.execute(sql); + } catch (Exception e) { + } + } + + public DatabaseMetaData getDatabaseMetaData() { + if (con == null) + throw illegalStateEx; + DatabaseMetaData m = null; + try { + m = con.getMetaData(); + } catch (Exception e) { + handle("Couldn't get database metadata", e); + } + return m; + } + + /** + * not used + * @param sql + * @return + */ + public List getObjectList(String sql) { + List result = new LinkedList(); + + try { + ResultSet rs = stmt.executeQuery(sql); + logFine(sql); + while (rs.next()) { + result.add(rs.getObject(1)); + } + rs.close(); + } catch (Exception e) { + handle("", e); + } + return result; + + } + + public Object[] getTablesStartingWith(String prefix) { + if (con == null) + throw illegalStateEx; + ArrayList list = new ArrayList(); + try { + ResultSet rs = con.getMetaData().getTables(null, null, + prefix + "%", null); + + while (rs.next()) { + list.add(rs.getString(3)); + } + rs.close(); + } catch (Exception e) { + handle("", e); + } + Object[] result = list.toArray(); + Arrays.sort(result); + return result; + } + + /** + * Es wird einfach das erste Objekt der ersten Spalte genommen + * + * @param sql + * @return + */ + public Double getDoubleValue(String sql) { + Double val = null; + try { + ResultSet rs = executeQuery(sql); + logFine(sql); + rs.next(); + Object o = rs.getObject(1); + rs.close(); + if (o instanceof Double) + val = (Double) o; + else if (o instanceof java.math.BigDecimal) { + BigDecimal merk = (BigDecimal) o; + val = new Double(merk.doubleValue()); + + } else + if (o!=null) + val = new Double(o.toString()); + + } catch (SQLException e) { + handle("sql was:" + sql, e); + } + return val; + } + + /** + * @deprecated + * + * @param sql + * @return + */ + public Double getDoubleValueOld(String sql) { + Object erg = null; + Double val = null; + /* + * try { ResultSet result = stmt.executeQuery(sql); logInfo(sql); while + * (result.next()) { // Print the first column of the result // could + * use also getString("Path") erg = result.getObject(1); } } catch + * (Exception e) { handle("", e); } + */ + erg = getValue(sql); + if (erg != null) { + if (erg instanceof Double) + val = (Double) erg; + else + val = new Double(erg.toString()); + } + return val; + } + + /** + * @deprecated + * @param sql + * @return + */ + + public Object getValue(String sql) { + Object erg = null; + try { + List resultvector = getResultList(sql); + List row1 = (List) resultvector.get(0); + erg = row1.get(0); //first row, first element + if (erg instanceof java.math.BigDecimal) { + BigDecimal merk = (BigDecimal) erg; + Double merk2 = new Double(merk.doubleValue()); + erg = merk2; + } + + } catch (Exception e) { + handle("", e); + } + + return erg; + + } + + /** + * not in use + * @param query + * @return + */ + public Integer getIntegerIncremented(String query) { + Double read = getDoubleValue(query); + Integer erg = null; + if (read == null) + erg = new Integer(1); + else + erg = new Integer(read.intValue() + 1); + return erg; + } + + public static void main(String arg[]) { + } + + /** + * Method getTableList. + * + * @return List + */ + + /** + * Method hasColumn. can be problem for other databases. + * + * @param aTablename + * @param string + * @return boolean + */ + public boolean hasColumn(String aTablename, String colname) { + if (con == null) + throw illegalStateEx; + boolean result = false; + try { + if (!hasTable(aTablename)) + throw new IllegalArgumentException( + "Database doesn't contain table " + aTablename); + //Hsql had problems with metadata stuff + + ResultSet rs = con.getMetaData().getColumns(null, null, + aTablename.toUpperCase(), colname.toUpperCase()); + // ResultSetMetaData rsmd = rs.getMetaData(); + // int numberOfColumns = rsmd.getColumnCount(); + + while (rs.next()) { + //wenn etwas gefunden wurde, gibt's die Spalte + result = true; + } + rs.close(); + + //easy variant + /* + * String sql = "select distinct " + colname + " from " + + * aTablename; ResultSet rs = stmt.executeQuery(sql); rs.close(); + * result = true; } + */ + } catch (SQLException e) { + e.printStackTrace(); + result = false; + } catch (IllegalArgumentException e) { + result = false; + } + + return result; + + } + + /* + * If more than one value is found, only considers the first null if nothing + * found + * not in use + */ + public Date getDate(String query) { + Date erg = null; + Object o = null; + try { + ResultSet rs = stmt.executeQuery(query); + logInfo(query); + + while (rs.next()) { + if (rs.isFirst()) + o = rs.getObject(1); + } + if (o != null) + erg = (Date) o; + rs.close(); + } catch (Exception e) { + handle(query, e); + } + + return erg; + } + + public int getInt(String query, Object ...args) { + Integer result = getInteger(query, args); + if (result == null) + throw new RuntimeException("nothing or null found"); + return result.intValue(); + } + + /* + * If more than one value is found, only considers the first + */ + public Integer getInteger(String pstSQL, Object ... args) { + Integer erg = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = this.con.prepareStatement(pstSQL); + int paramPos = 1; + for (Object arg : args) { + pst.setObject(paramPos, arg); + paramPos++; + } + rs = pst.executeQuery(); + logFine(pstSQL); + Object o=null; + boolean isFirst=true; + while (rs.next()) + { + if (isFirst) + { + o = rs.getObject(1); + isFirst=false; + } + } + if (o != null) { + if (o instanceof Integer) + erg = (Integer) o; + else if (o instanceof Long) + erg = new Integer(((Long) o).intValue()); + else if (o instanceof Short) + erg = new Integer(((Short) o).intValue()); + else { + throw new IllegalArgumentException( + "Unbekannter Datentyp in DBAccess getInteger:" + + o.getClass() + " - " + pstSQL); + + } + } + rs.close(); + } catch (Exception e) { + handle("", e); + } + + return erg; + } + + /** + * Sets the logger. + * + * @param logger + * The logger to set + */ + public void addLogger(Logger logger) { + loggerList.add(logger); + } + + public void removeLogger(Logger logger) { + loggerList.remove(logger); + } + + /** + * Method createQuitOnException. + * + * @param string + * @param connection + */ + public static void createQuitOnException(String name, Connection connection) { + try { + addConnection(name, connection); + } catch (Exception e) { + System.out.println("Couldn't create database connection " + name + + "\n" + e.toString()); + System.exit(-1); + } + } + + public List getTableList() { + if (con == null) + throw illegalStateEx; + List result = new LinkedList(); + try { + + ResultSet rs = con.getMetaData().getTables(null, null, null, null); + while (rs.next()) { + result.add(rs.getObject(3).toString()); + } + rs.close(); + } catch (SQLException e) { + handle("", e); + } + return result; + } + + /** + * + * @param sql + * @return List in LIst!! + */ + public List getResultList(String sql) { + List result = new LinkedList(); + try { + ResultSet rs = executeQuery(sql); + logFine(sql); + result = DbUtils.toResultList(rs); + rs.close(); + } catch (SQLException e) { + handle("sql was:" + sql, e); + } + return result; + } + + /* + * public Vector getResultVector(String sql) { List result = new + * LinkedList(); try { ResultSet rs = executeQuery(sql); logInfo(sql); + * result = toResultList(rs); } catch (SQLException e) { handle("", e); } + * return result; } + */ + /** + * Hsql needs uppercase! + */ + public int getColumnType(String tablename, String colname) { + int result = -9999; + try { + if (!hasTable(tablename)) + throw new RuntimeException("Database doesn't contain table " + + tablename); + if (!hasColumn(tablename, colname)) + throw new RuntimeException("Table " + tablename + + " doesn't have column:" + colname); + + ResultSet rs = con.getMetaData().getColumns(null, null, + tablename.toUpperCase(), colname.toUpperCase()); + while (rs.next()) { + result = rs.getInt(5); + } + rs.close(); + } catch (SQLException e) { + handle("", e); + } catch (RuntimeException e) { + handle("", e); + } + return result; + } + + public int getColumnCount(String tablename) { + int result = 0; + try { + if (!hasTable(tablename)) + throw new RuntimeException("Database doesn't contain table " + + tablename); + + ResultSet rs = con.getMetaData().getColumns(null, null, + tablename.toUpperCase(), null); + while (rs.next()) { + result++; + } + rs.close(); + } catch (SQLException e) { + handle("", e); + } catch (RuntimeException e) { + handle("", e); + } + return result; + } + + /** + * Hsql needs uppercase! + */ + public List getColumnNames(String tablename) { + List result = new LinkedList(); + try { + if (!hasTable(tablename)) + throw new RuntimeException("Database doesn't contain table " + + tablename); + + ResultSet rs = con.getMetaData().getColumns(null, null, + tablename.toUpperCase(), null); + while (rs.next()) { + result.add(rs.getObject(4).toString()); + } + rs.close(); + } catch (SQLException e) { + handle("", e); + } catch (RuntimeException e) { + handle("", e); + } + return result; + } + + /** + * Returns the isThrowRuntimeExceptionsActive. * if true runtime Exception + * are thrown otherwise designated exceptionHandler is called + * + * @return boolean + */ + public boolean isThrowRuntimeExceptionsActive() { + return isThrowRuntimeExceptionsActive; + } + + /** + * Sets the isThrowRuntimeExceptionsActive. if true runtime Exception are + * thrown otherwise designated exceptionHandler is called + * + * @param isThrowRuntimeExceptionsActive + * The isThrowRuntimeExceptionsActive to set + */ + public void setThrowRuntimeExceptionsActive( + boolean isThrowRuntimeExceptionsActive) { + this.isThrowRuntimeExceptionsActive = isThrowRuntimeExceptionsActive; + } + + public void handle(String txt, Exception e) { + System.out.println(e); + if (isThrowRuntimeExceptionsActive) + throw new RuntimeException(txt + " " + e.toString()); + else { + exceptionHandler.handle(txt, e); + } + } + + public void handle(Exception e) { + handle(null, e); + } + + /** + * Method executeAndCheckUpdate1Row. + * + * @param string + */ + public void executeAndCheckUpdate1Row(String sql) { + execute(sql); + checkIfOneRowWasUpdated(); + } + + /** + * Sets a property in the properties table of a db + * + * @param key + * @param value + */ + public void setProperty(String key, String value) { + if (key == null || value == null) + throw new IllegalArgumentException( + "no nulls allowed in properties table"); + execute("delete from properties where name='key';insert into properties (name,value) values('" + + key + "','" + value + "');"); + } + + /** + * Gets a property from the properties table + * + * @param key + * @return String - null if nothing found + */ + public String getProperty(String key) { + return getString("select value from properties where name='" + key + + "'"); + } + + public ExceptionHandler getExceptionHandler() { + return exceptionHandler; + } + + /** + * @param handler + */ + public void setExceptionHandler(ExceptionHandler handler) { + exceptionHandler = handler; + } + + /** + * creates a java.util.List with NamedIDObjects from a table in the database + * not in use + * + * @param tablename - + * name of the source table + * @param idColName - + * name of the ID column in the table (e.g. tid) + * @param nameColName - + * name of the name column in the table (e.g. name or text) + * @param restriction - + * optionally a restriction like "where id>2" may be null + * @return NamedIdObjectList + * @throws NoSuchMethodException + * @throws SecurityException + * @throws InvocationTargetException + * @throws IllegalAccessException + * @throws InstantiationException + * @throws IllegalArgumentException + */ + public NamedIdObjectList getNamedIdObjectList(String tablename, + String idColName, String nameColName, String restriction, + String orderby, Class targetClass) throws SecurityException, + NoSuchMethodException, IllegalArgumentException, + InstantiationException, IllegalAccessException, + InvocationTargetException { + NamedIdObjectList result = new NamedIdObjectList(); + if (restriction == null) + restriction = ""; + Object id; + String name; + List rawList = getResultList("select " + idColName + "," + nameColName + + " from " + tablename + " " + restriction + " " + orderby); + Class[] constparams = { Object.class, String.class }; + Object[] data = new Object[2]; + Constructor constr = targetClass.getConstructor(constparams); + for (Iterator it = rawList.iterator(); it.hasNext();) { + List row = (List) it.next(); + id = row.get(0); + name = ""; + if (row.get(1) != null) + name = row.get(1).toString(); + + data[0] = id; + data[1] = name; + + Object o = constr.newInstance(data); + + result.add(o); + } + return result; + } + + /** + * not in use + * @param tablename + * @param idColName + * @param nameColName + * @param restriction + * @param orderby + * @return + */ + public NamedIdObjectList getNamedIdObjectList(String tablename, + String idColName, String nameColName, String restriction, + String orderby) { + NamedIdObjectList result = null; + try { + result = getNamedIdObjectList(tablename, idColName, nameColName, + restriction, orderby, NamedIdObject.class); + } + //Die Fehler können eigentlich nicht auftreten, weil + catch (SecurityException e) { + WarningMessage.show(null, + "Reflectionproblem bei DBAccess.getNamedIdObjectList", ""); + e.printStackTrace(); + System.exit(1); + } catch (NoSuchMethodException e) { + WarningMessage.show(null, + "Reflectionproblem bei DBAccess.getNamedIdObjectList", ""); + + e.printStackTrace(); + System.exit(1); + } catch (InstantiationException e) { + WarningMessage.show(null, + "Reflectionproblem bei DBAccess.getNamedIdObjectList", ""); + + e.printStackTrace(); + System.exit(1); + } catch (IllegalAccessException e) { + WarningMessage.show(null, + "Reflectionproblem bei DBAccess.getNamedIdObjectList", ""); + + e.printStackTrace(); + System.exit(1); + } catch (InvocationTargetException e) { + WarningMessage.show(null, + "Reflectionproblem bei DBAccess.getNamedIdObjectList", ""); + + e.printStackTrace(); + System.exit(1); + } + return result; + } + + public NamedIdObjectWithParentList getNamedIdObjectWithParentList( + String tablename, String idColName, String nameColName, + String restriction) { + NamedIdObjectWithParentList result = new NamedIdObjectWithParentList(); + if (restriction == null) + restriction = ""; + Object id; + String name; + Object parentKey; + NamedIdObjectWithParent one; + List rawList = getResultList("select " + idColName + "," + nameColName + + ",parent from " + tablename + " " + restriction); + for (Iterator it = rawList.iterator(); it.hasNext();) { + List row = (List) it.next(); + id = row.get(0); + name = ""; + if (row.get(1) != null) + name = row.get(1).toString(); + parentKey = row.get(2); + try { + one = new NamedIdObjectWithParent(id, name, parentKey); + result.add(one); + } catch (KeyParentEqualException e) { + handle(e); + } + + } + return result; + } + + public void execute(StringBuffer sql) { + execute(sql.toString()); + } +} \ No newline at end of file diff --git a/src/de/memtext/db/DBComparison.java b/src/de/memtext/db/DBComparison.java new file mode 100644 index 0000000..ba32f48 --- /dev/null +++ b/src/de/memtext/db/DBComparison.java @@ -0,0 +1,104 @@ +package de.memtext.db; + +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.List; + +import de.memtext.util.StringUtils; + +public class DBComparison { + + private DBComparison() { + super(); + } + public static void main(String a[]) { + try { + Class.forName("org.hsqldb.jdbcDriver"); + + java.sql.Connection con = + DriverManager.getConnection( + "jdbc:hsqldb:hsql://localhost:9000", + "sa", + ""); + DBAccess.addConnection("ssc", con); + java.sql.Connection con2 = + DriverManager.getConnection( + "jdbc:hsqldb:hsql://localhost:9500", + "sa", + ""); + DBAccess.addConnection("ssc-test", con2); + compare("ssc", "ssc-test"); + + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + private static void compare(String db1, String db2) { + System.out.println("Start comparing..."); + StringBuffer fineTables = + new StringBuffer("The following tables are fine: "); + List tableList = DBAccess.get(db1).getTableList(); + boolean isOk = false; + for (Iterator it = tableList.iterator(); it.hasNext();) { + String table = (String) it.next(); + + if (DBAccess.get(db2).hasTable(table)) { + isOk = true; + if (DBAccess.get(db1).getColumnCount(table) + != DBAccess.get(db2).getColumnCount(table)) { + System.out.println( + "Table " + + table + + " has a different number of columns"); + isOk = false; + } else { + List colList = DBAccess.get(db1).getColumnNames(table); + for (Iterator it2 = colList.iterator(); it2.hasNext();) { + String colname = (String) it2.next(); + if (!DBAccess.get(db2).hasColumn(table, colname)) { + System.out.println( + "Table " + + table + + " in " + + db2 + + " doesn't have column:" + + colname); + isOk = false; + } else { + + if (DBAccess.get(db1).getColumnType(table, colname) + != DBAccess.get(db2).getColumnType( + table, + colname)) { + System.out.println( + "Table " + + table + + " column:" + + colname + + " are of different types"); + isOk = false; + } + + } + } + if (isOk) + fineTables.append(table + ","); + } + + } else { + System.out.println(db2 + " doesn't contain table:" + table); + } + } + StringUtils.deleteLastChar(fineTables); + System.out.println(fineTables); + System.out.println("..done"); + } +} + +//Created on 11.02.2004 at 13:19:36 \ No newline at end of file diff --git a/src/de/memtext/db/DBServletException.java b/src/de/memtext/db/DBServletException.java new file mode 100644 index 0000000..68f0c65 --- /dev/null +++ b/src/de/memtext/db/DBServletException.java @@ -0,0 +1,20 @@ +package de.memtext.db; +/** + * Eine spezielle Exception im Servlet. + * Wird zwar im Applet eigentlich nicht gebraucht, aber trotzdem + * in diesem Package, damit Klassen wie Sicht einheitliche throws-Deklarationen haben. + * + * @author Marlies Winterstein + * @version 2.0, 18.2.2002 +*/ +public class DBServletException extends Exception +{ + public DBServletException() + { + super(); + } + public DBServletException(String msg) + { + super(msg); + } +} diff --git a/src/de/memtext/db/DBTimer.java b/src/de/memtext/db/DBTimer.java new file mode 100644 index 0000000..6caecb5 --- /dev/null +++ b/src/de/memtext/db/DBTimer.java @@ -0,0 +1,96 @@ +package de.memtext.db; + +import java.sql.Connection; +import java.sql.Statement; + +import de.memtext.util.TimeUtils; + +public class DBTimer { +private static int runCount=200; +private static boolean logEachRun=false; +//private static String driver="org.hsqldb.jdbcDriver"; +private static String driver="com.informix.jdbc.IfxDriver"; +//private static String url="jdbc:hsqldb:hsql://localhost:9001"; +private static String url="jdbc:informix-sqli://jupiter:50000:informixserver=superx_host;database=superx"; +private static String user="superx"; +private static String passwd="anfang12"; +private static String sql="execute procedure sp_cob_keychild('1',0);"; + +//wenn ein zweiter Sql folgen soll - drop table tmp_xx muss z.B. in eigenem Aufruf sein. +private static String sql2=null;//"select sum(betrag) from cob_busa,tmp_children T where fikrkey=T.key"; + //"select sum(betrag) from cob_busa where fikrkey in (select key from tmp_children)"; +private static String sql3=null;//"drop table tmp_children;"; + public static void main(String[] args) { + //sql="select sum(betrag) from cob_busa C, tmp_children T where fikrkey=T.key and T.parent='1'"; + sql = "select sum(betrag) from cob_busa where fikrkey in ('1', \n" + + " '11 ', \n" + + " '111 ', \n" + + " '1111 ', \n" + + " '1112 ', \n" + + " '112 ', \n" + + " '1121 ', \n" + + " '1122 ', \n" + + " '113 ', \n" + + " '1131 ', \n" + + " '1132 ', \n" + + " '12 ', \n" + + " '121 ', \n" + + " '1211 ', \n" + + " '1212 ', \n" + + " '1213 ', \n" + + " '122 ', \n" + + " '123 ', \n" + + " '124 ', \n" + + " '125 ', \n" + + " '126 ', \n" + + " '13 ', \n" + + " '131 ', \n" + + " '1311 ', \n" + + " '1312 ', \n" + + " '1313 ', \n" + + " '132 ', \n" + + " '1321 ', \n" + + " '1322 ', \n" + + " '1323 ', \n" + + " '133 ', \n" + + " '1331 ', \n" + + " '1332 ', \n" + + " '1333 ', \n" + + " '1334 ', \n" + + " '134 ', \n" + + " '135 ', \n" + + " '136 ', \n" + + " '137 ', \n" + + " '138 ')"; + try { + Class.forName(driver); + Connection conn = + java.sql.DriverManager.getConnection( + url, + user, + passwd); + Statement stmt = conn.createStatement(); + TimeUtils t=new TimeUtils(); + System.out.println("start "+sql); + for (int i=1;i<=runCount;i++) + { + if (logEachRun) System.out.println(i); + stmt.execute(sql); + if (sql2!=null) + stmt.execute(sql2); + if (sql3!=null) + stmt.execute(sql3); + } + t.print(runCount+" times"); + stmt.close(); + conn.close(); + System.out.println("done"); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } +} + +//Created on 09.03.2005 at 10:05:37 \ No newline at end of file diff --git a/src/de/memtext/db/DataSource.java b/src/de/memtext/db/DataSource.java new file mode 100644 index 0000000..3d7cb1f --- /dev/null +++ b/src/de/memtext/db/DataSource.java @@ -0,0 +1,106 @@ +package de.memtext.db; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +import de.memtext.baseobjects.NamedObject; +import de.memtext.util.CryptUtils; +/** + * wonder what this is + */ +public class DataSource extends NamedObject { + + private static final String CRYPT_PREFIX = "^^@@@"; + private String url, username, cryptPassword, driver; + private transient String password; + private DB db; + public DataSource() { + } + + public DataSource(String url, String username, String password) { + setUrl(url); + setUsername(username); + setPassword(password); + } + + public void setInformixSampleValues() { + setUrl("jupiter:50000:informixserver=superx_host;database=superx"); + setUsername("informix"); + setPassword(""); + this.db=DB.INFORMIX; + } + public void setAccessSampleValues() { + setUrl("jdbc:odbc:jdbcodbc:"); + setUsername("informix"); + setPassword(""); + this.db=DB.ACCESS; + } + + public String getDriver() { + return driver; + } + + public String getPassword() { + return password; + } + + public String getUrl() { + return url; + } + + public String getUsername() { + return username; + } + + public void setDriver(String string) { + driver = string; + } + + public void setPassword(String string) { + password = string; + this.setCryptPassword(string); + } + + public void setUrl(String string) { + url = string; + } + + public void setUsername(String string) { + username = string; + } + + public DB getDb() { + return db; + } + + public void setDb(DB db) { + this.db = db; + } + + public void testConnection() throws SQLException, ClassNotFoundException { + Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); + Connection con=DriverManager.getConnection(url,username,password); + con.close(); + + + } + + public String getCryptPassword() { + return cryptPassword; + } + + public void setCryptPassword(String aPwd) { + if (!isEncrypted(aPwd)) + { + //cryptPassword =CRYPT_PREFIX + CryptUtils.encryptStringDES(aPwd); + } + } + +public boolean isEncrypted(String aPwd) +{ + return aPwd.startsWith(CRYPT_PREFIX); +} +} + +//Created on 17.04.2004 at 16:28:15 \ No newline at end of file diff --git a/src/de/memtext/db/DataSourceEditPanel.java b/src/de/memtext/db/DataSourceEditPanel.java new file mode 100644 index 0000000..c81c502 --- /dev/null +++ b/src/de/memtext/db/DataSourceEditPanel.java @@ -0,0 +1,116 @@ +package de.memtext.db; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.sql.SQLException; + +import javax.swing.JButton; +import javax.swing.JPanel; + +import de.memtext.observ.DocumentListenerObserver; +import de.memtext.widgets.InfoMessage; +import de.memtext.widgets.LabeledPasswordField; +import de.memtext.widgets.LabeledTextField; +import de.memtext.widgets.MultilineEditPanel; +import de.memtext.widgets.WarningMessage; + +public class DataSourceEditPanel extends MultilineEditPanel { + private DataSource ds; + private LabeledTextField hostField = new LabeledTextField("Host", 10); + private LabeledTextField serverField = new LabeledTextField("Server", 10); + private LabeledTextField serviceField = new LabeledTextField("Service", 10); + private LabeledTextField odbcSourceField = + new LabeledTextField("Odbc-DSN", 10); + private LabeledTextField usernameField = + new LabeledTextField("Kennung", 10); + private LabeledTextField passwordField = + new LabeledPasswordField("Password", 10); + private JPanel pButtons = new JPanel(); + + public DataSourceEditPanel() { + this.setBackground(null); + odbcSourceField.setValue("sospos"); + odbcSourceField.setBackground(null); + usernameField.setValue("admin"); + this.add(hostField); + this.add(serverField); + this.add(serviceField); + this.add(odbcSourceField); + + this.add(usernameField); + + this.add(passwordField); + //this.addGlue(); + JButton btnTesten = new JButton("testen"); + btnTesten.setBackground(null); + pButtons.setBackground(null); + btnTesten.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + test(); + } + }); + pButtons.add(btnTesten); + //this.addGlue(); + this.add(pButtons); + } + public void setDataSource(DataSource ds) { + this.ds = ds; + setMode(ds.getDb()); + } + public void addButton(JButton btn) { + pButtons.add(btn); + } + private void setMode(DB db) { + if (db.equals(DB.ACCESS)) { + odbcSourceField.setVisible(true); + hostField.setVisible(false); + serverField.setVisible(false); + serviceField.setVisible(false); + } + if (db.equals(DB.INFORMIX)) { + odbcSourceField.setVisible(false); + hostField.setVisible(true); + serverField.setVisible(true); + serviceField.setVisible(true); + } + } + protected void test() { + updateDataSource(); + try { + ds.testConnection(); + InfoMessage.show(this, "Verbindung erfolgreich aufgebaut", "Erfolg"); + } catch (SQLException e) { + if (ds.getDb().equals( DB.ACCESS)) { + WarningMessage.show(this, + "Verbindung zur ODBC-Quelle " + + odbcSourceField.getValue() + + " konnte nicht aufgebaut werden.\n" + + e, + "Achtung"); + } + } catch (ClassNotFoundException e) { + WarningMessage.show(this, + "Benötigte Treiber-Klase nicht gefunden ", + "Achtung"); + } + } + public void updateDataSource() { + if (ds.getDb() == DB.ACCESS) { + ds.setUrl("jdbc:odbc:" + odbcSourceField.getValue()); + } + ds.setUsername(usernameField.getValue().toString()); + ds.setPassword(""); + } + public void addDocumentListener(DocumentListenerObserver listener) { + hostField.addDocumentListener(listener); + serverField.addDocumentListener(listener); + serviceField.addDocumentListener(listener); + odbcSourceField.addDocumentListener(listener); + + usernameField.addDocumentListener(listener); + + passwordField.addDocumentListener(listener); + } +} + +//Created on 17.04.2004 at 16:37:44 \ No newline at end of file diff --git a/src/de/memtext/db/DbRequest.java b/src/de/memtext/db/DbRequest.java new file mode 100644 index 0000000..1120154 --- /dev/null +++ b/src/de/memtext/db/DbRequest.java @@ -0,0 +1,94 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DbRequest + + implements java.io.Serializable { + static final long serialVersionUID = -2L; + + + private String sql; + private String name; + private Object[] params; + private int type; + private DbRequestType dbRequestType; + public DbRequest(String sql) + { + this(null,sql,null,null); + } + public DbRequest(String name,String sql,Object[] params) + { + this(name,sql,params,null); + } + /** + * Request type used by servlet + * @param name + * @param sql + * @param params + * @param dbRequestType + */ + public DbRequest(String name,String sql,Object[] params,DbRequestType dbRequestType) + { + setName(name); + setSql(sql); + setParams(params); + this.dbRequestType=dbRequestType; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name=name; + } + + public Object[] getParams() + { + return params; + } + + public void setParams(Object[] params) + { + this.params=params; + } + + public String getSql() + { + return sql; + } + + public void setSql(String sql) + { + this.sql=sql; + } + + /** + * @return + */ + public DbRequestType getDbRequestType() { + return dbRequestType; + } + + /** + * @param type + */ + public void setDbRequestType(DbRequestType type) { + dbRequestType = type; + } + + } + diff --git a/src/de/memtext/db/DbRequestType.java b/src/de/memtext/db/DbRequestType.java new file mode 100644 index 0000000..aa76b07 --- /dev/null +++ b/src/de/memtext/db/DbRequestType.java @@ -0,0 +1,27 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DbRequestType { + + private final String name; + +public static final DbRequestType QUERY=new DbRequestType("QUERY"); +public static final DbRequestType UPDATE=new DbRequestType("UPDATE"); +private DbRequestType(String name) +{ + this.name=name; +} +public String toString() {return name; +} +} diff --git a/src/de/memtext/db/DbResponse.java b/src/de/memtext/db/DbResponse.java new file mode 100644 index 0000000..658294d --- /dev/null +++ b/src/de/memtext/db/DbResponse.java @@ -0,0 +1,58 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +import java.util.Collection; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DbResponse implements java.io.Serializable { +static final long serialVersionUID = -3L; +private Collection result; +private boolean OK; +private Exception exception; +private int updatedRowsCount; + +/** +* MyServletResponse constructor comment. +*/ +public DbResponse(Collection result, boolean OK, Exception exception) { + this.result = result; + this.OK = OK; + this.exception = exception; +} +public Exception getException() { + return exception; +} +public Collection getResult() { + return result; +} +public boolean isOK() { + return OK; +} +public void setException(Exception exception) { + this.exception = exception; +} +public void setOK(boolean OK) { + this.OK = OK; +} +public void setResult(Collection result) { + this.result = result; +} +public int getUpdatedRowsCount() { + return updatedRowsCount; +} + +public void setUpdatedRowsCount(int updatedRowsCount) { + this.updatedRowsCount = updatedRowsCount; +} + +} diff --git a/src/de/memtext/db/DbRmiClient.java b/src/de/memtext/db/DbRmiClient.java new file mode 100644 index 0000000..eef2fa0 --- /dev/null +++ b/src/de/memtext/db/DbRmiClient.java @@ -0,0 +1,110 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +import java.net.MalformedURLException; +import java.rmi.Naming; +import java.rmi.NotBoundException; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; +import java.util.Iterator; +import java.util.List; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DbRmiClient { + private DbServerI dbServerI= null; + String name="DbServer"; //"//localhost/DbServer" +public DbRmiClient() +{ + if (System.getSecurityManager() == null) { + System.setSecurityManager(new RMISecurityManager()); + } + try { + dbServerI = (DbServerI)Naming.lookup(name); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (RemoteException e) { + e.printStackTrace(); + } catch (NotBoundException e) { + e.printStackTrace(); + } +} +public void test() +{ + testUpdate(); + testQuery(); +} +private void testUpdate() { + try { + + DbRequest dbRequest=new DbRequest("update dummy set col2=99"); + DbResponse dbResponse=dbServerI.execute(dbRequest); + if (dbResponse.isOK()) + { + System.out.println("OK - updated rows :" + dbResponse.getUpdatedRowsCount()); + } + else + { + System.out.println("failed :"+dbResponse.getException()); + } + + + } catch (Exception e) { + System.out.println(" exception: " + e.getMessage()); + e.printStackTrace(); + } +} + +private void testQuery() { + try { + + DbRequest dbRequest=new DbRequest("select * from dummy"); + DbResponse dbResponse=dbServerI.executeQuery("select * from dummy"); + if (dbResponse.isOK()) + { + System.out.println("OK"); + List result=(List)dbResponse.getResult(); + System.out.println("rows:"+result.size()); + int i=0; + for (Iterator it=result.iterator();it.hasNext();) + { + List row=(List)it.next(); + i++; + System.out.print("row "+i+" "); + for (Iterator it2=row.iterator();it2.hasNext();) + { + Object o=it2.next(); + System.out.print(" - "+o); + } + System.out.println(""); + } + + } + else + { + System.out.println("failed :"+dbResponse.getException()); + } + + + } catch (Exception e) { + System.out.println(" exception: " + e.getMessage()); + e.printStackTrace(); + } +} + public static void main(String a[]) { + DbRmiClient c=new DbRmiClient(); + c.test(); + + + } + + } diff --git a/src/de/memtext/db/DbServerI.java b/src/de/memtext/db/DbServerI.java new file mode 100644 index 0000000..897ec7c --- /dev/null +++ b/src/de/memtext/db/DbServerI.java @@ -0,0 +1,23 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public interface DbServerI extends Remote { + public DbResponse execute(String sql) throws RemoteException; + public DbResponse executeQuery(String sql) throws RemoteException; +public DbResponse execute(DbRequest dbRequest) throws RemoteException; +public DbResponse executeQuery(DbRequest dbRequest) throws RemoteException; +} diff --git a/src/de/memtext/db/DbServerImpl.java b/src/de/memtext/db/DbServerImpl.java new file mode 100644 index 0000000..8eb2858 --- /dev/null +++ b/src/de/memtext/db/DbServerImpl.java @@ -0,0 +1,117 @@ +/* + * Created on 21.06.2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +package de.memtext.db; + +import java.rmi.Naming; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +/** + * @author MB + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class DbServerImpl + extends UnicastRemoteObject + implements de.memtext.db.DbServerI { + private String dbDriver = "org.hsqldb.jdbcDriver"; + private String dbURL = "jdbc:hsqldb:hsql://localhost:9000"; + private String userid = "SA"; + private String passwd = ""; + private int updateRowCount; + private Connection con; + private Statement stmt; + public DbServerImpl() throws RemoteException { + super(); + ConnectionCreator.loadClass(dbDriver); + try { + con = ConnectionCreator.getConnection(dbURL, userid, passwd); + stmt = con.createStatement(); + } catch (Exception e) { + e.printStackTrace(); + throw new RemoteException("Couldn't connect to DB" + e.toString()); + } + } + public DbResponse execute(String sql) throws RemoteException { + DbResponse result = new DbResponse(null, true, null); + try { + updateRowCount = stmt.executeUpdate(sql); + result.setUpdatedRowsCount(updateRowCount); + result.setOK(true); + } catch (SQLException e) { + e.printStackTrace(); + result.setOK(false); + result.setException(e); + } + return result; + } + + /* (non-Javadoc) + * @see de.mbisping.db.DbServerI#execute(de.mbisping.db.DbRequest) + */ + public DbResponse execute(DbRequest dbRequest) throws RemoteException { + DbResponse result = new DbResponse(null, true, null); + if (dbRequest.getSql() != null) + result = execute(dbRequest.getSql()); + + return result; + } + + public DbResponse executeQuery(String sql) throws RemoteException { + DbResponse result = new DbResponse(null, true, null); + try { + ResultSet rs=stmt.executeQuery(sql); + List list=DbUtils.toResultList(rs); + result.setResult(list); + result.setOK(true); + } catch (SQLException e) { + e.printStackTrace(); + result.setOK(false); + result.setException(e); + } + return result; + } + /* (non-Javadoc) + * @see de.mbisping.db.DbServerI#executeQuery(de.mbisping.db.DbRequest) + */ + public DbResponse executeQuery(DbRequest dbRequest) + throws RemoteException { + DbResponse result = new DbResponse(null, true, null); + result.setUpdatedRowsCount(20); + return result; + } + + public static void main(String args[]) { + + // Create and install a security manager + if (System.getSecurityManager() == null) { + System.setSecurityManager(new RMISecurityManager()); + } + + try { + + DbServerImpl obj = new DbServerImpl(); + //String name="//localhost/DbServer"; + String name = "DbServer"; + // Bind this object instance to the name "HelloServer" + Naming.rebind(name, obj); + + System.out.println(name + " bound in registry"); + } catch (Exception e) { + System.out.println("DbServerImpl err: " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/src/de/memtext/db/DbUtils.java b/src/de/memtext/db/DbUtils.java new file mode 100644 index 0000000..77cb86c --- /dev/null +++ b/src/de/memtext/db/DbUtils.java @@ -0,0 +1,177 @@ +package de.memtext.db; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * @author MB + */ +public class DbUtils { + + /** + * + */ + private DbUtils() { + } + + /* + * private Vector toResultVector(ResultSet rs) throws SQLException { Vector help + * = new Vector(); ResultSetMetaData rsmd = rs.getMetaData(); int + * numberOfColumns = rsmd.getColumnCount(); + * + * Vector row = null; while (rs.next()) { row = new Vector(); for (int i = 1; i + * <= numberOfColumns; i++) { row.add(rs.getObject(i)); } help.add(row); } + * rs.close(); return help; + * + * } + */ + public static List toResultList(ResultSet rs) throws SQLException { + List help = new LinkedList(); + ResultSetMetaData rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + + List row = null; + while (rs.next()) { + row = new LinkedList(); + for (int i = 1; i <= numberOfColumns; i++) { + row.add(rs.getObject(i)); + } + help.add(row); + } + rs.close(); + return help; + } + + public static void grantRightToAllTables() { + String url = "jdbc:hsqldb:hsql://localhost:9999"; + String user = ""; + String right = "select"; + try { + Class.forName("org.hsqldb.jdbcDriver"); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + try { + DBAccess.addConnection("dbConn", DriverManager.getConnection(url, "admin", "hatschi3000")); + } catch (SQLException e1) { + e1.printStackTrace(); + } catch (Exception e1) { + e1.printStackTrace(); + } + List tablist = DBAccess.get("dbConn").getTableList(); + StringBuffer buf = new StringBuffer(); + for (Iterator it = tablist.iterator(); it.hasNext();) { + String tabname = (String) it.next(); + buf.append("grant " + right + " on " + tabname + " to " + user + ";"); + + } + DBAccess.get("dbConn").execute(buf.toString()); + + DBAccess.closeConnection("dbConn"); + + } + + /** + * Places Object in inverted single commas if it isn't null + * + * @param val + * @return either "null" if val is null or "'val'" + */ + public static String placeInInvertedCommas(Object val) { + if (val == null) + return "null"; + return "'" + val + "'"; + } + + + public static int getInt(Statement stm, String query) throws SQLException { + int result = -1; + ResultSet rs = stm.executeQuery(query); + while (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + + return result; + } + + public static String getString(Statement stm, String query) throws SQLException { + String result = null; + ResultSet rs = stm.executeQuery(query); + while (rs.next()) { + result = rs.getString(1); + } + rs.close(); + + return result; + } + /** + * + * @param query + * @return -1 wenn nichts gefunden + * @throws SQLException + */ + public static int getInt(Connection con, String query,int param) throws SQLException { + int result = -1; + PreparedStatement pst=con.prepareStatement(query); + pst.setInt(1, param); + ResultSet rs = pst.executeQuery(); + while (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + pst.close(); + return result; + } + + /** + * + * @param query + * @return -1 wenn nichts gefunden + * @throws SQLException + */ + public static int getInt(Connection con, String query,String param) throws SQLException { + int result = -1; + PreparedStatement pst=con.prepareStatement(query); + pst.setString(1, param); + ResultSet rs = pst.executeQuery(); + while (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + pst.close(); + return result; + } + /** + * + * @param con + * @param query + * @param param + * @return null if nothing found + * @throws SQLException + */ + public static String getString(Connection con,String query,String param) throws SQLException + { + String result=null; + PreparedStatement pst=con.prepareStatement(query); + pst.setString(1, param); + ResultSet rs = pst.executeQuery(); + while (rs.next()) { + result = rs.getString(1); + } + rs.close(); + pst.close(); + return result; + + } +} +//Created on 21.06.2003 \ No newline at end of file diff --git a/src/de/memtext/db/HsqlProcedures.java b/src/de/memtext/db/HsqlProcedures.java new file mode 100644 index 0000000..03901c0 --- /dev/null +++ b/src/de/memtext/db/HsqlProcedures.java @@ -0,0 +1,123 @@ +package de.memtext.db; + +import java.sql.Statement; + +/** + * @author MB + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class HsqlProcedures { + + /** + * Constructor for HsqlProcedures. + */ + private HsqlProcedures() { + super(); + } + + public static Integer get1() + { + return new Integer(1); + + } + public static void alterTableColumnIntegerToVarchar( + java.sql.Connection con, + String tablename, + String columnname) { + try { + Statement stmt = con.createStatement(); + // add new tmp varchar col + stmt.execute( + "alter table " + + tablename + + " add column tmp" + + columnname + + " varchar"); + //update value of tmp + stmt.execute( + "update " + + tablename + + " set tmp" + + columnname + + "= " + + columnname); + //drop original + stmt.execute( + "alter table " + tablename + " drop column " + columnname); + //add col with original name and of varchar type + stmt.execute( + "alter table " + + tablename + + " add column " + + columnname + + " varchar"); + //update values + stmt.execute( + "update " + + tablename + + " set " + + columnname + + "= tmp" + + columnname); + //drop tmp + stmt.execute( + "alter table " + tablename + " drop column tmp" + columnname); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public static void alterTableColumnVarcharToInteger( + java.sql.Connection con, + String tablename, + String columnname) { + try { + Statement stmt = con.createStatement(); + // add new tmp varchar col + stmt.execute( + "alter table " + + tablename + + " add column tmp" + + columnname + + " integer"); + //update value of tmp + stmt.execute( + "update " + + tablename + + " set tmp" + + columnname + + "= " + + columnname); + //drop original + stmt.execute( + "alter table " + tablename + " drop column " + columnname); + //add col with original name and of varchar type + stmt.execute( + "alter table " + + tablename + + " add column " + + columnname + + " integer"); + //update values + stmt.execute( + "update " + + tablename + + " set " + + columnname + + "= tmp" + + columnname); + //drop tmp + stmt.execute( + "alter table " + tablename + " drop column tmp" + columnname); + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/src/de/memtext/db/HsqlStandaloneMgr.java b/src/de/memtext/db/HsqlStandaloneMgr.java new file mode 100644 index 0000000..adb3356 --- /dev/null +++ b/src/de/memtext/db/HsqlStandaloneMgr.java @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2001-2004, The HSQL Development Group All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the HSQL Development Group nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package de.memtext.db; + +import java.awt.Component; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.ResourceBundle; + +import javax.swing.JOptionPane; + +/** + * A class which helps managing multiple connections to a stand-alone database + * (e.g. on a network path). After one user has opened the database other users + * can get the option to open a temporary copy of the database. The temporary + * copy may be read-only, but doesn't has to be. If it's not read-only all, all + * changes will be discarded when the connection is closed. (May be useful if + * the application only does some dispensible logging or so). see + * SampleApplication + */ +public class HsqlStandaloneMgr { + private static AbstractHsqlStandaloneMgrResources resources; + + private HsqlStandaloneMgr() { + } + + private static void initResources() { + String mypackage = ""; + //if you place the Resources classes in some package, define it like this + mypackage="de.memtext.db."; + resources = (AbstractHsqlStandaloneMgrResources) ResourceBundle + .getBundle(mypackage + "HsqlStandaloneMgrResources"); + } + + + + /** + * Checks if a database is already opened (by checking if a .lck file + * exists) Use from HSQLDB 1.7.2 or higher + * + * @param String + * path - null,"" or "." for current directory + * @param String + * databasename + * @return true if database is already opened + */ + public static boolean isDatabaseOpen(String path, String databasename) { + File lckFile = new File(getAdaptedPath(path)+databasename+".lck"); + return lckFile.exists(); + } + + /** + * Deletes any temporary files which the HsqlStandaloneMgr may have created + * for the given url + * + * @param String + * url + * @param String + * path - null,"" or "." for current dir + * @param String + * databasename - of the original database, no _TMP_COPY appendix + */ + public static void deleteTmpFiles(String url, String path, + String databasename) { + if (databasename.indexOf("_TMP_COPY") > -1) + throw new IllegalArgumentException( + "Please specifiy the name of the original database without _TMP_COPY"); + path=getAdaptedPath(path); + + int tmpPos = url.indexOf("_TMP_COPY"); + if (tmpPos == -1) { + //if the main connection is closed delete info about the user + File f = new File(path + databasename + "_user.properties"); + if (f.exists()) + f.delete(); + } else { + //delete files for temp. connection + String tmp = url.substring(tmpPos); + if (path==null||path.equals("")) path="."; + File fpath = new File(path); + File tmpFiles[] = fpath.listFiles(new TmpFileFilter(databasename + + tmp)); + for (int i = 0; i < tmpFiles.length; i++) { + tmpFiles[i].delete(); + } + } + + } + + /** + * Asks the user if he/she wants to open a temporary copy of the database or + * not. A boolean indicates if the questions concerns read-only mode or not. + * + * @param Component + * parentComponent - usually the application Frame, but may be + * null + * @param String + * databasename - name of original database + * @param boolean + * isReadOnlyCopyWanted - should the temp. copy be read-only + * @return int from JOptionPane.showConfirmDialog + */ + public static int askUser(Component parentComponent, String path, + + String databasename, boolean isReadOnlyCopyWanted) { + if (resources == null) + initResources(); + + String username = null; + File f = new File(getAdaptedPath(path) + databasename + "_user.properties"); + if (f.exists()) { + Properties p = new Properties(); + FileInputStream fis; + try { + fis = new FileInputStream(f); + p.load(fis); + username = p.getProperty("user"); + fis.close(); + } catch (Exception e) { + System.err.println(resources + .getString("Couldn't read user name")); + e.printStackTrace(); + } + + } + StringBuffer msg = new StringBuffer(resources.getDbInUseBy( + databasename, username)); + + if (isReadOnlyCopyWanted) + msg + .append(resources + .getString("Would you like to open a temporary copy in read-only mode?")); + else + msg + .append(resources + .getString("Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!")); + return JOptionPane.showConfirmDialog(parentComponent, msg, "HSQLDB", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + + } + + /** + * Returns a connection to a temporary copy of a database either in + * read-only mode or not. + * + * @param Component + * parentComponent - usually the application Frame, but may be + * null + * @param String + * path - null,"" or "." for current dir + * @param String + * databasename + * @param String + * username + * @param String + * password + * @param boolean + * isReadOnlyCopyWanted - should the temporary copy of the + * database be in read-only mode + * @return Connection to the temporary copy of the database + * @throws ClassNotFoundException + * @throws SQLException + * @throws IOException + */ + public static Connection getTmpConnection(Component parentComponent, + String path, String databasename, String username, String password, + boolean isReadOnlyCopyWanted) throws ClassNotFoundException, + SQLException, IOException { + if (resources == null) + initResources(); + Class.forName("org.hsqldb.jdbcDriver"); + path = getAdaptedPath(path); + + int tmpInstanceNumber = checkNumber(path, databasename); + + try { + copyDatabaseFiles(path, databasename, tmpInstanceNumber); + } catch (IOException e) { + JOptionPane.showMessageDialog(parentComponent, resources + .getString("Could not create temporary copy of database.)") + + "\n" + e, "HSQLDB", JOptionPane.WARNING_MESSAGE); + throw e; + } + + if (isReadOnlyCopyWanted) { + try { + setReadonly(path + databasename + "_TMP_COPY" + + tmpInstanceNumber + ".properties"); + } catch (IOException e) { + JOptionPane + .showMessageDialog( + parentComponent, + resources + .getString("Could not set temporary copy of database to readonly mode.") + + "\n" + e, "HSQLDB", + JOptionPane.WARNING_MESSAGE); + throw e; + } + } + String url = "jdbc:hsqldb:file:" + path + databasename + + "_TMP_COPY" + tmpInstanceNumber; + + Connection con = java.sql.DriverManager.getConnection(url, username, + password); + + if (!isReadOnlyCopyWanted) { + Statement stmt = con.createStatement(); + ResultSet rs = stmt + .executeQuery("select count(*) from system_tables where hsqldb_type='TEXT'"); + rs.next(); + if (rs.getInt(1) > 0) { + stmt.execute("shutdown"); + stmt.close(); + con.close(); + deleteTmpFiles(url, path, databasename); + throw new SQLException( + resources + .getString("Handling non read-only temporary database with text tables is not supported")); + } + rs.close(); + stmt.close(); + } + return con; + } + + private static int checkNumber(String path, String databasename) { + int result = 1; + while (new File(path + databasename + "_TMP_COPY" + result + + ".script").exists()) + result++; + return result; + } + + /** + * Returns a regular connection to a database and creates a file + * database_user.properties with the name of the user that opens the + * database + * + * @param String + * path - null,"" or "." for current dir + * @param String + * databasename + * @param String + * username + * @param String + * password + * @return Connection to the database + * @throws ClassNotFoundException + * @throws SQLException + * @throws IOException + */ + public static Connection getConnection(String path, String databasename, + String username, String password) throws ClassNotFoundException, + SQLException, IOException { + Class.forName("org.hsqldb.jdbcDriver"); + String url=null; + if (path==null) + url="jdbc:hsqldb:"+databasename; + else + url = "jdbc:hsqldb:file:" + getAdaptedPath(path) + databasename; + + Connection con = java.sql.DriverManager.getConnection(url, username, + password); + + Properties p = new Properties(); + p.put("user", System.getProperty("user.name")); + String filename=(path!=null?path+"/"+databasename+"_user.properties":databasename+"_user.properties"); + FileOutputStream fos = new FileOutputStream(filename); + p.store(fos, "User which uses the HSQL database"); + fos.close(); + + return con; + } + + /** + * String and makes sure separator char is at the end + * + * @param String + * path + * @return adapted path String + */ + private static String getAdaptedPath(String path) { + if (path == null) path = ""; + if ((path.equals(".")||path.length()>1)&&!(path.endsWith("/")||path.endsWith("\\"))) + path+=File.separator; + + return path; + } + + /** + * Changes the property readonly to true in a database properties file + * + * @param String + * propertiesFile including path if necessary + * @throws IOException + */ + private static void setReadonly(String propertiesFile) throws IOException { + Properties p = new Properties(); + p.load(new FileInputStream(propertiesFile)); + p.put("readonly", "true"); + p.store(new FileOutputStream(propertiesFile), "HSQL database"); + + } + + /** + * Makes a temporary copy of all existing database files with the appendix + * _TMP_COPY + * + * @param String + * path - may be null for current dir, no / or \ at the end + * @param String + * databasename + * @throws IOException + */ + private static void copyDatabaseFiles(String path, String databasename, + int number) throws IOException { + + String s = path + databasename; + copyFile(s + ".script", s + "_TMP_COPY" + number + ".script"); + copyFile(s + ".properties", s + "_TMP_COPY" + number + ".properties"); + if (new File(s + ".log").exists()) + copyFile(s + ".log", s + "_TMP_COPY" + number + ".log"); + if (new File(s + ".data").exists()) + copyFile(s + ".data", s + "_TMP_COPY" + number + ".data"); + if (new File(s + ".backup").exists()) + copyFile(s + ".backup", s + "_TMP_COPY" + number + ".backup"); + if (new File(s + ".nio").exists()) + copyFile(s + ".nio", s + "_TMP_COPY" + number + ".nio"); + } + + /** + * Creates a copy of a file + * + * @param String + * source - source file name (incl. path if necessary) + * @param String + * target - target file name (incl. path if necessary) + * @throws IOException + */ + static public void copyFile(String source, String target) + throws IOException { + + try { + FileInputStream is = new FileInputStream(source); + FileOutputStream os = new FileOutputStream(target); + + BufferedInputStream in = new BufferedInputStream(is); + BufferedOutputStream out = new BufferedOutputStream(os); + + int buffer_size = 32768; + byte[] buffer = new byte[buffer_size]; + + int len = in.read(buffer, 0, buffer_size); + while (len != -1) { + out.write(buffer, 0, len); + len = in.read(buffer, 0, buffer_size); + } + in.close(); + is.close(); + out.close(); + os.close(); + + } catch (IOException e) { + throw new IOException("Couldn't copy file " + source + ": " + + e.toString()); + } + } + + private static class TmpFileFilter implements FilenameFilter { + private String tmpName; + + TmpFileFilter(String tmpName) { + this.tmpName = tmpName; + } + + public boolean accept(File dir, String name) { + return name.indexOf(tmpName) > -1; + } + + } + +} + +//Created on 21.10.2004 at 20:35:55 diff --git a/src/de/memtext/db/HsqlStandaloneMgrResources.java b/src/de/memtext/db/HsqlStandaloneMgrResources.java new file mode 100644 index 0000000..1206e05 --- /dev/null +++ b/src/de/memtext/db/HsqlStandaloneMgrResources.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2001-2004, The HSQL Development Group All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the HSQL Development Group nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package de.memtext.db; +/** + * Resources for HsqlStandaloneMgr. + * For other locales extend AbstractHsqlStandloneMgrResources, i.e. + * by copying HsqlStandaloneMgrResources_de to your locale + */ + +public class HsqlStandaloneMgrResources extends + AbstractHsqlStandaloneMgrResources { + public Object[][] getContents() { + return contents; + } + + static final Object[][] contents = { + + { "Couldn't read user name", "Couldn't read user name" }, + { "Would you like to open a temporary copy in read-only mode?", + "Would you like to open a temporary copy in read-only mode?" }, + { + "Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!", + "Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!" }, + { "Could not create temporary copy of database.", + "Could not create temporary copy of database." }, + { "Could not set temporary copy of database to readonly mode.", + "Could not set temporary copy of database to readonly mode." }, + { + "Handling non read-only temporary database with text tables is not supported", + "Handling non read-only temporary database with text tables is not supported" } + + }; + + public String getDbInUseBy(String dbname, String user) { + String result = "The database " + dbname + " is already in use"; + if (user != null) + result += " by user " + user; + result += ".\n"; + return result; + } +} + diff --git a/src/de/memtext/db/HsqlStandaloneMgrResources_de.java b/src/de/memtext/db/HsqlStandaloneMgrResources_de.java new file mode 100644 index 0000000..d06eb92 --- /dev/null +++ b/src/de/memtext/db/HsqlStandaloneMgrResources_de.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2001-2004, The HSQL Development Group All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the HSQL Development Group nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package de.memtext.db; +/** + * Resources for HsqlStandaloneMgr. + * For other locales extend AbstractHsqlStandloneMgrResources, i.e. + * by copying this class to your locale + */ +public class HsqlStandaloneMgrResources_de extends + AbstractHsqlStandaloneMgrResources { + public Object[][] getContents() { + return contents; + } + + static final Object[][] contents = { + { "Couldn't read user name", "Konnte Usernamen nicht lesen" }, + { "Would you like to open a temporary copy in read-only mode?", + "Möchten Sie eine schreibgeschützte Kopie öffnen?" }, + { + "Would you like to open a temporary copy?\nAttention - any changes to the database will be lost after closing the program!", + "Möchten Sie eine temporäre Kopie öffnen?\nAchtung, wenn Sie das Programm beenden, gehen alle Änderungen, die Sie vorgenommen haben, verloren!" }, + { "Could not create temporary copy of database.", + "Konnte keine temporäre Kopie der Datenbank anlegen." }, + { "Could not set temporary copy of database to readonly mode.", + "Konnte die temp. Kopie nicht auf schreibgeschützt setzen" }, + { + "Handling non read-only temporary database with text tables is not supported", + "Nicht schreibgeschützte Datenbanken mit Text-Tables werden nicht unterstützt" } + + }; + + public String getDbInUseBy(String dbname, String user) { + String result = "Die Datenbank " + dbname + " wird schon benutzt "; + if (user != null) + result += " vom User " + user; + result += ".\n"; + return result; + } +} + diff --git a/src/de/memtext/db/Library2.java b/src/de/memtext/db/Library2.java new file mode 100644 index 0000000..c67c2ee --- /dev/null +++ b/src/de/memtext/db/Library2.java @@ -0,0 +1,91 @@ +package de.memtext.db; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +/** + * Additional procedures for HSQLDB + * make sure that this class in the classpath. + * To constantly add it to hsql, go to the directory where your hsqldb.jar is located + * Call jar -xf hsqlAddOn.jar + * jar -uf hsqldb.jar org/hsqldb/Library2.class + * Delete the directory org. + * + * Open your Database in Database Manager and execute + * the following commands once: + * GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC and + * CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom" + */ +public class Library2 { + private Library2() { + super(); + } + /** + * Fills regular tables with values from a CSV-file. + * Similar to Postgres COPY FROM command. + * + * If you want to fill your table TEST with data from test.csv + * make sure that this class in the classpath and that + * GRANT ALL ON CLASS "org.hsqldb.Library2" TO PUBLIC and + * CREATE ALIAS COPYFROM FOR "org.hsqldb.Library2.copyFrom" + * has been called in your database at some point. + + * * Then execute + * COPYFROM("TEST","test.csv",null) + * + * if your not using , but | as a field separator + COPYFROM("TEST","test.csv","fs=|") + + * + * @param con - Connection is automatically handed over by HSQL + * @param table - the name of the table that is to be filled + * if your table isn't found capital letters may be required + * @param file - the filename of the CSV-file + * @param options - you can specify options separated by ; + * which are described in the text table documentation e.g. + * fs=| to use pipe instead of default comma as field separator or + * or + * fs=|;vs=.;lvs=~" varchar separator, longvarchar separator + * ignore_first=true; ignore first line + * all_quoted=true or + * encoding=UTF-8 if you don't have ASCII + * @throws SQLException + */ + public static void copyFrom( + Connection con, + String table, + String file, + String options) + throws SQLException { + StringBuffer buf = + new StringBuffer("create text table TMP_SOURCE_" + table + " ("); + + ResultSet rs = con.getMetaData().getColumns(null, null, table, null); + String colname, coltype; + boolean tableFound = false; + while (rs.next()) { + tableFound = true; + colname = rs.getObject(4).toString(); + coltype = rs.getObject(6).toString(); + buf.append(colname + " " + coltype + ","); + } + rs.close(); + if (!tableFound) + throw new IllegalArgumentException( + "Copy from failed - table " + table + " not found"); + buf.deleteCharAt(buf.lastIndexOf(",")); + buf.append("); SET TABLE TMP_SOURCE_" + table + " SOURCE \"" + file); + if (options != null) + buf.append(";" + options); + buf.append("\";"); + buf.append( + "insert into " + table + " select * from TMP_SOURCE_" + table); + Statement stmt = con.createStatement(); + try { + stmt.execute(buf.toString()); + } finally { + stmt.execute("drop table TMP_SOURCE_" + table + " IF EXISTS"); + } + } +} diff --git a/src/de/memtext/db/MemtextPool.java b/src/de/memtext/db/MemtextPool.java new file mode 100644 index 0000000..b8e8713 --- /dev/null +++ b/src/de/memtext/db/MemtextPool.java @@ -0,0 +1,262 @@ +package de.memtext.db; + +import java.io.File; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SignatureException; +import java.security.spec.InvalidKeySpecException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import javax.xml.transform.TransformerConfigurationException; + +import org.apache.commons.dbcp.ConnectionFactory; +import org.apache.commons.dbcp.DriverManagerConnectionFactory; +import org.apache.commons.dbcp.PoolableConnectionFactory; +import org.apache.commons.dbcp.PoolingDriver; +import org.apache.commons.pool.impl.GenericObjectPool; + +import de.memtext.baseobjects.NamedObjectI; +import de.memtext.tree.KeyParentEqualException; +import de.memtext.util.DSAHandler; + +/** + * A new Connection pool making use of Jakarta Commons dbcp. + */ +public class MemtextPool extends GenericObjectPool implements NamedObjectI { + + private String name, subpath; + private String nameNoAppendix; + + private Properties props = new Properties(); + private String privateKeyEncoded = null; + private String publicKeyEncoded = null; + private DSAHandler dsaHandler; + + public MemtextPool(String name, String nameAppendix, String subpath) + throws SQLException, IOException, DBServletException { + this.subpath = subpath; + nameNoAppendix = name; + this.setName(name + nameAppendix); + try { + readPropertiesAndUrl(); + System.out + .print(" (" + props.getProperty("connectionURL") + ") .."); + } catch (Exception e) { + System.out + .println("Konnte properties / Passwort nicht lesen. " + e); + e.printStackTrace(); + throw new DBServletException( + "Konnte properties / Passwort nicht lesen. " + e); + } + try { + + Class.forName(props.getProperty("driverName")); + } catch (ClassNotFoundException e1) { + throw new DBServletException("Treiber " + + props.getProperty("driverName") + + " nicht gefunden. Ggfs. nach tomcat/common/lib kopieren."); + } + + initLogging(); + this.setTestOnBorrow(true); + + int minIdle = 5; + if (props.getProperty("minIdle") != null + && !props.getProperty("minIdle").trim().equals("")) { + minIdle = Integer.parseInt(props.getProperty("minIdle")); + } + this.setMinIdle(minIdle); + int maxIdle = -1; + if (props.getProperty("maxIdle") != null + && !props.getProperty("maxIdle").trim().equals("")) { + maxIdle = Integer.parseInt(props.getProperty("maxIdle")); + } + if (maxIdle != -1) + setMaxIdle(maxIdle); + + int maxActive = -1; + if (props.getProperty("maxActive") != null + && !props.getProperty("maxActive").trim().equals("")) { + maxActive = Integer.parseInt(props.getProperty("maxActive")); + } + if (maxActive != -1) + setMaxActive(maxActive); + + ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( + props.getProperty("connectionURL"), props); + PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( + connectionFactory, this, null, "select count(*) from xdummy;" //validationQuery + , false, true); + int i = 1; + try { + // PoolingDriver driver = new PoolingDriver(); + Class.forName("org.apache.commons.dbcp.PoolingDriver"); + } catch (ClassNotFoundException e2) { + throw new DBServletException( + "ConnectionPool Klasse org.apache.commons.dbcp.PoolingDriver nicht gefunden.\ncommons-dbcp nach tomcat/common/lib stellen."); + } + PoolingDriver driver = (PoolingDriver) DriverManager + .getDriver("jdbc:apache:commons:dbcp:"); + + driver.registerPool(this.getName(), this); + + Object x = driver.getConnectionPool(this.getName()); + try { + Connection con = this.getConnection(); + Statement st = con.createStatement(); + ResultSet rs = st + .executeQuery("select value from properties where name='privatekey'"); + while (rs.next()) { + privateKeyEncoded = rs.getString(1); + } + rs.close(); + rs = st + .executeQuery("select value from properties where name='publickey'"); + while (rs.next()) { + publicKeyEncoded = rs.getString(1); + } + rs.close(); + st.close(); + con.close(); + + } catch (SQLException e) { + String msg = "Fehler beim Aufbau des ConnectionPools "; + if (!getName().startsWith("default")) + msg += " für Mandant: " + getName(); + msg += "\nKonnte keine Connection aus dem Pool holen.\n" + e; + + throw new SQLException(msg); + } + if (privateKeyEncoded != null) + initDSAHandler(); + } + + protected void initLogging() throws IOException { + /* + * LogUtils.initRawFile("superx_" + getName(), getLogDir() + "/superx_" + + * name + ".log", 2000, 1, false, true); LogUtils.initRawFile("superx_" + + * getName() + "_xml", getLogDir() + "/superx_" + name + "_xml.log", + * 2000, 1, false, true); + * + * Level lev = Level.SEVERE; + * + * try { if (props.getProperty("logLevelSQL") != null) lev = + * Level.parse(props.getProperty("logLevelSQL")); } catch + * (IllegalArgumentException e) { String msg = "Ungültiger Level für + * sqlLogger "; if (!this.getName().equals("default")) msg += "(Mandant :" + + * getName() + ") "; msg += " :" + props.getProperty("logLevelSQL"); + * System.out.println(msg); } Logger.getLogger("superx_" + + * getName()).setLevel(lev); lev = Level.SEVERE; + * + * try { if (props.getProperty("logLevelXML") != null) lev = + * Level.parse(props.getProperty("logLevelXML")); } catch + * (IllegalArgumentException e) { String msg = "Ungültiger Level für + * XMLLogger "; if (!this.getName().equals("default")) msg += "(Mandant :" + + * getName() + ") "; msg += " :" + props.getProperty("logLevelXML"); + * System.out.println(msg); } Logger.getLogger("superx_" + getName() + + * "_xml").setLevel(lev); + */ + } + + public static String getLogDir() { + String tomcat_home = System.getProperty("catalina.home"); //tomcat 4 + // and 5 + if (tomcat_home == null) + tomcat_home = System.getProperty("tomcat.home"); //tomcat 3.x + if (tomcat_home == null) + tomcat_home = "/home/superx/webserver/tomcat"; + + return tomcat_home + "/logs"; + + } + + public Properties getProperties() { + return props; + } + + private void readPropertiesAndUrl() throws Exception { + String propname = "db_" + nameNoAppendix + ".properties"; + if (nameNoAppendix.equals("default")) + propname = "db.properties"; + + java.net.URL url = MemtextPool.class.getProtectionDomain() + .getCodeSource().getLocation(); + File myJar = new File(url.getFile()); + File myPath = new File(myJar.getParent()); + String pfad = myPath.getParent() + System.getProperty("file.separator"); + if (subpath != null) + pfad += subpath + System.getProperty("file.separator"); + props = PropsReader.prepareProps(new File(pfad + propname)); + int i = 1; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void close() throws SQLException { + PoolingDriver driver = (PoolingDriver) DriverManager + .getDriver("jdbc:apache:commons:dbcp:"); + driver.closePool(this.getName()); + + } + + public Connection getConnection() throws SQLException { + return DriverManager.getConnection("jdbc:apache:commons:dbcp:" + + this.getName()); + + } + + public void init() throws TransformerConfigurationException, + KeyParentEqualException, SQLException, DBServletException { + } + + public void clearLogFiles() throws IOException { + } + + private void initDSAHandler() throws DBServletException { + //privateKey wird ggfs. im Konstruktur bei Connection-Test, public key + // aus properties eingelesen + if (privateKeyEncoded == null) + throw new IllegalStateException( + "privatekey war null - properties-table auf Eintrag überprüfen"); + if (publicKeyEncoded == null) + throw new IllegalStateException( + "publickey war null - properties-table prüfen"); + try { + dsaHandler = new DSAHandler(privateKeyEncoded, publicKeyEncoded); + } catch (Exception e) { + throw new DBServletException(e.toString()); + } + } + + public boolean hasDSAHandler() { + return dsaHandler != null; + } + + public boolean verifiy(String data, String signature) + throws InvalidKeyException, NoSuchAlgorithmException, + InvalidKeySpecException, SignatureException { + if (dsaHandler == null) + throw new IllegalStateException( + "DSAHandler ist null, public und private key definition prüfen"); + return dsaHandler.verify(data, signature); + + } + + public String getPrivateKey() { + return privateKeyEncoded; + } +} + +//Created on 04.11.2004 at 20:18:11 as SxPool diff --git a/src/de/memtext/db/MemtextPools.java b/src/de/memtext/db/MemtextPools.java new file mode 100644 index 0000000..ebc6c5a --- /dev/null +++ b/src/de/memtext/db/MemtextPools.java @@ -0,0 +1,197 @@ +package de.memtext.db; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Iterator; + +import javax.xml.transform.TransformerConfigurationException; + +import org.apache.commons.dbcp.PoolingDriver; + +import de.memtext.baseobjects.coll.NamedObjectSet; +import de.memtext.tree.KeyParentEqualException; + + +public class MemtextPools extends NamedObjectSet { + + private NamedObjectSet pools = new NamedObjectSet(); + + public MemtextPools() { + super(); + } + + public synchronized Connection getConnection(String poolname) + throws SQLException { + if (pools.size() == 0) + throw new IllegalStateException("Kein ConnectionPool gefunden."); + if (!pools.containsItemWithName(poolname)) + throw new SQLException("Kein ConnectionPool für Mandant:" + + poolname + " gefunden"); + String pooldrv = "jdbc:apache:commons:dbcp:" + poolname; + if (DriverManager.getDriver(pooldrv) == null) { + String msg = "Kein ConnectionPool gefunden "; + if (!poolname.equals("default")) + msg += " für Mandant " + poolname; + throw new SQLException(msg); + } + return DriverManager.getConnection(pooldrv); + } + + public MemtextPool get(String poolname) { + if (!pools.containsItemWithName(poolname)) + throw new IllegalStateException("Kein ConnectionPool (" + poolname + + ") vorhanden"); + return (MemtextPool) pools.getByName(poolname); + } + + /* void initDefaultOnly() throws SQLException, IOException, + DBServletException { + pools.add(new MemtextPool("default")); + } +*/ + /** + * wenn mehrfach benutzt wird (ConnectionPools für SuperX und Joolap) + * mind ein sollte namensappendix haben, damit unterscheidbar - + * sonst wird z.B. Pool für joolap "default" von später erzeugten Pool für superx "default" + * überschrieben! + */ + public void init(String subpath,Class poolclass, String nameAppendix) throws SQLException, IOException, + DBServletException { + if (nameAppendix==null) nameAppendix=""; + Class[] params = new Class[2]; + params[0] = String.class; + params[1] = String.class; + Constructor constructor; + try { + constructor = poolclass.getConstructor(params); + + String db_extfile = "mandanten.cfg"; + if (db_extfile.indexOf(File.separator) == -1) { + java.net.URL url = MemtextPools.class.getProtectionDomain() + .getCodeSource().getLocation(); + File myJar = new File(url.getFile()); + File myPath = new File(myJar.getParent()); + String pfad = myPath.getParent(); + if (subpath!=null) pfad+=File.separator+subpath; + db_extfile = pfad + File.separator+db_extfile; ; + + + } + File f = new File(db_extfile); + if (!f.exists()) { + //einfach nur normale db.properties (default) + System.out.print("Aufbau Datenbank-ConnectionPool"); + Object[] args = new Object[2]; + args[0] = "default";//Appendix hängt JoolapPool an + args[1] = subpath; + MemtextPool connectionPool = (MemtextPool) constructor.newInstance(args); + System.out.println(" OK"); + System.out.println(" public/private key "+(connectionPool.hasDSAHandler()?" aktiv ":" nicht aktiv")); + + pools.add(connectionPool); + } else { //mehrereMandanten + FileReader fr = new FileReader(f); + BufferedReader bfr = new BufferedReader(fr); + String line; + while ((line = bfr.readLine()) != null) { + System.out.print("Aufbau Datenbank-ConnectionPool für " + + line); + Object[] args = new Object[2]; + args[0] = line;//Appendix hängt JoolapPool an + args[1] = subpath; + MemtextPool connectionPool = (MemtextPool) constructor.newInstance(args); + System.out.println("OK"); + System.out.println(" public/private key"+(connectionPool.hasDSAHandler()?" aktiv ":" nicht aktiv")); + + pools.add(connectionPool); + } + bfr.close(); + fr.close(); + } + } catch (SecurityException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } catch (InstantiationException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } catch (IllegalAccessException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } catch (InvocationTargetException e) { + e.printStackTrace(); + throw new DBServletException(e.toString()); + } + } + + /** + * Destroys all ConnectionPools + * + * @throws Exception + */ + public void closeAll() throws Exception { + for (Iterator it = pools.iterator(); it.hasNext();) { + MemtextPool pool = (MemtextPool) it.next(); + pool.close(); + } + + } + + public void main(String args[]) { + try { + init("xx",MemtextPool.class, null); + } catch (Exception e) { + e.printStackTrace(); + } + int i = 1; + } + + public void invalidate(String poolname, Connection con) + throws DBServletException { + if (!pools.containsItemWithName(poolname)) + throw new DBServletException( + "Kann Connection nicht invalidieren - kein ConnectionPool " + + poolname + " gefunden."); + try { + PoolingDriver driver = (PoolingDriver) DriverManager + .getDriver("jdbc:apache:commons:dbcp:"); + + //driver.invalidateConnection(con); + driver.getConnectionPool(poolname).invalidateObject(con); + } catch (Exception e) { + e.printStackTrace(); + throw new DBServletException("Invalidating connection failed -" + e); + } + + } + + public void resetAllPools() + throws TransformerConfigurationException, KeyParentEqualException, + SQLException, DBServletException { + for (Iterator it = pools.iterator(); it.hasNext();) { + MemtextPool aPool = (MemtextPool) it.next(); + aPool.init(); + } + } + + public void clearLogFiles() throws IOException { + for (Iterator it = pools.iterator(); it.hasNext();) { + MemtextPool aPool = (MemtextPool) it.next(); + aPool.clearLogFiles(); + } + } +} + +//Created on 04.11.2004 at 20:18:11 als SxPools diff --git a/src/de/memtext/db/NichtAngemeldetException.java b/src/de/memtext/db/NichtAngemeldetException.java new file mode 100644 index 0000000..e2d6515 --- /dev/null +++ b/src/de/memtext/db/NichtAngemeldetException.java @@ -0,0 +1,22 @@ +package de.memtext.db; +public class NichtAngemeldetException extends Exception { + + public NichtAngemeldetException() { + super(); + } + + public NichtAngemeldetException(String message) { + super(message); + } + + public NichtAngemeldetException(String message, Throwable cause) { + super(message, cause); + } + + public NichtAngemeldetException(Throwable cause) { + super(cause); + } + +} + +//Created on 05.10.2004 at 13:12:23 \ No newline at end of file diff --git a/src/de/memtext/db/ProcedureSql.java b/src/de/memtext/db/ProcedureSql.java new file mode 100644 index 0000000..e8d318e --- /dev/null +++ b/src/de/memtext/db/ProcedureSql.java @@ -0,0 +1,101 @@ +package de.memtext.db; + +import de.memtext.util.StringUtils; +/** + * Hilfsklasse zum Erstellen von Prozeduraufrüfen für verschd. + * Datenbanken. + * Wird mit DB Object erstellt, z.B. ProcedureSql(DB.INFORMIX) + * dann setName() + * dann beliebig oft addParam(),oder addDateParam() + * Falls nach Aufruf der Prozedur ein select notwendig ist, + * reinsetzen mit setFinalSelect() + * zum Schluss. getFinishedCall für fertigen Datenbankspezifischen + * Prozeduraufruf + */ +public class ProcedureSql { + + private DB dbsystem; + private boolean isAddPossible = true,isNameSet, isFinished; + private String finalSelect = ""; + + private StringBuffer result = new StringBuffer(); + + public ProcedureSql(DB db) { + this.dbsystem = db; + if (dbsystem.equals(DB.INFORMIX)) + result.append("execute procedure "); + if (dbsystem.equals(DB.POSTGRES)) + result.append("select "); + + } + + public ProcedureSql(DB dbsystem, String procname) { + this(dbsystem); + result.append(procname + ("(")); + isNameSet=true; + } + public void setName(String procName) { + if (isNameSet)throw new IllegalStateException("Name wurde schon gesetzt"); + result.append(procName+("(")); + isNameSet=true; + } + public void addParam(String param) { + if (!isAddPossible) + throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen"); + result.append(param + ","); + } + public void addDateParam(String param) { + if (!isAddPossible) + throw new IllegalStateException("kann keine Parameter hinzufügen, vielleicht wurde getFinishedCall schon aufgerufen"); + + if (dbsystem.equals(DB.INFORMIX)) + result.append("date"); + if (dbsystem.equals(DB.POSTGRES)) + result.append("date_val"); + result.append("('" + param + "'),"); + } + public void setFinalSelect(String sel) { + finalSelect = sel; + } + + public String getFinishedCall() { + if (!isFinished) + finish(); + return result.toString(); + } + + private void finish() { + addClosingBracket(); + result.append(finalSelect); + isAddPossible = false; + isFinished = true; + } + + private void addClosingBracket() { + char lc=result.charAt(result.length()-1);// StringUtils.getLastChar(result); + if (lc==',') + StringUtils.deleteLastChar(result); + result.append(");"); + } + + public void addParam(Integer integer) { + addParam(integer.toString()); + } + + public void addParam(int in) { + addParam(new Integer(in).toString()); + } + + public void addParam(Object param) { + addParam(param.toString()); + } + + public static void main(String args[]) { + ProcedureSql p=new ProcedureSql(DB.POSTGRES,"test"); + p.addParam(23); + System.out.println(p.getFinishedCall()); + } +} + + +//Created on 03.12.2003 at 15:56:43 \ No newline at end of file diff --git a/src/de/memtext/db/PropDescriptor.java b/src/de/memtext/db/PropDescriptor.java new file mode 100644 index 0000000..0c6540f --- /dev/null +++ b/src/de/memtext/db/PropDescriptor.java @@ -0,0 +1,72 @@ +package de.memtext.db; + +import de.memtext.baseobjects.NamedIdObject; +/** + * Beschreibt eine (zusätzliche) in der Datenbank hinterlegt Eigenschaft. + * (z.B. Accident meister) + */ +public class PropDescriptor extends NamedIdObject { +//wie heißt die Spalte in der DB + private String colname; + //bei Combobox sql für quelle select key,name from xx + private String quelle; + //soll auf dem Bildschirm sichtbar sein + private boolean isVisible; + + private String defaultkey; + private int sortnr; + + + public PropDescriptor() { + + } + + public PropDescriptor(Object id, String name) { + super(id,name); + } + + public String getColname() { + return colname; + } + + public void setColname(String colname) { + this.colname = colname; + } + + public String getDefaultkey() { + return defaultkey; + } + + public void setDefaultkey(String defaultkey) { + this.defaultkey = defaultkey; + } + + public boolean isVisible() { + return isVisible; + } + + public void setVisible(boolean isVisible) { + this.isVisible = isVisible; + } + + public String getQuelle() { + return quelle; + } + + public void setQuelle(String quelle) { + this.quelle = quelle; + } + + public int getSortnr() { + return sortnr; + } + public void setSortnr(int sortnr) { + this.sortnr = sortnr; + } + public String toString() + { + return getName(); + } +} + +//Created on 17.05.2005 at 10:17:03 diff --git a/src/de/memtext/db/PropsReader.java b/src/de/memtext/db/PropsReader.java new file mode 100644 index 0000000..059316a --- /dev/null +++ b/src/de/memtext/db/PropsReader.java @@ -0,0 +1,88 @@ +package de.memtext.db; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +import de.memtext.util.CryptUtils; + +public class PropsReader { + private static byte key[] = { (byte) 255, (byte) 221, (byte) 127, + (byte) 109, (byte) 129 }; + private static int keyLength = key.length; +/* + * + * 28.10.08 EInfache Verschlüsselungsmethode wird nicht mehr unterstützt + */ + public static String check(String mandantenID, String d) throws Exception { + String result = ""; + // Logger.getLogger("superx_" + mandantenID).log(Level.FINEST, + // "Verschlüsseltes Passwort " + d); + if (d.startsWith("sx_des")) { + result = CryptUtils.decryptStringDES(d.substring(6)); + } + else { + result=d; + /* try { + byte[] tmp; + tmp = d.getBytes(); + + int size = (byte) (tmp[0] ^ key[0 % keyLength]); + int index = (byte) (tmp[1] ^ key[1 % keyLength]); + byte de[] = new byte[size]; + + for (int i = index; i < (size + index); i++) { + de[i - index] = (byte) (tmp[i] ^ key[i % keyLength]); + } + result = new String(de); + } catch (Exception e) { + throw new DBServletException( + "Konnte Passwort nicht entschlüsseln (altes Verfahren). Bitte mit propadmin.x prüfen.\n" + + e); + }*/ + } + return result; + } + + public static Properties prepareProps(File propfile) throws IOException, + FileNotFoundException, Exception { + Properties props = new Properties(); + if (!propfile.exists()) { + throw new IOException("Datei nicht gefunden: " + propfile); + } + InputStream is = new FileInputStream(propfile); + + if (is != null) { + props.load(is); + is.close(); + } else { + throw new IOException("cannot open " + propfile); + } + String mandantenID = props.getProperty("MandantenID"); + if (mandantenID == null) + mandantenID = "default"; + props.put("user", props.getProperty("connectionName")); + props.put("password", check(mandantenID, props + .getProperty("connectionPassword"))); + + if (props.getProperty("driverName").indexOf("postgres") > -1) { + props.put("charSet", "Latin-1"); + props.put("DateStyle", "German, DMY"); + // props.put("DateStyle", "ISO, DMY"); + } + if (props.getProperty("driverName").indexOf("informix") > -1) + + { + props.put("GL_DATETIME", "%d.%m.%Y %T"); + props.put("CLIENT_LOCALE", "de_de.8859-1"); + } + return props; + } +} + +//Created on 27.04.2005 at 09:07:18 diff --git a/src/de/memtext/db/RestrictionCollector.java b/src/de/memtext/db/RestrictionCollector.java new file mode 100644 index 0000000..a43b34b --- /dev/null +++ b/src/de/memtext/db/RestrictionCollector.java @@ -0,0 +1,90 @@ +package de.memtext.db; +/** + * collects restrictions for sql-clauses, manages where and + * and what to delete + * take care of inital where yourself + */ +public class RestrictionCollector { + private StringBuffer restrict = new StringBuffer(); + + private int count=0; + public RestrictionCollector() { + } + public RestrictionCollector(String restriction) { + restrict.append(restriction); + count = 1; + + } + public boolean isSomethingAdded() + { + return count>0; + } + public void addAndRestriction(StringBuffer restriction) { + addAndRestriction(restriction.toString()); + } + public void addAndRestriction(String restriction) { + if (restriction==null||restriction.length()<3) + throw new IllegalArgumentException("Not OK:"+restriction); + boolean isNewlineAtStart=restriction.startsWith("\n"); + restriction = restriction.trim(); + if (isNewlineAtStart) restriction="\n"+restriction; + if (restriction.substring(0, 3).equalsIgnoreCase("and")) + restriction = restriction.substring(3); + if (count>0) + restrict.append(" and " + restriction + " "); + else + restrict.append(restriction + " "); + count++; + } + + public void addOrRestriction(StringBuffer restriction) { + addOrRestriction(restriction.toString()); + } + public void addOrRestriction(String restriction) { + if (restriction==null||restriction.length()<3) + throw new IllegalArgumentException("Not OK:"+restriction); + + restriction = restriction.trim(); + if (restriction.substring(0, 3).equalsIgnoreCase("or ")) + restriction = restriction.substring(3); + + if (count>0) + restrict.append(" or " + restriction + " "); + else + restrict.append(restriction + " "); + count++; + } + public void addOrRestriction(RestrictionCollector collector) { + addOrRestriction(collector.toString()); + } + public String toString() { + if (count>0) + return restrict.toString(); + else + return ""; + } + public String toStringInclusiveWhere() + { + if (count>0) + return " where "+restrict; + else + return ""; + } + public int getArgumentCount() + { + return count; + } + public void addAndRestriction(RestrictionCollector collector) { + if (collector.getArgumentCount()>1) + addAndRestriction( collector.toString()); + else + addAndRestriction( collector.toString() ); + } + public static void main(String[] args) { + RestrictionCollector r = new RestrictionCollector(); + r.addAndRestriction(" AND 1=1"); + r.addAndRestriction("2=2"); + System.out.println(r); + } +} +// Created on 23.07.2003 \ No newline at end of file diff --git a/src/de/memtext/db/SampleApp.java b/src/de/memtext/db/SampleApp.java new file mode 100644 index 0000000..b572d69 --- /dev/null +++ b/src/de/memtext/db/SampleApp.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2001-2004, The HSQL Development Group All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the HSQL Development Group nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package de.memtext.db; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; + +public class SampleApp extends JFrame { + private Connection con = null; + private String path = ""; // null , "" or "." for current directory + private String dbname = "testing"; + + public SampleApp() throws ClassNotFoundException, SQLException, IOException { + super("SampleApp"); + initDb(); + + JLabel lbl = new JLabel("got a connection to " + + con.getMetaData().getURL()); + this.getContentPane().add(lbl); + this.setSize(600, 400); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent we) { + try { + String url=con.getMetaData().getURL(); + Statement stmt= con.createStatement(); + stmt.execute("shutdown"); + stmt.close(); + con.close(); + //delete all temporary files that may exists + HsqlStandaloneMgr.deleteTmpFiles( url,path, dbname); + } catch (SQLException e) { + e.printStackTrace(); + } + System.exit(0); + } + }); + + } + + private void initDb() throws ClassNotFoundException, SQLException, + IOException { + + if (!HsqlStandaloneMgr.isDatabaseOpen(path, dbname)) { + //if the database isn't open yet, we just open a regular connection + //the system username is written to a special properties file + con = HsqlStandaloneMgr.getConnection(path, dbname, "sa", ""); + Statement stmt = con.createStatement(); + stmt + .execute("drop table test if exists;create table test( col1 integer);insert into test values(1);checkpoint;"); + stmt.close(); + } else + // the database is already open + { + //you can decide if the temporary copy should be read-only mode + //if not, all changes to the database will be lost after closing + // the connection + boolean isReadOnlyModeWanted = true; + int result = HsqlStandaloneMgr.askUser(this, path, dbname, + isReadOnlyModeWanted); + if (result == JOptionPane.YES_OPTION) { + con = HsqlStandaloneMgr.getTmpConnection(this, path, dbname, + "sa", "", isReadOnlyModeWanted); + } else + { +// opening of temp. copy not wanted + System.exit(0); + } + } + } + + public static void main(String args[]) { + + try { + SampleApp app = new SampleApp(); + app.show(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} + +//Created on 23.10.2004 at 12:10:38 diff --git a/src/de/memtext/db/SchemaReader.java b/src/de/memtext/db/SchemaReader.java new file mode 100644 index 0000000..ad0f1c4 --- /dev/null +++ b/src/de/memtext/db/SchemaReader.java @@ -0,0 +1,48 @@ +package de.memtext.db; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; + +import de.memtext.util.StringUtils; + +public class SchemaReader { + + public static void main(String[] args) { + if (args.length != 1) { + System.out.println("SchemaReader db.properties"); + System.exit(1); + } + try { + Connection con = ConnectionCreator.getConnectionCryptPassword(args[0],"driverName","connectionURL","connectionName","connectionPassword"); + DatabaseMetaData md = con.getMetaData(); + ResultSet myTables = md.getTables(null, null, null, null); + StringBuffer result = new StringBuffer(); + if (myTables != null) { + while (myTables.next()) { + String tabname = myTables.getString(3); + result.append("TABLE " + tabname + "\n"); + ResultSet cols = md.getColumns(null, null, tabname, null); + while (cols.next()) { + result.append(cols.getString(4) + ":" + + cols.getObject(5) + "\n"); + } + result.append("----\n"); + } + } + StringUtils.write(new File("schema.txt"),result.toString()); + + } catch (IOException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } +} + +//Created on 21.02.2006 at 10:38:08 diff --git a/src/de/memtext/db/ValueRandomizer.java b/src/de/memtext/db/ValueRandomizer.java new file mode 100644 index 0000000..c735e71 --- /dev/null +++ b/src/de/memtext/db/ValueRandomizer.java @@ -0,0 +1,266 @@ +package de.memtext.db; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Enumeration; +import java.util.Random; +import java.util.Vector; +/** + * Randomizes values in a database. + * Reads all values of a given table column (select distinct x from..) and + * multiplies all occurences of a single value (e.g. 150) with a factor between + * minFactor and maxFactor (e.g. 150*1.1 -> all entries with 150 become 165) + * + * if boolean printOutOnly is true the update sql statements are only logged + * to console, not performed + * */ +public class ValueRandomizer { + //private static String driver = "org.hsqldb.jdbcDriver"; + private static String driver = "org.postgresql.Driver"; + //private static String dbUrl = "jdbc:hsqldb:hsql://localhost:9999"; + private static String dbUrl = "jdbc:postgresql://localhost:5432/superx"; + private static String username = "superx"; //"joolap"; + private static String password = ""; //"loopja3000"; + private static String tablename = "cob_busa"; + private static String colname = "betrag"; //"value"; + private static String datenart = "DOUBLE"; //or "INTEGER"; + + private static double minFactor = 0.6; + private static double maxFactor = 1.8; + + private static boolean printOutOnly = false; + private static Statement stat; + private static Random r = new Random(); + public static void main(String args[]) { + + try { + Class.forName(driver); + Connection conn; + System.out.println("establishing connection to " + dbUrl); + conn = DriverManager.getConnection(dbUrl, username, password); + stat = conn.createStatement(); + System.out.println("done."); + out(); + stat.close(); + conn.close(); + System.exit(-1); + + + //alle werte einlesen + Vector werte = readDistinctValues(); + if (datenart.toUpperCase().equalsIgnoreCase("DOUBLE")) { + //massiveRandomizeDouble(werte); + randomize(werte); + } else //integer + { + massiveRandomizeInteger(werte); + } + + System.out.println("Randomizierung erfolgreich beendet"); + } catch (Exception e) { + System.out.println(e.toString()); + System.exit(0); + } + + } + /** + * randomizes in categories of values + * only for double + * @param werte + */ + private static void randomize(Vector werte) { + int categories = 15; + int valuesPerCategory = (int) werte.size() / categories; + StringBuffer updates = new StringBuffer(); + float limit = 0, limit2; + for (int i = 1; i < categories; i++) { + limit = + (float) ((Double) werte.get(i * valuesPerCategory)) + .doubleValue(); + updates.append( + "update " + + tablename + + " set " + + colname + + "=" + + colname + + "*" + + getRndFactor() + + " where " + + colname + + ">" + + limit); + if (i > 1) { + limit2 = + (float) ((Double) werte.get((i - 1) * valuesPerCategory)) + .doubleValue(); + updates.append(" and " + colname + "<" + limit2); + } + updates.append(";\n"); + } + limit = + (float) ((Double) werte.get((categories - 1) * valuesPerCategory)) + .doubleValue(); + updates.append( + "update " + + tablename + + " set " + + colname + + "=" + + colname + + "*" + + getRndFactor() + + " where " + + colname + + "<" + + limit + + ";"); + + System.out.println(updates); + } + /** + * * multiplies all occurences of a single value (e.g. 150) with a factor between + * minFactor and maxFactor (e.g. 150*1.1 -> all entries with 150 become 165) + + * @param werte + * @throws SQLException + */ + private static void massiveRandomizeInteger(Vector werte) + throws SQLException { + Integer einWert; + String upd = null; + for (Enumeration en = werte.elements(); en.hasMoreElements();) { + einWert = (Integer) en.nextElement(); + int neuerwert = (int) (einWert.intValue() * getRndFactor()); + upd = + "update " + + tablename + + " set " + + colname + + "=" + + neuerwert + + " where " + + colname + + "=" + + einWert.toString() + + ";"; + + if (printOutOnly) + System.out.println(upd); + else + stat.executeUpdate(upd); + } + + } + /** + * * multiplies all occurences of a single value (e.g. 150) with a factor between + * minFactor and maxFactor (e.g. 150*1.1 -> all entries with 150 become 165) + + * @param werte + * @throws SQLException + */ + private static void massiveRandomizeDouble(Vector werte) + throws SQLException { + Double einWert; + double zufallswert; + String upd; + int i = 0; + int count = werte.size(); + for (Enumeration en = werte.elements(); en.hasMoreElements();) { + einWert = (Double) en.nextElement(); + i++; + zufallswert = einWert.doubleValue() * getRndFactor(); + upd = + "update " + + tablename + + " set " + + colname + + "=" + + zufallswert + + " where " + + colname + + "=" + + einWert + + ";"; + if (printOutOnly) + System.out.println(upd); + else { + stat.executeUpdate(upd); + if (i % 20 == 0) + System.out.println("Done " + i + " updates of " + count); + } + + } + } + private static float getRndFactor() { + double rnd = Math.abs(r.nextDouble()); + while (rnd < minFactor) + rnd += minFactor; + while (rnd > maxFactor) + rnd -= 0.05; + return (float) rnd; + } + private static Vector readDistinctValues() throws SQLException { + Vector werte = new Vector(); + ResultSet rs = null; + Object item; + System.out.println( + "Alle werte einlesen:" + + "select distinct " + + colname + + " from " + + tablename + + " order by 1 DESC"); + + rs = + stat.executeQuery( + "select distinct " + + colname + + " from " + + tablename + + " order by " + + colname + + " DESC"); + while (rs.next()) { + item = rs.getObject(1); + werte.add(item); + } + rs.close(); + return werte; + } + + private static void out() { + try { + FileWriter fw = + new FileWriter("c:\\cygwin\\home\\superx\\cob_busa.unl"); + BufferedWriter bw = new BufferedWriter(fw); + StringBuffer buf = new StringBuffer(); + + ResultSet rs = stat.executeQuery("select * from cob_busa"); + + int cols = 20;String s;Object o; + while (rs.next()) { + for (int i = 1; i <= cols; i++) + {o=rs.getObject(i); + if (o==null) s=""; + else s=o.toString(); + + buf.append(s.trim() + "^");} + buf.append("^\n"); + + } + rs.close(); + + bw.write(buf.toString()); + bw.close(); + fw.close(); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("done"); + } +} diff --git a/src/de/memtext/db/dataexchange/MyRequest.java b/src/de/memtext/db/dataexchange/MyRequest.java new file mode 100644 index 0000000..b41ac1e --- /dev/null +++ b/src/de/memtext/db/dataexchange/MyRequest.java @@ -0,0 +1,69 @@ +package de.memtext.db.dataexchange; + +/** + * Insert the type's description here. + * Creation date: (29.11.2002 16:53:06) + * @author: + */ +public class MyRequest implements java.io.Serializable { +static final long serialVersionUID = -2L; +static final int NORMAL=1; +static final int EXPECT_ONE_UPDATE=2; + +private String sql; +private String name; +private Object[] params; +private int type; +public MyRequest(String name,String sql,Object[] params) +{ + this(name,sql,params,NORMAL); +} +public MyRequest(String name,String sql,Object[] params,int type) +{ +setName(name); +setSql(sql); +setParams(params); +setType(type); +} + +public int getType() +{ +return type; +} + +public void setType(int type) +{ +this.type=type; +} +public String getName() +{ +return name; +} + +public void setName(String name) +{ +this.name=name; +} + +public Object[] getParams() +{ +return params; +} + +public void setParams(Object[] params) +{ +this.params=params; +} + +public String getSql() +{ +return sql; +} + +public void setSql(String sql) +{ +this.sql=sql; +} + +} + diff --git a/src/de/memtext/db/dataexchange/MyServletResponse.java b/src/de/memtext/db/dataexchange/MyServletResponse.java new file mode 100644 index 0000000..385af59 --- /dev/null +++ b/src/de/memtext/db/dataexchange/MyServletResponse.java @@ -0,0 +1,49 @@ +package de.memtext.db.dataexchange; + +import java.util.Vector; +/** + * Insert the type's description here. + * Creation date: (28.11.2002 19:25:34) + * @author: + */ +public class MyServletResponse implements java.io.Serializable { + static final long serialVersionUID = -3L; + private Vector result; + private boolean OK; + private Exception exception; + private int updatedRowsCount; + + /** + * MyServletResponse constructor comment. + */ + public MyServletResponse(Vector result, boolean OK, Exception exception) { + this.result = result; + this.OK = OK; + this.exception = exception; + } + public Exception getException() { + return exception; + } + public Vector getResult() { + return result; + } + public boolean isOK() { + return OK; + } + public void setException(Exception exception) { + this.exception = exception; + } + public void setOK(boolean OK) { + this.OK = OK; + } + public void setResult(Vector result) { + this.result = result; + } + public int getUpdatedRowsCount() { + return updatedRowsCount; + } + + public void setUpdatedRowsCount(int updatedRowsCount) { + this.updatedRowsCount = updatedRowsCount; + } +} \ No newline at end of file diff --git a/src/de/memtext/dlg/AboutDialog.java b/src/de/memtext/dlg/AboutDialog.java new file mode 100644 index 0000000..483866c --- /dev/null +++ b/src/de/memtext/dlg/AboutDialog.java @@ -0,0 +1,49 @@ +package de.memtext.dlg; + +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.HeadlessException; +import java.io.IOException; + +import javax.swing.JLabel; + +import de.memtext.util.BrowserLauncher; +import de.memtext.util.WindowUtils; +import de.memtext.widgets.VerticalBox; + +public class AboutDialog extends OkDlg { + private JLabel infoLbl, homepageLabel; + public AboutDialog( + Frame parent, + String title, + String infoText, + String homePageLink, + final String homepageUrl) + throws HeadlessException { + super(parent, title); + infoLbl = new JLabel(infoText); + homepageLabel = new JLabel("" + homePageLink); + homepageLabel.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + + try { + BrowserLauncher.openURL(homepageUrl); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + + VerticalBox vbox = new VerticalBox(); + vbox.addWithCenterAlignment(infoLbl); + vbox.addWithCenterAlignment(homepageLabel); + setCenter(vbox); + pack(); + Dimension size = this.getSize(); + setSize(size.width + 30, size.height + 30); + WindowUtils.center(this); + } + +} + +//Created on 18.06.2004 at 12:20:35 \ No newline at end of file diff --git a/src/de/memtext/dlg/DialogWithExit.java b/src/de/memtext/dlg/DialogWithExit.java new file mode 100644 index 0000000..b304edd --- /dev/null +++ b/src/de/memtext/dlg/DialogWithExit.java @@ -0,0 +1,113 @@ +package de.memtext.dlg; + +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.GraphicsConfiguration; +import java.awt.HeadlessException; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JComponent; +import javax.swing.JDialog; + +public class DialogWithExit extends JDialog { + + public DialogWithExit() throws HeadlessException { + super(); + initMe(); + } + + public DialogWithExit(Frame owner) throws HeadlessException { + super(owner); + initMe(); + } + + public DialogWithExit(Frame owner, boolean arg1) throws HeadlessException { + super(owner, arg1); + initMe(); + } + + public DialogWithExit(Frame owner, String arg1) throws HeadlessException { + super(owner, arg1); + initMe(); + } + + public DialogWithExit(Frame owner, String arg1, boolean arg2) + throws HeadlessException { + super(owner, arg1, arg2); + initMe(); + } + + public DialogWithExit( + Frame owner, + String arg1, + boolean arg2, + GraphicsConfiguration arg3) { + super(owner, arg1, arg2, arg3); + initMe(); + } + + public DialogWithExit(Dialog owner) throws HeadlessException { + super(owner); + initMe(); + } + + public DialogWithExit(Dialog owner, boolean arg1) throws HeadlessException { + super(owner, arg1); + initMe(); + } + + public DialogWithExit(Dialog owner, String arg1) throws HeadlessException { + super(owner, arg1); + initMe(); + } + + public DialogWithExit(Dialog owner, String arg1, boolean arg2) + throws HeadlessException { + super(owner, arg1, arg2); + } + + public DialogWithExit( + Dialog owner, + String arg1, + boolean arg2, + GraphicsConfiguration arg3) + throws HeadlessException { + super(owner, arg1, arg2, arg3); + initMe(); + } + private void initMe(){ + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent we) { + exit(); + } + }); +} +/** + * called if window is closed, does nothing by default, + * subclasses can override + * + */ +protected void exit() { +} + +//man könnte noch abfragen ob auch wirklich Borderlayout benutzt +//wird +/** + * installs a component in the center of the dialog + * @param comp + */ +public void setCenter(JComponent comp) { + this.getContentPane().add(comp, BorderLayout.CENTER); +} +/** + * installs a component in the notrh of the dialog + * @param comp + */ +public void setNorth(JComponent comp) { + this.getContentPane().add(comp, BorderLayout.NORTH); +} +} + +//Created on 21.11.2003 \ No newline at end of file diff --git a/src/de/memtext/dlg/EnterDateDlg.java b/src/de/memtext/dlg/EnterDateDlg.java new file mode 100644 index 0000000..aa60df5 --- /dev/null +++ b/src/de/memtext/dlg/EnterDateDlg.java @@ -0,0 +1,57 @@ +package de.memtext.dlg; + +import java.awt.Component; +import java.text.ParseException; + +import javax.swing.JOptionPane; + +import de.memtext.util.DateUtils; +import de.memtext.widgets.WarningMessage; + +public class EnterDateDlg { + private java.util.Date date; + private Component parentComp; + private String title, text; + + public EnterDateDlg(Component parentComp, String text, String title) { + this.parentComp = parentComp; + this.title = title; + this.text = text; + } + + public boolean wasOkSelected() + { + return date!=null; + } + public void show() { + date = null; + String in; + boolean ok = false; + while (!ok) { + in = JOptionPane.showInputDialog(parentComp, text, title, + JOptionPane.QUESTION_MESSAGE); + if (in == null) { + date = null; + ok = true; + } else { + try { + date = DateUtils.parse(in); + ok = true; + } catch (ParseException e) { + WarningMessage.show(parentComp, "Ungültige Datumseingabe", + title); + } + } + } + } + + public static void main(String args[]) { + new EnterDateDlg(null, "test", "title").show(); + } + + public java.util.Date getDate() { + return date; + } +} + +//Created on 18.08.2004 at 12:36:12 diff --git a/src/de/memtext/dlg/ImportDlg.java b/src/de/memtext/dlg/ImportDlg.java new file mode 100644 index 0000000..13e868e --- /dev/null +++ b/src/de/memtext/dlg/ImportDlg.java @@ -0,0 +1,63 @@ +package de.memtext.dlg; + +import java.awt.Frame; +import java.io.File; + +import javax.swing.JLabel; + +import de.memtext.util.FilenamesFilter; +import de.memtext.util.WindowUtils; +import de.memtext.widgets.FileSelectionPanel; +import de.memtext.widgets.VerticalBox; + +public class ImportDlg extends OkCancelDlg { + private JLabel lblTop = new JLabel(); + private FileSelectionPanel fsp = new FileSelectionPanel("Datei"); + + public ImportDlg(Frame owner, String title, String infoTxt) { + super(owner, title, true); + VerticalBox vbox = new VerticalBox(); + lblTop.setText(infoTxt); + vbox.add(lblTop); + vbox.add(fsp); + setCenter(vbox); + this.pack(); + WindowUtils.center(this); + + } + + public void setCurrentDir(File defaultdir) + { + fsp.setCurrentDir(defaultdir); + } + /** + + * @param endings + */ + public void setFileFilter(String endings) { + fsp.setFileFilter(new FilenamesFilter("CSV oder XML Dateien", endings)); + } + + protected void performOk() { + this.dispose(); + } + + protected void performCancel() { + this.dispose(); + } + + public File getSelectedFile() { + return fsp.getSelectedFile(); + } + + public static void main(String[] args) { + ImportDlg d = + new ImportDlg( + null, + "titl", + "Unfälle importieren aus CSV- oder XML-Datei (z.B. Universum Unfallanzeige 3.0)"); + d.setFileFilter(".xml|.csv"); + d.show(); + } +} +//Created on 19.02.2004 at 11:56:06 \ No newline at end of file diff --git a/src/de/memtext/dlg/InputDialog.java b/src/de/memtext/dlg/InputDialog.java new file mode 100644 index 0000000..176cf56 --- /dev/null +++ b/src/de/memtext/dlg/InputDialog.java @@ -0,0 +1,40 @@ +package de.memtext.dlg; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import javax.swing.JOptionPane; + +/** + Convienience class to create and Input Dialog with JOptionPane. + I.e. selection item from drop down (combobox) + */ +public class InputDialog { + private String title, txt; + private ArrayList list; + + public InputDialog(Collection col, String title, String txt) { + super(); + this.title = title; + this.txt = txt; + list = new ArrayList(); + if (col==null||col.size()==0) throw new IllegalArgumentException("Collection mustn't be null or empty"); + for (Iterator it = col.iterator(); it.hasNext();) { + list.add(it.next()); + } + } + + public Object show() { + return JOptionPane.showInputDialog( + null, + txt, + title, + JOptionPane.QUESTION_MESSAGE, + null, + list.toArray(), + null); + } +} + + diff --git a/src/de/memtext/dlg/LoginDlg.java b/src/de/memtext/dlg/LoginDlg.java new file mode 100644 index 0000000..9770807 --- /dev/null +++ b/src/de/memtext/dlg/LoginDlg.java @@ -0,0 +1,67 @@ +package de.memtext.dlg; + +import javax.swing.JFrame; + +import de.memtext.widgets.LabeledPasswordField; +import de.memtext.widgets.LabeledTextField; +import de.memtext.widgets.MultilineEditPanel; + +/** + A Login Dialog + */ +public class LoginDlg extends OkCancelDlg { + private LabeledTextField lUser = new LabeledTextField("Kennung", 15); + private LabeledPasswordField lPass = + new LabeledPasswordField("Passwort", 15); + public LoginDlg(JFrame frame, String title) { + super(frame, title,true); + initdlg(); + } + + private void initdlg() { + MultilineEditPanel vbox = new MultilineEditPanel(); + vbox.add(lUser); + vbox.add(lPass); + this.setCenter(vbox); + this.pack(); + } + + protected void performOk() { + this.hide(); + } + public void setUsername(String username) + { + lUser.setValue(username); + } + public void setPassword(String password) + { + lPass.setValue(password); + } + protected void performCancel() { + this.hide(); + } + public String getUsername() { + return lUser.getValue().toString(); + } + /** + * can be returned only once, cleared for security reasons + * afterwards + * @return + */ + public String getPassword() { + /* char[] pw = passw.getPassword(); + String result = new String(pw); + for (int i = 0; i < pw.length; i++) { + pw[i] = 0; + } + return result; + */ + return lPass.getValue().toString(); + } + public static void main(String args[]) { + LoginDlg d=new LoginDlg(null,"asdf"); + d.show(); + System.out.println(d.getPassword()); + + } +} diff --git a/src/de/memtext/dlg/NodeSelectionDlg.java b/src/de/memtext/dlg/NodeSelectionDlg.java new file mode 100644 index 0000000..f111658 --- /dev/null +++ b/src/de/memtext/dlg/NodeSelectionDlg.java @@ -0,0 +1,113 @@ +package de.memtext.dlg; + +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeCellRenderer; +import javax.swing.tree.TreeNode; + +import de.memtext.util.WindowUtils; + +/** + * A dialog that presents a tree and allows the selection of + * one node or to clear the selection + */ +public class NodeSelectionDlg extends OkCancelClearDlg { + private JTree tree; + private Object selectedNode = null; + private String title; + public NodeSelectionDlg(Frame owner, String title, JTree tree) { + super(owner, title); + this.tree = tree; + this.title=title; + this.setCenter(new JScrollPane(tree)); + selectedNode = null; + if (tree.getLastSelectedPathComponent() != null) + selectedNode = (TreeNode) tree.getLastSelectedPathComponent(); + this.pack(); + WindowUtils.center(this); + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent we) { + exit(); + } + }); + } + /** + * called if window is closed, does nothing by default, + * subclasses can override + * + */ + protected void exit() { + } + + public NodeSelectionDlg( + Frame owner, + String title, + DefaultTreeModel treeModel) { + this(owner, title, new JTree(treeModel)); + } + public NodeSelectionDlg(Frame owner, String title, TreeNode node) { + this(owner, title, new JTree(node)); + } + /** + * can be overriden by subclasses to perform a check if + * the selected node is OK + * @return + */ + protected boolean isSelectedNodeOk(TreeNode testme) + { + return true; + } + protected void performOk() { + if (!isSelectedNodeOk((TreeNode)tree.getLastSelectedPathComponent())) return; + selectedNode = tree.getLastSelectedPathComponent(); + this.setVisible(false); + } + + protected void performCancel() { + this.setVisible(false); + } + public TreeNode getSelectedNode() { + return selectedNode == null ? null : (TreeNode) selectedNode; + } + protected void performClear() { + selectedNode = null; + tree.clearSelection(); + this.setVisible(false); + } + public void setSize(Dimension dim) { + super.setSize(dim); + WindowUtils.center(this); + } + public void setSize(int x, int y) { + super.setSize(x, y); + WindowUtils.center(this); + } + public static void main(String a[]) { + NodeSelectionDlg t = new NodeSelectionDlg(null, "adsf", new JTree()); + t.pack(); + t.show(); + System.out.println(t.getSelectedNode()); + t.show(); + System.out.println(t.getSelectedNode()); + } + public void setNode(TreeNode node) { + tree.setModel(new DefaultTreeModel(node)); + selectedNode=null; + } + public void setCellRenderer(TreeCellRenderer renderer) { + tree.setCellRenderer(renderer); + } + public String getTitle() { + return title; + } + public String getInfoText() { + return title; + } +} +//Created on 17.11.2003 \ No newline at end of file diff --git a/src/de/memtext/dlg/ObjectCheckBoxDlg.java b/src/de/memtext/dlg/ObjectCheckBoxDlg.java new file mode 100644 index 0000000..16d63cc --- /dev/null +++ b/src/de/memtext/dlg/ObjectCheckBoxDlg.java @@ -0,0 +1,54 @@ +package de.memtext.dlg; + +import java.awt.Frame; +import java.awt.HeadlessException; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.JScrollPane; + +import de.memtext.widgets.ObjectCheckBox; +import de.memtext.widgets.VerticalBox; +import de.memtext.util.WindowUtils; + +public class ObjectCheckBoxDlg extends OkCancelDlg { + private List boxList = new LinkedList(); + private List selectedObjectsList; + public ObjectCheckBoxDlg(Frame frame, String title, List itemList,boolean selected) + throws HeadlessException { + super(frame, title); + VerticalBox vbox = new VerticalBox(); + for (Iterator it = itemList.iterator(); it.hasNext();) { + Object element = (Object) it.next(); + ObjectCheckBox cb = new ObjectCheckBox(element,selected); + boxList.add(cb); + vbox.add(cb); + } + this.setCenter(new JScrollPane(vbox)); + this.pack(); + WindowUtils.center(this); + } + + protected void performOk() { + selectedObjectsList=new LinkedList(); + for (Iterator it = boxList.iterator(); it.hasNext();) { + ObjectCheckBox element = (ObjectCheckBox) it.next(); + if (element.isSelected()) + selectedObjectsList.add(element.getObject()); + } + this.hide(); + } + + protected void performCancel() { + selectedObjectsList=new LinkedList(); + this.hide(); + } + + public List getSelectedObjectsList() { + return selectedObjectsList; + } + +} + +//Created on 26.11.2003 at 12:47:31 \ No newline at end of file diff --git a/src/de/memtext/dlg/OkCancelClearDlg.java b/src/de/memtext/dlg/OkCancelClearDlg.java new file mode 100644 index 0000000..0a55ea4 --- /dev/null +++ b/src/de/memtext/dlg/OkCancelClearDlg.java @@ -0,0 +1,72 @@ +package de.memtext.dlg; + +import java.awt.Frame; +import java.awt.HeadlessException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; + +/** + * Abstract Dialog in which OK or Cancel can be clicked. + * Subclasses must implement performCancel and performOk. + * setCenter for convenience. + * + It's important that clients don't call + getContentPane().setLayout(new BorderLayout()) or something like that, + because that will cause southPanel to disappear + */ +public abstract class OkCancelClearDlg + extends OkCancelDlg + { + private boolean wasClearSelected; + protected JButton btnClear = new JButton("Leeren"); + /** + * Constructor for OkCancelClearDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkCancelClearDlg(Frame arg0, String title) + throws HeadlessException { + super(arg0, title, true); + initOkCancelClearDlg(); + } + + private void initOkCancelClearDlg() { + + btnClear.setActionCommand("Clear"); + btnClear.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + wasOkSelected = false; + wasClearSelected = true; + performClear(); + } + }); + addAfterCancel(btnClear); + } + public boolean wasClearSelected() { + return wasClearSelected; + } + protected abstract void performClear(); + public static void main(String[] args) { + + OkCancelClearDlg dlg = new OkCancelClearDlg(new JFrame(), "test") { + protected void performOk() { + } + + protected void performCancel() { + } + + protected void performClear() { + } + }; + + // dlg.addAboveOK(new JLabel("bla")); + dlg.setCenter(new JLabel("cnter")); + dlg.pack(); + dlg.show(); + } +} diff --git a/src/de/memtext/dlg/OkCancelDlg.java b/src/de/memtext/dlg/OkCancelDlg.java new file mode 100644 index 0000000..630f62d --- /dev/null +++ b/src/de/memtext/dlg/OkCancelDlg.java @@ -0,0 +1,200 @@ +package de.memtext.dlg; + +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.HeadlessException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; + +import de.memtext.widgets.HorizontalBox; +import de.memtext.widgets.VerticalBox; + +/** + * Abstract Dialog in which OK or Cancel can be clicked. + * Subclasses must implement performCancel and performOk. + * setCenter for convenience. + * + It's important that clients don't call + getContentPane().setLayout(new BorderLayout()) or something like that, + because that will cause southPanel to disappear + */ +public abstract class OkCancelDlg + extends DialogWithExit + { + private OkCancelPanel pOkCancel; + private HorizontalBox boxAboverOkCancel = new HorizontalBox(); + protected boolean wasOkSelected,wasCancelSelected; + public OkCancelDlg(Frame owner, String title, boolean isModal) { + super(owner, title, isModal); + initOkCancelDlg(); + } + + /** + * Constructor for OkCancelDlg. + * @param arg0 + * @param arg1 + * @param arg2 + * @throws HeadlessException + */ + public OkCancelDlg(Frame frame, String title) throws HeadlessException { + super(frame, title, true); + initOkCancelDlg(); + } + + /** + * Constructor for OkCancelDlg. + * @param arg0 + * @throws HeadlessException + */ + public OkCancelDlg(Dialog arg0) throws HeadlessException { + super(arg0, true); + initOkCancelDlg(); + } + + /** + * Constructor for OkCancelDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkCancelDlg(Dialog arg0, String arg1) throws HeadlessException { + super(arg0, arg1, true); + initOkCancelDlg(); + } + + private void initOkCancelDlg() { + //this.setContentPane(new OneTimeInitContentPane()); + VerticalBox pSouth = new VerticalBox(); + pOkCancel = new OkCancelPanel(); + pSouth.add(boxAboverOkCancel); + pSouth.add(pOkCancel); + + this.getContentPane().add(pSouth, BorderLayout.SOUTH); + pOkCancel.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent ae) + { + String cmd = ae.getActionCommand(); + if (cmd.equals("OK")) { + wasOkSelected = true; + wasCancelSelected=false; + performOk(); + } + + if (cmd.equals("Cancel")) { + wasOkSelected = false; + wasCancelSelected=true; + performCancel(); + } + } + }); + this.getRootPane().setDefaultButton(pOkCancel.getBtnOk()); + } + public void addAboveOK(JComponent comp) { + boxAboverOkCancel.add(comp); + } + + public boolean wasOkSelected() { + return wasOkSelected; + } + public boolean wasCancelSelected() { + return wasCancelSelected; + } + /** + * subclasses must implement this method and specify commands + * to be executed when OK was clicked + */ + protected abstract void performOk(); + /** + * subclasses must implement this method and specify commands + * to be executed when Cancel was clicked + * + */ + protected abstract void performCancel(); + /** + * Adds a Component before the OK button + * @param comp + */ + public void addBeforeOK(JComponent comp) { + int pos = + de.memtext.util.ComponentUtils.getPositionOnComponent( + pOkCancel.getBtnOk(), + pOkCancel); + pOkCancel.add(comp, pos); + } + /** + * Adds a component right of the OK Button + * @param comp + */ + public void addAfterOK(JComponent comp) { + int pos = + de.memtext.util.ComponentUtils.getPositionOnComponent( + pOkCancel.getBtnOk(), + pOkCancel); + pOkCancel.add(comp, pos + 1); + } + /** + * Adds a component right of the Cancel Button + * @param comp + */ + public void addAfterCancel(JComponent comp) { + int pos = + de.memtext.util.ComponentUtils.getPositionOnComponent( + pOkCancel.getBtnCancel(), + pOkCancel); + pOkCancel.add(comp, pos + 1); + } + /* class OneTimeInitContentPane extends Container { + private int setLayoutCount=0; + public void setLayout(LayoutManager manager) { + if (!(manager instanceof BorderLayout)) { + throw new IllegalArgumentException("OKCancel Dlg must have BorderLayout"); + } + super.setLayout(manager); + setLayoutCount++; + if (setLayoutCount > 0) { + System.out.println( + "changing layout may cause problems in OKCancelDlg"); + + } + } + }*/ + + public void setOkVisible(boolean b) { + pOkCancel.setOkVisible(b); + } + public void setCancelVisible(boolean b) { + pOkCancel.setCancelVisible(b); + } + public boolean requestFocusForOK() { + return pOkCancel.getBtnOk().requestFocusInWindow(); + } + public void setOkBold(boolean b) { + pOkCancel.setOkBold(b); + } + + public void setOkDefaultButton() { + this.getRootPane().setDefaultButton(pOkCancel.getBtnOk()); + } + + public static void main(String[] args) { + + OkCancelDlg dlg = new OkCancelDlg(new JFrame(), "test") { + protected void performOk() { + } + + protected void performCancel() { + } + }; + + // dlg.addAboveOK(new JLabel("bla")); + dlg.setCenter(new JLabel("cnter")); + dlg.pack(); + dlg.show(); + } + +} diff --git a/src/de/memtext/dlg/OkCancelPanel.java b/src/de/memtext/dlg/OkCancelPanel.java new file mode 100644 index 0000000..d66826f --- /dev/null +++ b/src/de/memtext/dlg/OkCancelPanel.java @@ -0,0 +1,56 @@ +package de.memtext.dlg; + +import java.awt.Font; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JPanel; + +/** +A Panel with an OK and a Cancel button. + */ +public class OkCancelPanel extends JPanel { + protected JButton btnOk, btnCancel; + public OkCancelPanel() { + btnOk = new JButton("OK"); + btnCancel = new JButton("Abbrechen"); + btnCancel.setActionCommand("Cancel"); + add(btnOk); + add(btnCancel); + + } + public void addActionListener(ActionListener al) { + btnOk.addActionListener(al); + btnCancel.addActionListener(al); + } + + /** + * Returns the btnCancel. + * @return JButton + */ + public JButton getBtnCancel() { + return btnCancel; + } + + /** + * Returns the btnOk. + * @return JButton + */ + public JButton getBtnOk() { + return btnOk; + } + public void setOkVisible(boolean b) { + btnOk.setVisible(b); + } + public void setCancelVisible(boolean b) { + btnCancel.setVisible(b); + } + public void setOkBold(boolean b) { + Font f=btnOk.getFont(); + if (b) + btnOk.setFont(f.deriveFont(Font.BOLD)); + else + btnOk.setFont(f.deriveFont(Font.PLAIN)); + } + +} diff --git a/src/de/memtext/dlg/OkDlg.java b/src/de/memtext/dlg/OkDlg.java new file mode 100644 index 0000000..20d2bcd --- /dev/null +++ b/src/de/memtext/dlg/OkDlg.java @@ -0,0 +1,106 @@ +package de.memtext.dlg; + +import java.awt.BorderLayout; +import java.awt.Container; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.HeadlessException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPanel; +/** + * Dialog which can only be closed by clicking OK. + * + * setCenter for convenienance. + * + * @author MB + * + */ + +public class OkDlg extends DialogWithExit { + private JPanel psouth = new JPanel(); + protected JButton ok = new JButton("OK"); + + /** + * Constructor for OkDlg. + * @param arg0 + * @throws HeadlessException + */ + public OkDlg(Frame owner) throws HeadlessException { + super(owner,true); + initSouth(); + } + public OkDlg(Frame owner, String title, boolean isModal) { + super(owner,title,isModal); + initSouth(); + } + + + public OkDlg(Frame owner, String title) throws HeadlessException { + super(owner, title,true); + initSouth(); + } + + + public JButton getOkBtn() + { + return ok; + } + + + /** + * Constructor for OkDlg. + * @param arg0 + * @throws HeadlessException + */ + public OkDlg(Dialog arg0) throws HeadlessException { + super(arg0,true); + initSouth(); + } + + + private void initSouth() { + + ok.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent ae) + { + performOk(); + } + }); + psouth.add(ok); + + Container cp = this.getContentPane(); + cp.add(psouth, BorderLayout.SOUTH); + this.getRootPane().setDefaultButton(ok); + + } + + + + + public void addBeforeOK(JComponent comp) { + int pos = + de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth); + psouth.add(comp, pos); + } + public void addAfterOK(JComponent comp) { + int pos = + de.memtext.util.ComponentUtils.getPositionOnComponent(ok, psouth); + psouth.add(comp, pos+1); + } + /** + * subclasses can override this method and specify commands + * to be executed when OK was clicked + */ + protected void performOk() + { + this.hide(); + } + public static void main(String args[]) { + OkDlg d=new OkDlg(new javax.swing.JFrame()); + d.show(); + } +} diff --git a/src/de/memtext/dlg/OkDoneDlg.java b/src/de/memtext/dlg/OkDoneDlg.java new file mode 100644 index 0000000..79500fd --- /dev/null +++ b/src/de/memtext/dlg/OkDoneDlg.java @@ -0,0 +1,185 @@ +package de.memtext.dlg; + + + + +import java.awt.BorderLayout; +import java.awt.Container; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.GraphicsConfiguration; +import java.awt.HeadlessException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + + +/** +A abstract dialog with OK and DONE buttons. Subclasses must implement +performDone() and performOK(); + */ +public abstract class OkDoneDlg extends DialogWithExit { + /** + * Constructor for OkDoneDlg. + * @throws HeadlessException + */ + public OkDoneDlg() throws HeadlessException { + super(); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @throws HeadlessException + */ + public OkDoneDlg(Frame arg0) throws HeadlessException { + super(arg0); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkDoneDlg(Frame arg0, boolean arg1) throws HeadlessException { + super(arg0, arg1); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkDoneDlg(Frame arg0, String arg1) throws HeadlessException { + super(arg0, arg1); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @param arg2 + * @throws HeadlessException + */ + public OkDoneDlg(Frame arg0, String arg1, boolean arg2) + throws HeadlessException { + super(arg0, arg1, arg2); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @param arg2 + * @param arg3 + */ + public OkDoneDlg( + Frame arg0, + String arg1, + boolean arg2, + GraphicsConfiguration arg3) { + super(arg0, arg1, arg2, arg3); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @throws HeadlessException + */ + public OkDoneDlg(Dialog arg0) throws HeadlessException { + super(arg0); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkDoneDlg(Dialog arg0, boolean arg1) throws HeadlessException { + super(arg0, arg1); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @throws HeadlessException + */ + public OkDoneDlg(Dialog arg0, String arg1) throws HeadlessException { + super(arg0, arg1); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @param arg2 + * @throws HeadlessException + */ + public OkDoneDlg(Dialog arg0, String arg1, boolean arg2) + throws HeadlessException { + super(arg0, arg1, arg2); + initSouth(); + } + + /** + * Constructor for OkDoneDlg. + * @param arg0 + * @param arg1 + * @param arg2 + * @param arg3 + * @throws HeadlessException + */ + public OkDoneDlg( + Dialog arg0, + String arg1, + boolean arg2, + GraphicsConfiguration arg3) + throws HeadlessException { + super(arg0, arg1, arg2, arg3); + initSouth(); + } + + private void initSouth() { + OkCancelPanel ocp = new OkCancelPanel(); + Container cp = this.getContentPane(); + cp.add(ocp, BorderLayout.SOUTH); + ocp.addActionListener(new ActionListener(){ + public void actionPerformed(ActionEvent ae) + { + String cmd = ae.getActionCommand(); + if (cmd.equals("OK")) { + performOk(); + } + + if (cmd.equals("Done")) { + performDone(); + } + } + });; + } + + + /** + * subclasses must implement this method and specify commands + * to be executed when OK was clicked + */ + protected abstract void performOk(); + /** + * subclasses must implement this method and specify commands + * to be executed when DONE was clicked + */ + + protected abstract void performDone(); +} diff --git a/src/de/memtext/dlg/OkDonePanel.java b/src/de/memtext/dlg/OkDonePanel.java new file mode 100644 index 0000000..9b71cb1 --- /dev/null +++ b/src/de/memtext/dlg/OkDonePanel.java @@ -0,0 +1,32 @@ +package de.memtext.dlg; + +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JPanel; + +/** + * @author MB + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class OkDonePanel extends JPanel { +JButton btnOk,btnDone; +public OkDonePanel() +{ + btnOk=new JButton("OK"); + btnDone=new JButton("Fertig"); + add(btnOk); + add(btnDone); +} +public void addActionListener(ActionListener al) +{ + btnOk.addActionListener(al); + btnDone.addActionListener(al); +} + + +} diff --git a/src/de/memtext/dlg/PasswdChangeDlg.java b/src/de/memtext/dlg/PasswdChangeDlg.java new file mode 100644 index 0000000..609713f --- /dev/null +++ b/src/de/memtext/dlg/PasswdChangeDlg.java @@ -0,0 +1,185 @@ +package de.memtext.dlg; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.event.KeyEvent; + +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; +import javax.swing.KeyStroke; + +import de.memtext.rights.NewPasswordChecker; +import de.memtext.util.WindowUtils; +import de.memtext.widgets.HorizontalBox; +import de.memtext.widgets.WarningMessage; + +public abstract class PasswdChangeDlg extends OkCancelDlg { + private JLabel lblInfoDummy=new JLabel(); + private NewPasswordChecker newPasswordChecker; + private boolean isCheckOldPasswdWanted = true,isNewPasswordRequired=true; + private JTextField usernameField = new JTextField(20); + private KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); + private JLabel lblInfo=new JLabel(); + private JLabel lbl0 = new JLabel("Username:", JLabel.RIGHT); + private JLabel lbl1 = new JLabel("altes Passwort:", JLabel.RIGHT); + private JPasswordField oldpasswField = new JPasswordField(30); + private JLabel lbl2 = new JLabel("neues Passwort:", JLabel.RIGHT); + private JPasswordField newpasswField = new JPasswordField(30); + private JLabel lbl3 = new JLabel("wiederholen:", JLabel.RIGHT); + private JPasswordField newpasswField2 = new JPasswordField(30); + + public PasswdChangeDlg(Frame frame, String title) { + super(frame, title, true); + JPanel p=new JPanel(); + p.add(lblInfo); + HorizontalBox hbox = new HorizontalBox(); + JPanel lblPanel = new JPanel(new GridLayout(0, 1)); + lblPanel.setMaximumSize(new Dimension(150, 100)); + + + lblPanel.add(lbl0); + lblPanel.add(lbl1); + lblPanel.add(lbl2); + lblPanel.add(lbl3); + + lblInfo.setVisible(false); + hbox.add(lblPanel); + JPanel fieldPanel = new JPanel(new GridLayout(0, 1)); + + fieldPanel.add(usernameField); + usernameField.getKeymap().removeKeyStrokeBinding(enter); + + fieldPanel.add(oldpasswField); + oldpasswField.getKeymap().removeKeyStrokeBinding(enter); + fieldPanel.add(newpasswField); + newpasswField.getKeymap().removeKeyStrokeBinding(enter); + fieldPanel.add(newpasswField2); + newpasswField2.getKeymap().removeKeyStrokeBinding(enter); + hbox.add(fieldPanel); + this.setCenter(hbox); + this.setNorth(p); + this.pack(); + WindowUtils.center(this); + } + public void setNewPasswordChecker(NewPasswordChecker newPasswordChecker) + { + this.newPasswordChecker=newPasswordChecker; + } + public void setUsername(String username) { + usernameField.setText(username); + } + public void clear() { + usernameField.setText(""); + oldpasswField.setText(""); + newpasswField.setText(""); + newpasswField2.setText(""); + } + protected abstract boolean isOldPasswordOK(String username, String passwd); + + /** + * wenn OK geklickt wird wird automatisch geprüft ob die Länge des neuen + * Passwort passt und beide gleich sind + */ + protected final void performOk() { + String new1 = new String(newpasswField.getPassword()); + if (new1==null||new1.length()<4 ) + { + WarningMessage.show(this, + "Das neue Passwort ist zu kurz.", + "Achtung"); + return; + } + + String new2 = new String(newpasswField2.getPassword()); + String oldPassword = new String(oldpasswField.getPassword()); + if (!new1.equals(new2)) { + WarningMessage.show(this, + "Die beiden neuen Passwörter stimmen nicht überein", + "Achtung"); + return; + } + String faults=null; + if (newPasswordChecker!=null) faults=newPasswordChecker.checkForFaults(getUsername(),new String(newpasswField.getPassword())); + + if (faults!=null) { + WarningMessage.show(this, + faults, + "Achtung"); + return; + } + + if (isNewPasswordRequired&&new1.equals(oldPassword)) + { + WarningMessage.show(this,"Sie müssen ein neues Passwort eingeben","Achtung"); + return; + } + + if (isCheckOldPasswdWanted + && !isOldPasswordOK(usernameField.getText(), + oldPassword)) { + WarningMessage.show(this,"Das alte Passwort stimmt nicht", "Achtung"); + return; + } + this.hide(); + } + + protected void performCancel() { + this.hide(); + } + + + public void setUsernameFieldEnabled(boolean b) { + usernameField.setEnabled(b); + } + public void setOldPassword(String passw) { + oldpasswField.setText(passw); + } + public String getUsername() { + return usernameField.getText(); + } + public String getOldPasswd() { + return new String(oldpasswField.getPassword()); + } + public String getNewPasswd() { + return new String(newpasswField.getPassword()); + } + public boolean isCheckOldPasswdWanted() { + return isCheckOldPasswdWanted; + } + + public void setCheckOldPasswdWanted(boolean b) { + isCheckOldPasswdWanted = b; + lbl1.setVisible(b); + oldpasswField.setVisible(b); + } + public void setInfoLabel(String txt) { + lblInfo.setVisible(true); + lblInfo.setText(txt); + lblInfo.setFont(new Font("SansSerif",Font.BOLD,12)); + } + + public boolean isNewPasswordRequired() { + return isNewPasswordRequired; + } + + public void setNewPasswordRequired(boolean b) { + isNewPasswordRequired = b; + } +public static void main(String a[]) +{ + PasswdChangeDlg dlg=new PasswdChangeDlg(null,"dummy"){ + + protected boolean isOldPasswordOK(String username, String passwd) { + return false; + }} + ; + dlg.setInfoLabel("bitte ändern"); + dlg.show(); +} +} + +//Created on 09.01.2004 at 17:16:16 \ No newline at end of file diff --git a/src/de/memtext/hbt/AbstractAriel.java b/src/de/memtext/hbt/AbstractAriel.java new file mode 100644 index 0000000..3a9adec --- /dev/null +++ b/src/de/memtext/hbt/AbstractAriel.java @@ -0,0 +1,122 @@ +package de.memtext.hbt; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.mail.Flags; +import javax.mail.Folder; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.search.FlagTerm; + +import de.memtext.util.LogUtils; +import de.superx.servlet.SxMail; +import de.superx.servlet.SxPool; + +public abstract class AbstractAriel extends Thread { + // this is defined as private static method to use as little memory as possible, + // it would be neglectable in moder computers to create it every time the method + // runs, GarbargeCollection would easily do the job + // yet I define it that way out of respect for the programmers of beginning in + // the 50ies/60ies or whenever +// private static FlagTerm flagUnseen = new FlagTerm(new Flags(Flags.Flag.SEEN), true); // ja ich weiß, flagUnseen + Flags seen = new Flags(Flags.Flag.RECENT); + private static FlagTerm flagUnseen = new FlagTerm(new Flags(Flags.Flag.SEEN), false); + static Flags flagsContainingOnlySeen=new Flags(Flags.Flag.SEEN); + protected Logger logger=null; + // wird bisher nicht + // benötigt, aber ist doch + // klar, dass ich das gleich + // nutzen will, dass nervt, + // dass die Meldung jetzt + // kommt + private boolean isActive = true; + private int interval = 10; + protected SxMail sxmail; + + public AbstractAriel() { + super(); + } + + public AbstractAriel(Runnable target) { + super(target); + } + + public AbstractAriel(String name) { + super(name); + } + + public AbstractAriel(ThreadGroup group, Runnable target) { + super(group, target); + } + + public AbstractAriel(ThreadGroup group, String name) { + super(group, name); + } + + public AbstractAriel(Runnable target, String name) { + super(target, name); + } + + public AbstractAriel(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + } + + public AbstractAriel(ThreadGroup group, Runnable target, String name, long stackSize) { + super(group, target, name, stackSize); + } + + public void initLogging()throws IOException + { + String filename=SxPool.getLogDir() + "/superx_" + + getArielName() + ".log"; + LogUtils.initRawFile("superx_" + getArielName(), filename, 20000, 1, true, true); + System.out.println("Superx Mail logging in "+filename); + logger=Logger.getLogger("superx_" + getArielName()); + Level lev = Level.SEVERE; + logger.setLevel(lev); + + + + } + public String getArielName() + { + return "mail"; + } + public void run() { + while (isActive) { + try { + Thread.sleep(interval * 1000); + + } catch (InterruptedException e) { + // e.printStackTrace(); + } + + try { + + logger.log(Level.INFO,"SuperX is checking mails for new heartbeats..."); + + + Folder inbox=sxmail.getInbox(); + //if (inbox.hasNewMessages()) + processNewMessages(inbox.getMessages()); // processed messages will be deleted -> don#t need inbox.search(flagUnseen)); // former first attempt was : processNewMessages(inbox.getMessages()); // should be in differnt colour (<- British English) + + sxmail.closeInbox(); //deletes marked mails + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + } + + abstract void processNewMessages(Message[] messages) throws MessagingException, IOException, SQLException; + + public void setActive(boolean isActive) { + this.isActive=isActive; + + } + +} \ No newline at end of file diff --git a/src/de/memtext/hbt/Checker.java b/src/de/memtext/hbt/Checker.java new file mode 100644 index 0000000..a74e239 --- /dev/null +++ b/src/de/memtext/hbt/Checker.java @@ -0,0 +1,96 @@ +package de.memtext.hbt; + +import java.io.IOException; +import java.util.Properties; + +import javax.mail.Folder; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Store; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +public class Checker { + + public static void check(Session emailSession, String user, String password) + throws MessagingException, IOException { + + // create the POP3 store object and connect with the pop server + // pop3s wichtig -> vermutlich secure + Store store = emailSession.getStore("pop3s"); + store.connect(emailSession.getProperty("mail.pop3.host"), user, password); + + Folder emailFolder = store.getFolder("INBOX"); + emailFolder.open(Folder.READ_ONLY); + + // messages werden geholt, können nur ausgelesen werden, wenn Folder noch open + // ist! + Message[] messages = emailFolder.getMessages(); + + System.out.println("messages.length---" + messages.length); + + for (int i = 0, n = messages.length; i < n; i++) { + Message message = messages[i]; + System.out.println("---------------------------------"); + System.out.println("Email Number " + (i + 1)); + System.out.println("Subject: " + message.getSubject()); + System.out.println("From: " + message.getFrom()[0]); + System.out.println("Text: " + message.getContent().toString()); + + } + + // close the store and folder objects + emailFolder.close(false); + store.close(); + + } + + private static void send(Session emailSession, String user, String recipient, String subject, String text, + String password) throws AddressException, MessagingException { + MimeMessage replyMessage = new MimeMessage(emailSession); + // replyMessage = (MimeMessage) message.reply(false); + replyMessage.setFrom(new InternetAddress(user)); + replyMessage.setRecipients(Message.RecipientType.TO, recipient); + replyMessage.setSubject(subject); + replyMessage.setText(text); + Transport t = emailSession.getTransport("smtp"); + t.connect(user, password); + t.sendMessage(replyMessage, replyMessage.getAllRecipients()); + System.out.println("Message sent..."); + } + + private static Session initSession(String pophost, String smtphost) { + Properties properties = new Properties(); + properties.put("mail.pop3.host", pophost); + properties.put("mail.pop3.port", "995"); + properties.put("mail.pop3.starttls.enable", "true"); + properties.put("mail.smtp.auth", "true"); + properties.put("mail.smtp.starttls.enable", "true"); + properties.put("mail.smtp.host", smtphost); + properties.put("mail.smtp.port", "25"); + return Session.getDefaultInstance(properties); + } + + public static void main(String[] args) { + Session session = initSession("pop3.strato.de", "smtp.strato.de"); + String username = "heartbeat@mbisping.de"; + String password = "$Anfang1200"; + + try { + check(session, username, password); + send(session, username, "danielq@memtext.de", "From Düsseldorf with fun...", "This is the memtext's first digitial 'heartbeat' :-)\n send via java mail - \nThanks and see you around :-)", + password); + } catch (MessagingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} \ No newline at end of file diff --git a/src/de/memtext/hbt/NewHeartBeatAriel.java b/src/de/memtext/hbt/NewHeartBeatAriel.java new file mode 100644 index 0000000..e0b406b --- /dev/null +++ b/src/de/memtext/hbt/NewHeartBeatAriel.java @@ -0,0 +1,293 @@ +package de.memtext.hbt; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.mail.BodyPart; +import javax.mail.Flags; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Part; +import javax.mail.internet.AddressException; +import javax.mail.internet.MimeMessage; + +import clover.com.atlassian.extras.common.org.springframework.util.StringUtils; +import de.memtext.db.DbUtils; +import de.memtext.util.FileUtils; +import de.memtext.util.MailUtils; +import de.superx.servlet.SuperXManager; +import de.superx.servlet.SxMail; +import de.superx.servlet.SxPools; + +public class NewHeartBeatAriel extends AbstractAriel { + private static final Pattern pHbtId = Pattern.compile("@hbt:\\d*@"); + + public NewHeartBeatAriel(SxMail sxmail) throws IOException { + this.sxmail = sxmail; + initLogging(); + } + + void processNewMessages(Message newMessages[]) throws MessagingException, IOException, SQLException { + + + logger.log(Level.INFO," found " + newMessages.length + " new messages"); + for (int i = 0, n = newMessages.length; i < n; i++) { + Message aNewMessage = newMessages[i]; + + String content = MailUtils.getContent(aNewMessage); + if (content.indexOf("@hbt:") == -1) + createNewHeartBeat(aNewMessage, content); + else + appendToHeartBeat(aNewMessage, content); + // had thought setting via inbox nessary, but that's only the preferred way to + // set flags for group of messages since some mail implementations by have + // optimized support for groups of messages + // inbox.setFlags(new Message[] {message}, , true); + // message.setFlags(flagsContainingOnlySeen, true); + // unseen wäre schöner, mailapi.jar aktualisieren bei HIS Antrag + // nötig,vielleicht klappt mit delete + aNewMessage.setFlag(Flags.Flag.DELETED, true); // AbstractAriel.run ruft sxmail.closeInbox() auf mit + // Anweisung zu löschen + + // sorry to bother you, Garbage collector , need message only to times, hey or + // doesn't that matter anyway since only a simple reference (like in good old + // C), but clearer/easier to read if line Message message=.. was superfolous + + } + } + + private void appendToHeartBeat(Message message, String content) + throws SQLException, IOException, MessagingException { + StringBuffer result = new StringBuffer(); + int hbtTid = -1; + Connection con = SxPools.getConnection(sxmail.getMandantenID()); + Statement stm = con.createStatement(); + boolean isHbtFoundInDb = false; + String feedbackSubject = ""; + Matcher m = pHbtId.matcher(content); + boolean foundHbtTag=m.find(); + if (foundHbtTag) { + String hbtIdString = content.substring(m.start() + 5, m.end() - 1); + content=content.replaceAll("@hbt:\\d*@", ""); + try { + hbtTid = Integer.parseInt(hbtIdString); + if (DbUtils.getInt(con, "select count(*) from hbt_heartbeat where tid=?", hbtTid) > 0) + isHbtFoundInDb = true; + } catch (NumberFormatException e) { + result.append(" hbt:" + hbtIdString + + " konnte nicht in integer transformiert werden, Nachricht wird zwischengespeichert"); + isHbtFoundInDb = false; + } + if (isHbtFoundInDb) { + // TODO ggfs. mehrer Topics + int maxTopic = DbUtils.getInt(con, "select max(tid) from hbt_topic where hbt_id=?", hbtTid); + // int maxNote = DbUtils.getInt(stm, "select max(tid) from hbt_note where + // hbt_id=" + hbtTid + " hbt_topic_id=" + maxTopic); + int newNoteId = createNote(con, stm, hbtTid, maxTopic, message, content); + feedbackSubject = "Your new note was added to Heartbeat " + hbtTid; + result.append("Feel free to view this HeartBeat by visiting " + sxmail.getWTFAI() + + "/edit/hbt/hbt_viewer.jsp?tid=" + hbtTid + " \n\n" + "Always at your service: \n" + + " your HeartBeatAriel @ SuperX"); + + } + } + + if (!foundHbtTag || !isHbtFoundInDb) { + feedbackSubject = "Sorry, target hbt found found ..."; + PreparedStatement pst=con.prepareStatement("insert into hbt_tmp_note (note) values (?)"); + pst.setString(1,content); + pst.execute(); + pst.close(); + int newNoteId=DbUtils.getInt(stm, "select max(tid) from hbt_tmp_note"); + result.append("you can select the right hbt_id by visiting " + sxmail.getWTFAI()+"/servlet/SuperXmlMaske?tid=60040?note_id="+newNoteId); + } +stm.close(); +con.close(); + sendFeedbackEmail(feedbackSubject, result.toString(), message); + } + + private void createNewHeartBeat(Message inMessage, String content) + throws SQLException, MessagingException, IOException { + int newHbtTid = performHbtInsert(inMessage, content); + String text = "Feel free to complete this heartbeat's details by visiting " + sxmail.getWTFAI() + + "/edit/hbt/hbt_edit.jsp?tid=" + newHbtTid + " \n\n" + "Always at your service: \n" + + " your HeartBeatAriel @ SuperX"; + sendFeedbackEmail("Your new digital heartbeat has been created ...", text, inMessage); + } + + /** + * Performs the creation of a new HeartBeat in the database + * + * @param message + * @return newHbtTid + * @throws SQLException + * @throws MessagingException + * @throws IOException + */ + private int performHbtInsert(Message m, String content) throws SQLException, IOException, MessagingException { + Connection con = SxPools.getConnection(sxmail.getMandantenID()); + Statement stm = con.createStatement(); + + int newHbtTid = createHbt(con, stm, content, m.getSubject()); + int newTopicId = createTopic(stm, newHbtTid); + createNote(con, stm, newHbtTid, newTopicId, m, content); + con.close(); + return newHbtTid; + } + + private int createHbt(Connection dbConnection, Statement stm, String content, String subject) + throws IOException, MessagingException, SQLException { + String primary_customer_id = identifyPrimaryCustomerId(dbConnection, stm, content); + String name = StringUtils.replace(subject, "'", "''");// for SQL insert + // Sql insert - fuck prepared statements, nobody hacks this, I don't give a + // shit, not worth my extra time or effort, I want to get things done now while + // having fun :-) + stm.execute("select sp_update_sequence('hbt_heartbeat')"); + String insertSql = "INSERT INTO hbt_heartbeat \n" + "( primary_customer_id,name," + " created_at, \n" + + " status \n" + ") \n" + "VALUES \n" + "( " + primary_customer_id + ",'" + name + "', " + + " today(), \n" + " 1 \n" + ") " + ""; + stm.execute(insertSql); + int newHbtTid = DbUtils.getInt(stm, "select max(tid) from hbt_heartbeat"); + return newHbtTid; + } + + /** + * + * Wenn im Text der weitergeleiteten Email der Absender mit @@ markiert ist, + * z.B. @@hiber@his.de@@, diesen auslesen zugehörige Organisation auslesen + * + * @param m + * @return String null oder key_apnr z.B. '1001' + * @throws IOException + * @throws MessagingException + * @throws SQLException + */ + private String identifyPrimaryCustomerId(Connection con, Statement stm, String content) + throws IOException, MessagingException, SQLException { + String result = "null"; + int pos1 = content.indexOf("@@"); + int pos2 = content.substring(pos1 + 2).indexOf("@@"); + if (pos1 > -1 && pos2 > -1) { + String absender = content.substring(pos1 + 2); + absender = absender.substring(0, absender.lastIndexOf("@@")); + logger.log(Level.INFO," checking customer " + absender); + int userinfo_id = DbUtils.getInt(con, "select tid from userinfo where email=?", absender); + result = DbUtils.getString(stm, + "select min(ch110_institut) from user_institution where userid=" + userinfo_id); + + if (result == null) + result = "null"; + else + result = "'" + result + "'"; + } + return result; + } + + private int createTopic(Statement stm, int newHbtTid) throws SQLException { + stm.execute("select sp_update_sequence('hbt_topic')"); + String insertSql = "INSERT INTO hbt_topic \n" + "( hbt_id,name, created_at)" + "VALUES (" + newHbtTid + + ",'Start',now() )"; + stm.execute(insertSql); + int newTopicId = DbUtils.getInt(stm, "select max(tid) from hbt_topic"); + return newTopicId; + } + + private int createNote(Connection con, Statement stm, int hbtId, int topicId, Message m, String content) + throws IOException, MessagingException, SQLException { + stm.execute("select sp_update_sequence('hbt_note')"); + PreparedStatement pst = con + .prepareStatement(" INSERT INTO hbt_note (hbt_id,hbt_topic_id,note, created_at) VALUES (?,?,?,now());"); + pst.setInt(1, hbtId); + pst.setInt(2, topicId); + + pst.setString(3, content); + pst.execute(); + pst.close(); + int newNoteId = DbUtils.getInt(stm, "select max(tid) from hbt_note"); + saveAttachments(stm, hbtId, topicId, newNoteId, m); + return newNoteId; + } + + private void saveAttachments(Statement stm, int newHbtTid, int newTopicId, int newNoteId, Message m) + throws IOException, MessagingException, SQLException { + // List attachments = new ArrayList(); + Object content = m.getContent(); + // if (content instanceof String) return null; + + if (content instanceof Multipart) { + Multipart multipart = (Multipart) content; + for (int i = 0; i < multipart.getCount(); i++) { + BodyPart part = multipart.getBodyPart(i); + logger.log(Level.INFO,part.getFileName() + " " + part.getContentType() + " " + part.getDisposition()); + if (part.getDisposition() != null && part.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { + // result.addAll(getAttachments(multipart.getBodyPart(i))); + String filename = SuperXManager.getWEB_INFPfad()+"/downloads/hbt_"+newHbtTid+"_" +newNoteId+"_"+FileUtils.removeProblemChars(part.getFileName()); + sxDownloadsInsert(stm, newHbtTid, newTopicId, newNoteId, filename, part.getContentType()); + // javaxmail >1.4 bodyPart.saveFile(filename); + // old version + InputStream is = part.getInputStream(); + File f = new File(filename); + FileOutputStream fos = new FileOutputStream(f); + byte[] buf = new byte[4096]; + int bytesRead; + while ((bytesRead = is.read(buf)) != -1) { + fos.write(buf, 0, bytesRead); + } + fos.close(); + logger.log(Level.INFO," saving attachment " + (i++) + " as " + filename); + } + } + + } + + } + + private void sxDownloadsInsert(Statement stm, int newHbtTid, int newTopicId, int newNoteId, String filename, + String contenttype) throws SQLException { + stm.execute("select sp_update_sequence('sx_downloads')"); + String filenameShort = filename.substring(filename.indexOf(File.separator + "hbt") + 1); + String insertSQLSxDownloads = "INSERT INTO sx_downloads \n" + "( \n" + " name, \n" + " importdatum, \n" + + " kommentar, \n" + " kommentar_url, \n" + " contenttype, \n" + " datei, \n" + " gueltig_seit, \n" + + " gueltig_bis \n" + ") \n" + "VALUES \n" + "( \n" + " '" + filenameShort + "', \n" + " today(), \n" + + " 'kommentar_value', \n" + " 'kommentar_url_value', \n" + " '" + contenttype + "', \n" + " '" + + filenameShort + "', \n" + " today(), \n" + " date_val('1.1.3000') \n" + ") \n" + ""; + stm.execute(insertSQLSxDownloads); + int newDownloadTid = DbUtils.getInt(stm, "select max(tid) from sx_downloads"); + stm.executeUpdate("insert into hbt_attachment (hbt_id,topic_id,note_id,download_id) values (" + newHbtTid + "," + + newTopicId + "," + newNoteId + "," + newDownloadTid + ")"); + } + + /** + * sendFeedBackEmail -- hier hätte ich gern automatisch newline in Zeile 60 + * direkt unter createNewHeartBeat automatisch erzeugt, dann nach weiter unten + * im Quelltext verlagert, damit von der Reihenfolge in + * createNewHeartBeat(Message message) her passt + * + * @param newHbtTid : tid von neuem HeartBeat in der Datenbank + * @param inMessage + * @throws MessagingException + * @throws AddressException + */ + private void sendFeedbackEmail(String subject, String text, Message inMessage) + throws AddressException, MessagingException { + MimeMessage reply = sxmail.createMessage(); + reply.setRecipients(Message.RecipientType.TO, inMessage.getFrom()); + reply.setSubject(subject); + reply.setText(text); + sxmail.setMessage(reply); + + logger.log(Level.INFO,"Reply message happily sent..."); + } + + +} \ No newline at end of file diff --git a/src/de/memtext/icons/ArrowDownIcon.java b/src/de/memtext/icons/ArrowDownIcon.java new file mode 100644 index 0000000..540a550 --- /dev/null +++ b/src/de/memtext/icons/ArrowDownIcon.java @@ -0,0 +1,10 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +public class ArrowDownIcon extends BasicIcon { + public void myPaint(Graphics g) { + drawArrowDown(g, 6); + } + +} diff --git a/src/de/memtext/icons/ArrowRight.java b/src/de/memtext/icons/ArrowRight.java new file mode 100644 index 0000000..47b89fc --- /dev/null +++ b/src/de/memtext/icons/ArrowRight.java @@ -0,0 +1,13 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +public class ArrowRight extends BasicIcon { + + void myPaint(Graphics g) { + drawArrowRight(g); + } + +} + +//Created on 17.04.2004 at 21:42:08 \ No newline at end of file diff --git a/src/de/memtext/icons/ArrowUpIcon.java b/src/de/memtext/icons/ArrowUpIcon.java new file mode 100644 index 0000000..c13fb14 --- /dev/null +++ b/src/de/memtext/icons/ArrowUpIcon.java @@ -0,0 +1,14 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +import javax.swing.Icon; + +public class ArrowUpIcon extends BasicIcon implements Icon { + + public void myPaint(Graphics g) { + drawArrowUp(g, 4); + + } + +} diff --git a/src/de/memtext/icons/BasicIcon.java b/src/de/memtext/icons/BasicIcon.java new file mode 100644 index 0000000..8609242 --- /dev/null +++ b/src/de/memtext/icons/BasicIcon.java @@ -0,0 +1,99 @@ +package de.memtext.icons; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; + +import javax.swing.Icon; +import javax.swing.JButton; + +public abstract class BasicIcon implements Icon { + private int iconWidth = 16, iconHeight = 16; + private Color color = Color.black; + /** + * @see javax.swing.Icon#getIconWidth() + */ + public int getIconWidth() { + return iconWidth; + } + + /** + * @see javax.swing.Icon#getIconHeight() + */ + public int getIconHeight() { + return iconHeight; + } + public void paintIcon(Component c, Graphics g, int x, int y) { + g.translate(x, y); + if (c.isEnabled()) + g.setColor(color); + else + g.setColor(Color.GRAY); + myPaint(g); + g.translate(-x, -y); + } + abstract void myPaint(Graphics g); + void drawDoubleLine(Graphics g, int y) { + if (y > getIconHeight() - 2) + throw new IllegalArgumentException("can't draw that low"); + g.drawLine(0, y, getIconWidth(), y); + g.drawLine(0, y + 1, getIconWidth(), y + 1); + } + + void drawArrowRight(Graphics g) { + int midx = (int) Math.floor(getIconWidth() / 2); + int midy = (int) Math.floor(getIconHeight() / 2); + // mittellinie + g.drawLine(0, midy - 1, getIconWidth(), midy - 1); + g.drawLine(0, midy, getIconWidth(), midy); + g.drawLine(0, midy + 1, getIconWidth(), midy + 1); + + g.drawLine(midx + 1, 1, getIconWidth(), midy - 1); + g.drawLine(midx + 1, 2, getIconWidth(), midy); + + g.drawLine(midx + 1, getIconHeight() - 1, getIconWidth(), midy + 1); + g.drawLine(midx + 1, getIconHeight() - 2, getIconWidth(), midy); + + } + + void drawArrowUp(Graphics g, int y) { + int midx = (int) Math.floor(getIconWidth() / 2); + int midy = (int) Math.floor(getIconHeight() / 2); + g.drawLine(0, y + midy, midx, y); + g.drawLine(midx, y, getIconWidth(), y + midy); + g.drawLine(0, y + midy + 1, midx, y + 1); + g.drawLine(midx, y + 1, getIconWidth(), y + midy + 1); + + } + void drawArrowDown(Graphics g, int y) { + int midx = (int) Math.floor(getIconWidth() / 2); + int midy = (int) Math.floor(getIconHeight() / 2); + g.drawLine(0, y, midx, midy + y); + g.drawLine(midx, y + midy, getIconWidth(), y); + g.drawLine(0, y + 1, midx, midy + y + 1); + g.drawLine(midx, y + midy + 1, getIconWidth(), y + 1); + + } + public static void main(String[] args) { + de.memtext.widgets.MBFrame f = new de.memtext.widgets.MBFrame("test"); + f.setCenter(new JButton("test", new ArrowRight())); + f.pack(); + f.show(); + } + public void setIconHeight(int i) { + iconHeight = i; + } + + public void setIconWidth(int i) { + iconWidth = i; + } + + public Color getColor() { + return color; + } + + public void setColor(Color color) { + this.color = color; + } + +} diff --git a/src/de/memtext/icons/DoubleArrowDownIcon.java b/src/de/memtext/icons/DoubleArrowDownIcon.java new file mode 100644 index 0000000..43cc69a --- /dev/null +++ b/src/de/memtext/icons/DoubleArrowDownIcon.java @@ -0,0 +1,16 @@ +package de.memtext.icons; + +import java.awt.Graphics; + + +public class DoubleArrowDownIcon extends BasicIcon { +public void myPaint(Graphics g) +{ +drawArrowDown(g,2); +drawArrowDown(g,6); + + +} + +} + diff --git a/src/de/memtext/icons/DoubleArrowDownLineIcon.java b/src/de/memtext/icons/DoubleArrowDownLineIcon.java new file mode 100644 index 0000000..3698551 --- /dev/null +++ b/src/de/memtext/icons/DoubleArrowDownLineIcon.java @@ -0,0 +1,23 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +/** + * @author MB + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class DoubleArrowDownLineIcon extends BasicIcon { +public void myPaint(Graphics g) +{ +drawArrowDown(g,0); +drawArrowDown(g,4); +drawDoubleLine(g,getIconHeight()-2); + +} + +} + diff --git a/src/de/memtext/icons/DoubleArrowUpIcon.java b/src/de/memtext/icons/DoubleArrowUpIcon.java new file mode 100644 index 0000000..89d82eb --- /dev/null +++ b/src/de/memtext/icons/DoubleArrowUpIcon.java @@ -0,0 +1,22 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +/** + * @author MB + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class DoubleArrowUpIcon extends BasicIcon { +public void myPaint(Graphics g) +{ +drawArrowUp(g,0); +drawArrowUp(g,4); + +} + +} + diff --git a/src/de/memtext/icons/DoubleArrowUpLineIcon.java b/src/de/memtext/icons/DoubleArrowUpLineIcon.java new file mode 100644 index 0000000..1e610c6 --- /dev/null +++ b/src/de/memtext/icons/DoubleArrowUpLineIcon.java @@ -0,0 +1,23 @@ +package de.memtext.icons; + +import java.awt.Graphics; + +/** + * @author MB + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class DoubleArrowUpLineIcon extends BasicIcon { +public void myPaint(Graphics g) +{ +drawDoubleLine(g,0); +drawArrowUp(g,2); +drawArrowUp(g,6); + +} + +} + diff --git a/src/de/memtext/icons/MBStandardIcons.java b/src/de/memtext/icons/MBStandardIcons.java new file mode 100644 index 0000000..28880f5 --- /dev/null +++ b/src/de/memtext/icons/MBStandardIcons.java @@ -0,0 +1,101 @@ +package de.memtext.icons; + +import javax.swing.ImageIcon; + +import de.memtext.util.IconUtils; + +/** + * @author MB + * + changed xxx + */ +public class MBStandardIcons { + private static ImageIcon indexBox, + newDoc, + copyWin, + searchWin, + viewingGlass, + table, + delete, + properties; + private static ClassLoader cl; + /** + * Constructor for StandardIcons. + */ + private MBStandardIcons() { + + } + public static ImageIcon get(String name) { + return IconUtils.get("de/memtext/icons/" + name); + } + static { + MBStandardIcons s = new MBStandardIcons(); + cl = s.getClass().getClassLoader(); + copyWin = + new ImageIcon(cl.getResource("de/memtext/icons/copyWindows.gif")); + searchWin = + new ImageIcon(cl.getResource("de/memtext/icons/searchWindows.gif")); + viewingGlass = + new ImageIcon(cl.getResource("de/memtext/icons/viewingGlass.gif")); + table = new ImageIcon(cl.getResource("de/memtext/icons/table.gif")); + newDoc = new ImageIcon(cl.getResource("de/memtext/icons/newDoc.gif")); + delete = new ImageIcon(cl.getResource("de/memtext/icons/delete.gif")); + properties = + new ImageIcon(cl.getResource("de/memtext/icons/properties.gif")); + indexBox = + new ImageIcon(cl.getResource("de/memtext/icons/indexBox.gif")); + } + public static ImageIcon getEntry() { + return new ImageIcon(cl.getResource("de/memtext/icons/entry.gif")); + } + public static ImageIcon getCopy() { + return copyWin; + } + public static ImageIcon getSearch() { + return searchWin; + } + public static ImageIcon getDelete() { + return delete; + } + public static ImageIcon getPrint() + { + return new ImageIcon(cl.getResource("de/memtext/icons/print.gif")); + + + } + public static ImageIcon getProperties() { + return properties; + } + /** + * Returns the table. + * @return ImageIcon + */ + public static ImageIcon getTable() { + return table; + } + + /** + * Returns the viewingGlass. + * @return ImageIcon + */ + public static ImageIcon getViewingGlass() { + return viewingGlass; + } + + /** + * Returns the newDoc. + * @return ImageIcon + */ + public static ImageIcon getNewDoc() { + return newDoc; + } + + /** + * Returns the indexBox. + * @return ImageIcon + */ + public static ImageIcon getIndexBox() { + return indexBox; + } + +} diff --git a/src/de/memtext/icons/chart.gif b/src/de/memtext/icons/chart.gif new file mode 100644 index 0000000..2dd1090 Binary files /dev/null and b/src/de/memtext/icons/chart.gif differ diff --git a/src/de/memtext/icons/copyWindows.gif b/src/de/memtext/icons/copyWindows.gif new file mode 100644 index 0000000..63ac391 Binary files /dev/null and b/src/de/memtext/icons/copyWindows.gif differ diff --git a/src/de/memtext/icons/delete.gif b/src/de/memtext/icons/delete.gif new file mode 100644 index 0000000..3b04322 Binary files /dev/null and b/src/de/memtext/icons/delete.gif differ diff --git a/src/de/memtext/icons/entry.gif b/src/de/memtext/icons/entry.gif new file mode 100644 index 0000000..0e7ed1e Binary files /dev/null and b/src/de/memtext/icons/entry.gif differ diff --git a/src/de/memtext/icons/film.gif b/src/de/memtext/icons/film.gif new file mode 100644 index 0000000..1a3d487 Binary files /dev/null and b/src/de/memtext/icons/film.gif differ diff --git a/src/de/memtext/icons/floppy.gif b/src/de/memtext/icons/floppy.gif new file mode 100644 index 0000000..deec80d Binary files /dev/null and b/src/de/memtext/icons/floppy.gif differ diff --git a/src/de/memtext/icons/help.gif b/src/de/memtext/icons/help.gif new file mode 100644 index 0000000..fb14ce3 Binary files /dev/null and b/src/de/memtext/icons/help.gif differ diff --git a/src/de/memtext/icons/i.gif b/src/de/memtext/icons/i.gif new file mode 100644 index 0000000..2e9a739 Binary files /dev/null and b/src/de/memtext/icons/i.gif differ diff --git a/src/de/memtext/icons/indexBox.gif b/src/de/memtext/icons/indexBox.gif new file mode 100644 index 0000000..8e5b572 Binary files /dev/null and b/src/de/memtext/icons/indexBox.gif differ diff --git a/src/de/memtext/icons/info.gif b/src/de/memtext/icons/info.gif new file mode 100644 index 0000000..46f9598 Binary files /dev/null and b/src/de/memtext/icons/info.gif differ diff --git a/src/de/memtext/icons/newDoc.gif b/src/de/memtext/icons/newDoc.gif new file mode 100644 index 0000000..ddc819f Binary files /dev/null and b/src/de/memtext/icons/newDoc.gif differ diff --git a/src/de/memtext/icons/powerOff.gif b/src/de/memtext/icons/powerOff.gif new file mode 100644 index 0000000..d3712a9 Binary files /dev/null and b/src/de/memtext/icons/powerOff.gif differ diff --git a/src/de/memtext/icons/print.gif b/src/de/memtext/icons/print.gif new file mode 100644 index 0000000..5379227 Binary files /dev/null and b/src/de/memtext/icons/print.gif differ diff --git a/src/de/memtext/icons/properties.gif b/src/de/memtext/icons/properties.gif new file mode 100644 index 0000000..adec560 Binary files /dev/null and b/src/de/memtext/icons/properties.gif differ diff --git a/src/de/memtext/icons/redo.gif b/src/de/memtext/icons/redo.gif new file mode 100644 index 0000000..4af1d7e Binary files /dev/null and b/src/de/memtext/icons/redo.gif differ diff --git a/src/de/memtext/icons/save.gif b/src/de/memtext/icons/save.gif new file mode 100644 index 0000000..90b0c51 Binary files /dev/null and b/src/de/memtext/icons/save.gif differ diff --git a/src/de/memtext/icons/searchWindows.gif b/src/de/memtext/icons/searchWindows.gif new file mode 100644 index 0000000..c602f0e Binary files /dev/null and b/src/de/memtext/icons/searchWindows.gif differ diff --git a/src/de/memtext/icons/table.gif b/src/de/memtext/icons/table.gif new file mode 100644 index 0000000..fcd3f1d Binary files /dev/null and b/src/de/memtext/icons/table.gif differ diff --git a/src/de/memtext/icons/undo.gif b/src/de/memtext/icons/undo.gif new file mode 100644 index 0000000..559066e Binary files /dev/null and b/src/de/memtext/icons/undo.gif differ diff --git a/src/de/memtext/icons/viewingGlass.gif b/src/de/memtext/icons/viewingGlass.gif new file mode 100644 index 0000000..265dfb6 Binary files /dev/null and b/src/de/memtext/icons/viewingGlass.gif differ diff --git a/src/de/memtext/lang/SingOrPluralWord.java b/src/de/memtext/lang/SingOrPluralWord.java new file mode 100644 index 0000000..ba7d5e5 --- /dev/null +++ b/src/de/memtext/lang/SingOrPluralWord.java @@ -0,0 +1,28 @@ +package de.memtext.lang; +public class SingOrPluralWord { + public final static SingOrPluralWord SEIN=new SingOrPluralWord("ist","sind"); +private int count; +private String singular,plural; + public SingOrPluralWord(String singular,String plural) { + this.singular=singular; + this.plural=plural; + } + +public static String format(int count,String sing,String plural) +{ + if (count==1) return count+" "+sing; + else + return count+" "+plural; +} + +public String say(int count) +{ + if (count==1) return singular; + else + return plural; +} + + +} + +//Created on 12.12.2003 at 15:53:43 \ No newline at end of file diff --git a/src/de/memtext/observ/DocumentListenerObserver.java b/src/de/memtext/observ/DocumentListenerObserver.java new file mode 100644 index 0000000..14c5682 --- /dev/null +++ b/src/de/memtext/observ/DocumentListenerObserver.java @@ -0,0 +1,32 @@ +package de.memtext.observ; + +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +/** + * A document listener that will inform an observable about changes + * in the document + */ +public class DocumentListenerObserver implements DocumentListener { +private MyObservable observable; + public DocumentListenerObserver(MyObservable observable) { + this.observable= observable; + } + + public void insertUpdate(DocumentEvent e) { + observable.markChanged(); + observable.notifyObservers(); + } + + public void removeUpdate(DocumentEvent e) { + observable.markChanged(); + observable.notifyObservers(); + } + + public void changedUpdate(DocumentEvent e) { + observable.markChanged(); + observable.notifyObservers(); + } + +} + +//Created on 19.04.2004 at 18:30:30 \ No newline at end of file diff --git a/src/de/memtext/observ/MyObservable.java b/src/de/memtext/observ/MyObservable.java new file mode 100644 index 0000000..866af1e --- /dev/null +++ b/src/de/memtext/observ/MyObservable.java @@ -0,0 +1,17 @@ +package de.memtext.observ; + +import java.io.Serializable; +import java.util.Observable; + +/** + * Rather silly, but for some reason Java complained + * that the setChanged() method was not visible + */ + +public class MyObservable extends Observable implements Serializable { + + public void markChanged() { + super.setChanged(); + } + +} diff --git a/src/de/memtext/rights/Allowable.java b/src/de/memtext/rights/Allowable.java new file mode 100644 index 0000000..d65b338 --- /dev/null +++ b/src/de/memtext/rights/Allowable.java @@ -0,0 +1,9 @@ +package de.memtext.rights; + +public interface Allowable { + public boolean isAllowed(); + + public void setAllowed(boolean b); +} + +//Created on 24.04.2005 at 07:45:25 diff --git a/src/de/memtext/rights/AllowableHierarchy.java b/src/de/memtext/rights/AllowableHierarchy.java new file mode 100644 index 0000000..92c1f0d --- /dev/null +++ b/src/de/memtext/rights/AllowableHierarchy.java @@ -0,0 +1,12 @@ +package de.memtext.rights; + +public interface AllowableHierarchy extends Allowable { + /** + * @returns true if node itself or any of descendants is allowed + */ + public boolean isAnyDescendantAllowed(); + + public void setDescendantsAllowed(boolean b); +} + +//Created on 24.04.2005 at 07:54:08 diff --git a/src/de/memtext/rights/AllowableHierarchyUtil.java b/src/de/memtext/rights/AllowableHierarchyUtil.java new file mode 100644 index 0000000..16ada67 --- /dev/null +++ b/src/de/memtext/rights/AllowableHierarchyUtil.java @@ -0,0 +1,117 @@ +package de.memtext.rights; + +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.tree.DefaultMutableTreeNode; + +import de.memtext.tree.TreeEntryI; + +public class AllowableHierarchyUtil { + + /** + * Entfernt unerlaubte Blätter und Äste, in denen es gar keine erlaubten + * Knoten gibt + * + * @param root + * must also extend DefaultMutableTreeNode + */ + public static void removeUnallowedNodes(AllowableHierarchy root) { + if (!(root instanceof DefaultMutableTreeNode)) + throw new IllegalArgumentException(" must be a node!"); + DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root; + boolean needAnotherRound = true, killedOne = false; + + while (needAnotherRound) { + killedOne = false; + for (Enumeration en = rootNode.breadthFirstEnumeration(); en + .hasMoreElements();) { + Object o = en.nextElement(); + if (o == root) + continue; + AllowableHierarchy ah = (AllowableHierarchy) o; + + if (!ah.isAnyDescendantAllowed()) { + // System.out.println("removing: "+ah); + DefaultMutableTreeNode node = ((DefaultMutableTreeNode) ah); + markParentsAsNotAllowed(node); + + node.removeFromParent(); + killedOne = true; + break; + } + } + if (killedOne == false) + needAnotherRound = false; + } + + } + + private static void markParentsAsNotAllowed(DefaultMutableTreeNode node) { + if (!node.isRoot()&& node instanceof Allowable) { + Allowable al = null; + if (node.getParent() instanceof Allowable) + al = (Allowable) node.getParent(); + al.setAllowed(false); + + markParentsAsNotAllowed((DefaultMutableTreeNode) node + .getParent()); + } + + } + + /** + * Restrukturiert einen Baum, so dass nicht erlaubte "Zwischenäste" entfernt + * werden. root - noterl - erl3 + * + * wird root - erl3 + * + * @param root + */ + public static void reorg(AllowableHierarchy root) { + if (!(root instanceof DefaultMutableTreeNode)) + throw new IllegalArgumentException(" must be a node!"); + DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root; + boolean needAnotherRound = true; + List nodeList = new LinkedList(); + while (needAnotherRound) { + nodeList.clear(); + needAnotherRound = false; + for (int i = 0; i < rootNode.getChildCount(); i++) { + AllowableHierarchy ah = (AllowableHierarchy) rootNode + .getChildAt(i); + if (!ah.isAllowed()) { + needAnotherRound = true; + ((DefaultMutableTreeNode) ah).removeFromParent(); + for (int i2 = 0; i2 < ((DefaultMutableTreeNode) ah) + .getChildCount(); i2++) + nodeList.add(((DefaultMutableTreeNode) ah) + .getChildAt(i2)); + } + } + for (Iterator it = nodeList.iterator(); it.hasNext();) { + rootNode.add((DefaultMutableTreeNode) it.next()); + } + } + } + + public static void markNotAllowedNodes(AllowableHierarchy root, String mark) { + if (!(root instanceof DefaultMutableTreeNode)) + throw new IllegalArgumentException(" must be a node!"); + DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root; + int i = 0; + for (Enumeration en = rootNode.breadthFirstEnumeration(); en + .hasMoreElements();) { + AllowableHierarchy ah = (AllowableHierarchy) en.nextElement(); + if (!ah.isAllowed()) { + TreeEntryI te = (TreeEntryI) ah; + if (!te.getName().endsWith(mark)) + te.setName(te.getName() + mark); + } + } + } +} + +// Created on 24.04.2005 at 08:05:45 diff --git a/src/de/memtext/rights/NewPasswordChecker.java b/src/de/memtext/rights/NewPasswordChecker.java new file mode 100644 index 0000000..649fb0e --- /dev/null +++ b/src/de/memtext/rights/NewPasswordChecker.java @@ -0,0 +1,51 @@ +package de.memtext.rights; + +import java.io.Serializable; + +import de.memtext.util.PWChecker; + +public class NewPasswordChecker implements Serializable { +private int minimumLength=0; +private boolean isLowerAndUpperCaseNeeded=false; +private boolean isNumberNeeded=false; + + +public NewPasswordChecker(int minLaenge, int grossklein,int ziffernoetig) +{ + this.minimumLength=minLaenge; + isLowerAndUpperCaseNeeded=grossklein==1; + isNumberNeeded=ziffernoetig==1; +} + +/** + * + * @param check + * @return null wenn alles OK + */ +public String checkForFaults(String username,String check) +{ + StringBuffer result=new StringBuffer(); + if (check==null) + { + result.append("Es wurde kein Passwort übermittelt."); + } + else + { + if (check.equals(username)) + result.append("Passwort darf nicht gleich Benutzername sein"); + if (minimumLength>0&&check.length()1) return result.toString(); + else + return null; +} +} + +//Created on 20.11.2006 at 11:25:19 \ No newline at end of file diff --git a/src/de/memtext/rights/Rights.java b/src/de/memtext/rights/Rights.java new file mode 100644 index 0000000..9606fee --- /dev/null +++ b/src/de/memtext/rights/Rights.java @@ -0,0 +1,128 @@ +package de.memtext.rights; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; +import java.util.TreeSet; + +import de.memtext.util.EqualsUtil; + +/** + * A class for managing rights. In particular c + */ +public class Rights implements Serializable { + + private static final long serialVersionUID = 1; + private boolean isAdmin = false; + private boolean hasAllRights; + private Collection keyColl = new TreeSet(); + + public Rights() { + + } + + public Rights(boolean isAdmin, boolean hasAllRights) { + setAdmin(isAdmin); + setHasAllRights(hasAllRights); + } + + public boolean isAdmin() { + return isAdmin; + } + + public void setAdmin(boolean isAdmin) { + this.isAdmin = isAdmin; + } + + public void addAllowed(RightsKeyEntry rke) { + keyColl.add(rke); + } + + public void clear() { + keyColl.clear(); + } + + public boolean isEmpty() { + return keyColl.isEmpty(); + } + + public boolean hasNoRights() { + return !isAdmin && !hasAllRights && isEmpty(); + } + + public Iterator iterator() { + return keyColl.iterator(); + } + + /** + * @return + */ + public boolean hasAllRights() { + return hasAllRights; + } + + /** + * @param b + */ + public void setHasAllRights(boolean b) { + hasAllRights = b; + } + + /** + * @param dn + * @return + */ + public boolean isAllowed(Object id) { + boolean result = false; + if (isAdmin || hasAllRights()) { + result = true; + } else { + for (Iterator it = keyColl.iterator(); it.hasNext();) { + RightsKeyEntry entry = (RightsKeyEntry) it.next(); + if (EqualsUtil.areEqual(entry.getKey(), id)) { + result = true; + break; + } + } + } + return result; + + } + + public boolean isSubordinatesAllowed(Object key) { + boolean result = false; + if (isAdmin || hasAllRights()) { + result = true; + } else { + for (Iterator it = keyColl.iterator(); it.hasNext();) { + RightsKeyEntry entry = (RightsKeyEntry) it.next(); + if (EqualsUtil.areEqual(entry.getKey(), key)) { + result = entry.isSubordinatesAllowed(); + break; + } + } + } + return result; + } + + public Object clone() throws CloneNotSupportedException { + Rights cl = new Rights(isAdmin, hasAllRights); + for (Iterator it = keyColl.iterator(); it.hasNext();) { + RightsKeyEntry key = (RightsKeyEntry) it.next(); + cl.keyColl.add(key.clone()); + } + return cl; + } + + public String toString() { + StringBuffer result = new StringBuffer("Rechte: "); + for (Iterator it = keyColl.iterator(); it.hasNext();) { + RightsKeyEntry entry = (RightsKeyEntry) it.next(); + result.append(entry.toString() + ","); + } + de.memtext.util.StringUtils.removeLastChar(result); + return result.toString(); + } +} + +// Created on 07.09.2004 at 11:10:06 diff --git a/src/de/memtext/rights/RightsKeyEntry.java b/src/de/memtext/rights/RightsKeyEntry.java new file mode 100644 index 0000000..700f18d --- /dev/null +++ b/src/de/memtext/rights/RightsKeyEntry.java @@ -0,0 +1,81 @@ +package de.memtext.rights; + +import java.io.Serializable; + +public class RightsKeyEntry implements Comparable,Serializable { + + + private static final long serialVersionUID = 1L; + private final Object key; + private final boolean isSubordinatesAllowed; + + public RightsKeyEntry(Object key, boolean isSubordinatesAllowed) { + this.key = key; + this.isSubordinatesAllowed = isSubordinatesAllowed; + + } + + /** + * Returns the isSubordinatesAllowed. + * + * @return boolean + */ + public boolean isSubordinatesAllowed() { + return isSubordinatesAllowed; + } + + /** + * Returns the key. + * + * @return Object + */ + public Object getKey() { + return key; + } + + public boolean equals(Object o) { + if (!(o instanceof RightsKeyEntry)) + return false; + + Object otherKey = ((RightsKeyEntry) o).getKey(); + boolean result = false; + if (key instanceof Integer) { + result = ((Integer) key).equals((Integer) otherKey); + } else { + result = key.toString().equals(otherKey.toString()); + } + return result; + + } + + public int hashCode() { + int result = 37 + key.hashCode() + (isSubordinatesAllowed ? 0 : 1); + return result; + } + + public int compareTo(Object o) { + Object otherKey = ((RightsKeyEntry) o).getKey(); + int result = 0; + if (key instanceof Integer) { + result = ((Integer) key).compareTo((Integer) otherKey); + } else { + result = key.toString().compareTo((String)otherKey); + } + + return result; + } + + public Object clone() throws CloneNotSupportedException { + if (key != null && !(key instanceof String || key instanceof Integer)) + throw new CloneNotSupportedException("Prüfen, ob " + key.getClass() + + " problemlos geclont werden kann"); + RightsKeyEntry cl = new RightsKeyEntry(key, isSubordinatesAllowed); + return cl; + + } + public String toString() + { + return key.toString(); + } +} +//Created on 11.08.2003 diff --git a/src/de/memtext/stat/Statistics.java b/src/de/memtext/stat/Statistics.java new file mode 100644 index 0000000..a498e5c --- /dev/null +++ b/src/de/memtext/stat/Statistics.java @@ -0,0 +1,200 @@ +package de.memtext.stat; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.Vector; + +public class Statistics { + + /** + * + */ + public static double getAverage(Collection zahlen) { + BigDecimal aNumber; + double summe = 0; + int nonNullValues = 0; + Object obj; + Iterator it = zahlen.iterator(); + while (it.hasNext()) { + obj = it.next(); + // if (obj==null) throw new RuntimeException("Null values not allowed!"); + // if (obj==null){System.out.println("got null");} + if (obj != null) { + aNumber = new BigDecimal(obj.toString()); + summe += aNumber.doubleValue(); + nonNullValues++; + } + + } + return summe / nonNullValues; + } + + public static double getStd(Collection zahlen) { + BigDecimal aNumber; + double zahl, quadrate = 0, std; + Object obj; + double mittelwert = getAverage(zahlen); + Iterator it = zahlen.iterator(); + int nonNullValues = 0; + while (it.hasNext()) { + obj = it.next(); + if (obj != null) { + aNumber = new BigDecimal(obj.toString()); + zahl = aNumber.doubleValue(); + quadrate += ((zahl - mittelwert) * (zahl - mittelwert)); + //System.out.println(zahl+" "+((zahl - mittelwert) * (zahl - mittelwert))); + nonNullValues++; + } + + } + //System.out.println(quadrate); + std = java.lang.Math.sqrt(quadrate / (nonNullValues - 1)); + return std; + } + public static double getAverage(Vector zahlen) { + return getAverage((Collection) zahlen); + } + public static double getStd(Vector zahlen) { + return getStd((Collection) zahlen); + } + + public static Double getZValue( + double zahl, + double mittelwert, + double std) { + double z = (zahl - mittelwert) / std; + Double test = new Double(z); + //if (test.isNaN()) return "0"; else return z+""; + return test; + } + public static float getMedian(float[] a) { + Arrays.sort(a); + int x = a.length / 2; + if (a.length % 2 == 0) + return (a[x] + a[x-1]) / 2; + return a[x]; + } + public static double getMedian(double[] a) { + Arrays.sort(a); + int x = a.length / 2; + if (a.length % 2 == 0) + return (a[x] + a[x-1]) / 2; + return a[x]; + } + public static int getMedian(int[] a) { + Arrays.sort(a); + int x = a.length / 2; + if (a.length % 2 == 0) + return (a[x] + a[x-1]) / 2; + return a[x]; + } + public static void main(String[] arg) { + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Double d3 = new Double(3.5); + Double d4m = new Double(-4.5); + Long l5 = new Long(5); + Long l11 = new Long(11); + BigDecimal bd = new BigDecimal(8.7); + Vector allzahlen = new Vector(); + + allzahlen.add(i1); + allzahlen.add(i2); + allzahlen.add(i3); + allzahlen.add(d3); + allzahlen.add(d4m); + allzahlen.add(null); + allzahlen.add(l5); + allzahlen.add(l11); + allzahlen.add(bd); + System.out.println(Statistics.getAverage(allzahlen)); + System.out.println(Statistics.getStd(allzahlen)); + + } + /** + + * Null-values are not counted + + */ + /* + public static double getAverage(Collection zahlen) { + + BigDecimal aNumber; + + double summe = 0; + + Object obj; + + Iterator it=zahlen.iterator(); + + int notNullCount=0; + + while (it.hasNext()){ + + obj = it.next(); + + if (obj==null) continue; + + aNumber=new BigDecimal(obj.toString()); + + summe += aNumber.doubleValue(); + + notNullCount++; + + + } + + return summe / notNullCount; + + } + + /** + + * Null-values are not counted + + */ + /* + public static double getStd(Collection zahlen) { + + BigDecimal aNumber; + + double zahl, quadrate = 0, std; + + Object obj; + + double mittelwert = getAverage(zahlen); + + int notNullCount=0; + + Iterator it=zahlen.iterator(); + + while (it.hasNext()){ + + obj = it.next(); + + if (obj==null) continue; + + aNumber=new BigDecimal(obj.toString()); + + zahl=aNumber.doubleValue(); + + quadrate += ((zahl - mittelwert) * (zahl - mittelwert)); + + //System.out.println(zahl+" "+((zahl - mittelwert) * (zahl - mittelwert))); + + notNullCount++; + + + } + + //System.out.println(quadrate); + + std = java.lang.Math.sqrt(quadrate / (notNullCount - 1)); + + return std; + + } + */ +} diff --git a/src/de/memtext/time/EphemeralI.java b/src/de/memtext/time/EphemeralI.java new file mode 100644 index 0000000..4ffa29c --- /dev/null +++ b/src/de/memtext/time/EphemeralI.java @@ -0,0 +1,10 @@ +package de.memtext.time; +public interface EphemeralI { + public java.util.Date getValidSince(); + public java.util.Date getValidTill(); + public void setValidSince(java.util.Date date); + public void setValidTill(java.util.Date date); + public boolean isValidAt(java.util.Date date); +} + +//Created on 05.02.2005 at 14:02:38 \ No newline at end of file diff --git a/src/de/memtext/time/Period.java b/src/de/memtext/time/Period.java new file mode 100644 index 0000000..d992b9b --- /dev/null +++ b/src/de/memtext/time/Period.java @@ -0,0 +1,116 @@ +package de.memtext.time; + +import java.io.Serializable; +import java.util.Date; + +import de.memtext.util.DateUtils; + +/** + * A class representing a period in time, from - till + */ +public class Period implements Serializable { + private Date from, till; + private boolean isEternity; + private static final long serialVersionUID = 1; + + /** + * Convience constructor + * + * @param from + * -must be null or java.util.Date + * @param till + * -must be null or java.util.Date + */ + public Period(Object from, Object till) { + if (from != null && !(from instanceof Date)) + throw new IllegalArgumentException("only Date allowed"); + if (till != null && !(from instanceof Date)) + throw new IllegalArgumentException("only Date allowed"); + if (from != null) + setFrom((Date) from); + else + setFrom(null); + if (till != null) + setTill((Date) till); + else + setTill(null); + + } + + public Period(Date from, Date till) { + this.from = from; + this.till = till; + } + + public Date getFrom() { + return from; + } + + public Date getTill() { + return till; + } + + public void setFrom(Date date) { + from = date; + } + + public void setTill(Date date) { + till = date; + } + + public String toString() { + return DateUtils.format(from) + " - " + DateUtils.format(till); + } + + public boolean isEternity() { + return isEternity; + } + + public void setEternity(boolean isEternity) { + this.isEternity = isEternity; + } + + public boolean isInPeriod(java.util.Date date) { + return isEternity||from.compareTo(date)<=0&&till.compareTo(date)>=0; + } + public static void main(String args[]) { + Period validityPeriod=new Period(java.sql.Date.valueOf("1900-01-01"),java.sql.Date.valueOf("3000-01-01")); + System.out.println(validityPeriod.isInPeriod(java.sql.Date.valueOf("1800-01-01"))); + System.out.println(validityPeriod.isInPeriod(java.sql.Date.valueOf("1900-01-01"))); + System.out.println(validityPeriod.isInPeriod(java.sql.Date.valueOf("2000-01-01"))); + System.out.println(validityPeriod.isInPeriod(java.sql.Date.valueOf("3000-01-01"))); + System.out.println(validityPeriod.isInPeriod(java.sql.Date.valueOf("3000-02-01"))); + } + public Object clone() throws CloneNotSupportedException { + Date clfrom=null; + if (from!=null) clfrom=new Date(from.getTime()); + Date cltill=null; + if (till!=null) cltill=new Date(till.getTime()); + Period cl=new Period(clfrom,cltill); + cl.isEternity=isEternity; + return cl; + + } +/** + * Returns from-date formatted as German string. + * "" if from is null + * @return + */ + public String getFromString() { + String result=""; + if (from!=null) result=DateUtils.formatGerman(from); + return result; + } + /** + * Returns till-date formatted as German string. + * "" if till is null + * @return + */ + public String getTillString() { + String result=""; + if (till!=null) result=DateUtils.formatGerman(till); + return result; + } +} + +//Created on 20.11.2003 diff --git a/src/de/memtext/time/PeriodBuilder.java b/src/de/memtext/time/PeriodBuilder.java new file mode 100644 index 0000000..699e357 --- /dev/null +++ b/src/de/memtext/time/PeriodBuilder.java @@ -0,0 +1,30 @@ +package de.memtext.time; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class PeriodBuilder { + + private PeriodBuilder() { + + } + /** + * creates a list of Period objects + * @param rawList - a List containing Lists for every row + * @return + */ +public static List createPeriodList(List rawList) +{ + Period p; + List result=new LinkedList(); + for (Iterator it = rawList.iterator(); it.hasNext();) { + List row = (List) it.next(); + p=new Period(row.get(0),row.get(1)); + result.add(p); + } + return result; +} +} + +//Created on 20.11.2003 \ No newline at end of file diff --git a/src/de/memtext/tree/AbstractCellEditor.java b/src/de/memtext/tree/AbstractCellEditor.java new file mode 100644 index 0000000..045aabd --- /dev/null +++ b/src/de/memtext/tree/AbstractCellEditor.java @@ -0,0 +1,106 @@ +package de.memtext.tree; +import java.awt.Component; +import java.awt.event.MouseEvent; +import java.util.EventObject; + +import javax.swing.JTable; +import javax.swing.JTree; +import javax.swing.event.CellEditorListener; +import javax.swing.event.ChangeEvent; +import javax.swing.event.EventListenerList; +import javax.swing.table.TableCellEditor; +import javax.swing.tree.TreeCellEditor; + +/** + * unused + **/ +public class AbstractCellEditor implements TableCellEditor, TreeCellEditor { + protected EventListenerList listenerList = new EventListenerList(); + protected Object value; + protected ChangeEvent changeEvent = null; + protected int clickCountToStart = 1; + + public Object getCellEditorValue() { + return value; + } + public void setCellEditorValue(Object value) { + this.value = value; + } + public void setClickCountToStart(int count) { + clickCountToStart = count; + } + public int getClickCountToStart() { + return clickCountToStart; + } + public boolean isCellEditable(EventObject anEvent) { + if (anEvent instanceof MouseEvent) { + if (((MouseEvent) anEvent).getClickCount() < clickCountToStart) + return false; + } + return true; + } + public boolean shouldSelectCell(EventObject anEvent) { + if (this.isCellEditable(anEvent)) { + if (anEvent == null + || ((MouseEvent) anEvent).getClickCount() >= clickCountToStart) + return true; + } + return false; + } + public boolean stopCellEditing() { + fireEditingStopped(); + return true; + } + public void cancelCellEditing() { + fireEditingCanceled(); + } + public void addCellEditorListener(CellEditorListener l) { + listenerList.add(CellEditorListener.class, l); + } + public void removeCellEditorListener(CellEditorListener l) { + listenerList.remove(CellEditorListener.class, l); + } + public Component getTreeCellEditorComponent( + JTree tree, + Object value, + boolean isSelected, + boolean expanded, + boolean leaf, + int row) { + return null; + } + public Component getTableCellEditorComponent( + JTable table, + Object value, + boolean isSelected, + int row, + int column) { + return null; + } + protected void fireEditingStopped() { + Object[] listeners = listenerList.getListenerList(); + + for (int i = listeners.length - 2; i >= 0; i -= 2) { + if (listeners[i] == CellEditorListener.class) { + if (changeEvent == null) + changeEvent = new ChangeEvent(this); + + ((CellEditorListener) listeners[i + 1]).editingStopped( + changeEvent); + } + } + } + protected void fireEditingCanceled() { + Object[] listeners = listenerList.getListenerList(); + + for (int i = listeners.length - 2; i >= 0; i -= 2) { + if (listeners[i] == CellEditorListener.class) { + if (changeEvent == null) + changeEvent = new ChangeEvent(this); + + ((CellEditorListener) listeners[i + 1]).editingCanceled( + changeEvent); + } + } + } +} diff --git a/src/de/memtext/tree/AutoScrollJTree.java b/src/de/memtext/tree/AutoScrollJTree.java new file mode 100644 index 0000000..2b702ed --- /dev/null +++ b/src/de/memtext/tree/AutoScrollJTree.java @@ -0,0 +1,91 @@ +package de.memtext.tree; + +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.dnd.Autoscroll; +import java.util.Hashtable; +import java.util.Vector; + +import javax.swing.JTree; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; + +/** + * This class adds auto scrolling functionality to JTree. + * This means that during a drag operation the tree automatically scrolls + * up or down in JScrollPane if necessary. + */ +public class AutoScrollJTree extends JTree implements Autoscroll{ + private int lastRowOver=-1; + /** + * + */ + public AutoScrollJTree() { + super(); + } + + /** + * @param arg0 + */ + public AutoScrollJTree(Object[] arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public AutoScrollJTree(Vector arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public AutoScrollJTree(Hashtable arg0) { + super(arg0); + } + + /** + * @param arg0 + */ + public AutoScrollJTree(TreeNode arg0) { + super(arg0); + } + + /** + * @param arg0 + * @param arg1 + */ + public AutoScrollJTree(TreeNode arg0, boolean arg1) { + super(arg0, arg1); + } + + /** + * @param arg0 + */ + public AutoScrollJTree(TreeModel arg0) { + super(arg0); + } + public void autoscroll(Point p){ + int currentRow = this.getClosestRowForLocation(p.x,p.y); + // (int) lastRowOver is a member of the class, initialized with -1 + if (lastRowOver==-1) {lastRowOver=currentRow;return;} + + if(currentRow > lastRowOver) + scrollRowToVisible(currentRow + 1); + else if(currentRow > 0) + scrollRowToVisible(currentRow - 1); + lastRowOver = currentRow; + } + + public Insets getAutoscrollInsets() { + int margin=12; + Rectangle outer = getBounds(); + Rectangle inner = getParent().getBounds(); + return new Insets( + inner.y - outer.y + margin, inner.x - outer.x + margin, + outer.height - inner.height - inner.y + outer.y + margin, + outer.width - inner.width - inner.x + outer.x + margin); + } +} diff --git a/src/de/memtext/tree/CheckBoxNodeDec.java b/src/de/memtext/tree/CheckBoxNodeDec.java new file mode 100644 index 0000000..cc1c22a --- /dev/null +++ b/src/de/memtext/tree/CheckBoxNodeDec.java @@ -0,0 +1,120 @@ +package de.memtext.tree; + +import java.lang.reflect.Method; +import java.util.Enumeration; + +import javax.swing.tree.DefaultMutableTreeNode; + +/** + * A TreeNode which has a checkbox and thus can be selected or deselected. + * + */ +public class CheckBoxNodeDec extends DefaultMutableTreeNode { + private DefaultMutableTreeNode internalNode; + public final static int SINGLE_SELECTION = 0; + public final static int DIG_IN_SELECTION = 4; + private static final Class[] booleanparam = { Boolean.TYPE }; + protected int selectionMode; + protected boolean isSelected,isCheckBoxVisible; + private Method setMethod = null; + + public CheckBoxNodeDec(DefaultMutableTreeNode node, String setMethodName,boolean isCheckBoxVisible) { + super(node.getUserObject()); + this.isCheckBoxVisible=isCheckBoxVisible; + this.internalNode = node; + setSelectionMode(DIG_IN_SELECTION); + if (setMethodName != null) { + + try { + setMethod = + node.getClass().getMethod(setMethodName, booleanparam); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + System.exit(-1); + } + } + } + + /*public CheckBoxNodeDec(DefaultMutableTreeNode node, Method setMethod) { + super(node.getUserObject()); + this.setMethod = setMethod; + this.internalNode = node; + setSelectionMode(DIG_IN_SELECTION); + }*/ + public DefaultMutableTreeNode getInternalNode() { + return internalNode; + } + /* public CheckBoxNodeDec() { + this(null); + } + + public CheckBoxNodeDec(Object userObject) { + this(userObject, true, false); + } + + public CheckBoxNodeDec(Object userObject, boolean allowsChildren + , boolean isSelected) { + super(userObject, allowsChildren); + this.isSelected = isSelected; + setSelectionMode(DIG_IN_SELECTION); + } + */ + + public void setSelectionMode(int mode) { + selectionMode = mode; + } + + public int getSelectionMode() { + return selectionMode; + } + + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + if (setMethod != null) { + try { + Object param[] = { new Boolean(isSelected)}; + setMethod.invoke(internalNode, param); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + if ((selectionMode == DIG_IN_SELECTION) && (children != null)) { + Enumeration en = children.elements(); + while (en.hasMoreElements()) { + CheckBoxNodeDec node = (CheckBoxNodeDec) en.nextElement(); + node.setSelected(isSelected); + } + } + } + } + + public boolean isSelected() { + return isSelected; + } + + // If you want to change "isSelected" by CellEditor, + /* + public void setUserObject(Object obj) { + if (obj instanceof Boolean) { + setSelected(((Boolean)obj).booleanValue()); + } else { + super.setUserObject(obj); + } + } + */ + + /** + * @return + */ + public boolean isCheckBoxVisible() { + return isCheckBoxVisible; + } + + /** + * @param b + */ + public void setCheckBoxVisible(boolean b) { + isCheckBoxVisible = b; + } + +} diff --git a/src/de/memtext/tree/CheckBoxTreeDec.java b/src/de/memtext/tree/CheckBoxTreeDec.java new file mode 100644 index 0000000..fe3b01b --- /dev/null +++ b/src/de/memtext/tree/CheckBoxTreeDec.java @@ -0,0 +1,249 @@ +package de.memtext.tree; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.Icon; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.UIManager; +import javax.swing.plaf.ColorUIResource; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeCellRenderer; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; + +//import jp.gr.java_conf.tame.swing.tree.*; + +/** + * Shows a JTree in a JScrollPane and gives possibility to mark nodes with checkboxes. + * Reflection makes it possible to pass a setmethod name (boolean) + * @version 1.1 01/15/99 + */ +public class CheckBoxTreeDec extends JScrollPane { +private String setMethodName; +private List acceptableClasses=new LinkedList(); +public CheckBoxTreeDec(JTree tree,String setMethodName) +{ + throw new UnsupportedOperationException(); + //needs activityNode + /*this.setMethodName=setMethodName; + //CheckBoxNodeDec root= new CheckBoxNodeDec(((DefaultMutableTreeNode)) ((DefaultTreeModel)tree.getModel()).getRoot(),setMethodName); + CheckBoxNodeDec root= new CheckBoxNodeDec(((DefaultMutableTreeNode)) ((DefaultTreeModel)tree.getModel()).getRoot(),null,false); + addSubNodes(root); + init(root); + acceptableClasses.add(DefaultMutableTreeNode.class);*/ +} +public CheckBoxTreeDec(JTree tree,String setMethodName,List acceptableClasses) +{ + this.setMethodName=setMethodName; + //CheckBoxNodeDec root= new CheckBoxNodeDec(((DefaultMutableTreeNode)) ((DefaultTreeModel)tree.getModel()).getRoot(),setMethodName); + //addSubNodes(root); + //init(root); + this.acceptableClasses=acceptableClasses; +} +private void addSubNodes(CheckBoxNodeDec aNode) +{ + throw new UnsupportedOperationException(); +/* String currentSetMethodName=null; + if (aNode.getInternalNode().getClass()==ActivityNode.class) + currentSetMethodName=setMethodName; + + for (int i=0;i