From: zapata Date: Wed, 9 Apr 2003 02:06:06 +0000 (+0000) Subject: new admin templates! with many thanks to init... X-Git-Tag: BEFORE_MERGE_1_1~190 X-Git-Url: http://erislabs.net/gitweb/?a=commitdiff_plain;h=55d545036aa5c04676f2d20f0e98316a4679ec27;hp=86a7f9a337462ad82b23c77e91621929b2a741e3;p=mir.git new admin templates! with many thanks to init... --- diff --git a/bundles/admin.properties b/bundles/admin.properties deleted file mode 100755 index 934648a3..00000000 --- a/bundles/admin.properties +++ /dev/null @@ -1,2 +0,0 @@ -# you can replace this file with a link to your default language admin bundle -htmlcharset=utf-8 diff --git a/bundles/admin_ay.properties b/bundles/admin_ay.properties deleted file mode 100755 index 3dffa24a..00000000 --- a/bundles/admin_ay.properties +++ /dev/null @@ -1,312 +0,0 @@ -########## admin ########## -# language: aymara - -languagename=Aymara - -# general -yes=sí -no=no -dontcare=no importa -all=todo - -# actions -insert=insertar -save=guardar -edit=editar -delete=borrar -add=añadir -filter=filtrar -attach=vincular -list=mostrar lista -back=atrás -cancel=cancelar - -# records -records=registros -show_from_to=mostrando entradas desde {0} hasta {1} -no_matches_found=No se encontraron resultados! -list.next=siguiente -list.previous=anterior - -# media - used by image, audio, video and other media -media.created=creado -media.changed=cambiado -media.published=publicado -media.format=Formato -media.rights=Copyright -media.type=Tipo -media.mediafolder=Carpeta de recursos mediáticos -media.title=Título -media.description=Descripción -media.date=Fecha -media.location=Lugar de origen -media.creator=Creador -media.keywords=Palabras clave -media.comment=Comentario -media.source=Origen -media.is_published=Disponible para publicación -media.icon=Icono -media.nr_of_media=Número de recursos mediáticos -media.nr_of_media.submit=Anzahl festlegen -medialist.search_text_in=Buscar texto en - -# image -image.htmltitle=imagen -imagelist.htmltitle=lista de imagenes - -# audio -audio.htmltitle=audio -audiolist.htmltitle=lista de audio - -# video -video.htmltitle=video -videolist.htmltitle=lista de video - -# other -other_media.htmltitle=otros recursos mediáticos -other_media.htmltitle=lista de recursos mediáticos - -# breaking -breaking.htmltitle=últimas noticias -breakinglist.htmltitle=listado de últimas noticias -breaking.textinfo=(max. 5 líneas / 250 caracteres) -breaking.text=texto -breaking.date=fecha - - -# comment -comment.htmltitle=commentario -comment.date=fecha -comment.title=título -comment.published=publicado -comment.text=texto-del-comentario -comment.address=dirección -comment.phone=teléfono -comment.email=email -comment.url=url -comment.creator=autor -comment.article=del artículo -comment.html=HTML? -comment.status=Status # needs translation - -commentlist.htmltitle=lista de comentarios -commentlist.published=publicado -commentlist.hidden=oculto -commentlist.search=buscar! - -commentlist.order.datedesc= date (desc.) # needs translation -commentlist.order.dateasc= date (asc.) # needs translation -commentlist.order.articletitle= article title # needs translation - - -# confirm -confirm.htmltitle=confirmar borrado -confirm.really_delete=Desea borrar esta entrada? - -# content -content.htmltitle=contenido -content.owner=Propietario -content.topic=Tema -content.feature=Característica -content.title=titulo largo -content.subtitle=subtítulo/título de contexto -content.location=Lugar de origen -content.creator=autor -content.creator.email=Email -content.creator.url=Web -content.creator.address=Dirección -content.creator.telephone=Teléfono -content.abstract=Descripción breve -content.content=Contenido -content.html=es HTML? -content.comment=Comentario interno -content.internal=(propósito interno) -content.attachments=Vínculos -content.images=Imágenes -content.audio=Audio -content.video=Video -content.other=Otros recursos mediáticos -content.media=Recursos mediáticos -content.addimage=añadir imagen -content.addaudio=añadir audio -content.addvideo=añadir video -content.addother=añadir otros recursos mediáticos -content.creationdate=fecha -content.modificationdate=último cambio -content.status=Estado -content.type=Tipo de artículo -content.published=publicado -content.comments=Comentarios - -contentlist.htmltitle=lista de contenidos - -# language -language.htmltitle=idiomas -language.name=idioma -language.code=Código del idioma - -languagelist.htmltitle=lista de idiomas - -# imcs -linkimcs.htmltitle=Enlaces a IMCs -linkimcs.name=Nombre -linkimcs.continent=Continente -linkimcs.new_parent=Nuevo Ancestro -linkimcs.url=URL -linkimcs.sort_by=Criterio de orden -linkimcs.language=Idioma -linkimcs.parent=ancestro - -linkimcslist.htmltitle=Lista de enlaces a IMCs -linkimcslist.search_in=Buscar texto en - -# login -login.htmltitle=registro -login.info=Esta zona es accesible exclusivamente a grupos autorizados. Si desea colaborar como editor, por favor contacte con nosotros en {0} -login.title=login -login.name=Login -login.password=Password -login.language=Idioma -login.submit= Envíar - -# mediafolder -mediafolder.htmltitle=carpeta de recursos mediáticos -mediafolder.date=fecha -mediafolder.name=nombre -mediafolder.location=lugar de origen -mediafolder.keywords=palabras clave -mediafolder.comment=commentario - -mediafolderlist.htmltitle=lista de carpetas de recursos mediáticos - -# message -message.htmltitle=mensajes -message.date=fecha -message.title=título -message.creator=Autor -message.text=texto -message.textinfo=(max. 5 líneas / 250 caracteres) - -messagelist.htmltitle=lista de mensajes - -# feature -feature.htmltitle=presentación -feature.title=Título -feature.published=publicado -feature.is_published=está publicado -feature.is_not_published=no está publicado -feature.filename=Nombre del fichero -feature.abstract=Descripción breve -feature.link=Enlace - -featurelist.htmltitle=lista de presentaciones - -# admin start page -start.htmltitle=administración -start.openpostings.title=ENVÍOSABIERTOS -start.comments.title=COMENTARIOS -start.breaking.title=ÚLTIMAS NOTICIAS -start.breaking.new=últimas noticias recientes -start.content.title=ARTICULOS -start.content.new=nuevos artículos -start.show=mostrar -start.content.newswire=newswire -start.content.feature=presentación -start.content.topicspecial=especiales-por-tema -start.content.startspecial=especiales-página-de-inicio -start.content.not_published=artículos aun sin publicar -start.content.with_media=con recursos mediáticos -start.content.last_changes=últimos cambios -start.content.with_comments=con comentarios de propósito interno -start.content.all=todos -start.content.search=buscar -start.generate.title=GENERAR MANUALMENTE -start.generate.all.title=todas las areas -start.generate.all.new=todo nuevo (estándar, actualización en la web > 5min.) -start.generate.parts.title=partes específicas del website -start.generate.startpages.new=nueva página de inicio -start.generate.all_forced=todos (forzado) -start.generate.all_sync=todos (forzado y sincronizado) -start.generate.content.new=nuevo contenido -start.generate.topics.new=nuevos temas -start.generate.postings.new=nuevos envios abiertos -start.generate.images.new=nuevas imágenes -start.generate.audio.new=nuevos ficheros de audio -start.generate.video.new=nuevos ficheros de video -start.generate.other.new=otros recursos mediáticos nuevos -start.generate.navigation=navegación -start.coverage.title=COBERTURA -start.topics.title=TEMAS -start.images.title=MATERIAL GRAFICO -start.mediafolder.title=CARPETA DE RECURSOS MEDIATICOS -start.languages.title=TÍTULO -start.imcs.title=IMCS -start.messageboard.title=Mensajería Interna -start.messageboard.no_messages=no hay mensajes - -start.superusermenu=Superuser menu (use with care!) # needs translation - -# topic -topic.htmltitle=tema -topic.title=Nombre -topic.description=descripción -topic.filename=Nombre del fichero -topic.main_url=página de información principal -topic.archive_url=URL del archivo - -topiclist.htmltitle=lista de temas - -articletype.htmltitle=Article type # needs translation -articletype.id=id # needs translation -articletype.name=Name # needs translation - -articletypelist.htmltitle=Article types # needs translation - -commentstatus.htmltitle=Comment status # needs translation -commentstatus.id=id # needs translation -commentstatus.name=Name # needs translation - -commentstatuslist.htmltitle=Comment status values # needs translation - - -superusermenu.htmltitle = Super-user functions # needs translation -superusermenu.topics = Manage topics # needs translation -superusermenu.articletypes = Manage article types # needs translation -superusermenu.comment_statuses = Manage comment status values # needs translation -superusermenu.users = Manage users # needs translation -superusermenu.languages = Manage languages # needs translation -superusermenu.imcs = Manage IMCS (obsolete) # needs translation - - -# users -user.htmltitle=usuario -user.login=login -user.password=password -user.admin=administrador - -userlist.htmltitle=lista de usuarios - -# head -head.start=inicio -head.logout=salir -head.help=ayuda -head.search=buscar -head.logged_in=estás registrado - -# foot -foot.top=arriba - - -########## error ########## - -error.htmltitle=error -error.title=oi! oi! oi! -error.text=El siguiente mensaje puede que no le sea de mucha ayuda, pero seguramente lo será para {1}: -error.text2=Por favor envíe un mensaje con el texto que aparece en rojo y una descripción detallada a la siguiente dirección {1}. Gracias! - - -usererror.htmltitle=error de datos -usererror.title=oi! oi! oi! -usererror.text=Los datos que ha introducido han causado el siguiente error: -usererror.what_to_do=Por favor, pulse el botón para volver e intentelo de nuevo -htmlcharset=utf-8 diff --git a/bundles/admin_de.properties b/bundles/admin_de.properties index 24044cea..ef099c1b 100755 --- a/bundles/admin_de.properties +++ b/bundles/admin_de.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: deutsch / german -# $Id: admin_de.properties,v 1.26 2003/02/21 05:38:36 zapata Exp $ +# $Id: admin_de.properties,v 1.27 2003/04/09 02:06:06 zapata Exp $ languagename=Deutsch @@ -9,30 +9,43 @@ yes=ja no=nein dontcare=egal all=alle -year=Jahr month=Monat +year=Jahr file=Datei +new=neu +by=von +help=Hilfe + # actions insert=einfügen save=speichern edit=bearbeiten delete=löschen -add=hinzufügen -filter=filter -attach=attach -list=browse +add=neu +filter=filtern +attach=anhängen +list=auflisten back=zurück cancel=abbrechen preview=Vorschau +reset=reset +administer=administrieren +search=suchen + + +# special +fileedit=Dateien bearbeiten + # records -records=Datensätze -show_from_to=Anzeige von {0} bis {1} -no_matches_found=Noch keine passenden Einträge gefunden! +records=Einträge +show_from_to=zeige von {0} bis {1} +no_matches_found=(noch) keine Einträge gefunden list.next=weiter list.previous=zurück + # media - used by image, audio, video and other media media.created=erzeugt media.changed=letzte änderung @@ -55,23 +68,28 @@ media.icon=Icon media.nr_of_media=Anzahl der Medien (max 20) media.nr_of_media.submit=Anzahl festlegen -medialist.search_text_in=Text suchen in +medialist.search_text_in=Search text in + # image -image.htmltitle=image -imagelist.htmltitle=imagelist +image.htmltitle=Bilder +imagelist.htmltitle=Bilder Liste + # audio -audio.htmltitle=audio -audiolist.htmltitle=audiolist +audio.htmltitle=Audio +audiolist.htmltitle=Audio Liste + # video -video.htmltitle=video -videolist.htmltitle=videolist +video.htmltitle=Video +videolist.htmltitle=Video Liste + # other -other_media.htmltitle=other media -other_media.htmltitle=other medialist +other_media.htmltitle=andere Medien +other_medialist.htmltitle=andere Medien Liste + # breaking breaking.htmltitle=breaking news @@ -79,10 +97,11 @@ breaking.textinfo=(max. 5 Zeilen / 250 Zeichen) breaking.text=Text breaking.date=Datum -breakinglist.htmltitle=breaking new list +breakinglist.htmltitle=Breaking news Liste + # comment -comment.htmltitle=comment +comment.htmltitle=Ergänzungen comment.date=Datum comment.title=Titel comment.published=publiziert @@ -92,72 +111,142 @@ comment.phone=Telefon comment.email=Email comment.url=Url comment.creator=Uhrheber -comment.article=zu artikel +comment.article=zu Artikel comment.html=HTML? -comment.status=Status # needs translation +comment.status=Status comment.language=Sprache -commentlist.htmltitle=commentlist -commentlist.published=publiziert +comment.operation.hide=verstecken +comment.operation.unhide=zeigen + + +#commentlist +commentlist.htmltitle=Kommentare Liste +commentlist.published=sichtbar commentlist.hidden=versteckt commentlist.search=go! +commentlist.activate = Änderungen aktivieren +commentlist.order = Reihenfolge +commentlist.order.datedesc= Datum (abst.) +commentlist.order.dateasc= Datum (aufst.) +commentlist.order.articletitle= Artikel Titel -commentsearch.order.datedesc= date (desc.) # needs translation -contentsearch.order.dateasc= date (asc.) # needs translation -contentsearch.order.articletitle= article title # needs translation +commentsearch.field = Suchen +commentsearch.field.title = Title +commentsearch.field.creator = Author +commentsearch.field.description = Beschreibung +commentsearch.value = Feld + +commentsearch.publishedstate = Publish Status +commentsearch.publishedstate.hidden = versteckt +commentsearch.publishedstate.published = sichtbar + +commentsearch.status = Status + +commentsearch.order = Reihenfolge +commentsearch.order.datedesc= Datum (abst.) +commentsearch.order.dateasc= Datum (aufst.) +commentsearch.order.articletitle= Artikeltitel + +commentsearch.searchbutton = suchen # confirm -confirm.htmltitle=confirm delete -confirm.really_delete=Datensatz wirklich löschen? +confirm.htmltitle=Löschen bestätigen +confirm.really_delete=Eintrag wirklich löschen? +confirm.text=Der Eintrag wird endgültig aus der Datenbank entfernt! + # content -content.htmltitle=content -content.owner=Datensatz gehört -content.topic=Thema -content.feature=Feature -content.title=Langer Titel -content.subtitle=Kurztitel/Kontexttitel +content.htmltitle=Artikel +content.owner=Eigner +content.language=Sprache +content.articletype=Artikel Typ +content.topic=Topic +content.title=Titel +content.subtitle=Subtitel / Kontenttitek content.location=Ort content.creator=Autor -content.creator.email=Email +content.creator.email=E-mail content.creator.url=Web content.creator.address=Adresse content.creator.telephone=Telefon content.abstract=Abstract content.content=Inhalt -content.html=HTML? -content.comment=Internes Kommentar +content.html=HTML +content.comment=interne Bemerkung content.internal=(intern) + content.attachments=Attachments content.images=Bilder content.audio=Audio content.video=Video -content.other=Sonstiges +content.other=Andere Medien content.media=Medien -content.addimage=Bild hinzufügen -content.addaudio=Audio hinzufügen -content.addvideo=Video hinzufügen -content.addother=Sonstiges medien hinzufügen -content.creationdate=date -content.modificationdate=last change +content.addimage=Bild anhängen +content.uploadimage=Bild hochladen +content.addaudio=Audio anhängen +content.uploadaudio=Audio hochladen +content.addvideo=Video anhängen +content.uploadvideo=Video hochladen +content.addother=Medien anhängen +content.uploadother=Andere Medien hochladen + +content.creationdate=Datum +content.modificationdate=letzte Änderung content.status=Status -content.type=articletype -content.import_date=Importiert -content.lastchange_date=zuletzt geäendert -content.create_date=Datum -content.published=publiziert -content.comments=Ergänzungen +content.type=Artikeltyp +content.import_date=Einfügedatum +content.lastchange_date=letzte Änderung +content.create_date=Datum +content.published=veröffentlicht +content.comments=Ergänzungen + +content.family=Kinder & Eltern +content.children=Kind +content.viewchildren=zeigen +content.parent=Mutter +content.viewparent=zeigen +content.clearparent=lösen +content.selectparent=wählen + +content.operation.hide=verstecken +content.operation.unhide=zeigen +content.operation.newswire=Newswire + +contentsearch.value = suchen: +contentsearch.field = Feld +contentsearch.field.title = Titel +contentsearch.field.creator = Autor +contentsearch.field.contents=Inhalt + +contentsearch.publishedstate = Status +contentsearch.publishedstate.hidden=versteckt +contentsearch.publishedstate.published=sichtbar + +contentsearch.articletype = Artikeltyp + +contentsearch.order = sortieren nach +contentsearch.order.datedesc=Neue zuerst +contentsearch.order.dateasc=Alte zuerst +contentsearch.order.title=nach Titel +contentsearch.order.creator=nach Autor +contentsearch.searchbutton=suchen + + +#contentlist +contentlist.htmltitle=Artikel Liste +contentlist.comments=Ergänzungen +contentlist.select=wählen -contentlist.htmltitle=contentlist -contentlist.comments=ergänzungen # language -language.htmltitle=languages +language.htmltitle=Sprache language.name=Sprache -language.code=Ländercode +language.code=Language code + +languagelist.htmltitle=Sprachen -languagelist.htmltitle=languages list # imcs linkimcs.htmltitle=LinksImcs @@ -172,6 +261,7 @@ linkimcs.parent=parent linkimcslist.htmltitle=LinksImcsList linkimcslist.search_in=Text suchen in + # login login.htmltitle=login login.info=Dieser Bereich steht nur authorisierten Gruppen zur Verfügung. Wenn ihr aktuelle Nachrichten einspielen wollt, so koennt ihr als Redaktionsgruppe teilnehmen. Bitte meldet Euch bei der {0}. @@ -182,152 +272,216 @@ login.language=Sprache login.submit= OK # mediafolder -mediafolder.htmltitle=mediafolder -mediafolder.date=datum -mediafolder.name=name -mediafolder.location=ort -mediafolder.keywords=stichworte -mediafolder.comment=kommentar +mediafolder.htmltitle=Mediafolder +mediafolder.date=Datum +mediafolder.name=Name +mediafolder.location=Ort +mediafolder.keywords=Stichworte +mediafolder.comment=Kommentar + +mediafolderlist.htmltitle=Mediafolderlist -mediafolderlist.htmltitle=mediafolderlist # message -message.htmltitle=messages -message.date=datum -message.title=titel -message.creator=autor -message.text=text -message.textinfo=(max. 5 zeilen / 250 zeichen) - -messagelist.htmltitle=message list - -# feature -feature.htmltitle=feature -feature.title=Titel -feature.published=frei -feature.is_published=freigeschaltet -feature.is_not_published=nicht freigesch. -feature.filename=Filename -feature.abstract=Abstract -feature.link=Link - -featurelist.htmltitle=featurelist +message.htmltitle=Messages +message.date=Datum +message.title=Titel +message.creator=Autor +message.text=Text +message.textinfo=(max. 5 Zeilen / 250 Zeichen) + +messagelist.htmltitle=Messages Liste # admin start page -start.htmltitle=admin +start.htmltitle=Admin-Startpage + +start.breaking.new=neue breaking news +start.content.new=neuer Artikel +start.show=zeigen +start.open_by_id=id öffnen + +start.content.comments=Ergänzungen +start.content.hidden=alle versteckten eines Monats +start.content.not_published=(noch) nicht veröffentlicht +start.content.with_media=mit Medien +start.content.last_changes=letzte Änderungen +start.content.with_comments=mit internen Kommentaren +start.content.all=Alle Artikel +start.content.search=suchen + +start.allarticlesoftype={0} + +start.producers.title=MANUELL GENERIEREN +start.producers.produceAllNew=alle neuen generieren +start.producers.advanced=extra Optionen (Vorsicht!) + start.openpostings.title=OPENPOSTINGS -start.comments.title=KOMMENTARE -start.breaking.title=BREAKING NEWS -start.breaking.new=neue nachricht -start.content.title=BEITRÄGE -start.content.new=neue nachricht -start.show=anzeigen -start.content.newswire=newswire -start.content.feature=feature -start.content.topicspecial=themenspecials -start.content.startspecial=startspecials -start.content.not_published=nicht veröffentlichte nachrichten -start.content.hidden=versteckte Artikel -start.content.with_media=mit medien -start.content.last_changes=letzte änderungen -start.content.with_comments=mit internen kommentaren -start.content.all=alle -start.content.search=Suche - -start.allarticlesoftype=alle Artikel vom Typ {0} - -start.generate.title=MANUELL GENERIEREN -start.generate.all.title=Alle Bereiche -start.generate.all.new=alles neue (standard, update auf www > 5min.) -start.generate.parts.title=Folgende sind Teilbereiche -start.generate.startpages.new=neue startseiten -start.generate.all_forced=alle (forced) -start.generate.all_sync=alle (forced + sync) -start.generate.content.new=neuer content -start.generate.topics.new=neue themen -start.generate.postings.new=neue openpostings -start.generate.images.new=neue bilder -start.generate.audio.new=neue audio dateien -start.generate.video.new=neue video dateien -start.generate.other.new=neue andere medien -start.generate.navigation=Navigation -start.coverage.title=SCHWERPUNKTEs -start.topics.title=THEMEN -start.images.title=BILDER -start.audio.title=AUDIO -start.video.title=VIDEO -start.other_media.title=ANDERE MEDIEN -start.mediafolder.title=MEDIAFOLDER +start.comments.title=ERGÄNZUNGEN +start.breaking.title=breaking news +start.content.title=ARTIKEL +start.administer.title=AUFRÄUMEN +start.list.title=LIST +start.fileedit.title=Includes editieren +start.addandedit.title=NEU / ÄNDERN +start.extra.title=EXTRA +start.search.title=SUCHEN +start.topics.title=TOPICS +start.other_media.title=andere Medien +start.images.title=Bilder +start.video.title=Video +start.audio.title=Audio +start.media.title=MEDIA +start.mediafolder.title=Media-Mappen start.languages.title=SPRACHEN start.imcs.title=IMCS -start.messageboard.title=Internes Messageboard -start.messageboard.no_messages=keine nachrichten +start.messageboard.title=MESSAGEBOARD +start.messageboard.no_messages=keine Nachrichten -start.superusermenu=Superuser menu (use with care!) # needs translation +start.superusermenu=Mehr Funktionen (Vorsicht!) # topic -topic.htmltitle=topic +topic.htmltitle=Themen topic.title=Name -topic.description=beschreibung -topic.filename=Filename -topic.main_url=Hauptinfoseite -topic.archive_url=Archiv url +topic.description=Beschreibung +topic.filename=Dateiname +topic.main_url=Haupt Infoseite +topic.archive_url=ArchivURL + +topiclist.htmltitle=Themenliste -topiclist.htmltitle=topiclist -articletype.htmltitle=Article type # needs translation -articletype.id=id # needs translation -articletype.name=Name # needs translation +# users +user.htmltitle=BenutzerInnen +user.login=Login +user.password=Password +user.password2=Password (bestätigen) +user.admin=Admin -articletypelist.htmltitle=Article types # needs translation +userlist.htmltitle=BenutzerInnen -commentstatus.htmltitle=Comment status # needs translation -commentstatus.id=id # needs translation -commentstatus.name=Name # needs translation -commentstatuslist.htmltitle=Comment status values # needs translation +#articletype +articletype.htmltitle=Artikeltyp +articletype.id=id +articletype.name=Name +articletypelist.htmltitle=Artikeltyp Liste -superusermenu.htmltitle = Super-user functions # needs translation -superusermenu.topics = Manage topics # needs translation -superusermenu.articletypes = Manage article types # needs translation -superusermenu.comment_statuses = Manage comment status values # needs translation -superusermenu.users = Manage users # needs translation -superusermenu.languages = Manage languages # needs translation -superusermenu.imcs = Manage IMCS (obsolete) # needs translation -# users -user.htmltitle=user -user.login=login -user.password=password -user.admin=admin +#commentstatus +commentstatus.htmltitle=Comment status +commentstatus.id=id +commentstatus.name=Name + +commentstatuslist.htmltitle=Comment status Werte + + + +#file editing +fileedit.htmltitle = Datei bearbeiten +fileedit.filename = Dateiname +fileedit.subdirectory = Unterverzeichnis + +fileeditlist.htmltitle = editierbare Dateien +fileeditlist.filename = Dateiname +fileeditlist.dirname = Unterverzeichnis + + +#producers +producer.producer = Producer Name +producer.verb.name = Task Name +producer.verb.description = Task Beschreibung +producer.verb.enqueue = produzieren + +producer.job.name = Job +producer.job.status = Status +producer.job.date = seit: +producer.job.cancel = cancel +producer.job.abort = abort +producer.job.empty = Nix zu tun ;-) + +producer.jobqueue.title = Laufende Jobs +producer.jobqueue.refresh = neu laden +producer.producerlist.title = neuer Job + +producerqueue.htmltitle = manuell generieren + + +#superusermenu +superusermenu.htmltitle = Extra-Funktionen +superusermenu.manage = BEARBEITEN +superusermenu.topics = Topics +superusermenu.articletypes = Artikeltypen +superusermenu.comment_statuses = comment status Werte +superusermenu.users = BenutzerInnen +superusermenu.languages = Sprachen +superusermenu.abuse = Spamabwehr +superusermenu.imcs = IMCS (nicht aktiv) + + +#abuse +abuse.htmltitle = Spam abwehr + +abuse.setting = Einstellungen +abuse.value = Werte + +abuse.disableopenpostings=Openposting abschalten +abuse.openpostingpassword=Passwort für Openposting +abuse.logpostings=IPs für Openposting listen +abuse.logsize=wieviele IPs listen +abuse.cookies=Cookies für geblockte Nutzer +abuse.articleaction=Aktion für geblockte Artikel +abuse.commentaction=Aktion für geblockte Ergänzungen + +abuse.showlog=IP-Liste zeigen +abuse.showfilters=Filter bearbeiten + +abuse.log.time=Zeit +abuse.log.address=IP-Nummer +abuse.log.object=Objekt +abuse.log.browser=Browser + +abuse.filters = Filter +abuse.filter.type = Type +abuse.filtertype.ip = IP Nummer +abuse.filtertype.regexp = Regular expression +abuse.filter.expression = Expression -userlist.htmltitle=userlist # head head.start=start head.logout=logout -head.help=hilfe -head.search=suche +head.help=help +head.search=search head.logged_in=logged in # foot foot.top=top -# article types -articletypes.openposting=Open posting +########## dynamic values ########## + +# (users can add new types, how to translate these) +# suggestion if not in bundle use value as Text + + +# Article types +articletypes.openposting=open posting articletypes.newswire=Newswire articletypes.feature=Feature -articletypes.topicspecial=Themen special -articletypes.startspecial=Startpage special +articletypes.topicspecial=Topic-Special +articletypes.startspecial=Startpage-Special +# Comment status values +commentstatus.normal=normal +commentstatus.good=gut +commentstatus.bad=böse -########## error ########## +########## error ########## error.htmltitle=das system ist der fehler error.title=OOPS! error.text=Nunja, kann passieren! Wahrscheinlich wird Dir der folgende Fehlertext nichts sagen, koennte aber sein, daß {1}damit was anfangen kann: @@ -338,6 +492,13 @@ usererror.title=OOPS! usererror.text=Bei der Eingabe hat es folgende fehler gegeben: usererror.what_to_do=Also, bitte druecke die zurueck taste und versuche es nochmal +media.error.unsupportedformat=Das Format der hochgeladenen Mediendatei wird nicht unterstützt. +user.error.missingpasswords=Das neue Passwort muss zwei mal eingegeben werden. +user.error.passwordmismatch=Die Passwörterstimmen nicht überein. +user.error.missingpassword=Bitte ein Passwort angebenn. + +########## infomessages ########## +infomessage.htmltitle = zu Ihrer Information +infomessage.produceAllNewAddedToQueue = Der Vorgang wird bearbeitet. -htmlcharset=utf-8 diff --git a/bundles/admin_en.properties b/bundles/admin_en.properties index 9b354167..a64e2cf9 100755 --- a/bundles/admin_en.properties +++ b/bundles/admin_en.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: english -# $Id: admin_en.properties,v 1.41 2003/03/27 20:13:44 zapata Exp $ +# $Id: admin_en.properties,v 1.42 2003/04/09 02:06:06 zapata Exp $ languagename=English @@ -12,6 +12,10 @@ all=all month=month year=year file=file +new=new +by=by +help=help + # actions insert=insert @@ -26,10 +30,14 @@ back=back cancel=cancel preview=preview reset=reset +administer=administer +search=search + # special fileedit=fileEdit + # records records=entries show_from_to=showing from {0} to {1} @@ -37,6 +45,7 @@ no_matches_found=No matching entries! list.next=next list.previous=previous + # media - used by image, audio, video and other media media.created=created media.changed=last modification @@ -61,22 +70,27 @@ media.nr_of_media.submit=define number medialist.search_text_in=Search text in + # image image.htmltitle=Image -imagelist.htmltitle=Images +imagelist.htmltitle=Images overview + # audio audio.htmltitle=Audio audiolist.htmltitle=Audio overview + # video video.htmltitle=Video videolist.htmltitle=Video overview + # other other_media.htmltitle=Other media other_medialist.htmltitle=Other media overview + # breaking breaking.htmltitle=Breaking news breaking.textinfo=(max. 5 lines / 250 characters) @@ -85,6 +99,7 @@ breaking.date=date breakinglist.htmltitle=Breaking news overview + # comment comment.htmltitle=Comment comment.date=Date @@ -97,19 +112,27 @@ comment.email=Email comment.url=Url comment.creator=Author comment.article=For article -comment.html=HTML? +comment.html=HTML comment.status=Status comment.language=Language -comment.hidden=Hidden +comment.operation.hide=hide +comment.operation.unhide=unhide -comment.operation.hide=Hide -comment.operation.unhide=Unhide -commentlist.htmltitle=Comments -commentlist.allcomments=All comments +#commentlist +commentlist.htmltitle=comments +commentlist.published=published +commentlist.hidden=hidden +commentlist.allcomments=All comments for this article +commentlist.search=go! +commentlist.activate = activate changes +commentlist.order = order +commentlist.order.datedesc= date (desc.) +commentlist.order.dateasc= date (asc.) +commentlist.order.articletitle= article title -commentsearch.field = Field +commentsearch.field = Search commentsearch.field.title = Title commentsearch.field.creator = Author commentsearch.field.description = Description @@ -129,18 +152,18 @@ commentsearch.order.articletitle= article title commentsearch.searchbutton = Search - # confirm confirm.htmltitle=confirm delete confirm.really_delete=Do you really want to delete this entry? +confirm.text=This will erase the entry from the database unrecoverably. + # content -content.id=Article number content.htmltitle=Article content.owner=Owner content.language=Language content.articletype=Article type -content.topic=Topics +content.topic=Topic content.title=Long title content.subtitle=Sub title / context title content.location=Location @@ -151,9 +174,10 @@ content.creator.address=Address content.creator.telephone=Phone content.abstract=Abstract content.content=Content -content.html=HTML? +content.html=HTML content.comment=Internal Comment content.internal=(internal) + content.attachments=Attachments content.images=Images content.audio=Audio @@ -168,6 +192,7 @@ content.addvideo=add video content.uploadvideo=upload video content.addother=add other media content.uploadother=upload other media + content.creationdate=date content.modificationdate=last change content.status=Status @@ -176,7 +201,7 @@ content.import_date=Import date content.lastchange_date=Last modified content.create_date=Date content.published=published -content.comments=Comments +content.comments=comments content.family=Children & Parents content.children=Children @@ -186,12 +211,11 @@ content.viewparent=view content.clearparent=de-select content.selectparent=select -content.operation.hide=Hide -content.operation.unhide=Unhide -content.operation.newswire=Newswire - +content.operation.hide=hide +content.operation.unhide=unhide +content.operation.newswire=newswire -contentsearch.value = value +contentsearch.value = search contentsearch.field = field contentsearch.field.title = Title contentsearch.field.creator = Author @@ -208,9 +232,10 @@ contentsearch.order.datedesc=Newest first contentsearch.order.dateasc=Oldest first contentsearch.order.title=Title contentsearch.order.creator=Author - contentsearch.searchbutton=Search + +#contentlist contentlist.htmltitle=Articles contentlist.comments=Comments contentlist.select=Select @@ -223,6 +248,7 @@ language.code=Language code languagelist.htmltitle=Languages + # imcs linkimcs.htmltitle=LinksImcs linkimcs.name=Name @@ -236,6 +262,7 @@ linkimcs.parent=parent linkimcslist.htmltitle=LinksImcsList linkimcslist.search_in=Search text in + # login login.htmltitle=login login.info=This area is only accessible to authorized groups. If you want to join as an editorial group, please contact us at the {0}. @@ -245,6 +272,7 @@ login.password=Password login.language=Language login.submit= OK + # mediafolder mediafolder.htmltitle=mediafolder mediafolder.date=date @@ -255,11 +283,12 @@ mediafolder.comment=comment mediafolderlist.htmltitle=media folder list + # message message.htmltitle=messages message.date=date message.title=title -message.creator=Author +message.creator=author message.text=text message.textinfo=(max. 5 lines / 250 characters) @@ -267,15 +296,14 @@ messagelist.htmltitle=message list # admin start page start.htmltitle=admin -start.openpostings.title=OPENPOSTINGS -start.comments.title=COMMENTS -start.breaking.title=BREAKING NEWS + start.breaking.new=add breaking news -start.content.title=ARTICLES start.content.new=new article start.show=show +start.open_by_id=open id -start.content.hidden=hidden articles +start.content.comments=comments +start.content.hidden=produce all hidden articles start.content.not_published=not (yet) published articles start.content.with_media=with media start.content.last_changes=latest changes @@ -283,42 +311,48 @@ start.content.with_comments=with internal comments start.content.all=all articles start.content.search=search -start.allarticlesoftype=View all "{0}" articles - +start.allarticlesoftype={0} start.producers.title=GENERATE MANUALLY -start.producers.produceAllNew=Generate all new -start.producers.advanced=Advanced page (use with care!) - - - +start.producers.produceAllNew=generate all new +start.producers.advanced=advanced page (use with care!) +start.openpostings.title=OPENPOSTINGS +start.comments.title=COMMENTS +start.breaking.title=breaking news +start.content.title=ARTICLES +start.administer.title=ADMINISTER +start.list.title=LIST +start.fileedit.title=edit include files +start.addandedit.title=ADD / EDIT +start.extra.title=EXTRA +start.search.title=SEARCH start.topics.title=TOPICS -start.other_media.title=OTHER MEDIA -start.images.title=PICTURES -start.video.title=VIDEO -start.audio.title=AUDIO -start.mediafolder.title=MEDIAFOLDER +start.other_media.title=other media +start.images.title=pictures +start.video.title=video +start.audio.title=audio +start.media.title=MEDIA +start.mediafolder.title=mediafolder start.languages.title=LANGUAGES start.imcs.title=IMCS -start.messageboard.title=Internal Messageboard +start.messageboard.title=MESSAGEBOARD start.messageboard.no_messages=no messages -start.superusermenu=Super-user functions (use with care!) +start.superusermenu=super-user functions (use with care!) -start.editfiles.title=EDIT FILES -start.editfiles.include=Include files # topic topic.htmltitle=topic -topic.title=Name +topic.title=name topic.description=description -topic.filename=Filename +topic.filename=filename topic.main_url=main infopage -topic.archive_url=Archive url +topic.archive_url=archive url topiclist.htmltitle=topiclist + # users user.htmltitle=User user.login=Login @@ -329,12 +363,16 @@ user.admin=Admin userlist.htmltitle=Users +#articletype articletype.htmltitle=Article type articletype.id=id articletype.name=Name articletypelist.htmltitle=Article types + + +#commentstatus commentstatus.htmltitle=Comment status commentstatus.id=id commentstatus.name=Name @@ -342,11 +380,15 @@ commentstatus.name=Name commentstatuslist.htmltitle=Comment status values + #file editing +fileedit.htmltitle = Edit file +fileedit.filename = Filename +fileedit.subdirectory = Subdirectory + fileeditlist.htmltitle = Editable files fileeditlist.filename = Filename -fileedit.filename = Filename -fileedit.htmltitle = Edit file +fileeditlist.dirname = Subdirectory #producers @@ -360,6 +402,7 @@ producer.job.status = Status producer.job.date = Last change producer.job.cancel = cancel producer.job.abort = abort +producer.job.empty = Queue is empty producer.jobqueue.title = Current jobs producer.jobqueue.refresh = refresh @@ -368,15 +411,20 @@ producer.producerlist.title = Add a new job producerqueue.htmltitle = Generate manually -superusermenu.htmltitle = Super-user functions -superusermenu.topics = Manage topics -superusermenu.articletypes = Manage article types -superusermenu.comment_statuses = Manage comment status values -superusermenu.users = Manage users -superusermenu.languages = Manage languages -superusermenu.abuse = Apply anti-abuse measures -superusermenu.imcs = Manage IMCS (obsolete) +#superusermenu +superusermenu.htmltitle = Super-user functions +superusermenu.manage = MANAGE +superusermenu.topics = topics +superusermenu.articletypes = article types +superusermenu.comment_statuses = comment status values +superusermenu.users = users +superusermenu.languages = languages +superusermenu.abuse = apply anti-abuse measures +superusermenu.imcs = IMCS (obsolete) + +#abuse +abuse.htmltitle = anti-abuse measures abuse.setting = Setting abuse.value = Value @@ -404,7 +452,6 @@ abuse.filtertype.regexp = Regular expression abuse.filter.expression = Expression - # head head.start=start head.logout=logout @@ -416,6 +463,12 @@ head.logged_in=logged in foot.top=top +########## dynamic values ########## + +# (users can add new types, how to translate these) +# suggestion if not in bundle use value as Text + + # Article types articletypes.openposting=Open posting articletypes.newswire=Newswire @@ -424,29 +477,32 @@ articletypes.topicspecial=Topic-special articletypes.startspecial=Startpage-special # Comment status values -commentstatus.normal=Normal - +commentstatus.normal=normal +commentstatus.good=good +commentstatus.bad=bad ########## error ########## - error.htmltitle=the system caused an error error.title=The system caused an error -error.text=This can happen. Even if the following error message is not be comprehensible for you, it might be helpful to {1}: +error.text=This can happen. Even if the following error message is not be comprehensible for you,
it might be helpful to {1}: error.text2=So please send an e-mail with the red text and detailed information regarding the events that led to this error to {1}. Thanks! -usererror.htmltitle=User error -usererror.title=User error +usererror.htmltitle=validation error +usererror.title=Validation error usererror.text=Your input caused the following error: usererror.what_to_do=Please press the back button and try it again -media.error.unsupportedformat=The format of the media you uploaded is not supported -user.error.missingpasswords=The new password must be entered twice +media.error.unsupportedformat=The format of the media you uploaded is not supported +user.error.missingpasswords=The new password must be entered twice user.error.passwordmismatch=The passwords are not equal -user.error.missingpassword=A password must be entered +user.error.missingpassword=A password must be entered + +########## infomessages ########## infomessage.htmltitle = Information infomessage.produceAllNewAddedToQueue = Your request has been added to the queue. +########## HTML-charset ########## htmlcharset=utf-8 diff --git a/bundles/admin_es.properties b/bundles/admin_es.properties index a813d5f9..f5a0cfd8 100755 --- a/bundles/admin_es.properties +++ b/bundles/admin_es.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: espanol / spanish -# $Id: admin_es.properties,v 1.22 2003/02/21 05:38:36 zapata Exp $ +# $Id: admin_es.properties,v 1.23 2003/04/09 02:06:06 zapata Exp $ languagename=Español @@ -142,9 +142,9 @@ content.status=Estado content.type=Tipo de artículo content.published=publicado content.comments=Comentarios -content.import_date=fecha de importación -content.lastchange_date=último cambio -content.create_date=fecha +content.import_date=fecha de importación +content.lastchange_date=último cambio +content.create_date=fecha contentlist.htmltitle=lista de contenidos contentlist.comments=comentarios @@ -371,4 +371,3 @@ usererror.text=Los datos que ha introducido han causado el siguiente error: usererror.what_to_do=Por favor, pulse el botón para volver e intentelo de nuevo -htmlcharset=utf-8 diff --git a/bundles/admin_eu.properties b/bundles/admin_eu.properties index ba67237f..7df359d7 100755 --- a/bundles/admin_eu.properties +++ b/bundles/admin_eu.properties @@ -1,305 +1,470 @@ ########## admin ########## # language: euskera / basque -# $Id: admin_eu.properties,v 1.8 2003/02/21 05:38:36 zapata Exp $ +# $Id: admin_eu.properties,v 1.9 2003/04/09 02:06:06 zapata Exp $ -languagename=Euskera +languagename = Euskera # general -yes=bai -no=ez -dontcare=ez du axola -all=dena +yes = bai +no = ez +dontcare = ez du axola +all = dena +# missing (master value = "month") +month = +# missing (master value = "year") +year = +# missing (master value = "file") +file = +# missing (master value = "new") +new = +# missing (master value = "by") +by = +# missing (master value = "help") +help = + # actions -insert=sartu -save=gorde -edit=aldatu -delete=ezabatu -add=gehitu -filter=iragazi -attach=atxeki -list=zerrenda erakutsi -back=atzera -cancel=utzi -preview=aurrebista -reset=berrasieratu +insert = sartu +save = gorde +edit = aldatu +delete = ezabatu +add = gehitu +filter = iragazi +attach = atxeki +list = zerrenda erakutsi +back = atzera +cancel = utzi +preview = aurrebista +reset = berrasieratu +# missing (master value = "administer") +administer = +# missing (master value = "search") +search = + + +# special +# missing (master value = "fileEdit") +fileedit = + # records -records=sarrerak -show_from_to={0}(e)tik {1}(e)ra bitarteko sarrerak erakusten -no_matches_found=Ez da horrelako sarrerarik aurkitu! -list.next=hurrengoa -list.previous=aurrekoa +records = sarrerak +show_from_to = {0}(e)tik {1}(e)ra bitarteko sarrerak erakusten +no_matches_found = Ez da horrelako sarrerarik aurkitu! +list.next = hurrengoa +list.previous = aurrekoa + # media - used by image, audio, video and other media -media.created=sortua -media.changed=aldatua -media.published=argitaratua -media.format=Formatua -media.rights=Egile eskubideak -media.type=Mota -media.mediafolder=Baliabide mediatikoen karpeta -media.title=Izenburua -media.size=Tamaina -media.description=Deskripzioa -media.date=Data -media.location=Jatorrizko lekua -media.creator=Egilea -media.keywords=Hitz gakoak -media.comment=Komentarioa -media.source=Jatorria -media.is_published=Argitaratzeko prest -media.icon=Ikonoa -medialist.search_text_in=Testua non bilatu -media.nr_of_media=Baliabide mediatikoen kopurua -media.nr_of_media.submit=Aldatu kopurua +media.created = sortua +media.changed = aldatua +media.published = argitaratua +media.format = Formatua +media.rights = Egile eskubideak +media.type = Mota +media.mediafolder = Baliabide mediatikoen karpeta +media.title = Izenburua +media.size = Tamaina +media.description = Deskripzioa +media.date = Data +media.location = Jatorrizko lekua +media.creator = Egilea +media.keywords = Hitz gakoak +media.comment = Komentarioa +media.source = Jatorria +media.is_published = Argitaratzeko prest +media.icon = Ikonoa +media.nr_of_media = Baliabide mediatikoen kopurua +media.nr_of_media.submit = Aldatu kopurua + +medialist.search_text_in = Testua non bilatu + # image -image.htmltitle=Indymedia Euskal Herria | Irudia -imagelist.htmltitle=Indymedia Euskal Herria | Irudien zerrenda +image.htmltitle = Irudia +imagelist.htmltitle = Irudien zerrenda + # audio -audio.htmltitle=Indymedia Euskal Herria | Audioa -audiolist.htmltitle=Indymedia Euskal Herria | Audio zerrenda +audio.htmltitle = Audioa +audiolist.htmltitle = Audio zerrenda + # video -video.htmltitle=Indymedia Euskal Herria | Bideoa -videolist.htmltitle=Indymedia Euskal Herria | Bideo zerrenda +video.htmltitle = Bideoa +videolist.htmltitle = Bideo zerrenda + # other -other_media.htmltitle=Indymedia Euskal Herria | Beste baliabide mediatikoak -other_media.htmltitle=Indymedia Euskal Herria | Baliabide mediatikoen zerrenda +other_media.htmltitle = Baliabide mediatikoen zerrenda +# missing (master value = "Other media overview") +other_medialist.htmltitle = + # breaking -breaking.htmltitle=Indymedia Euskal Herria | Azken albisteak -breakinglist.htmltitle=Indymedia Euskal Herria | Azken albisteen zerrenda -breaking.textinfo=(gehienez 5 lerrro / 250 letra) -breaking.text=testua -breaking.date=data +breaking.htmltitle = Azken albisteak +breaking.textinfo = (gehienez 5 lerrro / 250 letra) +breaking.text = testua +breaking.date = data + +breakinglist.htmltitle = Azken albisteen zerrenda + # comment -comment.htmltitle=Indymedia Euskal Herria | Komentarioa -comment.date=data -comment.title=izenburua -comment.published=argitaratuta -comment.text=komentarioaren testua -comment.address=helbidea -comment.phone=telefonoa -comment.email=posta elektronikoa -comment.url=URL -comment.creator=egilea -comment.article=hurrengo artikuluarena -comment.html=HTML da? -comment.status=Egoera -comment.language=Hizkuntza - -commentlist.htmltitle=Indymedia Euskal Herria | Komentarioen zerrenda -commentlist.produced=ekoiztua -commentlist.hidden=izkutua -commentlist.search=bilatu! - -commentsearch.order.datedesc= data (behera) -commentsearch.order.dateasc= data (gora) -commentsearch.order.articletitle= artikuluaren titulua +comment.htmltitle = Komentarioa +comment.date = data +comment.title = izenburua +comment.published = argitaratuta +comment.text = komentarioaren testua +comment.address = helbidea +comment.phone = telefonoa +comment.email = posta elektronikoa +comment.url = URL +comment.creator = egilea +comment.article = hurrengo artikuluarena +comment.html = HTML da? +comment.status = Egoera +comment.language = Hizkuntza + +# missing (master value = "hide") +comment.operation.hide = +# missing (master value = "unhide") +comment.operation.unhide = + + +#commentlist +commentlist.htmltitle = Komentarioen zerrenda +# missing (master value = "published") +commentlist.published = +commentlist.hidden = izkutua +# missing (master value = "All comments for this article") +commentlist.allcomments = +commentlist.search = bilatu! +# missing (master value = "activate changes") +commentlist.activate = +# missing (master value = "order") +commentlist.order = +# missing (master value = "date (desc.)") +commentlist.order.datedesc = +# missing (master value = "date (asc.)") +commentlist.order.dateasc = +# missing (master value = "article title") +commentlist.order.articletitle = + +# missing (master value = "Search") +commentsearch.field = +# missing (master value = "Title") +commentsearch.field.title = +# missing (master value = "Author") +commentsearch.field.creator = +# missing (master value = "Description") +commentsearch.field.description = +# missing (master value = "Value") +commentsearch.value = + +# missing (master value = "Published state") +commentsearch.publishedstate = +# missing (master value = "Hidden") +commentsearch.publishedstate.hidden = +# missing (master value = "Published") +commentsearch.publishedstate.published = + +# missing (master value = "Status") +commentsearch.status = + +# missing (master value = "Order") +commentsearch.order = +commentsearch.order.datedesc = data (behera) +commentsearch.order.dateasc = data (gora) +commentsearch.order.articletitle = artikuluaren titulua + +# missing (master value = "Search") +commentsearch.searchbutton = + # confirm -confirm.htmltitle=Indymedia Euskal Herria | Ezabaketa baieztatu -confirm.really_delete=Sarrera hau ezabatu nahi duzu? +confirm.htmltitle = Ezabaketa baieztatu +confirm.really_delete = Sarrera hau ezabatu nahi duzu? +# missing (master value = "This will erase the entry from the database unrecoverably.") +confirm.text = + # content -content.htmltitle=Indymedia Euskal Herria | Edukia -content.owner=Jabea -content.topic=Gaia -content.feature=Berezitasuna -content.title=Izenburu luzea -content.subtitle=Azpi-izenburua/testuinguru izenburua -content.location=Jatorrizko lekua -content.creator=Egilea -content.creator.email=Posta elektronikoa -content.creator.url=Web -content.creator.address=Helbidea -content.creator.telephone=Telefonoa -content.abstract=Deskripzio laburra -content.content=Edukia -content.html=HTML da? -content.comment=Barne komentarioa -content.internal=(barne xederako) -content.attachments=Atxekiak -content.images=Irudiak -content.audio=Audioa -content.video=Bideoa -content.other=Beste baliabide mediatikoak -content.media=Baliabide mediatikoak -content.addimage=irudia gehitu -content.addaudio=audio gehitu -content.addvideo=bideoa gehitu -content.addother=beste baliabide mediatikoa gehitu -content.creationdate=data -content.modificationdate=azken aldaketa -content.status=Egoera -content.type=Artikulu mota -content.published=argitaratua -content.comments=Komentarioak - -content.import_date=sarreraren data -content.lastchange_date=azken aldaketa -content.create_date=data - -contentlist.htmltitle=Indymedia Euskal Herria | Edukien zerrenda -contentlist.comments=komentarioak +content.htmltitle = Edukia +content.owner = Jabea +# missing (master value = "Language") +content.language = +# missing (master value = "Article type") +content.articletype = +content.topic = Gaia +content.title = Izenburu luzea +content.subtitle = Azpi-izenburua/testuinguru izenburua +content.location = Jatorrizko lekua +content.creator = Egilea +content.creator.email = Posta elektronikoa +content.creator.url = Web +content.creator.address = Helbidea +content.creator.telephone = Telefonoa +content.abstract = Deskripzio laburra +content.content = Edukia +content.html = HTML da? +content.comment = Barne komentarioa +content.internal = (barne xederako) + +content.attachments = Atxekiak +content.images = Irudiak +content.audio = Audioa +content.video = Bideoa +content.other = Beste baliabide mediatikoak +content.media = Baliabide mediatikoak +content.addimage = irudia gehitu +# missing (master value = "upload image") +content.uploadimage = +content.addaudio = audio gehitu +# missing (master value = "upload audio") +content.uploadaudio = +content.addvideo = bideoa gehitu +# missing (master value = "upload video") +content.uploadvideo = +content.addother = beste baliabide mediatikoa gehitu +# missing (master value = "upload other media") +content.uploadother = + +content.creationdate = data +content.modificationdate = azken aldaketa +content.status = Egoera +content.type = Artikulu mota +content.import_date = sarreraren data +content.lastchange_date = azken aldaketa +content.create_date = data +content.published = argitaratua +content.comments = Komentarioak + +# missing (master value = "Children & Parents") +content.family = +# missing (master value = "Children") +content.children = +# missing (master value = "view") +content.viewchildren = +# missing (master value = "Parent") +content.parent = +# missing (master value = "view") +content.viewparent = +# missing (master value = "de-select") +content.clearparent = +# missing (master value = "select") +content.selectparent = + +# missing (master value = "hide") +content.operation.hide = +# missing (master value = "unhide") +content.operation.unhide = +# missing (master value = "newswire") +content.operation.newswire = + +# missing (master value = "search") +contentsearch.value = +# missing (master value = "field") +contentsearch.field = +# missing (master value = "Title") +contentsearch.field.title = +# missing (master value = "Author") +contentsearch.field.creator = +# missing (master value = "Contents") +contentsearch.field.contents = + +# missing (master value = "publication state") +contentsearch.publishedstate = +# missing (master value = "hidden") +contentsearch.publishedstate.hidden = +# missing (master value = "published") +contentsearch.publishedstate.published = + +# missing (master value = "article type") +contentsearch.articletype = + +# missing (master value = "order by") +contentsearch.order = +# missing (master value = "Newest first") +contentsearch.order.datedesc = +# missing (master value = "Oldest first") +contentsearch.order.dateasc = +# missing (master value = "Title") +contentsearch.order.title = +# missing (master value = "Author") +contentsearch.order.creator = +# missing (master value = "Search") +contentsearch.searchbutton = + + +#contentlist +contentlist.htmltitle = Edukien zerrenda +contentlist.comments = komentarioak +# missing (master value = "Select") +contentlist.select = + # language -language.htmltitle=Indymedia Euskal Herria | Hizkuntza -language.name=hizkuntza -language.code=Hizkuntza kodea +language.htmltitle = Hizkuntza +language.name = hizkuntza +language.code = Hizkuntza kodea + +languagelist.htmltitle = Hizkuntzen zerrenda -languagelist.htmltitle=Indymedia Euskal Herria | Hizkuntzen zerrenda # imcs -linkimcs.htmltitle=Indymedia Euskal Herria | MIGen loturak -linkimcs.name=Izena -linkimcs.continent=Kontinentea -linkimcs.new_parent=Aita berria -linkimcs.url=URL -linkimcs.sort_by=Hurrenkera irizpidea -linkimcs.language=Hizkuntza -linkimcs.parent=Aita - -linkimcslist.htmltitle=Indymedia Euskal Herria | MIGen loturen zerrenda -linkimcslist.search_in=Testua non bilatu +linkimcs.htmltitle = MIGen loturak +linkimcs.name = Izena +linkimcs.continent = Kontinentea +linkimcs.new_parent = Aita berria +linkimcs.url = URL +linkimcs.sort_by = Hurrenkera irizpidea +linkimcs.language = Hizkuntza +linkimcs.parent = Aita + +linkimcslist.htmltitle = MIGen loturen zerrenda +linkimcslist.search_in = Testua non bilatu + # login -login.htmltitle=Indymedia Euskal Herria | Sarrera -login.info=Eremu hau baimendutako taldeentzat bakarrik da. Editore lanetan lagundu nahi baduzu, jar zaitez gurekin kontaktuan imceuskalherria-editorial@lists.indymedia.org helbidean mesedez. -login.title=erabiltzailea -login.name=Erabiltzailea -login.password=Pasahitza -login.language=Hizkuntza -login.language.ay=Aymara -login.language.de=Deutsch -login.language.en=English -login.language.es=Español -login.language.eu=Euskera -login.language.gn=Guaran’ -login.language.qu=Quechua -login.language.tr=Turkish -login.submit=Ados +login.htmltitle = Sarrera +login.info = Eremu hau baimendutako taldeentzat bakarrik da. Editore lanetan lagundu nahi baduzu, jar zaitez gurekin kontaktuan imceuskalherria-editorial@lists.indymedia.org helbidean mesedez. +login.title = erabiltzailea +login.name = Erabiltzailea +login.password = Pasahitza +login.language = Hizkuntza +login.submit = Ados + # mediafolder -mediafolder.htmltitle=Indymedia Euskal Herria | Baliabide mediatikoen karpeta -mediafolder.date=data -mediafolder.name=izena -mediafolder.location=jatorrizko lekua -mediafolder.keywords=hitz gakoak -mediafolder.comment=komentarioa +mediafolder.htmltitle = Baliabide mediatikoen karpeta +mediafolder.date = data +mediafolder.name = izena +mediafolder.location = jatorrizko lekua +mediafolder.keywords = hitz gakoak +mediafolder.comment = komentarioa + +mediafolderlist.htmltitle = Baliabide mediatikoen karpeten zerrenda -mediafolderlist.htmltitle=Indymedia Euskal Herria | Baliabide mediatikoen karpeten zerrenda # message -message.htmltitle=Indymedia Euskal Herria | Mezuak -message.date=data -message.title=izenburua -message.creator=Egilea -message.text=testua -message.textinfo=(gehienez 5 lerrro / 250 letra) - -messagelist.htmltitle=Indymedia Euskal Herria | Mezuen zerrenda - -# feature -feature.htmltitle=Indymedia Euskal Herria | Lehen-orrikoak -feature.title=Izenburua -feature.published=argitaratua -feature.is_published=argitaratua dago -feature.is_not_published=argitaratu gabe dago -feature.filename=Fitxategiaren izena -feature.abstract=Deskripzio laburra -feature.link=lotura - -featurelist.htmltitle=Indymedia Euskal Herria | Lehen-orrikoen zerrenda +message.htmltitle = Mezuak +message.date = data +message.title = izenburua +message.creator = Egilea +message.text = testua +message.textinfo = (gehienez 5 lerrro / 250 letra) + +messagelist.htmltitle = Mezuen zerrenda # admin start page -start.htmltitle=Indymedia Euskal Herria | Administrazioa -start.openpostings.title=BIDALKETA IREKIAK -start.comments.title=KOMENTARIOAK -start.breaking.title=AZKEN ALBISTRAK -start.breaking.new=azken albiste berriak -start.content.title=ARTIKULUAK -start.content.new=artikulu berriak -start.show=Erakutsi -start.content.newswire=newswire -start.content.feature=lehen-orrikoak -start.content.topicspecial=bereziak gaika -start.content.startspecial=lehen-orriko bereziak -start.content.not_published=argitaratzeke dauden artikuluak -start.content.with_media=baliabide mediatikoekin -start.content.last_changes=azken aldaketak -start.content.with_comments=barne xederako komentarioekin -start.content.search=bilatu - -start.producers.title=Euskuz ekoiztu -start.producers.produceAllNew=Dena berria ekoiztu -start.producers.advanced=Aukera arreratuak (kontuz honekin!) - -start.coverage.title=ESTALDURA -start.topics.title=GAIAK -start.images.title=IRUDIAK -start.audio.title=AUDIO FITXATEGIAK -start.video.title=BIDEO FITXATEGIAK -start.other_media.title=BESTE MEDIOEN FITXATEGIAK -start.mediafolder.title=BALIABIDE MEDIATIKOEN ZERRENDA -start.languages.title=IZENBURUA -start.imcs.title=MIGak -start.messageboard.title=Barneko mezuak -start.messageboard.no_messages=ez dago mezurik - -start.content.hidden=aritukulu ezkutukoak -start.content.all=Artikulu guztiak - -start.editfiles.title=Fitxategiak aldatu -start.editfiles.include=Fitxategiak sartu - -start.superusermenu=Aukera aurreratuak (kontuz honekin!) - -start.allarticlesoftype={0} motatako artikulu guztiak - - -# article types -articletypes.feature=azalakoa -articletypes.newswire=newswire -articletypes.openposting=bidalitako mezu ireki bat -articletypes.topicspecial=gaiaz berezia -articletypes.startspecial=berezia +start.htmltitle = Administrazioa + +start.breaking.new = azken albiste berriak +start.content.new = artikulu berriak +start.show = Erakutsi +# missing (master value = "open id") +start.open_by_id = + +# missing (master value = "comments") +start.content.comments = +start.content.hidden = aritukulu ezkutukoak +start.content.not_published = argitaratzeke dauden artikuluak +start.content.with_media = baliabide mediatikoekin +start.content.last_changes = azken aldaketak +start.content.with_comments = barne xederako komentarioekin +start.content.all = Artikulu guztiak +start.content.search = bilatu + +start.allarticlesoftype = {0} motatako artikulu guztiak + +start.producers.title = Euskuz ekoiztu +start.producers.produceAllNew = Dena berria ekoiztu +start.producers.advanced = Aukera arreratuak (kontuz honekin!) + +start.openpostings.title = BIDALKETA IREKIAK +start.comments.title = KOMENTARIOAK +start.breaking.title = AZKEN ALBISTRAK +start.content.title = ARTIKULUAK +# missing (master value = "ADMINISTER") +start.administer.title = +# missing (master value = "LIST") +start.list.title = +# missing (master value = "edit include files") +start.fileedit.title = +# missing (master value = "ADD / EDIT") +start.addandedit.title = +# missing (master value = "EXTRA") +start.extra.title = +# missing (master value = "SEARCH") +start.search.title = +start.topics.title = GAIAK +start.other_media.title = BESTE MEDIOEN FITXATEGIAK +start.images.title = IRUDIAK +start.video.title = BIDEO FITXATEGIAK +start.audio.title = AUDIO FITXATEGIAK +# missing (master value = "MEDIA") +start.media.title = +start.mediafolder.title = BALIABIDE MEDIATIKOEN ZERRENDA +start.languages.title = IZENBURUA +start.imcs.title = MIGak +start.messageboard.title = Barneko mezuak +start.messageboard.no_messages = ez dago mezurik + +start.superusermenu = Aukera aurreratuak (kontuz honekin!) + # topic -topic.htmltitle=Indymedia Euskal Herria | Gaia -topic.title=Izena -topic.description=deskripzioa -topic.filename=Fitxategiaren izena -topic.main_url=Informazio nagusiko orria -topic.archive_url=Fitxategiaren URLa +topic.htmltitle = Gaia +topic.title = Izena +topic.description = deskripzioa +topic.filename = Fitxategiaren izena +topic.main_url = Informazio nagusiko orria +topic.archive_url = Fitxategiaren URLa -topiclist.htmltitle=Indymedia Euskal Herria | Gaien zerrenda +topiclist.htmltitle = Gaien zerrenda -articletype.htmltitle=Indymedia Euskal Herria | Artikuluen motak -articletype.id=ID -articletype.name=Izena -articletypelist.htmltitle=Indymedia Euskal Herria | Artikuluen mota zerrenda +# users +user.htmltitle = Erabiltzailea +user.login = erabiltzailea +user.password = pasahitza +# missing (master value = "Password (confirmation)") +user.password2 = +user.admin = administratzailea -commentstatus.htmltitle=Indymedia Euskal Herria | Komentarioen egoera -commentstatus.id=ID -commentstatus.name=Izena +userlist.htmltitle = Erabiltzaileen zerrenda -commentstatuslist.htmltitle=Indymedia Euskal Herria | Komentarioen egoeraren zerrenda +#articletype +articletype.htmltitle = Artikuluen motak +articletype.id = ID +articletype.name = Izena -# users -user.htmltitle=Indymedia Euskal Herria | Erabiltzailea -user.login=erabiltzailea -user.password=pasahitza -user.admin=administratzailea +articletypelist.htmltitle = Artikuluen mota zerrenda + + + +#commentstatus +commentstatus.htmltitle = Komentarioen egoera +commentstatus.id = ID +commentstatus.name = Izena + +commentstatuslist.htmltitle = Komentarioen egoeraren zerrenda + + + +#file editing +fileedit.htmltitle = Fitxategia aldatu +fileedit.filename = Fitxategiaren izena +# missing (master value = "Subdirectory") +fileedit.subdirectory = + +fileeditlist.htmltitle = Fitxategien aldaketak +fileeditlist.filename = Fitxategiaren izena +# missing (master value = "Subdirectory") +fileeditlist.dirname = -userlist.htmltitle=Indymedia Euskal Herria | Erabiltzaileen zerrenda #producers producer.producer = Ekoizlearen izena @@ -312,6 +477,8 @@ producer.job.status = Egoera producer.job.date = azken aldaketa producer.job.cancel = ezeztatu producer.job.abort = utzi +# missing (master value = "Queue is empty") +producer.job.empty = producer.jobqueue.title = Oraingo lanak producer.jobqueue.refresh = birkargatu @@ -319,51 +486,128 @@ producer.producerlist.title = Lan berri bat gehitu producerqueue.htmltitle = Eskuz ekoiztu -infomessage.produceAllNewAddedToQueue=Lana zerrendan sartuta -infomessage.htmltitle=Oharra - -superusermenu.htmltitle = Indymedia Euskal Herria | Aukera aurreratuak +#superusermenu +superusermenu.htmltitle = Aukera aurreratuak +# missing (master value = "MANAGE") +superusermenu.manage = superusermenu.topics = Gaien kudeaketa superusermenu.articletypes = Artiukuluen moten kudeaketa superusermenu.comment_statuses = Komentarioen egoeraren kudeaketa superusermenu.users = Erabiltzailen kudeaketa superusermenu.languages = Hizkuntzen kudeaketa +# missing (master value = "apply anti-abuse measures") +superusermenu.abuse = superusermenu.imcs = MIGen zerrendaren kudeaketa (zaharkitua) -#file editing -fileeditlist.htmltitle = Indymedia Euskal Herria | Fitxategien aldaketak -fileeditlist.filename = Fitxategiaren izena -fileedit.filename = Fitxategiaren izena -fileedit.htmltitle = Fitxategia aldatu - +#abuse +# missing (master value = "anti-abuse measures") +abuse.htmltitle = + +# missing (master value = "Setting") +abuse.setting = +# missing (master value = "Value") +abuse.value = + +# missing (master value = "Turn off open posting") +abuse.disableopenpostings = +# missing (master value = "Require a password for open postings") +abuse.openpostingpassword = +# missing (master value = "Log IPs for open postings") +abuse.logpostings = +# missing (master value = "Logging buffer size") +abuse.logsize = +# missing (master value = "Use cookies for blocked users") +abuse.cookies = +# missing (master value = "Action for blocked article") +abuse.articleaction = +# missing (master value = "Action for blocked comment") +abuse.commentaction = + +# missing (master value = "Show the IP log") +abuse.showlog = +# missing (master value = "Manage filters") +abuse.showfilters = + +# missing (master value = "Time") +abuse.log.time = +# missing (master value = "IP number") +abuse.log.address = +# missing (master value = "Object") +abuse.log.object = +# missing (master value = "Browser") +abuse.log.browser = + +# missing (master value = "Filters") +abuse.filters = +# missing (master value = "Type") +abuse.filter.type = +# missing (master value = "IP Number") +abuse.filtertype.ip = +# missing (master value = "Regular expression") +abuse.filtertype.regexp = +# missing (master value = "Expression") +abuse.filter.expression = # head -head.start=hasiera -head.logout=irten -head.help=laguntza -head.search=bilatu -head.logged_in=erregistraturik zaude +head.start = hasiera +head.logout = irten +head.help = laguntza +head.search = bilatu +head.logged_in = erregistraturik zaude # foot -foot.top=gora +foot.top = gora +########## dynamic values ########## +# (users can add new types, how to translate these) +# suggestion if not in bundle use value as Text -########## error ########## +# Article types +articletypes.openposting = bidalitako mezu ireki bat +articletypes.newswire = newswire +articletypes.feature = azalakoa +articletypes.topicspecial = gaiaz berezia +articletypes.startspecial = berezia -error.htmltitle=Indymedia Euskal Herria | Errakuntza -error.title=Iep! Errakuntza bat gertatu da -error.text=Ondoren datorren mezak agian ez dizu askorik lagunduko, baina seguraski {1}koei bai. -error.text2=Mesedez, mezu bat bidali {1}ra gorriz agertzen den testuarekin eta egiten ari zinenaren azalpen zehatzarekin. Eskerrik asko! +# Comment status values +# missing (master value = "normal") +commentstatus.normal = +# missing (master value = "good") +commentstatus.good = +# missing (master value = "bad") +commentstatus.bad = -usererror.htmltitle=Indymedia Euskal Herria | Errakuntza datuetan -usererror.title=Arranopola! Errakuntza bat gertatu da -usererror.text=Sartu dituzun datuek ondoko errakuntza sortarazi dute: -usererror.what_to_do=Mesedez, sakatu atzera botoia eta saiatu berriz -htmlcharset=utf-8 + +########## error ########## +error.htmltitle = Errakuntza +error.title = Iep! Errakuntza bat gertatu da +error.text = Ondoren datorren mezak agian ez dizu askorik lagunduko, baina seguraski {1}koei bai. +error.text2 = Mesedez, mezu bat bidali {1}ra gorriz agertzen den testuarekin eta egiten ari zinenaren azalpen zehatzarekin. Eskerrik asko! + +usererror.htmltitle = Errakuntza datuetan +usererror.title = Arranopola! Errakuntza bat gertatu da +usererror.text = Sartu dituzun datuek ondoko errakuntza sortarazi dute: +usererror.what_to_do = Mesedez, sakatu atzera botoia eta saiatu berriz + +# missing (master value = "The format of the media you uploaded is not supported") +media.error.unsupportedformat = +# missing (master value = "The new password must be entered twice") +user.error.missingpasswords = +# missing (master value = "The passwords are not equal") +user.error.passwordmismatch = +# missing (master value = "A password must be entered") +user.error.missingpassword = + + +########## infomessages ########## +infomessage.htmltitle = Oharra +infomessage.produceAllNewAddedToQueue = Lana zerrendan sartuta + +########## HTML-charset ########## diff --git a/bundles/admin_gn.properties b/bundles/admin_gn.properties deleted file mode 100755 index cac890c4..00000000 --- a/bundles/admin_gn.properties +++ /dev/null @@ -1,320 +0,0 @@ -########## admin ########## -# language: guarani - -languagename=Guaran’ - - -# general -yes=sí -no=no -dontcare=no importa -all=todo - -# actions -insert=insertar -save=guardar -edit=editar -delete=borrar -add=añadir -filter=filtrar -attach=vincular -list=mostrar lista -back=atrás -cancel=cancelar - -# records -records=registros -show_from_to=mostrando entradas desde {0} hasta {1} -no_matches_found=No se encontraron resultados! -list.next=siguiente -list.previous=anterior - -# media - used by image, audio, video and other media -media.created=creado -media.changed=cambiado -media.published=publicado -media.format=Formato -media.rights=Copyright -media.type=Tipo -media.size=Tamaño -media.mediafolder=Carpeta de recursos mediáticos -media.title=Título -media.description=Descripción -media.date=Fecha -media.location=Lugar de origen -media.creator=Creador -media.keywords=Palabras clave -media.comment=Comentario -media.source=Origen -media.is_published=Disponible para publicación -media.icon=Icono -media.nr_of_media=Número de recursos mediáticos -media.nr_of_media.submit=define number -medialist.search_text_in=Buscar texto en - -# image -image.htmltitle=imagen -imagelist.htmltitle=lista de imagenes - -# audio -audio.htmltitle=audio -audiolist.htmltitle=lista de audio - -# video -video.htmltitle=video -videolist.htmltitle=lista de video - -# other -other_media.htmltitle=otros recursos mediáticos -other_media.htmltitle=lista de recursos mediáticos - -# breaking -breaking.htmltitle=últimas noticias -breakinglist.htmltitle=listado de últimas noticias -breaking.textinfo=(max. 5 líneas / 250 caracteres) -breaking.text=texto -breaking.date=fecha - - -# comment -comment.htmltitle=commentario -comment.date=fecha -comment.title=título -comment.published=publicado -comment.text=texto-del-comentario -comment.address=dirección -comment.phone=teléfono -comment.email=email -comment.url=url -comment.creator=autor -comment.article=del artículo -comment.html=es HTML? -comment.status=Status # needs translation -comment.language=Lengua - -commentlist.htmltitle=lista de comentarios -commentlist.published=publicado -commentlist.hidden=oculto -commentlist.search=buscar! - -commentlist.order.datedesc= date (desc.) # needs translation -commentlist.order.dateasc= date (asc.) # needs translation -commentlist.order.articletitle= article title # needs translation - - -# confirm -confirm.htmltitle=confirmar borrado -confirm.really_delete=Desea borrar esta entrada? - -# content -content.htmltitle=contenido -content.owner=Propietario -content.topic=Tema -content.feature=Característica -content.title=titulo largo -content.subtitle=subtítulo/título de contexto -content.location=Lugar de origen -content.creator=autor -content.creator.email=Email -content.creator.url=Web -content.creator.address=Dirección -content.creator.telephone=Teléfono -content.abstract=Descripción breve -content.content=Contenido -content.html=es HTML? -content.comment=Comentario interno -content.internal=(propósito interno) -content.attachments=Vínculos -content.images=Imágenes -content.audio=Audio -content.video=Video -content.other=Otros recursos mediáticos -content.media=Recursos mediáticos -content.addimage=añadir imagen -content.addaudio=añadir audio -content.addvideo=añadir video -content.addother=añadir otros recursos mediáticos -content.creationdate=fecha -content.modificationdate=último cambio -content.status=Estado -content.type=Tipo de artículo -content.published=publicado -content.comments=Comentarios - -contentlist.htmltitle=lista de contenidos - -# language -language.htmltitle=idiomas -language.name=idioma -language.code=Código del idioma - -languagelist.htmltitle=lista de idiomas - -# imcs -linkimcs.htmltitle=Enlaces a IMCs -linkimcs.name=Nombre -linkimcs.continent=Continente -linkimcs.new_parent=Nuevo Ancestro -linkimcs.url=URL -linkimcs.sort_by=Criterio de orden -linkimcs.language=Idioma -linkimcs.parent=ancestro - -linkimcslist.htmltitle=Lista de enlaces a IMCs -linkimcslist.search_in=Buscar texto en - -# login -login.htmltitle=registro -login.info=Esta zona es accesible exclusivamente a grupos autorizados. Si desea colaborar como editor, por favor contacte con nosotros en {0}. -login.title=login -login.name=Login -login.password=Password -login.language=Idioma -login.submit= Envíar - -# mediafolder -mediafolder.htmltitle=carpeta de recursos mediáticos -mediafolder.date=fecha -mediafolder.name=nombre -mediafolder.location=lugar de origen -mediafolder.keywords=palabras clave -mediafolder.comment=commentario - -mediafolderlist.htmltitle=lista de carpetas de recursos mediáticos - -# message -message.htmltitle=mensajes -message.date=fecha -message.title=título -message.creator=Autor -message.text=texto -message.textinfo=(max. 5 líneas / 250 caracteres) - -messagelist.htmltitle=lista de mensajes - -# feature -feature.htmltitle=presentación -feature.title=Título -feature.published=publicado -feature.is_published=está publicado -feature.is_not_published=no está publicado -feature.filename=Nombre del fichero -feature.abstract=Descripción breve -feature.link=Enlace - -featurelist.htmltitle=lista de presentaciones - -# admin start page -start.htmltitle=administración -start.openpostings.title=ENVÍOSABIERTOS -start.comments.title=COMENTARIOS -start.breaking.title=ÚLTIMAS NOTICIAS -start.breaking.new=últimas noticias recientes -start.content.title=ARTICULOS -start.content.new=nuevos artículos -start.show=mostrar -start.content.newswire=newswire -start.content.feature=presentación -start.content.topicspecial=especiales-por-tema -start.content.startspecial=especiales-página-de-inicio -start.content.not_published=artículos aun sin publicar -start.content.with_media=con recursos mediáticos -start.content.last_changes=últimos cambios -start.content.with_comments=con comentarios de propósito interno -start.content.all=todos -start.content.search=buscar -start.generate.title=GENERAR MANUALMENTE -start.generate.all.title=todas las areas -start.generate.all.new=todo nuevo (estándar, actualización en la web > 5min.) -start.generate.parts.title=partes específicas del website -start.generate.startpages.new=nueva página de inicio -start.generate.all_forced=todos (forzado) -start.generate.all_sync=todos (forzado y sincronizado) -start.generate.content.new=nuevo contenido -start.generate.topics.new=nuevos temas -start.generate.postings.new=nuevos envios abiertos -start.generate.images.new=nuevas imágenes -start.generate.audio.new=nuevos ficheros de audio -start.generate.video.new=nuevos ficheros de video -start.generate.other.new=otros recursos mediáticos nuevos -start.generate.navigation=navegación -start.coverage.title=COBERTURA -start.topics.title=TEMAS -start.images.title=MATERIAL GRAFICO -start.mediafolder.title=CARPETA DE RECURSOS MEDIATICOS -start.languages.title=TÍTULO -start.imcs.title=IMCS -start.messageboard.title=Mensajería Interna -start.messageboard.no_messages=no hay mensajes - -start.superusermenu=Superuser menu (use with care!) # needs translation - - -# topic -topic.htmltitle=tema -topic.title=Nombre -topic.description=descripción -topic.filename=Nombre del fichero -topic.main_url=página de información principal -topic.archive_url=URL del archivo - -topiclist.htmltitle=lista de temas - -articletype.htmltitle=Article type # needs translation -articletype.id=id # needs translation -articletype.name=Name # needs translation - -articletypelist.htmltitle=Article types # needs translation - -commentstatus.htmltitle=Comment status # needs translation -commentstatus.id=id # needs translation -commentstatus.name=Name # needs translation - -commentstatuslist.htmltitle=Comment status values # needs translation - - -superusermenu.htmltitle = Super-user functions # needs translation -superusermenu.topics = Manage topics # needs translation -superusermenu.articletypes = Manage article types # needs translation -superusermenu.comment_statuses = Manage comment status values # needs translation -superusermenu.users = Manage users # needs translation -superusermenu.languages = Manage languages # needs translation -superusermenu.imcs = Manage IMCS (obsolete) # needs translation - - -# users -user.htmltitle=usuario -user.login=login -user.password=password -user.admin=administrador - -userlist.htmltitle=lista de usuarios - -# head -head.start=inicio -head.logout=salir -head.help=ayuda -head.search=buscar -head.logged_in=estás registrado - -# foot -foot.top=arriba - - -########## error ########## - -error.htmltitle=error -error.title=oi! oi! oi! -error.text=El siguiente mensaje puede que no le sea de mucha ayuda, pero seguramente lo será para {1}: -error.text2=Por favor envíe un mensaje con el texto que aparece en rojo y una descripción detallada a la siguiente dirección {1}. Gracias! - - -usererror.htmltitle=error de datos -usererror.title=oi! oi! oi! -usererror.text=Los datos que ha introducido han causado el siguiente error: -usererror.what_to_do=Por favor, pulse el botón para volver e intentelo de nuevo - - - - -htmlcharset=utf-8 diff --git a/bundles/admin_nl.properties b/bundles/admin_nl.properties index 489c8ae2..5fe89089 100755 --- a/bundles/admin_nl.properties +++ b/bundles/admin_nl.properties @@ -1,288 +1,395 @@ ########## admin ########## # language: dutch -# $Id: admin_nl.properties,v 1.4 2003/02/21 05:38:36 zapata Exp $ +# $Id: admin_nl.properties,v 1.5 2003/04/09 02:06:06 zapata Exp $ -languagename=Nederlands +languagename = Nederlands # general -yes=ja -no=nee -dontcare=maakt niet uit -all=allemaal -month=maand -year=jaar -file=bestand +yes = ja +no = nee +dontcare = maakt niet uit +all = allemaal +month = maand +year = jaar +file = bestand +new = nieuw +by = door +help = help + # actions -insert=Toevoegen -save=Bewaren -edit=Bewerken -delete=Wissen -add=Toevoegen -filter=Filtreren -attach=Attach -list=Bladeren -back=Terug -cancel=Ongedaan maken -preview=Preview -reset=Herstellen +insert = Toevoegen +save = Bewaren +edit = Bewerken +delete = Wissen +add = Toevoegen +filter = Filtreren +attach = Attach +list = Bladeren +back = Terug +cancel = Ongedaan maken +preview = Preview +reset = Herstellen +administer = Opruimen +search = zoeken + # special -fileedit=Bestand bewerken +fileedit = Bestand bewerken + # records -records=items -show_from_to=van {0} to {1} -no_matches_found=Geen items gevonden! -list.next=volgende -list.previous=vorige +records = items +show_from_to = van {0} to {1} +no_matches_found = Geen items gevonden! +list.next = volgende +list.previous = vorige + # media - used by image, audio, video and other media -media.created=aangemaakt -media.changed=laatste wijziging -media.published=gepubliceerd -media.format=formaat -media.rights=status auteursrecht -media.type=soort -media.mediafolder=Media map -media.title=Titel -media.size=Grootte -media.description=Omschrijving -media.date=Datum -media.location=Locatie -media.creator=Auteur -media.keywords=Sleutelwoorden -media.comment=Aantekeningen (voor intern gebruik) -media.source=Bron -media.is_published=Gepubliceerd -media.icon=Pictogram -media.nr_of_media=Aantal media items -media.nr_of_media.submit=Stel in - -medialist.search_text_in=Zoek tekst in +media.created = aangemaakt +media.changed = laatste wijziging +media.published = gepubliceerd +media.format = formaat +media.rights = status auteursrecht +media.type = soort +media.mediafolder = Media map +media.title = Titel +media.size = Grootte +media.description = Omschrijving +media.date = Datum +media.location = Locatie +media.creator = Auteur +media.keywords = Sleutelwoorden +media.comment = Aantekeningen (voor intern gebruik) +media.source = Bron +media.is_published = Gepubliceerd +media.icon = Pictogram +media.nr_of_media = Aantal media items +media.nr_of_media.submit = Stel in + +medialist.search_text_in = Zoek tekst in + # image -image.htmltitle=Afbeelding -imagelist.htmltitle=Overzicht afbeeldingen +image.htmltitle = Afbeelding +imagelist.htmltitle = Overzicht afbeeldingen + # audio -audio.htmltitle=Geluidsfragmenten -audiolist.htmltitle=Overzicht geluidsfragmenten +audio.htmltitle = Geluidsfragmenten +audiolist.htmltitle = Overzicht geluidsfragmenten + # video -video.htmltitle=Beeldfragment -videolist.htmltitle=Overzicht beeldfragmenten +video.htmltitle = Beeldfragment +videolist.htmltitle = Overzicht beeldfragmenten + # other -other_media.htmltitle=Andere multi-media -other_medialist.htmltitle=Overzicht andere multi-media +other_media.htmltitle = Andere multi-media +other_medialist.htmltitle = Overzicht andere multi-media + # breaking -breaking.htmltitle=Breaking news -breaking.textinfo=(max. 5 regels en 250 karakters) -breaking.text=Tekst -breaking.date=Datum +breaking.htmltitle = Breaking news +breaking.textinfo = (max. 5 regels en 250 karakters) +breaking.text = Tekst +breaking.date = Datum + +breakinglist.htmltitle = Overzicht breaking news -breakinglist.htmltitle=Overzicht breaking news # comment -comment.htmltitle=Commentaar -comment.date=Datum -comment.title=Titel -comment.published=Gepubliceerd -comment.text=Commetaar tekst -comment.address=Adres -comment.phone=Telefoon -comment.email=E-mail -comment.url=Homepage -comment.creator=Auteur -comment.article=Voor artikel -comment.html=HTML? -comment.status=Status -comment.language=Taal - -commentlist.htmltitle=Overzicht commentaren -commentlist.published=Gepubliceerd -commentlist.hidden=Verborgen -commentlist.search=Zoek - -commentsearch.order.datedesc= Datum (nieuwste eerst) -commentsearch.order.dateasc= Datum (oudste eerst) -commentsearch.order.articletitle= Titel artikel +comment.htmltitle = Commentaar +comment.date = Datum +comment.title = Titel +comment.published = Gepubliceerd +comment.text = Commetaar tekst +comment.address = Adres +comment.phone = Telefoon +comment.email = E-mail +comment.url = Homepage +comment.creator = Auteur +comment.article = Voor artikel +comment.html = HTML? +comment.status = Status +comment.language = Taal + +comment.operation.hide = verbergen +comment.operation.unhide = zichtbaar maken + + +#commentlist +commentlist.htmltitle = Overzicht commentaren +commentlist.published = Gepubliceerd +commentlist.hidden = Verborgen +commentlist.allcomments = Alle commentaren van dit artikel +commentlist.search = Zoek +commentlist.activate = activeer veranderingen +commentlist.order = sortering +commentlist.order.datedesc = datum (aflopend) +commentlist.order.dateasc = datum (oplopend) +commentlist.order.articletitle = titel + +commentsearch.field = Zoeken +commentsearch.field.title = Titel +commentsearch.field.creator = Auteur +commentsearch.field.description = Inhoud +commentsearch.value = Waarde + +commentsearch.publishedstate = Publicatie status +commentsearch.publishedstate.hidden = Ongepubliceerd +commentsearch.publishedstate.published = Gepubliceerd + +commentsearch.status = Status + +commentsearch.order = Sortering +commentsearch.order.datedesc = Datum (nieuwste eerst) +commentsearch.order.dateasc = Datum (oudste eerst) +commentsearch.order.articletitle = Titel artikel + +commentsearch.searchbutton = Zoeken + # confirm -confirm.htmltitle=Bevestigen -confirm.really_delete=Weet je zeker dat je dit item wilt deleten? +confirm.htmltitle = Bevestigen +confirm.really_delete = Weet je zeker dat je dit item wilt deleten? +confirm.text = Deze operatie kan niet ongedaan gemaakt worden + # content -content.htmltitle=Artikel -content.owner=Eigenaar -content.topic=Onderwerp -content.feature=Feature -content.title=Titel -content.subtitle=Onder titel / Context titel -content.location=Locatie -content.creator=Auteur -content.creator.email=E-mail -content.creator.url=Homepage -content.creator.address=Adres -content.creator.telephone=Telefoon -content.abstract=Inleiding -content.content=Tekst -content.html=HTML? -content.comment=Aantekeningen -content.internal=(voor intern gebruik) -content.attachments=Attachments -content.images=Afbeeldingen -content.audio=Geluidsfragmenten -content.video=Beeldfragmenten -content.other=Andere multi-media -content.media=Multi-media -content.addimage=Afbeelding bijvoegen -content.addaudio=Geluidsfragment bijvoegen -content.addvideo=Beeldmateriaal bijvoegen -content.addother=Andere multi-media bijvoegen -content.creationdate=Aanmaak datum -content.modificationdate=Datum laatste wijziging -content.status=Status -content.type=Soort artikel -content.import_date=Import datum -content.lastchange_date=Datum laatste wijziging -content.create_date=Aanmaak datum -content.published=Gepubliceerd -content.comments=Commentaren - - -contentlist.htmltitle=Overzicht Artikelen -contentlist.comments=Commentaren +content.htmltitle = Artikel +content.owner = Eigenaar +content.language = Taal +content.articletype = Artikel soort +content.topic = Onderwerp +content.title = Titel +content.subtitle = Onder titel / Context titel +content.location = Locatie +content.creator = Auteur +content.creator.email = E-mail +content.creator.url = Homepage +content.creator.address = Adres +content.creator.telephone = Telefoon +content.abstract = Inleiding +content.content = Tekst +content.html = HTML? +content.comment = Aantekeningen +content.internal = (voor intern gebruik) + +content.attachments = Attachments +content.images = Afbeeldingen +content.audio = Geluidsfragmenten +content.video = Beeldfragmenten +content.other = Andere multi-media +content.media = Multi-media +content.addimage = Afbeelding bijvoegen +content.uploadimage = Afbeelding uploaden +content.addaudio = Geluidsfragment bijvoegen +content.uploadaudio = Geluidsfragment uploaden +content.addvideo = Beeldmateriaal bijvoegen +content.uploadvideo = Beeldmateriaal uploaden +content.addother = Andere multi-media bijvoegen +content.uploadother = Andere multi-media uploaden + +content.creationdate = Aanmaak datum +content.modificationdate = Datum laatste wijziging +content.status = Status +content.type = Soort artikel +content.import_date = Import datum +content.lastchange_date = Datum laatste wijziging +content.create_date = Aanmaak datum +content.published = Gepubliceerd +content.comments = Commentaren + +content.family = Dochter / moeder artikelen +content.children = Dochters +content.viewchildren = Tonen +content.parent = Moeder +content.viewparent = Tonen +content.clearparent = De-selecteren +content.selectparent = Selecteren + +content.operation.hide = Verbergen +content.operation.unhide = Zichtbaar maken +content.operation.newswire = Newslijn + +contentsearch.value = Zoeken +contentsearch.field = Veld +contentsearch.field.title = Titel +contentsearch.field.creator = Auteur +contentsearch.field.contents = Inhoud + +contentsearch.publishedstate = Publicatie status +contentsearch.publishedstate.hidden = Ongepubliceerd +contentsearch.publishedstate.published = Gepubliceerd + +contentsearch.articletype = Artikel type + +contentsearch.order = Sortering +contentsearch.order.datedesc = Nieuwste eerst +contentsearch.order.dateasc = Oudste eerst +contentsearch.order.title = Titel +contentsearch.order.creator = Auteur +contentsearch.searchbutton = Zoeken + + +#contentlist +contentlist.htmltitle = Overzicht Artikelen +contentlist.comments = Commentaren +contentlist.select = Selecteren + # language -language.htmltitle=Taal -language.name=Taal -language.code=Taal code +language.htmltitle = Taal +language.name = Taal +language.code = Taal code + +languagelist.htmltitle = Overzicht talen -languagelist.htmltitle=Overzicht talen # imcs -linkimcs.htmltitle=LinksImcs -linkimcs.name=Name -linkimcs.continent=Continent -linkimcs.new_parent=New Parent -linkimcs.url=URL -linkimcs.sort_by=Sortcriteria -linkimcs.language=Language -linkimcs.parent=parent - -linkimcslist.htmltitle=LinksImcsList -linkimcslist.search_in=Search text in +linkimcs.htmltitle = LinksImcs +linkimcs.name = Name +linkimcs.continent = Continent +linkimcs.new_parent = New Parent +linkimcs.url = URL +linkimcs.sort_by = Sortcriteria +linkimcs.language = Language +linkimcs.parent = parent + +linkimcslist.htmltitle = LinksImcsList +linkimcslist.search_in = Search text in + # login -login.htmltitle=Aanmelden -login.info=Deze website is niet toegankelijk voor onbevoegden. Neem contact op met {0} voor meer informatie. -login.title=Aanmelden -login.name=Gebruikersnaam -login.password=Wachtwoord -login.language=Taalkeuze -login.submit=Aanmelden +login.htmltitle = Aanmelden +login.info = Deze website is niet toegankelijk voor onbevoegden. Neem contact op met {0} voor meer informatie. +login.title = Aanmelden +login.name = Gebruikersnaam +login.password = Wachtwoord +login.language = Taalkeuze +login.submit = Aanmelden + # mediafolder -mediafolder.htmltitle=Multi-media map -mediafolder.date=Datum -mediafolder.name=Naam -mediafolder.location=Locatie -mediafolder.keywords=Sleutelwoorden -mediafolder.comment=Aantekeningen +mediafolder.htmltitle = Multi-media map +mediafolder.date = Datum +mediafolder.name = Naam +mediafolder.location = Locatie +mediafolder.keywords = Sleutelwoorden +mediafolder.comment = Aantekeningen + +mediafolderlist.htmltitle = Overzicht multi-media mappen -mediafolderlist.htmltitle=Overzicht multi-media mappen # message -message.htmltitle=Intern prikbord -message.date=Datum -message.title=Titel -message.creator=Auteur -message.text=Tekst -message.textinfo=(max. 5 regels / 250 karakters) +message.htmltitle = Intern prikbord +message.date = Datum +message.title = Titel +message.creator = Auteur +message.text = Tekst +message.textinfo = (max. 5 regels / 250 karakters) -messagelist.htmltitle=Overzicht intern prikbord +messagelist.htmltitle = Overzicht intern prikbord # admin start page -start.htmltitle=Beheer -start.openpostings.title=Open postings -start.comments.title=Commentaren -start.breaking.title=Breaking news -start.breaking.new=Breaking news toevoegen -start.content.title=Artikelen -start.content.new=Artikel aanmaken -start.show=bekijken - -start.content.hidden=Ongepubliceerde artikelen -start.content.not_published=Ongepubliceerde artikelen -start.content.with_media=Artikelen met multi-media -start.content.last_changes=Laatst gewijzigde artikelen -start.content.with_comments=Artikelen met interne opmerkingen -start.content.all=Alle artikelen -start.content.search=Zoeken - -start.allarticlesoftype=Alle "{0}" artikelen - - -start.producers.title=Handmatig genereren -start.producers.produceAllNew=Alle nieuwe pagina's genereren -start.producers.advanced=Geavanceerde functies (niet zomaar gebruiken!) - -start.topics.title=Onderwerpen -start.other_media.title=Andere multi-media -start.images.title=Afbeeldingen -start.video.title=Beeldfragmenten -start.audio.title=Geluidsfragmenten -start.mediafolder.title=Multi-media map -start.languages.title=Talen -start.imcs.title=IMCS -start.messageboard.title=Intern prikbord -start.messageboard.no_messages=Geen berichten - -start.superusermenu=Super-gebruiker functies (niet zomaar gebruiken!) - -start.editfiles.title=Bestanden bewerken -start.editfiles.include=Bewerken +start.htmltitle = Beheer + +start.breaking.new = Breaking news toevoegen +start.content.new = Artikel aanmaken +start.show = bekijken +start.open_by_id = open nummer + +start.content.comments = Commentaren +start.content.hidden = Ongepubliceerde artikelen +start.content.not_published = Ongepubliceerde artikelen +start.content.with_media = Artikelen met multi-media +start.content.last_changes = Laatst gewijzigde artikelen +start.content.with_comments = Artikelen met interne opmerkingen +start.content.all = Alle artikelen +start.content.search = Zoeken + +start.allarticlesoftype = Alle "{0}" artikelen + +start.producers.title = Handmatig genereren +start.producers.produceAllNew = Alle nieuwe pagina's genereren +start.producers.advanced = Geavanceerde functies (niet zomaar gebruiken!) + +start.openpostings.title = Open postings +start.comments.title = Commentaren +start.breaking.title = Breaking news +start.content.title = Artikelen +start.administer.title = OPRUIMEN +start.list.title = LIJST +start.fileedit.title = Include bestanden bewerken +start.addandedit.title = VOEG TOE / BEWERK +start.extra.title = EXTRA +start.search.title = ZOEKEN +start.topics.title = Onderwerpen +start.other_media.title = Andere multi-media +start.images.title = Afbeeldingen +start.video.title = Beeldfragmenten +start.audio.title = Geluidsfragmenten +start.media.title = MEDIA +start.mediafolder.title = Multi-media map +start.languages.title = Talen +start.imcs.title = IMCS +start.messageboard.title = Intern prikbord +start.messageboard.no_messages = Geen berichten + +start.superusermenu = Super-gebruiker functies (niet zomaar gebruiken!) + # topic -topic.htmltitle=Onderwerp -topic.title=Naam -topic.description=Omschrijving -topic.filename=Bestandsnaam -topic.main_url=Hoofd pagina -topic.archive_url=Archief pagina +topic.htmltitle = Onderwerp +topic.title = Naam +topic.description = Omschrijving +topic.filename = Bestandsnaam +topic.main_url = Hoofd pagina +topic.archive_url = Archief pagina + +topiclist.htmltitle = Overzicht onderwerpen -topiclist.htmltitle=Overzicht onderwerpen # users -user.htmltitle=Gebruiker -user.login=Gebruikersnaam -user.password=Wachtwoord -user.admin=Beheerder? +user.htmltitle = Gebruiker +user.login = Gebruikersnaam +user.password = Wachtwoord +user.password2 = Wachtwoord (bevestiging) +user.admin = Beheerder? + +userlist.htmltitle = Overzicht gebruikers -userlist.htmltitle=Overzicht gebruikers +#articletype +articletype.htmltitle = Artikelsoort +articletype.id = Nummer +articletype.name = Naam -articletype.htmltitle=Artikelsoort -articletype.id=Nummer -articletype.name=Naam +articletypelist.htmltitle = Overzicht artikel-soorten -articletypelist.htmltitle=Overzicht artikel-soorten -commentstatus.htmltitle=Commentaar status waarde -commentstatus.id=Nummer -commentstatus.name=Naam -commentstatuslist.htmltitle=Overzicht commentaar status waarden +#commentstatus +commentstatus.htmltitle = Commentaar status waarde +commentstatus.id = Nummer +commentstatus.name = Naam + +commentstatuslist.htmltitle = Overzicht commentaar status waarden + #file editing +fileedit.htmltitle = Bestand bewerken +fileedit.filename = Bestandsnaam +fileedit.subdirectory = Map + fileeditlist.htmltitle = Bewerkbare bestanden fileeditlist.filename = Bestandsnaam -fileedit.filename = Bestandsnaam -fileedit.htmltitle = Bestand bewerken +fileeditlist.dirname = Map + #producers producer.producer = Producer naam @@ -290,11 +397,12 @@ producer.verb.name = Opdracht naam producer.verb.description = Opdracht omschrijving producer.verb.enqueue = uitvoeren -producer.job.name= Taak -producer.job.status= Status -producer.job.date= Laatste wijziging -producer.job.cancel= opheffen -producer.job.abort= afbreken +producer.job.name = Taak +producer.job.status = Status +producer.job.date = Laatste wijziging +producer.job.cancel = opheffen +producer.job.abort = afbreken +producer.job.empty = wachtrij is leeg producer.jobqueue.title = Overzicht huidige opdrachten producer.jobqueue.refresh = Overzicht verversen @@ -303,49 +411,101 @@ producer.producerlist.title = Nieuwe opdracht toevoegen producerqueue.htmltitle = Handmatig generen -superusermenu.htmltitle = Super-user functies -superusermenu.topics = Onderwerpen beheren -superusermenu.articletypes = Artikel-soorten beheren -superusermenu.comment_statuses = Commentaar status waarden beheren -superusermenu.users = Gebruikers beheren -superusermenu.languages = Talen beheren -superusermenu.imcs = Manage IMCS (obsolete) +#superusermenu +superusermenu.htmltitle = Super-user functies +superusermenu.manage = BEHEER +superusermenu.topics = Onderwerpen beheren +superusermenu.articletypes = Artikel-soorten beheren +superusermenu.comment_statuses = Commentaar status waarden beheren +superusermenu.users = Gebruikers beheren +superusermenu.languages = Talen beheren +superusermenu.abuse = Misbruik preventie +superusermenu.imcs = Manage IMCS (obsolete) + + +#abuse +abuse.htmltitle = Misbruik preventie + +abuse.setting = Instelling +abuse.value = Waarde + +abuse.disableopenpostings = Open posting uitzetten +abuse.openpostingpassword = Wachtwoord beveiliging voor open postings aanzetten +abuse.logpostings = IP-nummers loggen +abuse.logsize = IP-nummer log grootte +abuse.cookies = "Cookies" gebruiken tegen misbruik +abuse.articleaction = Actie voor een geblokkeerd artikel +abuse.commentaction = Actie voor een geblokkeerd commentaar + +abuse.showlog = IP log bekijken +abuse.showfilters = Filters beheren + +abuse.log.time = Tijdstip +abuse.log.address = IP nummer +abuse.log.object = Object +abuse.log.browser = Browser + +abuse.filters = Filters +abuse.filter.type = Type +abuse.filtertype.ip = IP Nummer +abuse.filtertype.regexp = Reguliere Expressie +abuse.filter.expression = Expressie # head -head.start=menu -head.logout=uitloggen -head.help=help -head.search=zoeken -head.logged_in=ingelogd +head.start = menu +head.logout = uitloggen +head.help = help +head.search = zoeken +head.logged_in = ingelogd # foot -foot.top=bovenkant +foot.top = bovenkant + + +########## dynamic values ########## + +# (users can add new types, how to translate these) +# suggestion if not in bundle use value as Text # Article types -articletypes.openposting=Open posting -articletypes.newswire=Nieuwslijn -articletypes.feature=Feature -articletypes.topicspecial=Topic-special -articletypes.startspecial=Startpagina-special +articletypes.openposting = Open posting +articletypes.newswire = Nieuwslijn +articletypes.feature = Feature +articletypes.topicspecial = Topic-special +articletypes.startspecial = Startpagina-special # Comment status values -commentstatus.normal=Normaal +commentstatus.normal = Normaal +# missing (master value = "good") +commentstatus.good = +# missing (master value = "bad") +commentstatus.bad = + + ########## error ########## +error.htmltitle = Mir heeft een fout gemaakt +error.title = Mir heeft een fout gemaakt +error.text = Dit can gebeuren. Gelieve de volgende tekst te kopieren en naar {1} op te sturen: +error.text2 = Gelieve de volgende rode tekst en een gedetailleerde omschrijving van de gebeurtenissen die tot deze fout geleid hebben op te sturen aan {1}. Bij voorbaat dank! + +usererror.htmltitle = Validatie fout +usererror.title = Validatie fout +usererror.text = Jouw invoer heeft de volgende fout: +usererror.what_to_do = Druk op de back-toets en probeer het opnieuw! -error.htmltitle=Mir heeft een fout gemaakt -error.title=Mir heeft een fout gemaakt -error.text=Dit can gebeuren. Gelieve de volgende tekst te kopieren en naar {1} op te sturen: -error.text2=Gelieve de volgende de rode tekst en een gedetailleerde omschrijving van de gebeurtenissen die tot deze fout geleid hebben op te sturen aan {1}. Bij voorbaat dank! +media.error.unsupportedformat = Het formaat van het multi-media bestand dat je ge-upload hebt, wordt niet ondersteund +user.error.missingpasswords = Het nieuwe wachtwoord moet tweemaal ingevuld worden +user.error.passwordmismatch = De wachtwoorden zijn verschillend +user.error.missingpassword = Er moet een wachtwoord worden ingevuld -usererror.htmltitle=Validatie fout -usererror.title=Validatie fout -usererror.text=Jouw invoer heeft de volgende fout: -usererror.what_to_do=Druk op de back-toets en probeer het opnieuw! +########## infomessages ########## infomessage.htmltitle = Mededeling infomessage.produceAllNewAddedToQueue = Je opdracht wordt zo snel mogelijk uitgevoerd -htmlcharset=utf-8 +########## HTML-charset ########## +# missing (master value = "utf-8") +htmlcharset = diff --git a/bundles/admin_pt.properties b/bundles/admin_pt.properties index c633789e..e9e43bf6 100755 --- a/bundles/admin_pt.properties +++ b/bundles/admin_pt.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: portuguese -# $Id: admin_pt.properties,v 1.3 2003/02/21 05:38:36 zapata Exp $ +# $Id: admin_pt.properties,v 1.4 2003/04/09 02:06:06 zapata Exp $ languagename=Português @@ -307,13 +307,13 @@ producer.producerlist.title = Add a new job producerqueue.htmltitle = Generate manually -superusermenu.htmltitle = funções dos super-usuários -superusermenu.topics = Manutenção dos assuntos -superusermenu.articletypes = Manutenção dos tipos de artigos -superusermenu.comment_statuses = Manutenção comment status values -superusermenu.users = Manutenção de usuários -superusermenu.languages = Manutenção de línguas -superusermenu.imcs = Manutenção de CMIs (absoleto) +superusermenu.htmltitle = funções dos super-usuários +superusermenu.topics = Manutenção dos assuntos +superusermenu.articletypes = Manutenção dos tipos de artigos +superusermenu.comment_statuses = Manutenção comment status values +superusermenu.users = Manutenção de usuários +superusermenu.languages = Manutenção de línguas +superusermenu.imcs = Manutenção de CMIs (absoleto) @@ -353,4 +353,3 @@ usererror.what_to_do=Por favor pressione a tecla de retorno e tente novamente infomessage.title = Informação infoanguage codeQueue = O seu pedido foi adicionada à fila de pedidos. -htmlcharset=utf-8 diff --git a/bundles/admin_qu.properties b/bundles/admin_qu.properties deleted file mode 100755 index 972d2f4d..00000000 --- a/bundles/admin_qu.properties +++ /dev/null @@ -1,314 +0,0 @@ -########## admin ########## -# language: quechua - -languagename=Quechua - -# general -yes=sí -no=no -dontcare=no importa -all=todo - -# actions -insert=insertar -save=guardar -edit=editar -delete=borrar -add=añadir -filter=filtrar -attach=vincular -list=mostrar lista -back=atrás -cancel=cancelar - -# records -records=registros -show_from_to=mostrando entradas desde {0} hasta {1} -no_matches_found=No se encontraron resultados! -list.next=siguiente -list.previous=anterior - -# media - used by image, audio, video and other media -media.created=creado -media.changed=cambiado -media.published=publicado -media.format=Formato -media.rights=Copyright -media.type=Tipo -media.mediafolder=Carpeta de recursos mediáticos -media.title=Título -media.size=Tamaño -media.description=Descripción -media.date=Fecha -media.location=Lugar de origen -media.creator=Creador -media.keywords=Palabras clave -media.comment=Comentario -media.source=Origen -media.is_published=Disponible para publicación -media.icon=Icono -media.nr_of_media=Número de recursos mediáticos -media.nr_of_media.submit=define number -medialist.search_text_in=Buscar texto en - -# image -image.htmltitle=imagen -imagelist.htmltitle=lista de imagenes - -# audio -audio.htmltitle=audio -audiolist.htmltitle=lista de audio - -# video -video.htmltitle=video -videolist.htmltitle=lista de video - -# other -other_media.htmltitle=otros recursos mediáticos -other_media.htmltitle=lista de recursos mediáticos - -# breaking -breaking.htmltitle=últimas noticias -breakinglist.htmltitle=listado de últimas noticias -breaking.textinfo=(max. 5 líneas / 250 caracteres) -breaking.text=texto -breaking.date=fecha - - -# comment -comment.htmltitle=commentario -comment.date=fecha -comment.title=título -comment.published=publicado -comment.text=texto-del-comentario -comment.address=dirección -comment.phone=teléfono -comment.email=email -comment.url=url -comment.creator=autor -comment.article=del artículo -comment.html=es HTML? -comment.status=Status # needs translation -comment.language=Lengua - -commentlist.htmltitle=lista de comentarios -commentlist.published=publicado -commentlist.hidden=oculto -commentlist.search=buscar! - -commentlist.order.datedesc= date (desc.) # needs translation -commentlist.order.dateasc= date (asc.) # needs translation -commentlist.order.articletitle= article title # needs translation - - -# confirm -confirm.htmltitle=confirmar borrado -confirm.really_delete=Desea borrar esta entrada? - -# content -content.htmltitle=contenido -content.owner=Propietario -content.topic=Tema -content.feature=Característica -content.title=titulo largo -content.subtitle=subtítulo/título de contexto -content.location=Lugar de origen -content.creator=autor -content.creator.email=Email -content.creator.url=Web -content.creator.address=Dirección -content.creator.telephone=Teléfono -content.abstract=Descripción breve -content.content=Contenido -content.html=es HTML? -content.comment=Comentario interno -content.internal=(propósito interno) -content.attachments=Vínculos -content.images=Imágenes -content.audio=Audio -content.video=Video -content.other=Otros recursos mediáticos -content.media=Recursos mediáticos -content.addimage=añadir imagen -content.addaudio=añadir audio -content.addvideo=añadir video -content.addother=añadir otros recursos mediáticos -content.creationdate=fecha -content.modificationdate=último cambio -content.status=Estado -content.type=Tipo de artículo -content.published=publicado -content.comments=Comentarios - -contentlist.htmltitle=lista de contenidos - -# language -language.htmltitle=idiomas -language.name=idioma -language.code=Código del idioma - -languagelist.htmltitle=lista de idiomas - -# imcs -linkimcs.htmltitle=Enlaces a IMCs -linkimcs.name=Nombre -linkimcs.continent=Continente -linkimcs.new_parent=Nuevo Ancestro -linkimcs.url=URL -linkimcs.sort_by=Criterio de orden -linkimcs.language=Idioma -linkimcs.parent=ancestro - -linkimcslist.htmltitle=Lista de enlaces a IMCs -linkimcslist.search_in=Buscar texto en - -# login -login.htmltitle=registro -login.info=Esta zona es accesible exclusivamente a grupos autorizados. Si desea colaborar como editor, por favor contacte con nosotros en {0}. -login.title=login -login.name=Login -login.password=Password -login.language=Idioma -login.submit=Envíar - -# mediafolder -mediafolder.htmltitle=carpeta de recursos mediáticos -mediafolder.date=fecha -mediafolder.name=nombre -mediafolder.location=lugar de origen -mediafolder.keywords=palabras clave -mediafolder.comment=commentario - -mediafolderlist.htmltitle=lista de carpetas de recursos mediáticos - -# message -message.htmltitle=mensajes -message.date=fecha -message.title=título -message.creator=Autor -message.text=texto -message.textinfo=(max. 5 líneas / 250 caracteres) - -messagelist.htmltitle=lista de mensajes - -# feature -feature.htmltitle=presentación -feature.title=Título -feature.published=publicado -feature.is_published=está publicado -feature.is_not_published=no está publicado -feature.filename=Nombre del fichero -feature.abstract=Descripción breve -feature.link=Enlace - -featurelist.htmltitle=lista de presentaciones - -# admin start page -start.htmltitle=administración -start.openpostings.title=ENVÍOSABIERTOS -start.comments.title=COMENTARIOS -start.breaking.title=ÚLTIMAS NOTICIAS -start.breaking.new=últimas noticias recientes -start.content.title=ARTICULOS -start.content.new=nuevos artículos -start.show=mostrar -start.content.newswire=newswire -start.content.feature=presentación -start.content.topicspecial=especiales-por-tema -start.content.startspecial=especiales-página-de-inicio -start.content.not_published=artículos aun sin publicar -start.content.with_media=con recursos mediáticos -start.content.last_changes=últimos cambios -start.content.with_comments=con comentarios de propósito interno -start.content.all=todos -start.content.search=buscar -start.generate.title=GENERAR MANUALMENTE -start.generate.all.title=todas las areas -start.generate.all.new=todo nuevo (estándar, actualización en la web > 5min.) -start.generate.parts.title=partes específicas del website -start.generate.startpages.new=nueva página de inicio -start.generate.all_forced=todos (forzado) -start.generate.all_sync=todos (forzado y sincronizado) -start.generate.content.new=nuevo contenido -start.generate.topics.new=nuevos temas -start.generate.postings.new=nuevos envios abiertos -start.generate.images.new=nuevas imágenes -start.generate.audio.new=nuevos ficheros de audio -start.generate.video.new=nuevos ficheros de video -start.generate.other.new=otros recursos mediáticos nuevos -start.generate.navigation=navegación -start.coverage.title=COBERTURA -start.topics.title=TEMAS -start.images.title=MATERIAL GRAFICO -start.mediafolder.title=CARPETA DE RECURSOS MEDIATICOS -start.languages.title=TÍTULO -start.imcs.title=IMCS -start.messageboard.title=Mensajería Interna -start.messageboard.no_messages=no hay mensajes - -start.superusermenu=Superuser menu (use with care!) # needs translation - - -# topic -topic.htmltitle=tema -topic.title=Nombre -topic.description=descripción -topic.filename=Nombre del fichero -topic.main_url=página de información principal -topic.archive_url=URL del archivo - -topiclist.htmltitle=lista de temas - -articletype.htmltitle=Article type # needs translation -articletype.id=id # needs translation -articletype.name=Name # needs translation - -articletypelist.htmltitle=Article types # needs translation - -commentstatus.htmltitle=Comment status # needs translation -commentstatus.id=id # needs translation -commentstatus.name=Name # needs translation - -commentstatuslist.htmltitle=Comment status values # needs translation - -superusermenu.htmltitle = Super-user functions # needs translation -superusermenu.topics = Manage topics # needs translation -superusermenu.articletypes = Manage article types # needs translation -superusermenu.comment_statuses = Manage comment status values # needs translation -superusermenu.users = Manage users # needs translation -superusermenu.languages = Manage languages # needs translation -superusermenu.imcs = Manage IMCS (obsolete) # needs translation - -# users -user.htmltitle=usuario -user.login=login -user.password=password -user.admin=administrador - -userlist.htmltitle=lista de usuarios - -# head -head.start=inicio -head.logout=salir -head.help=ayuda -head.search=buscar -head.logged_in=estás registrado - -# foot -foot.top=arriba - - -########## error ########## - -error.htmltitle=error -error.title=oi! oi! oi! -error.text=El siguiente mensaje puede que no le sea de mucha ayuda, pero seguramente lo será para {1}: -error.text2=Por favor envíe un mensaje con el texto que aparece en rojo y una descripción detallada a la siguiente dirección {1}. Gracias! - - -usererror.htmltitle=error de datos -usererror.title=oi! oi! oi! -usererror.text=Los datos que ha introducido han causado el siguiente error: -usererror.what_to_do=Por favor, pulse el botón para volver e intentelo de nuevo - -htmlcharset=utf-8 diff --git a/bundles/admin_sv.properties b/bundles/admin_sv.properties index 5f4c2ae4..63b97daf 100755 --- a/bundles/admin_sv.properties +++ b/bundles/admin_sv.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: svenska -# $Id: admin_sv.properties,v 1.4 2003/03/16 14:26:30 zapata Exp $ +# $Id: admin_sv.properties,v 1.5 2003/04/09 02:06:06 zapata Exp $ languagename=Svenska @@ -353,4 +353,3 @@ usererror.what_to_do=Please press the back button and try it again infomessage.title = Information infomessage.produceAllNewAddedToQueue = Din begäran har placerats i kön. -htmlcharset=utf-8 diff --git a/bundles/admin_tr.properties b/bundles/admin_tr.properties index d80fc693..a2ca84a7 100755 Binary files a/bundles/admin_tr.properties and b/bundles/admin_tr.properties differ diff --git a/bundles/admin_zh.properties b/bundles/admin_zh.properties index 50d69cc0..f8f7ff76 100755 --- a/bundles/admin_zh.properties +++ b/bundles/admin_zh.properties @@ -1,297 +1,295 @@ ########## admin ########## # language: english -# $Id: admin_zh.properties,v 1.1 2003/01/18 08:15:19 mh Exp $ +# $Id: admin_zh.properties,v 1.2 2003/04/09 02:06:06 zapata Exp $ -languagename=Chinese +languagename = Chinese # general -yes=¬O -no=§_ -dontcare=ÀH·N -all=¥þ -month=¤ë -year=¦~ -file=ÀÉ +yes = \u662f +no = \u5426 +dontcare = \u96a8\u610f +all = \u5168 +month = \u6708 +year = \u5e74 +file = \u6a94 # actions -insert=´¡ -save=¦s -edit=­× -delete=§R -add=¥[ -filter=Âo -attach=ªþ -list=Äý -back=°h -cancel=ºM -preview=¹wÄý -reset=­«³] +insert = \u63d2 +save = \u5b58 +edit = \u4fee +delete = \u522a +add = \u52a0 +filter = \u6ffe +attach = \u9644 +list = \u89bd +back = \u9000 +cancel = \u64a4 +preview = \u9810\u89bd +reset = \u91cd\u8a2d # special -fileedit=½sÀÉ +fileedit = \u7de8\u6a94 # records -records=°O¿ý¶µ¥Ø -show_from_to=¦C¥X²Ä{0}µ§¨ì²Ä{1}µ§ -no_matches_found=µL²Å¦X¶µ¥Ø! -list.next=«á¤@µ§ -list.previous=«e¤@µ§ +records = \u8a18\u9304\u9805\u76ee +show_from_to = \u5217\u51fa\u7b2c{0}\u7b46\u5230\u7b2c{1}\u7b46 +no_matches_found = \u7121\u7b26\u5408\u9805\u76ee! +list.next = \u5f8c\u4e00\u7b46 +list.previous = \u524d\u4e00\u7b46 # media - used by image, audio, video and other media -media.created=¤w»s§@ -media.changed=¤w·s­× -media.published=¤wµoªí -media.format=®æ¦¡ -media.rights=µÛ§@Åvª¬ªp -media.type=´CÅé®æ¦¡ -media.mediafolder=´CÅé¸ê®Æ§¨ -media.title=¼ÐÃD -media.description=´y­z -media.date=¤é´Á -media.location=¦aÂI -media.creator=§@ªÌ -media.keywords=ÃöÁä¦r -media.comment=¤p·N¨£ (¤º³¡¨Ï¥Î) -media.source=¨Ó·½ -media.is_published=¤vµoªí -media.icon=¹Ï¥Ü -media.nr_of_media=´CÅ骫¥ó¼Æ¶q (³Ì¦h20) -media.nr_of_media.submit=©w¸q¼Æ¶q - -medialist.search_text_in=·j´M¤å¦r +media.created = \u5df2\u88fd\u4f5c +media.changed = \u5df2\u65b0\u4fee +media.published = \u5df2\u767c\u8868 +media.format = \u683c\u5f0f +media.rights = \u8457\u4f5c\u6b0a\u72c0\u6cc1 +media.type = \u5a92\u9ad4\u683c\u5f0f +media.mediafolder = \u5a92\u9ad4\u8cc7\u6599\u593e +media.title = \u6a19\u984c +media.description = \u63cf\u8ff0 +media.date = \u65e5\u671f +media.location = \u5730\u9ede +media.creator = \u4f5c\u8005 +media.keywords = \u95dc\u9375\u5b57 +media.comment = \u5c0f\u610f\u898b (\u5167\u90e8\u4f7f\u7528) +media.source = \u4f86\u6e90 +media.is_published = \u5df1\u767c\u8868 +media.icon = \u5716\u793a +media.nr_of_media = \u5a92\u9ad4\u7269\u4ef6\u6578\u91cf (\u6700\u591a20) +media.nr_of_media.submit = \u5b9a\u7fa9\u6578\u91cf + +medialist.search_text_in = \u641c\u5c0b\u6587\u5b57 # image -image.htmltitle=¼v¹³ -imagelist.htmltitle=¼v¹³ªí +image.htmltitle = \u5f71\u50cf +imagelist.htmltitle = \u5f71\u50cf\u8868 # audio -audio.htmltitle=Án­µ -audiolist.htmltitle=Án­µªí +audio.htmltitle = \u8072\u97f3 +audiolist.htmltitle = \u8072\u97f3\u8868 # video -video.htmltitle=¼v­µ -videolist.htmltitle=¼v­µªí +video.htmltitle = \u5f71\u97f3 +videolist.htmltitle = \u5f71\u97f3\u8868 # other -other_media.htmltitle=¨ä¥L´CÅé -other_media.htmltitle=¨ä¥L´CÅéªí +other_media.htmltitle = \u5176\u4ed6\u5a92\u9ad4 +other_media.htmltitle = \u5176\u4ed6\u5a92\u9ad4\u8868 # breaking -breaking.htmltitle=·s»D§Ö³ø -breaking.textinfo=(³Ì¦h¤­¦æ/300¦r) -breaking.text=¤º¤å -breaking.date=¤é´Á +breaking.htmltitle = \u65b0\u805e\u5feb\u5831 +breaking.textinfo = (\u6700\u591a\u4e94\u884c/300\u5b57) +breaking.text = \u5167\u6587 +breaking.date = \u65e5\u671f -breakinglist.htmltitle=§Ö³ø¦Cªí +breakinglist.htmltitle = \u5feb\u5831\u5217\u8868 # comment -comment.htmltitle=µû½× -comment.date=¤é´Á -comment.title=¼ÐÃD -comment.published=¤wµoªí -comment.text=µû½×¤º¤å -comment.address=¦a§} -comment.phone=¹q¸Ü -comment.email=¹q¶lemail -comment.url=¶W³sµ²url -comment.creator=§@ªÌ -comment.article=°w¹ï -comment.html=HTML? -comment.status=ª¬ºA -comment.language=»y¨¥ - - -commentlist.htmltitle=µû½×¦Cªí -commentlist.produced=¤w»s§@ -commentlist.hidden=ÁôÂà -commentlist.search=¶}©l·j´M! +comment.htmltitle = \u8a55\u8ad6 +comment.date = \u65e5\u671f +comment.title = \u6a19\u984c +comment.published = \u5df2\u767c\u8868 +comment.text = \u8a55\u8ad6\u5167\u6587 +comment.address = \u5730\u5740 +comment.phone = \u96fb\u8a71 +comment.email = \u96fb\u90f5email +comment.url = \u8d85\u9023\u7d50url +comment.creator = \u4f5c\u8005 +comment.article = \u91dd\u5c0d +comment.html = HTML? +comment.status = \u72c0\u614b +comment.language = \u8a9e\u8a00 + + +commentlist.htmltitle = \u8a55\u8ad6\u5217\u8868 +commentlist.produced = \u5df2\u88fd\u4f5c +commentlist.hidden = \u96b1\u85cf +commentlist.search = \u958b\u59cb\u641c\u5c0b! # confirm -confirm.htmltitle=½T»{§R -confirm.really_delete=¯u­n§R¦¹µ§¸ê®Æ? +confirm.htmltitle = \u78ba\u8a8d\u522a +confirm.really_delete = \u771f\u8981\u522a\u6b64\u7b46\u8cc7\u6599? # content -content.htmltitle=¤º®e -content.owner=¾Ö¦³ªÌ -content.topic=¥DÃD -content.feature=±MÃD -content.title=¥D¼ÐÃD -content.subtitle=°Æ¼ÐÃD -content.location=¦aÂI -content.creator=§@ªÌ -content.creator.email=¹q¶lEmail -content.creator.url=ºô¯¸ -content.creator.address=¦a§} -content.creator.telephone=¹q¸Ü -content.abstract=ºK­n -content.content=¤º®e -content.html=HTML? -content.comment=¤º³¡µû½× -content.internal=(¤º³¡) -content.attachments=ªþ¥ó -content.images=¼v¹³ -content.audio=Án­µ -content.video=¼v­µ -content.other=¨ä¥L´CÅé -content.media=´CÅé -content.addimage=¥[¼v¹³ -content.addaudio=¥[Án­µ -content.addvideo=¥[¼v­µ -content.addother=¥[¨ä¥L´CÅé -content.creationdate=³Ð§@¤é´Á -content.modificationdate=­×§ï¤é´Á -content.status=ª¬ºA -content.type=¤åÃþ -content.import_date=Âà¤J¤é´Á -content.lastchange_date=¤W¦¸­×§ï -content.create_date=¤é´Á -content.published=¤wµoªí -content.comments=µû½× - -contentlist.htmltitle=¤º®eªí +content.htmltitle = \u5167\u5bb9 +content.owner = \u64c1\u6709\u8005 +content.topic = \u4e3b\u984c +content.feature = \u5c08\u984c +content.title = \u4e3b\u6a19\u984c +content.subtitle = \u526f\u6a19\u984c +content.location = \u5730\u9ede +content.creator = \u4f5c\u8005 +content.creator.email = \u96fb\u90f5Email +content.creator.url = \u7db2\u7ad9 +content.creator.address = \u5730\u5740 +content.creator.telephone = \u96fb\u8a71 +content.abstract = \u6458\u8981 +content.content = \u5167\u5bb9 +content.html = HTML? +content.comment = \u5167\u90e8\u8a55\u8ad6 +content.internal = (\u5167\u90e8) +content.attachments = \u9644\u4ef6 +content.images = \u5f71\u50cf +content.audio = \u8072\u97f3 +content.video = \u5f71\u97f3 +content.other = \u5176\u4ed6\u5a92\u9ad4 +content.media = \u5a92\u9ad4 +content.addimage = \u52a0\u5f71\u50cf +content.addaudio = \u52a0\u8072\u97f3 +content.addvideo = \u52a0\u5f71\u97f3 +content.addother = \u52a0\u5176\u4ed6\u5a92\u9ad4 +content.creationdate = \u5275\u4f5c\u65e5\u671f +content.modificationdate = \u4fee\u6539\u65e5\u671f +content.status = \u72c0\u614b +content.type = \u6587\u985e +content.import_date = \u8f49\u5165\u65e5\u671f +content.lastchange_date = \u4e0a\u6b21\u4fee\u6539 +content.create_date = \u65e5\u671f +content.published = \u5df2\u767c\u8868 +content.comments = \u8a55\u8ad6 + +contentlist.htmltitle = \u5167\u5bb9\u8868 # language -language.htmltitle=»y¨¥ -language.name=»y¨¥ -language.code=»y¨¥½s½X +language.htmltitle = \u8a9e\u8a00 +language.name = \u8a9e\u8a00 +language.code = \u8a9e\u8a00\u7de8\u78bc -languagelist.htmltitle=»y¨¥¦Cªí +languagelist.htmltitle = \u8a9e\u8a00\u5217\u8868 # imcs -linkimcs.htmltitle=À³»¼´C¦Cªí -linkimcs.name=¦WºÙ -linkimcs.continent=¬w -linkimcs.new_parent=·s¥ÀÂI -linkimcs.url=ºô§}URL -linkimcs.sort_by=±Æ¦C¨Ì¾Ú -linkimcs.language=»y¨¥ -linkimcs.parent=¥ÀÂI - -linkimcslist.htmltitle=À³»¼´C¶W³sµ¸¦Cªí -linkimcslist.search_in=·j´M +linkimcs.htmltitle = \u61c9\u905e\u5a92\u5217\u8868 +linkimcs.name = \u540d\u7a31 +linkimcs.continent = \u6d32 +linkimcs.new_parent = \u65b0\u6bcd\u9ede +linkimcs.url = \u7db2\u5740URL +linkimcs.sort_by = \u6392\u5217\u4f9d\u64da +linkimcs.language = \u8a9e\u8a00 +linkimcs.parent = \u6bcd\u9ede + +linkimcslist.htmltitle = \u61c9\u905e\u5a92\u8d85\u9023\u7d61\u5217\u8868 +linkimcslist.search_in = \u641c\u5c0b # login -login.htmltitle=µn¤J -login.info=¥»°Ï¥u¤¹³\¸g±ÂÅvªº¹ÎÅé. ­Y±z·Q¦¨¬°½s¿è¹Î¶¤ªº¤@­û, ½Ð©ó¤U¦C¦ì¸m³sµ¸§Ú­Ì. -login.title=µn¤J -login.name=µn¤J -login.password=±K½X -login.language=»y¨¥ +login.htmltitle = \u767b\u5165 +login.info = \u672c\u5340\u53ea\u5141\u8a31\u7d93\u6388\u6b0a\u7684\u5718\u9ad4. \u82e5\u60a8\u60f3\u6210\u70ba\u7de8\u8f2f\u5718\u968a\u7684\u4e00\u54e1, \u8acb\u65bc\u4e0b\u5217\u4f4d\u7f6e\u9023\u7d61\u6211\u5011. +login.title = \u767b\u5165 +login.name = \u767b\u5165 +login.password = \u5bc6\u78bc +login.language = \u8a9e\u8a00 #login.language.ay=Aymara #login.language.de=Deutsch #login.language.en=English -#login.language.es=Espa–ol -#login.language.gn=Guaran’ -#login.language.qu=Quechua +#login.language.es=Espa?l +#login.language.gn=Guaran?#login.language.qu=Quechua #login.language.tr=Turkish -login.submit= ¦n¤F +login.submit = \u597d\u4e86 # mediafolder -mediafolder.htmltitle=´CÅé¸ê®Æ§¨ -mediafolder.date=¤é´Á -mediafolder.name=¦WºÙ -mediafolder.location=¦aÂI -mediafolder.keywords=ÃöÁä¦r -mediafolder.comment=µû½× +mediafolder.htmltitle = \u5a92\u9ad4\u8cc7\u6599\u593e +mediafolder.date = \u65e5\u671f +mediafolder.name = \u540d\u7a31 +mediafolder.location = \u5730\u9ede +mediafolder.keywords = \u95dc\u9375\u5b57 +mediafolder.comment = \u8a55\u8ad6 -mediafolderlist.htmltitle=´CÅé¸ê®Æ§¨ªí +mediafolderlist.htmltitle = \u5a92\u9ad4\u8cc7\u6599\u593e\u8868 # message -message.htmltitle=°T®§ -message.date=¤é´Á -message.title=¼ÐÃD -message.creator=§@ªÌ -message.text=¤º¤å -message.textinfo=(³Ì¦h¤­¦æ/300¦r) +message.htmltitle = \u8a0a\u606f +message.date = \u65e5\u671f +message.title = \u6a19\u984c +message.creator = \u4f5c\u8005 +message.text = \u5167\u6587 +message.textinfo = (\u6700\u591a\u4e94\u884c/300\u5b57) -messagelist.htmltitle=°T®§ªí +messagelist.htmltitle = \u8a0a\u606f\u8868 # feature -#feature.htmltitle=±MÃD -#feature.title=¼ÐÃD -#feature.published=¤wµoªí -#feature.is_published=¥¿µoªí -#feature.is_not_published=©|¥¼µoªí -#feature.filename=ÀɦW -#feature.abstract=ºK­n -#feature.link=³sµ² -#featurelist.htmltitle=±MÃDªí +#feature.htmltitle=?? +#feature.title=?? +#feature.published=??? +#feature.is_published=??? +#feature.is_not_published=???? +#feature.filename=?? +#feature.abstract=?? +#feature.link=?? +#featurelist.htmltitle=??? # admin start page -start.htmltitle=¦æ¬F -start.openpostings.title=¶}³õ¤å -start.comments.title=<µû½×> -start.breaking.title=<·s»D§Ö³ø> -start.breaking.new=·s·s»D§Ö³ø -start.content.title=<½Z> -start.content.new=·sº` -start.show=¨q -start.content.newswire=³q°T½Z -start.content.feature=±MÃD -start.content.topicspecial=¯S§OijÃD -start.content.startspecial=°_ÂI­¶-¯SÃD -start.content.hidden=ÂýZ -start.content.not_published=(©|)¥¼µoªí½Z¥ó -start.content.with_media=§t´CÅé -start.content.last_changes=³Ì·s­×§ï -start.content.with_comments=§t¤º³¡µû½× -start.content.all=¥þ³¡¤å³¹ -start.content.search=·j´M -start.allarticlesoftype=Æ[¬Ý "{0}" ¤å³¹ - - -start.producers.title=<¤â°Ê²£¥Í> -start.producers.produceAllNew=²£¥Í©Ò¦³·s½Z -start.producers.advanced=¶i¶¥ºô­¶ (½Ð¯S§O¤p¤ß¨Ï¥Î!) - -#start.coverage.title=<³ø¾É> -start.topics.title=<¥DÃD> -start.images.title=<¼v¹³> -start.video.title=<¼v­µ> -start.audio.title=<Án­µ> -start.other_media.title=<¨ä¥L´CÅé> -start.mediafolder.title=<´CÅé¸ê®Æ§¨> -start.languages.title=<¤¤¤å> -start.imcs.title=À³»¼´CIMCS -start.messageboard.title=¤º³¡°T®§ª© -start.messageboard.no_messages=µL°T®§ - -start.superusermenu=ºÞ²zªÌÅv­­(½Ð¤p¤ß!) - -start.editfiles.title=½s¿èÀÉ®× -start.editfiles.include=§t¤JÀÉ®× +start.htmltitle = \u884c\u653f +start.openpostings.title = \u958b\u5834\u6587 +start.comments.title = <\u8a55\u8ad6> +start.breaking.title = <\u65b0\u805e\u5feb\u5831> +start.breaking.new = \u65b0\u65b0\u805e\u5feb\u5831 +start.content.title = <\u7a3f> +start.content.new = \u65b0\u69c1 +start.show = \u79c0 +start.content.newswire = \u901a\u8a0a\u7a3f +start.content.feature = \u5c08\u984c +start.content.topicspecial = \u7279\u5225\u8b70\u984c +start.content.startspecial = \u8d77\u9ede\u9801-\u7279\u984c +start.content.hidden = \u85cf\u7a3f +start.content.not_published = (\u5c1a)\u672a\u767c\u8868\u7a3f\u4ef6 +start.content.with_media = \u542b\u5a92\u9ad4 +start.content.last_changes = \u6700\u65b0\u4fee\u6539 +start.content.with_comments = \u542b\u5167\u90e8\u8a55\u8ad6 +start.content.all = \u5168\u90e8\u6587\u7ae0 +start.content.search = \u641c\u5c0b +start.allarticlesoftype = \u89c0\u770b "{0}" \u6587\u7ae0 + + +start.producers.title = <\u624b\u52d5\u7522\u751f> +start.producers.produceAllNew = \u7522\u751f\u6240\u6709\u65b0\u7a3f +start.producers.advanced = \u9032\u968e\u7db2\u9801 (\u8acb\u7279\u5225\u5c0f\u5fc3\u4f7f\u7528!) + +#start.coverage.title= +start.topics.title = <\u4e3b\u984c> +start.images.title = <\u5f71\u50cf> +start.video.title = <\u5f71\u97f3> +start.audio.title = <\u8072\u97f3> +start.other_media.title = <\u5176\u4ed6\u5a92\u9ad4> +start.mediafolder.title = <\u5a92\u9ad4\u8cc7\u6599\u593e> +start.languages.title = <\u4e2d\u6587> +start.imcs.title = \u61c9\u905e\u5a92IMCS +start.messageboard.title = \u5167\u90e8\u8a0a\u606f\u7248 +start.messageboard.no_messages = \u7121\u8a0a\u606f + +start.superusermenu = \u7ba1\u7406\u8005\u6b0a\u9650(\u8acb\u5c0f\u5fc3!) + +start.editfiles.title = \u7de8\u8f2f\u6a94\u6848 +start.editfiles.include = \u542b\u5165\u6a94\u6848 # topic -topic.htmltitle=¥DÃD -topic.title=¦WºÙ -topic.description=´y­z -topic.filename=ÀɦW -topic.main_url=¥D­n¸ê°Tºô§} -topic.archive_url=¨åÂúô§} - -topiclist.htmltitle=¥DÃDªí -ê - +topic.htmltitle = \u4e3b\u984c +topic.title = \u540d\u7a31 +topic.description = \u63cf\u8ff0 +topic.filename = \u6a94\u540d +topic.main_url = \u4e3b\u8981\u8cc7\u8a0a\u7db2\u5740 +topic.archive_url = \u5178\u85cf\u7db2\u5740 + +topiclist.htmltitle = \u4e3b\u984c\u8868 +\ufffd = # users -user.htmltitle=¥ÎªÌ -user.login=µn¤J -user.password=±K½X -user.admin=¦æ¬FªÌ +user.htmltitle = \u7528\u8005 +user.login = \u767b\u5165 +user.password = \u5bc6\u78bc +user.admin = \u884c\u653f\u8005 -userlist.htmltitle=¥ÎªÌªí +userlist.htmltitle = \u7528\u8005\u8868 -articletype.htmltitle=Article type -articletype.id=id -articletype.name=Name +articletype.htmltitle = Article type +articletype.id = id +articletype.name = Name -articletypelist.htmltitle=Article types +articletypelist.htmltitle = Article types -commentstatus.htmltitle=Comment status -commentstatus.id=id -commentstatus.name=Name +commentstatus.htmltitle = Comment status +commentstatus.id = id +commentstatus.name = Name -commentstatuslist.htmltitle=Comment status values +commentstatuslist.htmltitle = Comment status values #file editing @@ -302,34 +300,34 @@ fileedit.htmltitle = Edit file # head -head.start=¶}©l -head.logout=µn¥X -head.help=¨D§U -head.search=·j´M -head.logged_in=¤w¦¨¥\µn¤J +head.start = \u958b\u59cb +head.logout = \u767b\u51fa +head.help = \u6c42\u52a9 +head.search = \u641c\u5c0b +head.logged_in = \u5df2\u6210\u529f\u767b\u5165 # foot -foot.top=ÀY +foot.top = \u982d -producer.producer = »s§@¤H -producer.verb.name = ¥ô°È¦W -producer.verb.description = ¥ô°È´y­z -producer.verb.enqueue = ¾Þ§@¦C(?hanteng) +producer.producer = \u88fd\u4f5c\u4eba +producer.verb.name = \u4efb\u52d9\u540d +producer.verb.description = \u4efb\u52d9\u63cf\u8ff0 +producer.verb.enqueue = \u64cd\u4f5c\u5217(?hanteng) -producer.job.name = ¨BÆJ¦W -producer.job.status = ª¬ºA -producer.job.date = ¤W¦¸­×§ï -producer.job.cancel = ºM -producer.job.abort = ¸õ +producer.job.name = \u6b65\u9a5f\u540d +producer.job.status = \u72c0\u614b +producer.job.date = \u4e0a\u6b21\u4fee\u6539 +producer.job.cancel = \u64a4 +producer.job.abort = \u8df3 -producer.jobqueue.title = ¥Ø«e¨BÆJ -producer.jobqueue.refresh = ­«¾ã -producer.producerlist.title = ·s¼W¨BÆJ +producer.jobqueue.title = \u76ee\u524d\u6b65\u9a5f +producer.jobqueue.refresh = \u91cd\u6574 +producer.producerlist.title = \u65b0\u589e\u6b65\u9a5f -producerqueue.htmltitle = ¤â°Ê²£¥Í +producerqueue.htmltitle = \u624b\u52d5\u7522\u751f superusermenu.htmltitle = Super-user functions superusermenu.topics = Manage topics @@ -341,30 +339,28 @@ superusermenu.imcs = Manage IMCS (obsolete) # Article types -articletypes.openposting=Open posting -articletypes.newswire=Newswire -articletypes.feature=Feature -articletypes.topicspecial=Topic-special -articletypes.startspecial=Startpage-special +articletypes.openposting = Open posting +articletypes.newswire = Newswire +articletypes.feature = Feature +articletypes.topicspecial = Topic-special +articletypes.startspecial = Startpage-special # Comment status values -commentstatus.normal=Normal +commentstatus.normal = Normal ########## error ########## -error.htmltitle=¥Xºl¤F...¨t²Î -error.title=¨t²Î¥Xºl... -error.text=·|µo¥Í.. §Y¨Ï¥H¤Uªº¿ù»~°T®§±z¤£¯àÁA¸Ñ, ¦ý¦³¥i¯à¹ï{1}¦³À°§U: -error.text2=³Â·Ð±z±H¤@«Ê«H±N¬õ¦âªº°T®§¤ÎÃö©ó¾É­P¦¹¿ù»~ªº¬ÛÃö°Ê§@»¡©ú, ±Hµ¹{1}. ·PÁ±z! - -usererror.htmltitle=¬dÃÒ¿ù»~ -usererror.title=¬dÃÒ¿ù»~ -usererror.text=±zªº¿é¤J¾É­P¥H¤Uªº¿ù»~: -usererror.what_to_do=½Ð«ö¤U<°h>Áä, ¦A¸Õ¤@¦¸Ð +error.htmltitle = \u51fa\u69cc\u4e86...\u7cfb\u7d71 +error.title = \u7cfb\u7d71\u51fa\u69cc... +error.text = \u6703\u767c\u751f.. \u5373\u4f7f\u4ee5\u4e0b\u7684\u932f\u8aa4\u8a0a\u606f\u60a8\u4e0d\u80fd\u77ad\u89e3, \u4f46\u6709\u53ef\u80fd\u5c0d{1}\u6709\u5e6b\u52a9: +error.text2 = \u9ebb\u7169\u60a8\u5bc4\u4e00\u5c01\u4fe1\u5c07\u7d05\u8272\u7684\u8a0a\u606f\u53ca\u95dc\u65bc\u5c0e\u81f4\u6b64\u932f\u8aa4\u7684\u76f8\u95dc\u52d5\u4f5c\u8aaa\u660e, \u5bc4\u7d66{1}. \u611f\u8b1d\u60a8! +usererror.htmltitle = \u67e5\u8b49\u932f\u8aa4 +usererror.title = \u67e5\u8b49\u932f\u8aa4 +usererror.text = \u60a8\u7684\u8f38\u5165\u5c0e\u81f4\u4ee5\u4e0b\u7684\u932f\u8aa4: +usererror.what_to_do = \u8acb\u6309\u4e0b<\u9000>\u9375, \u518d\u8a66\u4e00\u6b21\ufffd -infomessage.title = ¸ê°T»¡©ú -infomessage.produceAllNewAddedToQueue = ±zªº­n¨D¤w¦b§Ú­Ìªº¤u§@¶µ¥Ø¤¤. +infomessage.title = \u8cc7\u8a0a\u8aaa\u660e +infomessage.produceAllNewAddedToQueue = \u60a8\u7684\u8981\u6c42\u5df2\u5728\u6211\u5011\u7684\u5de5\u4f5c\u9805\u76ee\u4e2d. -htmlcharset=big5 diff --git a/source/Mir.java b/source/Mir.java index b4a880b2..2e4d0e65 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -1,34 +1,34 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Method; @@ -62,418 +62,435 @@ import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleUserExc; import mir.util.ExceptionFunctions; import mir.util.StringRoutines; +import mir.util.*; +import mir.entity.*; +import mir.entity.adapter.*; import mircoders.entity.EntityUsers; import mircoders.global.MirGlobal; import mircoders.module.ModuleMessage; import mircoders.module.ModuleUsers; import mircoders.storage.DatabaseArticleType; import mircoders.storage.DatabaseMessages; -import mircoders.storage.DatabaseUsers; - - - - -/** - * Mir.java - main servlet, that dispatches to servletmodules - * - * @author $Author: zapata $ - * @version $Id: Mir.java,v 1.41 2003/03/17 20:47:03 zapata Exp $ - * - */ -public class Mir extends AbstractServlet { - private static ModuleUsers usersModule = null; - private static ModuleMessage messageModule = null; - private final static Map servletModuleInstanceHash = new HashMap(); - - //I don't know about making this static cause it removes the - //possibility to change the config on the fly.. -mh - private static List loginLanguages = null; - public HttpSession session; - - protected TemplateModel getLoginLanguages() throws ServletException { - synchronized (Mir.class) { - try { - if (loginLanguages == null) { - MessageResources messageResources2 = - MessageResources.getMessageResources("bundles.admin"); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.adminlocal"); - List languages = - StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";"); - - loginLanguages = new Vector(); - - Iterator i = languages.iterator(); - - while (i.hasNext()) { - String code = (String) i.next(); - Locale locale = new Locale(code, ""); - String name = messageResources.getMessage(locale, "languagename"); - - if (name == null) { - name = messageResources2.getMessage(locale, "languagename"); - } - - if (name == null) { - name = code; - } - - Map record = new HashMap(); - record.put("name", name); - record.put("code", code); - loginLanguages.add(record); - } - } - - return FreemarkerGenerator.makeAdapter(loginLanguages); - } - catch (Throwable t) { - throw new ServletException(t.getMessage()); - } - } - } - - // FIXME: this should probalby go into AbstractServlet so it can be used in - // OpenMir as well -mh - protected String getDefaultLanguage(HttpServletRequest aRequest) { - String defaultlanguage = - MirGlobal.config().getString("Mir.Login.DefaultLanguage", ""); - - if (defaultlanguage.length() == 0) { - Locale locale = aRequest.getLocale(); - defaultlanguage = locale.getLanguage(); - } - - return defaultlanguage; - } - - public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletException, IOException, UnavailableException { - long startTime = System.currentTimeMillis(); - long sessionConnectTime = 0; - EntityUsers userEntity; - String http = ""; - - configuration.addProperty("ServletName", getServletName()); - - session = aRequest.getSession(true); - userEntity = (EntityUsers) session.getAttribute("login.uid"); - - if (aRequest.getServerPort() == 443) { - http = "https"; - } else { - http = "http"; - } - - //make sure client browsers don't cache anything - setNoCaching(aResponse); - - //FIXME: this seems kind of hackish and only here because we can have - // default other than the one that the browser is set to. - Locale locale = new Locale(getDefaultLanguage(aRequest), ""); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.admin"); - String htmlcharset = messageResources.getMessage(locale, "htmlcharset"); - - aResponse.setContentType("text/html; charset=" + htmlcharset); - - String moduleName = aRequest.getParameter("module"); - checkLanguage(session, aRequest); - - /** @todo for cleanup and readability this should be moved to - * method loginIfNecessary() */ - if ((moduleName != null) && moduleName.equals("direct")) { - //... - } - - // Authentication - if (((moduleName != null) && moduleName.equals("login")) || - (userEntity == null)) { - String user = aRequest.getParameter("login"); - String passwd = aRequest.getParameter("password"); - logger.debug("--login: evaluating for user: " + user); - userEntity = allowedUser(user, passwd); - - if (userEntity == null) { - // login failed: redirecting to login - logger.warn("--login: failed!"); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } else if ((moduleName != null) && moduleName.equals("login")) { - // login successful - logger.info("--login: successful! setting uid: " + userEntity.getId()); - session.setAttribute("login.uid", userEntity); - logger.debug("--login: trying to retrieve login.target"); - - String target = (String) session.getAttribute("login.target"); - - if (target != null) { - logger.debug("Redirect: " + target); - - int serverPort = aRequest.getServerPort(); - String redirect = ""; - String redirectString = ""; - - if (serverPort == 80) { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + target); - redirectString = - "going Mir"; - } else { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" + - aRequest.getServerPort() + target); - redirectString = - "going Mir"; - } - - aResponse.getWriter().println(redirectString); - - //aResponse.sendRedirect(redirect); - } else { - // redirecting to default target - logger.debug("--login: no target - redirecting to default"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); - } - - return; - } - // if login succesful - } - // if login - - if ((moduleName != null) && moduleName.equals("logout")) { - logger.info("--logout"); - session.invalidate(); - - //session = aRequest.getSession(true); - //checkLanguage(session, aRequest); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } - - // Check if authed! - if (userEntity == null) { - // redirect to loginpage - String redirectString = aRequest.getRequestURI(); - String queryString = aRequest.getQueryString(); - - if ((queryString != null) && !queryString.equals("")) { - redirectString += ("?" + aRequest.getQueryString()); - logger.debug("STORING: " + redirectString); - session.setAttribute("login.target", redirectString); - } - - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } - - // If no module is specified goto standard startpage - if ((moduleName == null) || moduleName.equals("")) { - logger.debug("no module: redirect to standardpage"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); - - return; - } - - // end of auth - // From now on regular dispatching... - try { - // get servletmodule by parameter and continue with dispacher - ServletModule smod = getServletModuleForName(moduleName); - ServletModuleDispatch.dispatch(smod, aRequest, aResponse); - } - catch (Throwable e) { - Throwable cause = ExceptionFunctions.traceCauseException(e); - - if (cause instanceof ServletModuleUserExc) - handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); - else - handleError(aRequest, aResponse, aResponse.getWriter(), cause); - - } - - // timing... - sessionConnectTime = System.currentTimeMillis() - startTime; - logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); - } - - /** - * Private method getServletModuleForName returns ServletModule - * from Cache - * - * @param moduleName - * @return ServletModule - * - */ - private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc { - // Instance in Map ? - if (!servletModuleInstanceHash.containsKey(moduleName)) { - // was not found in hash... - try { - Class theServletModuleClass = null; - - try { - // first we try to get ServletModule from stern.che3.servlet - theServletModuleClass = - Class.forName("mircoders.servlet.ServletModule" + moduleName); - } catch (ClassNotFoundException e) { - // on failure, we try to get it from lib-layer - theServletModuleClass = - Class.forName("mir.servlet.ServletModule" + moduleName); - } - - Method m = theServletModuleClass.getMethod("getInstance", null); - ServletModule smod = (ServletModule) m.invoke(null, null); - - // we put it into map for further reference - servletModuleInstanceHash.put(moduleName, smod); - - return smod; - } - catch (Exception e) { - throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage()); - } - } - else { - return (ServletModule) servletModuleInstanceHash.get(moduleName); - } - } - - private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, - PrintWriter out, ServletModuleUserExc anException) { - try { - logger.info("user error: " + anException.getMessage()); - SimpleHash modelRoot = new SimpleHash(); - MessageResources messages = MessageResources.getMessageResources("bundles.admin"); - modelRoot.put("errorstring", - new SimpleScalar( - messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) - )); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); - HTMLTemplateProcessor.process( - aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), - modelRoot, out, getLocale(aRequest)); - out.close(); - } - catch (Exception e) { - logger.error("Error in UserErrorTemplate"); - } - - } - - private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { - - try { - logger.error("error: " + anException); - SimpleHash modelRoot = new SimpleHash(); - modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( - new GregorianCalendar()))); - HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), - modelRoot,out, getLocale(aRequest)); - out.close(); - } - catch (Exception e) { - logger.error("Error in ErrorTemplate"); - } - } - - /** - * evaluate login for user / password - */ - protected EntityUsers allowedUser(String user, String password) { - try { - if (usersModule == null) { - usersModule = new ModuleUsers(DatabaseUsers.getInstance()); - } - - return usersModule.getUserForLogin(user, password); - } - catch (Exception e) { - logger.debug(e.getMessage()); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - return null; - } - } - - // Redirect-methods - private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out) { - String loginTemplate = configuration.getString("Mir.LoginTemplate"); - String sessionUrl = aResponse.encodeURL(""); - - try { - SimpleHash mergeData = new SimpleHash(); - SimpleList languages = new SimpleList(); - - mergeData.put("session", sessionUrl); - - mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); - mergeData.put("languages", getLoginLanguages()); - - HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out, - getLocale(aRequest)); - } - catch (Throwable e) { - handleError(aRequest, aResponse, out, e); - } - } - - private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out, EntityUsers userEntity) { - String startTemplate = "start_admin.template"; - String sessionUrl = aResponse.encodeURL(""); - - try { - // merge with logged in user and messages - SimpleHash mergeData = new SimpleHash(); - mergeData.put("session", sessionUrl); - mergeData.put("login_user", userEntity); - - if (messageModule == null) { - messageModule = new ModuleMessage(DatabaseMessages.getInstance()); - } - - mergeData.put("messages", - messageModule.getByWhereClause(null, "webdb_create desc", 0, 10)); - - mergeData.put("articletypes", - DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20)); - - HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out, - getLocale(aRequest)); - } - catch (Exception e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - handleError(aRequest, aResponse, out, e); - } - } - - public String getServletInfo() { - return "Mir " + configuration.getString("Mir.Version"); - } - - private void checkLanguage(HttpSession session, HttpServletRequest aRequest) { - // a lang parameter always sets the language - String lang = aRequest.getParameter("language"); - - if (lang != null) { - logger.info("selected language " + lang + " overrides accept-language"); - setLanguage(session, lang); - } - // otherwise store language from accept header in session - else if (session.getAttribute("language") == null) { - logger.info("accept-language is " + aRequest.getLocale().getLanguage()); - setLanguage(session, aRequest.getLocale().getLanguage()); - } - } -} +import mircoders.storage.DatabaseUsers; +import mircoders.servlet.*; + + + + +/** + * Mir.java - main servlet, that dispatches to servletmodules + * + * @author $Author: zapata $ + * @version $Id: Mir.java,v 1.42 2003/04/09 02:06:06 zapata Exp $ + * + */ +public class Mir extends AbstractServlet { + private static ModuleUsers usersModule = null; + private static ModuleMessage messageModule = null; + private final static Map servletModuleInstanceHash = new HashMap(); + private static Locale fallbackLocale = null; + + //I don't know about making this static cause it removes the + //possibility to change the config on the fly.. -mh + private static List loginLanguages = null; + + protected TemplateModel getLoginLanguages() throws ServletException { + synchronized (Mir.class) { + try { + if (loginLanguages == null) { + MessageResources messageResources = + MessageResources.getMessageResources("bundles.adminlocal"); + MessageResources messageResources2 = + MessageResources.getMessageResources("bundles.admin"); + + List languages = + StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";"); + + loginLanguages = new Vector(); + + Iterator i = languages.iterator(); + + while (i.hasNext()) { + String code = (String) i.next(); + Locale locale = new Locale(code, ""); + String name = messageResources.getMessage(locale, "languagename"); + + if (name == null) { + name = messageResources2.getMessage(locale, "languagename"); + } + + if (name == null) { + name = code; + } + + Map record = new HashMap(); + record.put("name", name); + record.put("code", code); + loginLanguages.add(record); + } + } + + return FreemarkerGenerator.makeAdapter(loginLanguages); + } + catch (Throwable t) { + throw new ServletException(t.getMessage()); + } + } + } + + // FIXME: this should probalby go into AbstractServlet so it can be used in + // OpenMir as well -mh + protected String getDefaultLanguage(HttpServletRequest aRequest) { + String defaultlanguage = + MirGlobal.config().getString("Mir.Login.DefaultLanguage", ""); + + if (defaultlanguage.length() == 0) { + Locale locale = aRequest.getLocale(); + defaultlanguage = locale.getLanguage(); + } + + return defaultlanguage; + } + + protected synchronized Locale getFallbackLocale() throws ServletException { + try { + if (fallbackLocale == null) { + fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), ""); + } + } + catch (Throwable t) { + throw new ServletException(t.getMessage()); + } + + return fallbackLocale; + } + + public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletException, IOException, UnavailableException { + long startTime = System.currentTimeMillis(); + long sessionConnectTime = 0; + EntityUsers userEntity; + HttpSession session; + String http = ""; + + configuration.addProperty("ServletName", getServletName()); + + session = aRequest.getSession(true); + userEntity = (EntityUsers) session.getAttribute("login.uid"); + + if (aRequest.getServerPort() == 443) { + http = "https"; + } else { + http = "http"; + } + + //make sure client browsers don't cache anything + setNoCaching(aResponse); + + //FIXME: this seems kind of hackish and only here because we can have + // default other than the one that the browser is set to. + Locale locale = new Locale(getDefaultLanguage(aRequest), ""); + MessageResources messageResources = + MessageResources.getMessageResources("bundles.admin"); + String htmlcharset = messageResources.getMessage(locale, "htmlcharset"); + + aResponse.setContentType("text/html; charset=" + htmlcharset); + + String moduleName = aRequest.getParameter("module"); + checkLanguage(session, aRequest); + + + + // Authentication + if (((moduleName != null) && moduleName.equals("login")) || + (userEntity == null)) { + String user = aRequest.getParameter("login"); + String passwd = aRequest.getParameter("password"); + logger.debug("--login: evaluating for user: " + user); + userEntity = allowedUser(user, passwd); + + if (userEntity == null) { + // login failed: redirecting to login + logger.warn("--login: failed!"); + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } + else if ((moduleName != null) && moduleName.equals("login")) { + // login successful + logger.info("--login: successful! setting uid: " + userEntity.getId()); + session.setAttribute("login.uid", userEntity); + logger.debug("--login: trying to retrieve login.target"); + + String target = (String) session.getAttribute("login.target"); + + if (target != null) { + logger.debug("Redirect: " + target); + + int serverPort = aRequest.getServerPort(); + String redirect = ""; + String redirectString = ""; + + if (serverPort == 80) { + redirect = + aResponse.encodeURL(http + "://" + aRequest.getServerName() + target); + redirectString = + "going Mir"; + } else { + redirect = + aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" + + aRequest.getServerPort() + target); + redirectString = + "going Mir"; + } + + aResponse.getWriter().println(redirectString); + + //aResponse.sendRedirect(redirect); + } else { + // redirecting to default target + logger.debug("--login: no target - redirecting to default"); + _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + } + + return; + } + // if login succesful + } + // if login + + if ((moduleName != null) && moduleName.equals("logout")) { + logger.info("--logout"); + session.invalidate(); + + //session = aRequest.getSession(true); + //checkLanguage(session, aRequest); + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } + + // Check if authed! + if (userEntity == null) { + // redirect to loginpage + String redirectString = aRequest.getRequestURI(); + String queryString = aRequest.getQueryString(); + + if ((queryString != null) && !queryString.equals("")) { + redirectString += ("?" + aRequest.getQueryString()); + logger.debug("STORING: " + redirectString); + session.setAttribute("login.target", redirectString); + } + + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } + + // If no module is specified goto standard startpage + if ((moduleName == null) || moduleName.equals("")) { + logger.debug("no module: redirect to standardpage"); + _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + + return; + } + + // end of auth + // From now on regular dispatching... + try { + // get servletmodule by parameter and continue with dispacher + ServletModule smod = getServletModuleForName(moduleName); + ServletModuleDispatch.dispatch(smod, aRequest, aResponse); + } + catch (Throwable e) { + Throwable cause = ExceptionFunctions.traceCauseException(e); + + if (cause instanceof ServletModuleUserExc) + handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); + else + handleError(aRequest, aResponse, aResponse.getWriter(), cause); + + } + + // timing... + sessionConnectTime = System.currentTimeMillis() - startTime; + logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); + } + + /** + * Private method getServletModuleForName returns ServletModule + * from Cache + * + * @param moduleName + * @return ServletModule + * + */ + private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc { + // Instance in Map ? + if (!servletModuleInstanceHash.containsKey(moduleName)) { + // was not found in hash... + try { + Class theServletModuleClass = null; + + try { + // first we try to get ServletModule from stern.che3.servlet + theServletModuleClass = + Class.forName("mircoders.servlet.ServletModule" + moduleName); + } catch (ClassNotFoundException e) { + // on failure, we try to get it from lib-layer + theServletModuleClass = + Class.forName("mir.servlet.ServletModule" + moduleName); + } + + Method m = theServletModuleClass.getMethod("getInstance", null); + ServletModule smod = (ServletModule) m.invoke(null, null); + + // we put it into map for further reference + servletModuleInstanceHash.put(moduleName, smod); + + return smod; + } + catch (Exception e) { + throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage()); + } + } + else { + return (ServletModule) servletModuleInstanceHash.get(moduleName); + } + } + + private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, + PrintWriter out, ServletModuleUserExc anException) { + try { + logger.info("user error: " + anException.getMessage()); + SimpleHash modelRoot = new SimpleHash(); + MessageResources messages = MessageResources.getMessageResources("bundles.admin"); + modelRoot.put("errorstring", + new SimpleScalar( + messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) + )); + modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); + HTMLTemplateProcessor.process( + aResponse, + MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), + modelRoot, + null, + out, + getLocale(aRequest), + fallbackLocale); + out.close(); + } + catch (Exception e) { + logger.error("Error in UserErrorTemplate"); + } + + } + + private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { + + try { + logger.error("error: " + anException); + SimpleHash modelRoot = new SimpleHash(); + modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); + modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( + new GregorianCalendar()))); + HTMLTemplateProcessor.process( + aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), + modelRoot,null,out, getLocale(aRequest), getFallbackLocale()); + out.close(); + } + catch (Exception e) { + logger.error("Error in ErrorTemplate"); + } + } + + /** + * evaluate login for user / password + */ + protected EntityUsers allowedUser(String user, String password) { + try { + if (usersModule == null) { + usersModule = new ModuleUsers(DatabaseUsers.getInstance()); + } + + return usersModule.getUserForLogin(user, password); + } + catch (Exception e) { + logger.debug(e.getMessage()); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + return null; + } + } + + // Redirect-methods + private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, + PrintWriter out) { + String loginTemplate = configuration.getString("Mir.LoginTemplate"); + String sessionUrl = aResponse.encodeURL(""); + + try { + SimpleHash mergeData = new SimpleHash(); + SimpleList languages = new SimpleList(); + + mergeData.put("session", sessionUrl); + + mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); + mergeData.put("languages", getLoginLanguages()); + + HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale()); + } + catch (Throwable e) { + handleError(aRequest, aResponse, out, e); + } + } + + private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, + PrintWriter out, EntityUsers userEntity) { + String startTemplate = configuration.getString("Mir.StartTemplate"); + String sessionUrl = aResponse.encodeURL(""); + + try { + Map mergeData = ServletHelper.makeGenerationData(new Locale[] {getLocale(aRequest), getFallbackLocale()}, "bundles.admin", "bundles.adminlocal"); + mergeData.put("messages", + new CachingRewindableIterator( + new EntityIteratorAdapter( "", "webdb_create desc", 10, + MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0))); + mergeData.put("searchvalue", null); + mergeData.put("searchfield", null); + mergeData.put("searchispublished", null); + mergeData.put("searcharticletype", null); + mergeData.put("searchorder", null); + mergeData.put("selectarticleurl", null); + + ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate); + } + catch (Exception e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + handleError(aRequest, aResponse, out, e); + } + } + + public String getServletInfo() { + return "Mir " + configuration.getString("Mir.Version"); + } + + private void checkLanguage(HttpSession session, HttpServletRequest aRequest) { + // a lang parameter always sets the language + String lang = aRequest.getParameter("language"); + + if (lang != null) { + logger.info("selected language " + lang + " overrides accept-language"); + setLanguage(session, lang); + } + // otherwise store language from accept header in session + else if (session.getAttribute("language") == null) { + logger.info("accept-language is " + aRequest.getLocale().getLanguage()); + setLanguage(session, aRequest.getLocale().getLanguage()); + } + } +} diff --git a/source/OpenMir.java b/source/OpenMir.java index 77807af0..f8cc73ef 100755 --- a/source/OpenMir.java +++ b/source/OpenMir.java @@ -29,25 +29,25 @@ * not wish to do so, delete this exception statement from your version. */ -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.servlet.AbstractServlet; -import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleUserExc; -import mir.util.ExceptionFunctions; -import mircoders.global.MirGlobal; +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.servlet.AbstractServlet; +import mir.servlet.ServletModuleDispatch; +import mir.servlet.ServletModuleUserExc; +import mir.util.ExceptionFunctions; +import mircoders.global.MirGlobal; import mircoders.servlet.ServletModuleOpenIndy; /** * OpenMir.java - main servlet for open posting and comment feature to articles * * @author RK 1999-2001, the mir-coders group - * @version $Id: OpenMir.java,v 1.30 2003/03/17 20:47:03 zapata Exp $ + * @version $Id: OpenMir.java,v 1.31 2003/04/09 02:06:06 zapata Exp $ * */ diff --git a/source/default.properties b/source/default.properties index 39aa89f3..bce4ee9f 100755 --- a/source/default.properties +++ b/source/default.properties @@ -44,7 +44,6 @@ Mir.Public-email.address=mir-coders@lists.indymedia.org Mir.Public-email.name=mir-coders mailinglist Mir.Version=1.1beta -StandardLanguage=de DirectOpenposting=yes # The name of the abuse config file (relative to the WEB-INF dir) @@ -76,7 +75,12 @@ Mir.Localizer.ProducerConfigFile=etc/producer/producers.xml # If the default language is left empty, it will set the accept-language of # the client browser as the default. Mir.Login.DefaultLanguage=en -Mir.Login.Languages=en;nl;de;qu;tr;ay;es;eu + +# The available languages in the login form: +Mir.Login.Languages=en;de;nl;es;pt;eu;sv;tr;zh + +# For missing values, the FallbackLanguage is used as default +Mir.Admin.FallbackLanguage=en # the templates @@ -292,6 +296,7 @@ ServletModule.OpenIndy.UserErrorTemplate=usererror.template Mir.TemplateDir=templates/admin/ Mir.LoginTemplate=login.template +Mir.StartTemplate=start_admin.template Mir.ErrorTemplate=error.template Mir.UserErrorTemplate=usererror.template diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index 84e87b5a..d6fb3f2d 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -1,313 +1,313 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -/** - * Base class the entities are derived from. Provides base functionality of - * an entity. Entities are used to represent rows of a database table.

- */ - -package mir.entity; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateHashModel; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateModelRoot; - -/** - * Base Class of Entities - * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant - * - * @version $Id: Entity.java,v 1.18 2003/03/05 19:23:14 idfx Exp $ - * @author rk - * - */ - -public class Entity implements TemplateHashModel, TemplateModelRoot -{ - protected static MirPropertiesConfiguration configuration; - - private boolean changed; - protected Map theValuesHash; // tablekey / value - protected StorageObject theStorageObject; - protected List streamedInput = null; - protected LoggerWrapper logger; - - static { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException(e.getMessage()); - } - } - - public Entity() { - logger = new LoggerWrapper("Entity"); - - this.changed = false; - } - - /** - * Constructor - * @param StorageObject The StorageObject of the Entity. - */ - public Entity(StorageObject StorageObject) { - this(); - setStorage(StorageObject); - } - - /* - * Sets the StorageObject of the Entity. - */ - public void setStorage(StorageObject storage) { - this.theStorageObject = storage; - } - - /** - * Sets the values of the Entity. - * @param theStringValues Map containing the new values of the Entity - */ - - public void setValues(Map theStringValues) { - /** @todo should be synchronized */ - if (theStringValues != null) { - theValuesHash = new HashMap(); - theValuesHash.putAll(theStringValues); - } - else - logger.warn("Entity.setValues called with null Map"); - } - - /** - * Returns whether the content of the Entity has changed. - * @return true wenn ja, sonst false - */ - public boolean changed() { - return changed; - } - - /** - * Returns the primary key of the Entity. - * @return String Id - */ - public String getId() { - return (String) getValue(theStorageObject.getIdName()); - } - - /** - * Defines the primary key of the Entity - * @param id - */ - public void setId(String id) { - theValuesHash.put(theStorageObject.getIdName(), id); - } - - /** - * Returns the value of a field by field name. - * @param field The name of the field - * @return value of the field - */ - public String getValue(String field) { - String returnValue = null; - if (field != null) { - if (field.equals("webdb_create_formatted")) { - if (hasValueForField("webdb_create")) - returnValue = StringUtil.dateToReadableDate(getValue("webdb_create")); - } - else if (field.equals("webdb_lastchange_formatted")) { - if (hasValueForField("webdb_lastchange")) - returnValue = StringUtil.dateToReadableDate(getValue( - "webdb_lastchange")); - } - else - returnValue = (String) theValuesHash.get(field); - } - return returnValue; - } - - public boolean hasValueForField(String field) { - if (theValuesHash != null) - return theValuesHash.containsKey(field); - return false; - } - - /** - * Insers Entity into the database via StorageObject - * @return Primary Key of the Entity - * @exception StorageObjectException - */ - public String insert() throws StorageObjectExc { - logger.debug("Entity: trying to insert ..."); - if (theStorageObject != null) { - return theStorageObject.insert( (Entity)this); - } - else - throw new StorageObjectExc("theStorageObject == null!"); - } - - /** - * Saves changes of this Entity to the database - * @exception StorageObjectException - */ - public void update() throws StorageObjectFailure { - theStorageObject.update( (Entity)this); - } - - /** - * Sets the value for a field. Issues a log message if the field name - * supplied was not found in the Entity. - * @param theProp The field name whose value has to be set - * @param theValue The new value of the field - * @exception StorageObjectException - */ - public void setValueForProperty(String theProp, String theValue) throws - StorageObjectFailure { - this.changed = true; - if (isField(theProp)) - theValuesHash.put(theProp, theValue); - else { - logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")"); - } - - } - - /** - * Returns the field names of the Entity as ArrayListe. - * @return ArrayList with field names - * @exception StorageObjectException is throuwn if database access was impossible - */ - public List getFields() throws StorageObjectFailure { - return theStorageObject.getFields(); - } - - /** - * Returns an int[] with the types of the fields - * @return int[] that contains the types of the fields - * @exception StorageObjectException - */ - public int[] getTypes() throws StorageObjectFailure { - return theStorageObject.getTypes(); - } - - /** - * Returns an ArrayList with field names - * @return List with field names - * @exception StorageObjectException - */ - public List getLabels() throws StorageObjectFailure { - return theStorageObject.getLabels(); - } - - /** - * Returns a Map with all values of the Entity. - * @return Map with field name as key and the corresponding values - * - * @deprecated This method is deprecated and will be deleted in the next release. - * Entity interfaces freemarker.template.TemplateHashModel now and can - * be used in the same way as SimpleHash. - */ - public Map getValues() { - logger.warn("using deprecated Entity.getValues() - a waste of resources"); - return theValuesHash; - } - - /** - * Returns an ArrayList with all database fields that can - * be evaluated as streamedInput. - * Could be automated by the types (blob, etc.) - * Until now to be created manually in the inheriting class - * - * Liefert einen ArrayList mit allen Datenbankfeldern, die - * als streamedInput ausgelesen werden muessen. - * Waere automatisierbar ueber die types (blob, etc.) - * Bisher manuell anzulegen in der erbenden Klasse - */ - - public List streamedInput() { - return streamedInput; - } - - /** Returns whether fieldName is a valid field name of this Entity. - * @param fieldName - * @return true in case fieldName is a field name, else false. - * @exception StorageObjectException - */ - public boolean isField(String fieldName) throws StorageObjectFailure { - return theStorageObject.getFields().contains(fieldName); - } - - protected void throwStorageObjectFailure(Throwable e, String wo) throws - StorageObjectFailure { - logger.error(e.toString() + " function: " + wo); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - throw new StorageObjectFailure("Storage Object Exception in entity", e); - } - - // Now implements freemarkers TemplateHashModel - // two methods have to be overridden: - // 1. public boolean isEmpty() throws TemplateModelException - // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException - - public boolean isEmpty() throws TemplateModelException { - return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false; - } - - public TemplateModel get(java.lang.String key) throws TemplateModelException { - return new SimpleScalar(getValue(key)); - } - - public void put(java.lang.String key, TemplateModel model) { - // putting should only take place via setValue and is limited to the - // database fields associated with the entity. no additional freemarker - // stuff will be available via Entity. - logger.warn("put is called on entity! - the values will be lost!"); - } - - public void remove(java.lang.String key) { - // do we need this? - } - - ////////////////////////////////////////////////////////////////////////////////// -} - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +/** + * Base class the entities are derived from. Provides base functionality of + * an entity. Entities are used to represent rows of a database table.

+ */ + +package mir.entity; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleScalar; +import freemarker.template.TemplateHashModel; +import freemarker.template.TemplateModel; +import freemarker.template.TemplateModelException; +import freemarker.template.TemplateModelRoot; + +/** + * Base Class of Entities + * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant + * + * @version $Id: Entity.java,v 1.19 2003/04/09 02:06:06 zapata Exp $ + * @author rk + * + */ + +public class Entity implements TemplateHashModel, TemplateModelRoot +{ + protected static MirPropertiesConfiguration configuration; + + private boolean changed; + protected Map theValuesHash; // tablekey / value + protected StorageObject theStorageObject; + protected List streamedInput = null; + protected LoggerWrapper logger; + + static { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new RuntimeException(e.getMessage()); + } + } + + public Entity() { + logger = new LoggerWrapper("Entity"); + + this.changed = false; + } + + /** + * Constructor + * @param StorageObject The StorageObject of the Entity. + */ + public Entity(StorageObject StorageObject) { + this(); + setStorage(StorageObject); + } + + /* + * Sets the StorageObject of the Entity. + */ + public void setStorage(StorageObject storage) { + this.theStorageObject = storage; + } + + /** + * Sets the values of the Entity. + * @param theStringValues Map containing the new values of the Entity + */ + + public void setValues(Map theStringValues) { + /** @todo should be synchronized */ + if (theStringValues != null) { + theValuesHash = new HashMap(); + theValuesHash.putAll(theStringValues); + } + else + logger.warn("Entity.setValues called with null Map"); + } + + /** + * Returns whether the content of the Entity has changed. + * @return true wenn ja, sonst false + */ + public boolean changed() { + return changed; + } + + /** + * Returns the primary key of the Entity. + * @return String Id + */ + public String getId() { + return (String) getValue(theStorageObject.getIdName()); + } + + /** + * Defines the primary key of the Entity + * @param id + */ + public void setId(String id) { + theValuesHash.put(theStorageObject.getIdName(), id); + } + + /** + * Returns the value of a field by field name. + * @param field The name of the field + * @return value of the field + */ + public String getValue(String field) { + String returnValue = null; + if (field != null) { + if (field.equals("webdb_create_formatted")) { + if (hasValueForField("webdb_create")) + returnValue = StringUtil.dateToReadableDate(getValue("webdb_create")); + } + else if (field.equals("webdb_lastchange_formatted")) { + if (hasValueForField("webdb_lastchange")) + returnValue = StringUtil.dateToReadableDate(getValue( + "webdb_lastchange")); + } + else + returnValue = (String) theValuesHash.get(field); + } + return returnValue; + } + + public boolean hasValueForField(String field) { + if (theValuesHash != null) + return theValuesHash.containsKey(field); + return false; + } + + /** + * Insers Entity into the database via StorageObject + * @return Primary Key of the Entity + * @exception StorageObjectException + */ + public String insert() throws StorageObjectExc { + logger.debug("Entity: trying to insert ..."); + if (theStorageObject != null) { + return theStorageObject.insert( (Entity)this); + } + else + throw new StorageObjectExc("theStorageObject == null!"); + } + + /** + * Saves changes of this Entity to the database + * @exception StorageObjectException + */ + public void update() throws StorageObjectFailure { + theStorageObject.update( (Entity)this); + } + + /** + * Sets the value for a field. Issues a log message if the field name + * supplied was not found in the Entity. + * @param theProp The field name whose value has to be set + * @param theValue The new value of the field + * @exception StorageObjectException + */ + public void setValueForProperty(String theProp, String theValue) throws + StorageObjectFailure { + this.changed = true; + if (isField(theProp)) + theValuesHash.put(theProp, theValue); + else { + logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")"); + } + + } + + /** + * Returns the field names of the Entity as ArrayListe. + * @return ArrayList with field names + * @exception StorageObjectException is throuwn if database access was impossible + */ + public List getFields() throws StorageObjectFailure { + return theStorageObject.getFields(); + } + + /** + * Returns an int[] with the types of the fields + * @return int[] that contains the types of the fields + * @exception StorageObjectException + */ + public int[] getTypes() throws StorageObjectFailure { + return theStorageObject.getTypes(); + } + + /** + * Returns an ArrayList with field names + * @return List with field names + * @exception StorageObjectException + */ + public List getLabels() throws StorageObjectFailure { + return theStorageObject.getLabels(); + } + + /** + * Returns a Map with all values of the Entity. + * @return Map with field name as key and the corresponding values + * + * @deprecated This method is deprecated and will be deleted in the next release. + * Entity interfaces freemarker.template.TemplateHashModel now and can + * be used in the same way as SimpleHash. + */ + public Map getValues() { + logger.warn("using deprecated Entity.getValues() - a waste of resources"); + return theValuesHash; + } + + /** + * Returns an ArrayList with all database fields that can + * be evaluated as streamedInput. + * Could be automated by the types (blob, etc.) + * Until now to be created manually in the inheriting class + * + * Liefert einen ArrayList mit allen Datenbankfeldern, die + * als streamedInput ausgelesen werden muessen. + * Waere automatisierbar ueber die types (blob, etc.) + * Bisher manuell anzulegen in der erbenden Klasse + */ + + public List streamedInput() { + return streamedInput; + } + + /** Returns whether fieldName is a valid field name of this Entity. + * @param fieldName + * @return true in case fieldName is a field name, else false. + * @exception StorageObjectException + */ + public boolean isField(String fieldName) throws StorageObjectFailure { + return theStorageObject.getFields().contains(fieldName); + } + + protected void throwStorageObjectFailure(Throwable e, String wo) throws + StorageObjectFailure { + logger.error(e.toString() + " function: " + wo); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + throw new StorageObjectFailure("Storage Object Exception in entity", e); + } + + // Now implements freemarkers TemplateHashModel + // two methods have to be overridden: + // 1. public boolean isEmpty() throws TemplateModelException + // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException + + public boolean isEmpty() throws TemplateModelException { + return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false; + } + + public TemplateModel get(java.lang.String key) throws TemplateModelException { + return new SimpleScalar(getValue(key)); + } + + public void put(java.lang.String key, TemplateModel model) { + // putting should only take place via setValue and is limited to the + // database fields associated with the entity. no additional freemarker + // stuff will be available via Entity. + logger.warn("put is called on entity! - the values will be lost!"); + } + + public void remove(java.lang.String key) { + // do we need this? + } + + ////////////////////////////////////////////////////////////////////////////////// +} + diff --git a/source/mir/entity/EntityBrowser.java b/source/mir/entity/EntityBrowser.java index 2e829c5f..8ce7a6e2 100755 --- a/source/mir/entity/EntityBrowser.java +++ b/source/mir/entity/EntityBrowser.java @@ -29,95 +29,95 @@ * not wish to do so, delete this exception statement from your version. */ -package mir.entity; - +package mir.entity; + import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; import mir.util.RewindableIterator; - -public class EntityBrowser implements RewindableIterator { - - private StorageObject storage; - private String whereClause; - private String orderByClause; - private int batchSize; - private int toFetch; - private EntityList currentBatch; - - private int skip; - private int limit; - - private int batchPosition; - private int positionInBatch; - - public EntityBrowser(StorageObject aStorage, String aWhereClause, String anOrderByClause, - int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { - - storage=aStorage; - whereClause=aWhereClause; - orderByClause=anOrderByClause; - batchSize=aBatchSize; - skip=aSkip; - limit=aLimit; - - rewind(); - } - - public EntityBrowser(StorageObject aStorage, - String aWhereClause, String anOrderByClause, - int aBatchSize) throws StorageObjectFailure { - this(aStorage, aWhereClause, anOrderByClause, aBatchSize, -1, 0); - } - - public void readCurrentBatch(int aSkip) throws StorageObjectFailure { - currentBatch = storage.selectByWhereClause(whereClause, orderByClause, aSkip, batchSize); - batchPosition = aSkip; - positionInBatch = 0; - } - - public void rewind() { - try { - readCurrentBatch(skip); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - - public boolean hasNext() { - try { - if (limit>-1 && batchPosition+positionInBatch>=skip+limit) - return false; - - if (positionInBatch>=currentBatch.size() && currentBatch.hasNextBatch()) { - readCurrentBatch(batchPosition+positionInBatch); - } - - return (positionInBatch-1 && batchPosition+positionInBatch>=skip+limit) + return false; + + if (positionInBatch>=currentBatch.size() && currentBatch.hasNextBatch()) { + readCurrentBatch(batchPosition+positionInBatch); + } + + return (positionInBatch=valuesCache.size() && i=valuesCache.size() && ianEntity in freemarker-Struktur um, mischt die Daten mit - * Template templateFilename und gibt das Ergebnis an den PrintWriter - * out - * - * @param templateFilename - * @param anEntity - * @param out - * @exception HTMLParseException - */ - - public static void process(String templateFilename, Entity anEntity, - PrintWriter out) throws HTMLParseException { - if (anEntity == null) - throw new HTMLParseException("entity is empty!"); - else - process(templateFilename, anEntity, out); - } - /** * Wandelt Liste mit Entities entList in freemarker-Struktur um, mischt die Daten mit * Template templateFilename und gibt das Ergebnis an den PrintWriter @@ -140,10 +120,9 @@ public final class HTMLTemplateProcessor { * @param out * @exception HTMLParseException */ - public static void process(HttpServletResponse res, String templateFilename, - EntityList entList, PrintWriter out, Locale locale) throws HTMLParseException { - process(res, templateFilename, entList, (String)null, (TemplateModelRoot)null, - out, locale); + + public static void process(HttpServletResponse res, String templateFilename, EntityList entList, PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException { + process(res, templateFilename, entList, (String)null, (TemplateModelRoot) null, out, locale, aFallbackLocale); } /** @@ -163,12 +142,12 @@ public final class HTMLTemplateProcessor { public static void process(HttpServletResponse res, String templateFilename, EntityList entList, String additionalModelName, TemplateModelRoot additionalModel, PrintWriter out, - Locale locale) throws HTMLParseException { + Locale locale, Locale aFallbackLocale) throws HTMLParseException { SimpleHash modelRoot = new SimpleHash(); if (entList == null) { - process(null, templateFilename, modelRoot, out, locale); + process(null, templateFilename, modelRoot, null, out, locale, aFallbackLocale); } else { try { @@ -178,7 +157,7 @@ public final class HTMLTemplateProcessor { if (additionalModelName != null && additionalModel != null) modelRoot.put(additionalModelName, additionalModel); - process(res, templateFilename, modelRoot, out, locale); + process(res, templateFilename, modelRoot, null, out, locale, aFallbackLocale); } catch (StorageObjectFailure e) { throw new HTMLParseException(e.toString()); @@ -188,20 +167,6 @@ public final class HTMLTemplateProcessor { /** - * Gibt Template templateFilename an den PrintWriter - * out - * - * @param templateFilename - * @param mergeData - * @param out - * @exception HTMLParseException - */ - public static void process(String templateFilename, PrintWriter out, - Locale locale) throws HTMLParseException { - process(null, templateFilename, (TemplateModelRoot)null, out, locale); - } - - /** * Mischt die freemarker-Struktur tmr mit * Template templateFilename und gibt das Ergebnis an den PrintWriter * out @@ -213,20 +178,8 @@ public final class HTMLTemplateProcessor { */ public static void process(HttpServletResponse res, String templateFilename, TemplateModelRoot tmr, PrintWriter out, - Locale locale) throws HTMLParseException { - process(res, templateFilename, tmr, null, out, locale); - } - - public static void process(HttpServletResponse res, String templateFilename, - TemplateModelRoot tmr, TemplateModelRoot extra, - PrintWriter out, Locale locale) throws HTMLParseException { - process(res, templateFilename, tmr, extra, out, locale, "bundles.adminlocal", "bundles.admin"); - } - - public static void process(HttpServletResponse res, String templateFilename, - TemplateModelRoot tmr, TemplateModelRoot extra, PrintWriter out, - Locale locale, String bundles) throws HTMLParseException { - process(res, templateFilename, tmr, extra, out, locale, bundles, null); + Locale locale, Locale aFallbackLocale) throws HTMLParseException { + process(res, templateFilename, tmr, null, out, locale, aFallbackLocale); } /** @@ -241,8 +194,8 @@ public final class HTMLTemplateProcessor { */ public static void process(HttpServletResponse res, String templateFilename, TemplateModelRoot tmr, TemplateModelRoot extra, - PrintWriter out, Locale locale, String bundles, - String bundles2) throws HTMLParseException { + PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException { + if (out == null) throw new HTMLParseException("no outputstream"); Template tmpl = getTemplateFor(templateFilename); @@ -309,12 +262,17 @@ public final class HTMLTemplateProcessor { outPutHash.put("config", configHash); outPutHash.put("utility", utilityHash); - MessageResources messages = MessageResources.getMessageResources(bundles); - if (bundles2!=null) { - outPutHash.put("lang", new MessageMethodModel(locale, MessageResources.getMessageResources(bundles), MessageResources.getMessageResources(bundles2))); + MessageResources messages[] = new MessageResources[bundles.length]; + + for (int i=0; iTemplateMethodModel that provides access to a - * Struts MessageResources, for use in Interantionalized templates. - * - * @author Kellan - */ - -public class MessageMethodModel implements TemplateMethodModel { - - /** - * The perferred locale for this instance of MessageMethod. - */ - private Locale locale; - - /** - * The MessageResources to query, a single instance shared for - * the lifetime of servlet. - */ - private MessageResources messages; - private MessageResources messages2; - - - /** - * Construct a MessageMethod that uses the JVM's default locale. - * - * @param message The MessageResources object to query - */ - public MessageMethodModel(MessageResources messages) { - this(null, messages); - } - - /** - * Construct a MessageMethod - * - * @param locale a Locale object, persumably initialized - * from users Accept-Language header field - * - * @param message The MessageResources object to query - */ - public MessageMethodModel(Locale aLocale, MessageResources aMessages) { - this(aLocale, aMessages, null); - } - - public MessageMethodModel(Locale aLocale, MessageResources aMessages, - MessageResources aMessages2) { - locale = aLocale; - messages = aMessages; - messages2 = aMessages2; - } - - /** - * Takes the first argument as a resource key, then looks up - * a string in the MessagesResources, based on that key, and the Locale - * - * TODO: error messages should be i18n :) - * - * @param arguments List passed in by FM, first arguement is a string used as the key - * all subsequent arguments are used as described in MessageResources - * (they are filled into the placehoders of the string being returned) - */ - public TemplateModel exec(List arguments) { - if (arguments != null) { - String key = (String) arguments.get(0); - arguments.remove(0); - String mesg = null; - - if (messages!=null) - mesg = messages.getMessage(locale, key, arguments.toArray()); - - if (mesg == null && messages2!=null) { - mesg = messages2.getMessage(locale, key, arguments.toArray()); - } - - if (mesg == null) { - return new SimpleScalar(errUnknownTag + key); - } - return new SimpleScalar(mesg); - } - else { - return missingKeyScalar; - } - } - - // i'm not real clear on how this is used - kellan :) - public boolean isEmpty() { - if (messages == null) - return true; - else - return false; - } - - private static String errUnknownTag = "MESSAGE NOT FOUND: "; - private static String missingKey = "MESSAGE CALL WITHOUT KEY"; - private static SimpleScalar missingKeyScalar = new SimpleScalar(missingKey); -} diff --git a/source/mir/misc/WebdbImage.java b/source/mir/misc/WebdbImage.java index 136acb15..253fd74e 100755 --- a/source/mir/misc/WebdbImage.java +++ b/source/mir/misc/WebdbImage.java @@ -1,157 +1,157 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.misc; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2002 Mir-coders - * @author $Author: idfx $ - * @version $Id: WebdbImage.java,v 1.12 2003/03/05 19:23:14 idfx Exp $ - */ - -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Random; - -import javax.media.jai.InterpolationBilinear; -import javax.media.jai.JAI; -import javax.media.jai.ParameterBlockJAI; -import javax.media.jai.PlanarImage; - -import mir.config.MirPropertiesConfiguration; - -import com.sun.media.jai.codec.FileSeekableStream; - -public class WebdbImage -{ - - // default values for scaling - private int maxIconSize; - private int maxImageSize; - - private int iconWidth; - private int iconHeight; - - Random r = new Random(); - - // internal representation of the image - private PlanarImage planarImage; - - // type of the image - private String _type; - - private WebdbImage() { - } - - // constructor - // takes a temporary file as a parameter - public WebdbImage(File f, String type) throws Exception { - // It has to be a FileSeekableStream cause the image conversion - // needs to seek backwards. - maxImageSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxSize"); - maxIconSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxIconSize"); - - planarImage = JAI.create("stream", new FileSeekableStream(f)); - _type = type; - scaleImage(); - } - - // acc3ssor-methods - // must be run after scaleIcon() - public int getIconWidth() throws IOException { - return iconWidth; - } - - // must be run after scaleIcon() - public int getIconHeight() throws IOException { - return iconHeight; - } - - public int getImageWidth() { - return (int) planarImage.getWidth(); - } - - public int getImageHeight() { - return (int) planarImage.getHeight(); - } - - public void setImage(OutputStream outStream) { - JAI.create("encode", planarImage, outStream, _type, null); - } - - public void setIcon(OutputStream outStream) throws IOException { - scaleIcon(outStream); - } - - private void scaleImage() throws java.io.IOException { - if (maxImageSize > 0 && - (getImageHeight() > maxImageSize || getImageWidth() > maxImageSize)) { - float scale; - ParameterBlockJAI params = new ParameterBlockJAI("scale"); - params.addSource(planarImage); - if (getImageHeight() > getImageWidth()) - scale = (float) maxImageSize / (float) getImageHeight(); - else - scale = (float) maxImageSize / (float) getImageWidth(); - - params.setParameter("xScale", scale); - params.setParameter("yScale", scale); - params.setParameter("xTrans", 0.0F); - params.setParameter("yTrans", 0.0F); - params.setParameter("interpolation", new InterpolationBilinear()); - planarImage = JAI.create("scale", params); - } - } - - private void scaleIcon(OutputStream outStream) throws java.io.IOException { - float scale; - ParameterBlockJAI params = new ParameterBlockJAI("scale"); - params.addSource(planarImage); - if (getImageHeight() > getImageWidth()) - scale = (float) maxIconSize / (float) getImageHeight(); - else - scale = (float) maxIconSize / (float) getImageWidth(); - - params.setParameter("xScale", scale); - params.setParameter("yScale", scale); - params.setParameter("xTrans", 0.0F); - params.setParameter("yTrans", 0.0F); - params.setParameter("interpolation", new InterpolationBilinear()); - PlanarImage temp = JAI.create("scale", params); - JAI.create("encode", temp, outStream, _type, null); - iconWidth = temp.getWidth(); - iconHeight = temp.getHeight(); - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.misc; + +/** + * Title: + * Description: + * Copyright: Copyright (c) 2002 Mir-coders + * @author $Author: zapata $ + * @version $Id: WebdbImage.java,v 1.13 2003/04/09 02:06:07 zapata Exp $ + */ + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Random; + +import javax.media.jai.InterpolationBilinear; +import javax.media.jai.JAI; +import javax.media.jai.ParameterBlockJAI; +import javax.media.jai.PlanarImage; + +import mir.config.MirPropertiesConfiguration; + +import com.sun.media.jai.codec.FileSeekableStream; + +public class WebdbImage +{ + + // default values for scaling + private int maxIconSize; + private int maxImageSize; + + private int iconWidth; + private int iconHeight; + + Random r = new Random(); + + // internal representation of the image + private PlanarImage planarImage; + + // type of the image + private String _type; + + private WebdbImage() { + } + + // constructor + // takes a temporary file as a parameter + public WebdbImage(File f, String type) throws Exception { + // It has to be a FileSeekableStream cause the image conversion + // needs to seek backwards. + maxImageSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxSize"); + maxIconSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxIconSize"); + + planarImage = JAI.create("stream", new FileSeekableStream(f)); + _type = type; + scaleImage(); + } + + // acc3ssor-methods + // must be run after scaleIcon() + public int getIconWidth() throws IOException { + return iconWidth; + } + + // must be run after scaleIcon() + public int getIconHeight() throws IOException { + return iconHeight; + } + + public int getImageWidth() { + return (int) planarImage.getWidth(); + } + + public int getImageHeight() { + return (int) planarImage.getHeight(); + } + + public void setImage(OutputStream outStream) { + JAI.create("encode", planarImage, outStream, _type, null); + } + + public void setIcon(OutputStream outStream) throws IOException { + scaleIcon(outStream); + } + + private void scaleImage() throws java.io.IOException { + if (maxImageSize > 0 && + (getImageHeight() > maxImageSize || getImageWidth() > maxImageSize)) { + float scale; + ParameterBlockJAI params = new ParameterBlockJAI("scale"); + params.addSource(planarImage); + if (getImageHeight() > getImageWidth()) + scale = (float) maxImageSize / (float) getImageHeight(); + else + scale = (float) maxImageSize / (float) getImageWidth(); + + params.setParameter("xScale", scale); + params.setParameter("yScale", scale); + params.setParameter("xTrans", 0.0F); + params.setParameter("yTrans", 0.0F); + params.setParameter("interpolation", new InterpolationBilinear()); + planarImage = JAI.create("scale", params); + } + } + + private void scaleIcon(OutputStream outStream) throws java.io.IOException { + float scale; + ParameterBlockJAI params = new ParameterBlockJAI("scale"); + params.addSource(planarImage); + if (getImageHeight() > getImageWidth()) + scale = (float) maxIconSize / (float) getImageHeight(); + else + scale = (float) maxIconSize / (float) getImageWidth(); + + params.setParameter("xScale", scale); + params.setParameter("yScale", scale); + params.setParameter("xTrans", 0.0F); + params.setParameter("yTrans", 0.0F); + params.setParameter("interpolation", new InterpolationBilinear()); + PlanarImage temp = JAI.create("scale", params); + JAI.create("encode", temp, outStream, _type, null); + iconWidth = temp.getWidth(); + iconHeight = temp.getHeight(); + } + } \ No newline at end of file diff --git a/source/mir/producer/ExpandedAssignmentProducerNode.java b/source/mir/producer/ExpandedAssignmentProducerNode.java index 2e0b628f..de00c447 100755 --- a/source/mir/producer/ExpandedAssignmentProducerNode.java +++ b/source/mir/producer/ExpandedAssignmentProducerNode.java @@ -31,9 +31,9 @@ package mir.producer; -import java.util.Map; - -import mir.log.LoggerWrapper; +import java.util.Map; + +import mir.log.LoggerWrapper; import mir.util.ParameterExpander; public class ExpandedAssignmentProducerNode implements ProducerNode { diff --git a/source/mir/producer/RSSProducerNode.java b/source/mir/producer/RSSProducerNode.java index c3d17e7e..d3ee397e 100755 --- a/source/mir/producer/RSSProducerNode.java +++ b/source/mir/producer/RSSProducerNode.java @@ -1,36 +1,36 @@ -package mir.producer; - -import java.util.Map; - -import mir.log.LoggerWrapper; -import mir.rss.RSSData; -import mir.rss.RSSReader; -import mir.rss.RSSToMapConverter; -import mir.util.ParameterExpander; -import mir.util.ExceptionFunctions; - -public class RSSProducerNode implements ProducerNode { - private String key; - private String url; - - public RSSProducerNode(String aKey, String anURL) { - key = aKey; - url = anURL; - } - - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { - try { - String expandedKey = ParameterExpander.expandExpression( aValueMap, key ); - String expandedUrl = ParameterExpander.expandExpression( aValueMap, url ); - - ParameterExpander.setValueForKey(aValueMap, expandedKey, null); - RSSReader reader = new RSSReader(); - RSSData rssData = reader.parseUrl(expandedUrl); - ParameterExpander.setValueForKey(aValueMap, expandedKey, RSSToMapConverter.convertRSSData(rssData)); - } - catch (Throwable t) { - Throwable s = ExceptionFunctions.traceCauseException(t); - aLogger.error("Error while processing RSS data: " + s.getClass().getName()+","+ s.getMessage()); - } - }; +package mir.producer; + +import java.util.Map; + +import mir.log.LoggerWrapper; +import mir.rss.RSSData; +import mir.rss.RSSReader; +import mir.rss.RSSToMapConverter; +import mir.util.ParameterExpander; +import mir.util.ExceptionFunctions; + +public class RSSProducerNode implements ProducerNode { + private String key; + private String url; + + public RSSProducerNode(String aKey, String anURL) { + key = aKey; + url = anURL; + } + + public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + try { + String expandedKey = ParameterExpander.expandExpression( aValueMap, key ); + String expandedUrl = ParameterExpander.expandExpression( aValueMap, url ); + + ParameterExpander.setValueForKey(aValueMap, expandedKey, null); + RSSReader reader = new RSSReader(); + RSSData rssData = reader.parseUrl(expandedUrl); + ParameterExpander.setValueForKey(aValueMap, expandedKey, RSSToMapConverter.convertRSSData(rssData)); + } + catch (Throwable t) { + Throwable s = ExceptionFunctions.traceCauseException(t); + aLogger.error("Error while processing RSS data: " + s.getClass().getName()+","+ s.getMessage()); + } + }; } \ No newline at end of file diff --git a/source/mir/producer/reader/DefaultProducerNodeBuilders.java b/source/mir/producer/reader/DefaultProducerNodeBuilders.java index 62524025..14f4953d 100755 --- a/source/mir/producer/reader/DefaultProducerNodeBuilders.java +++ b/source/mir/producer/reader/DefaultProducerNodeBuilders.java @@ -31,34 +31,34 @@ package mir.producer.reader; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import mir.entity.adapter.EntityAdapterModel; -import mir.generator.Generator; -import mir.generator.WriterEngine; -import mir.log.LoggerWrapper; -import mir.producer.ConditionalProducerNode; -import mir.producer.DirCopyingProducerNode; -import mir.producer.EntityBatchingProducerNode; -import mir.producer.EntityEnumeratingProducerNode; -import mir.producer.EntityListProducerNode; -import mir.producer.EvaluatedAssignmentProducerNode; -import mir.producer.ExpandedAssignmentProducerNode; -import mir.producer.FileDateSettingProducerNode; -import mir.producer.FileDeletingProducerNode; -import mir.producer.GeneratingProducerNode; -import mir.producer.LoggingProducerNode; -import mir.producer.LoopProducerNode; -import mir.producer.ProducerNode; -import mir.producer.RSSProducerNode; -import mir.producer.ResourceBundleProducerNode; -import mir.producer.ScriptCallingProducerNode; -import mir.util.XMLReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import mir.entity.adapter.EntityAdapterModel; +import mir.generator.Generator; +import mir.generator.WriterEngine; +import mir.log.LoggerWrapper; +import mir.producer.ConditionalProducerNode; +import mir.producer.DirCopyingProducerNode; +import mir.producer.EntityBatchingProducerNode; +import mir.producer.EntityEnumeratingProducerNode; +import mir.producer.EntityListProducerNode; +import mir.producer.EvaluatedAssignmentProducerNode; +import mir.producer.ExpandedAssignmentProducerNode; +import mir.producer.FileDateSettingProducerNode; +import mir.producer.FileDeletingProducerNode; +import mir.producer.GeneratingProducerNode; +import mir.producer.LoggingProducerNode; +import mir.producer.LoopProducerNode; +import mir.producer.ProducerNode; +import mir.producer.RSSProducerNode; +import mir.producer.ResourceBundleProducerNode; +import mir.producer.ScriptCallingProducerNode; +import mir.util.XMLReader; import mir.util.XMLReaderTool; public class DefaultProducerNodeBuilders { diff --git a/source/mir/producer/reader/ProducerConfigReader.java b/source/mir/producer/reader/ProducerConfigReader.java index 46249ef5..1eabcc2f 100755 --- a/source/mir/producer/reader/ProducerConfigReader.java +++ b/source/mir/producer/reader/ProducerConfigReader.java @@ -1,641 +1,641 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.producer.reader; - -import java.io.File; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - -import mir.producer.CompositeProducerNode; -import mir.producer.ProducerFactory; -import mir.producer.ProducerNode; -import mir.producer.SimpleProducerVerb; -import mir.util.XMLReader; -import mir.util.XMLReaderTool; - -public class ProducerConfigReader { - private ProducerNodeBuilderLibrary builderLibrary; - private ProducerNodeBuilderLibrary scriptedNodeBuilderLibrary; - - public ProducerConfigReader() { - super(); - }; - - public void parseFile(String aFileName, ProducerNodeBuilderLibrary aBuilderLibrary, List aProducerFactories) throws ProducerConfigFailure { - parseFile(aFileName, aBuilderLibrary, aProducerFactories, new Vector()); - } - - public void parseFile(String aFileName, ProducerNodeBuilderLibrary aBuilderLibrary, List aProducerFactories, List aUsedFiles) throws ProducerConfigFailure { - try { - XMLReader reader = new XMLReader(); - aUsedFiles.add(new File(aFileName)); - - builderLibrary = aBuilderLibrary; - scriptedNodeBuilderLibrary = new ProducerNodeBuilderLibrary(); - - reader.parseFile(aFileName, new RootSectionHandler(aProducerFactories)); - - } - catch (Throwable e) { - if ((e instanceof XMLReader.XMLReaderExc) && ((XMLReader.XMLReaderExc) e).getHasLocation()) { - XMLReader.XMLReaderExc f = (XMLReader.XMLReaderExc) e; - throw new ProducerConfigFailure("'" + f.getMessage()+"' in " + f.getFilename()+"(line " + f.getLineNr()+", column " + f.getColumnNr() + ")", e); - } - throw new ProducerConfigFailure( e ); - } - } - - - public class RootSectionHandler extends XMLReader.AbstractSectionHandler { - private List producers; - - public RootSectionHandler(List aProducers) { - producers = aProducers; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("producers")) { - return new ProducersSectionHandler(producers); - } - else - throw new XMLReader.XMLReaderExc("Tag 'producers' expected, tag '"+aTag+"' found"); - } - - public void endElement(XMLReader.SectionHandler aHandler) { - } - - public void finishSection() { - } - } - - - private final static String PRODUCER_NAME_ATTRIBUTE = "name"; - private final static String[] PRODUCER_REQUIRED_ATTRIBUTES = { PRODUCER_NAME_ATTRIBUTE }; - private final static String[] PRODUCER_OPTIONAL_ATTRIBUTES = { }; - - private final static String NODE_DEFINITION_NAME_ATTRIBUTE = "name"; - private final static String[] NODE_DEFINITION_REQUIRED_ATTRIBUTES = { NODE_DEFINITION_NAME_ATTRIBUTE }; - private final static String[] NODE_DEFINITION_OPTIONAL_ATTRIBUTES = { }; - - public class ProducersSectionHandler extends XMLReader.AbstractSectionHandler { - private List producers; - private Set producerNames; - private String name; - - public ProducersSectionHandler(List aProducers) { - producers = aProducers; - producerNames = new HashSet(); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("producer")) { - XMLReaderTool.checkAttributes(anAttributes, - PRODUCER_REQUIRED_ATTRIBUTES, - PRODUCER_OPTIONAL_ATTRIBUTES); - - name = (String) anAttributes.get(PRODUCER_NAME_ATTRIBUTE); - XMLReaderTool.checkValidIdentifier(name); - - if (producerNames.contains(name)) - throw new XMLReader.XMLReaderExc("Duplicate producer name: '" + - name + "'"); - - name = (String) anAttributes.get(PRODUCER_NAME_ATTRIBUTE); - - return new ProducerSectionHandler(name); - } - else if (aTag.equals("nodedefinition")) { - XMLReaderTool.checkAttributes(anAttributes, - NODE_DEFINITION_REQUIRED_ATTRIBUTES, - NODE_DEFINITION_OPTIONAL_ATTRIBUTES); - - name = (String) anAttributes.get(NODE_DEFINITION_NAME_ATTRIBUTE); - XMLReaderTool.checkValidIdentifier(name); - - name = (String) anAttributes.get(NODE_DEFINITION_NAME_ATTRIBUTE); - - return new NodeDefinitionSectionHandler(name); - } - throw new XMLReader.XMLReaderExc("Unexpected tag: " + aTag); - } - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (aHandler instanceof ProducerSectionHandler) { - producers.add(((ProducerSectionHandler) aHandler).getProducerFactory()); - producerNames.add(((ProducerSectionHandler) aHandler).getProducerFactory().getName()); - } - else if (aHandler instanceof NodeDefinitionSectionHandler) { - scriptedNodeBuilderLibrary.registerFactory(name, - new DefaultProducerNodeBuilders.ScriptedProducerNodeBuilder.factory( - ((NodeDefinitionSectionHandler) aHandler).getDefinition())); - } - else throw new XMLReader.XMLReaderExc("ProducersSectionHandler.endElement Internal error: Unexpected handler: " + aHandler.getClass().getName()); - } - - public void finishSection() { - } - } - - public class ProducerSectionHandler extends XMLReader.AbstractSectionHandler { - private ProducerFactory producerFactory; - private String factoryName; - - private ProducerNode body; - private Map verbNodes; - private List verbs; - private String defaultVerb; - - public ProducerSectionHandler(String aName) { - factoryName = aName; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("verbs")) { - if (verbs!=null) - throw new XMLReader.XMLReaderExc("Verbs already processed"); - if (body!=null) - throw new XMLReader.XMLReaderExc("Verbs should come before body"); - else - return new ProducerVerbsSectionHandler(); - } - else if (aTag.equals("body")) { - if (body==null) - return new ProducerNodeSectionHandler(); - else - throw new XMLReader.XMLReaderExc("Body already processed"); - } - throw new XMLReader.XMLReaderExc("Unexpected tag: '"+aTag+"'"); - } - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (aHandler instanceof ProducerNodeSectionHandler) { - body = ((ProducerNodeSectionHandler) aHandler).getProducerNode(); - } - else if (aHandler instanceof ProducerVerbsSectionHandler) - { - verbs = ((ProducerVerbsSectionHandler) aHandler).getVerbs(); - verbNodes = ((ProducerVerbsSectionHandler) aHandler).getVerbNodes(); - defaultVerb = ((ProducerVerbsSectionHandler) aHandler).getDefaultVerb(); - } - else throw new XMLReader.XMLReaderExc("ProducerSectionHandler.endElement Internal error: Unexpected handler: " + aHandler.getClass().getName()); - } - - public void finishSection() throws XMLReader.XMLReaderExc { - if (verbs==null) - throw new XMLReader.XMLReaderExc("No verbs defined"); - - if (body==null) - throw new XMLReader.XMLReaderExc("No body defined"); - - producerFactory = new ScriptedProducerFactory(factoryName, verbs, verbNodes, body, defaultVerb); - } - - public ProducerFactory getProducerFactory() { - return producerFactory; - } - } - - private final static String PRODUCER_VERB_NAME_ATTRIBUTE = "name"; - private final static String PRODUCER_VERB_DESCRIPTION_ATTRIBUTE = "description"; - private final static String PRODUCER_VERB_DEFAULT_ATTRIBUTE = "default"; - private final static String[] PRODUCER_VERB_REQUIRED_ATTRIBUTES = { PRODUCER_VERB_NAME_ATTRIBUTE }; - private final static String[] PRODUCER_VERB_OPTIONAL_ATTRIBUTES = { PRODUCER_VERB_DEFAULT_ATTRIBUTE, PRODUCER_VERB_DESCRIPTION_ATTRIBUTE }; - - public class ProducerVerbsSectionHandler extends XMLReader.AbstractSectionHandler { - private Map verbNodes; - private List verbs; - private String defaultVerb; - private String currentVerb; - private String currentVerbDescription; - - public ProducerVerbsSectionHandler() { - verbNodes = new HashMap(); - verbs = new Vector(); - defaultVerb = null; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("verb")) { - XMLReaderTool.checkAttributes(anAttributes, - PRODUCER_VERB_REQUIRED_ATTRIBUTES, - PRODUCER_VERB_OPTIONAL_ATTRIBUTES); - currentVerb = (String) anAttributes.get(PRODUCER_VERB_NAME_ATTRIBUTE); - - XMLReaderTool.checkValidIdentifier(currentVerb); - - if (verbNodes.containsKey(currentVerb)) - throw new XMLReader.XMLReaderExc("Duplicate definition of verb '" + - currentVerb + "'"); - - if (anAttributes.containsKey(PRODUCER_VERB_DEFAULT_ATTRIBUTE)) { - if (defaultVerb != null) - throw new XMLReader.XMLReaderExc("Default verb already declared"); - - defaultVerb = currentVerb; - } - - if (anAttributes.containsKey(PRODUCER_VERB_DESCRIPTION_ATTRIBUTE)) - currentVerbDescription = (String) anAttributes.get( - PRODUCER_VERB_DESCRIPTION_ATTRIBUTE); - else - currentVerbDescription = ""; - - return new ProducerNodeSectionHandler(); - } - else - throw new XMLReader.XMLReaderExc("Only 'verb' tags allowed here, '" + - aTag + "' encountered."); - } - - public void endElement(XMLReader.SectionHandler aHandler) { - verbNodes.put(currentVerb, ((ProducerNodeSectionHandler) aHandler).getProducerNode()); - verbs.add(new SimpleProducerVerb(currentVerb, currentVerbDescription)); - } - - public void finishSection() { - } - - public String getDefaultVerb() { - return defaultVerb; - } - - public List getVerbs() { - return verbs; - } - - public Map getVerbNodes() { - return verbNodes; - } - } - - public class EmptySectionHandler extends XMLReader.AbstractSectionHandler { - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - throw new XMLReader.XMLReaderExc("No tags are allowed here"); - } - - public void endElement(XMLReader.SectionHandler aHandler) { - } - - public void finishSection() { - } - } - - public class MultiProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler { - private Map nodeParameters; - private Set validNodeParameters; - private String currentNodeParameter; - private String scriptedNodeName; - private Set allowedNodeParameterReferences; - - public MultiProducerNodeSectionHandler(String aScriptedNodeName, Set anAllowedNodeParameterReferences, Set aValidNodeParameters) { - allowedNodeParameterReferences = anAllowedNodeParameterReferences; - scriptedNodeName = aScriptedNodeName; - validNodeParameters = aValidNodeParameters; - nodeParameters = new HashMap(); - } - public MultiProducerNodeSectionHandler(Set aValidNodeParameters) { - this("", new HashSet(), aValidNodeParameters); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (!validNodeParameters.contains(aTag)) - throw new XMLReader.XMLReaderExc("Invalid node parameter: '" + aTag + "'"); - else if (nodeParameters.containsKey(aTag)) - throw new XMLReader.XMLReaderExc("Node parameter: '" + aTag + "' already specified"); - else if (anAttributes.size()>0) - throw new XMLReader.XMLReaderExc("No parameters are allowed here"); - - currentNodeParameter = aTag; - - return new ProducerNodeSectionHandler(scriptedNodeName, validNodeParameters); - } - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (aHandler instanceof ProducerNodeSectionHandler) { - nodeParameters.put(currentNodeParameter, ((ProducerNodeSectionHandler) aHandler).getProducerNode()); - } - else { - throw new XMLReader.XMLReaderExc("Internal error: unknown section handler '" + aHandler.getClass().getName() + "'" ); - } - } - - public Map getNodeParameters() { - return nodeParameters; - } - - public void finishSection() { - } - } - - public class ProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler { - private CompositeProducerNode producerNode; - private ProducerNodeBuilder currentBuilder; - private String scriptedNodeName; - private Set allowedNodeParameterReferences; - - public ProducerNodeSectionHandler(String aScriptedNodeName, Set anAllowedNodeParameterReferences) { - producerNode = new CompositeProducerNode(); - scriptedNodeName = aScriptedNodeName; - allowedNodeParameterReferences = anAllowedNodeParameterReferences; - } - - public ProducerNodeSectionHandler() { - this("", new HashSet()); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - try { - if (allowedNodeParameterReferences.contains( (aTag))) { - if (!anAttributes.isEmpty()) { - throw new XMLReader.XMLReaderExc("No attributes allowed"); - } - - currentBuilder = new DefaultProducerNodeBuilders. - ScriptedProducerParameterNodeBuilder(scriptedNodeName, aTag); - return new EmptySectionHandler(); - } - else if (scriptedNodeBuilderLibrary.hasBuilderForName(aTag) || - builderLibrary.hasBuilderForName( (aTag))) { - - if (scriptedNodeBuilderLibrary.hasBuilderForName(aTag)) - currentBuilder = scriptedNodeBuilderLibrary.constructBuilder(aTag); - else - currentBuilder = builderLibrary.constructBuilder(aTag); - - currentBuilder.setAttributes(anAttributes); - if (currentBuilder.getAvailableSubNodes().isEmpty()) { - return new EmptySectionHandler(); - } - if (currentBuilder.getAvailableSubNodes().size() > 1) - return new MultiProducerNodeSectionHandler(scriptedNodeName, - allowedNodeParameterReferences, - currentBuilder.getAvailableSubNodes()); - else if (currentBuilder.getAvailableSubNodes().size() < 1) - return new EmptySectionHandler(); - else { - return new ProducerNodeSectionHandler(scriptedNodeName, - allowedNodeParameterReferences); - } - } - else - throw new XMLReader.XMLReaderExc("Unknown producer node tag: '" + - aTag + "'"); - } - catch (Throwable t) { - throw new XMLReader.XMLReaderFailure(t); - } - } - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - try { - if (aHandler instanceof ProducerNodeSectionHandler) { - currentBuilder.setSubNode( - (String) (currentBuilder.getAvailableSubNodes().iterator().next()), - ((ProducerNodeSectionHandler) aHandler).getProducerNode()); - } - else if (aHandler instanceof MultiProducerNodeSectionHandler) { - Iterator i; - Map nodeParameters; - Map.Entry entry; - - nodeParameters = ( (MultiProducerNodeSectionHandler) aHandler). - getNodeParameters(); - i = nodeParameters.entrySet().iterator(); - while (i.hasNext()) { - entry = (Map.Entry) i.next(); - currentBuilder.setSubNode( (String) entry.getKey(), - (ProducerNode) entry.getValue()); - } - } - else if (aHandler instanceof EmptySectionHandler) { - // deliberately empty: nothing expected, so nothing to process - } - else { - throw new XMLReader.XMLReaderExc( - "Internal error: unknown section handler '" + - aHandler.getClass().getName() + "'"); - } - - producerNode.addSubNode(currentBuilder.constructNode()); - currentBuilder = null; - } - catch (Throwable t) { - throw new XMLReader.XMLReaderFailure(t); - } - } - - public ProducerNode getProducerNode() { - if (producerNode.getNrSubNodes()==1) { - return producerNode.getSubNode(0); - } - else { - return producerNode; - } - } - - public void finishSection() { - } - } - - public class NodeDefinitionSectionHandler extends XMLReader.AbstractSectionHandler { - private ScriptedProducerNodeDefinition nodeDefinition; - private ProducerNode body; - private Map stringParameters; - private Map integerParameters; - private Map nodeParameters; - private String name; - - public NodeDefinitionSectionHandler(String aName) { - body = null; - nodeParameters = null; - stringParameters = null; - integerParameters = null; - name = aName; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("parameters")) { - if (!anAttributes.isEmpty()) { - throw new XMLReader.XMLReaderExc( "No attributes allowed for tag 'parameters'" ); - } - if (nodeParameters!=null) { - throw new XMLReader.XMLReaderExc( "Parameters have already been declared" ); - } - if (body!=null) { - throw new XMLReader.XMLReaderExc( "Parameters should come before definition in nodedefinition '" + name +"'" ); - } - - return new NodeDefinitionParametersSectionHandler(); - } - else if (aTag.equals("definition")) { - if (nodeParameters==null) - throw new XMLReader.XMLReaderExc( "Parameters should come before definition in nodedefinition '" + name +"'" ); - - return new ProducerNodeSectionHandler(name, nodeParameters.keySet()); - } - else throw new XMLReader.XMLReaderExc("Only 'definition' or 'parameters' tags allowed here, '" + aTag + "' encountered."); - } - - public void endElement(XMLReader.SectionHandler aHandler) { - if (aHandler instanceof NodeDefinitionParametersSectionHandler) { - stringParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getStringParameters(); - integerParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getIntegerParameters(); - nodeParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getNodeParameters(); - } - else if (aHandler instanceof ProducerNodeSectionHandler) { - body = ((ProducerNodeSectionHandler) aHandler).getProducerNode(); - } - } - - public void finishSection() throws XMLReader.XMLReaderExc { - Iterator i; - if (body == null) - throw new XMLReader.XMLReaderExc( "Definition missing" ); - - nodeDefinition = new ScriptedProducerNodeDefinition(name); - - nodeDefinition.setBody(body); - - i = nodeParameters.keySet().iterator(); - while (i.hasNext()) { - nodeDefinition.addNodeParameter((String) i.next()); - } - - i = stringParameters.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - nodeDefinition.addStringParameter((String) entry.getKey(), (String) entry.getValue()); - } - - i = integerParameters.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - nodeDefinition.addIntegerParameter((String) entry.getKey(), (String) entry.getValue()); - } - } - - public ScriptedProducerNodeDefinition getDefinition() { - return nodeDefinition; - } - } - - private final static String NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE = "name"; - private final static String NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE = "defaultvalue"; - private final static String[] NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES = { NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE }; - private final static String[] NODE_DEFINITION_PARAMETER_OPTIONAL_ATTRIBUTES = { NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE }; - private final static String[] NODE_DEFINITION_NODE_PARAMETER_OPTIONAL_ATTRIBUTES = { }; - - public class NodeDefinitionParametersSectionHandler extends XMLReader.AbstractSectionHandler { - private Map nodeParameters; - private Map stringParameters; - private Map integerParameters; - - public NodeDefinitionParametersSectionHandler() { - nodeParameters = new HashMap(); - stringParameters = new HashMap(); - integerParameters = new HashMap(); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - String parameterName; - String defaultValue; - - if (aTag.equals("node")) { - XMLReaderTool.checkAttributes(anAttributes, - NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES, - NODE_DEFINITION_NODE_PARAMETER_OPTIONAL_ATTRIBUTES); - parameterName = (String) anAttributes.get( - NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE); - - if (nodeParameters.containsKey(parameterName)) - throw new XMLReader.XMLReaderExc("Duplicate parameter name: '" + - parameterName + "'"); - - XMLReaderTool.checkValidIdentifier(parameterName); - - nodeParameters.put(parameterName, parameterName); - - return new EmptySectionHandler(); - } - else if (aTag.equals("string") || aTag.equals("integer")) { - XMLReaderTool.checkAttributes(anAttributes, - NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES, - NODE_DEFINITION_PARAMETER_OPTIONAL_ATTRIBUTES); - parameterName = (String) anAttributes.get( - NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE); - - if (stringParameters.containsKey(parameterName) || - integerParameters.containsKey(parameterName)) - throw new XMLReader.XMLReaderExc("Duplicate parameter name: '" + - parameterName + "'"); - - XMLReaderTool.checkValidIdentifier(parameterName); - - defaultValue = (String) anAttributes.get( - NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE); - - if (aTag.equals("string")) - stringParameters.put(parameterName, defaultValue); - else - integerParameters.put(parameterName, defaultValue); - - return new EmptySectionHandler(); - } - else - throw new XMLReader.XMLReaderExc( - "Only 'string', 'integer' and 'node' tags allowed here, '" + aTag + "' encountered."); - } - - public void endElement(XMLReader.SectionHandler aHandler) { - } - - public void finishSection() { - } - - public Map getNodeParameters() { - return nodeParameters; - } - - public Map getStringParameters() { - return stringParameters; - } - - public Map getIntegerParameters() { - return integerParameters; - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.producer.reader; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import mir.producer.CompositeProducerNode; +import mir.producer.ProducerFactory; +import mir.producer.ProducerNode; +import mir.producer.SimpleProducerVerb; +import mir.util.XMLReader; +import mir.util.XMLReaderTool; + +public class ProducerConfigReader { + private ProducerNodeBuilderLibrary builderLibrary; + private ProducerNodeBuilderLibrary scriptedNodeBuilderLibrary; + + public ProducerConfigReader() { + super(); + }; + + public void parseFile(String aFileName, ProducerNodeBuilderLibrary aBuilderLibrary, List aProducerFactories) throws ProducerConfigFailure { + parseFile(aFileName, aBuilderLibrary, aProducerFactories, new Vector()); + } + + public void parseFile(String aFileName, ProducerNodeBuilderLibrary aBuilderLibrary, List aProducerFactories, List aUsedFiles) throws ProducerConfigFailure { + try { + XMLReader reader = new XMLReader(); + aUsedFiles.add(new File(aFileName)); + + builderLibrary = aBuilderLibrary; + scriptedNodeBuilderLibrary = new ProducerNodeBuilderLibrary(); + + reader.parseFile(aFileName, new RootSectionHandler(aProducerFactories)); + + } + catch (Throwable e) { + if ((e instanceof XMLReader.XMLReaderExc) && ((XMLReader.XMLReaderExc) e).getHasLocation()) { + XMLReader.XMLReaderExc f = (XMLReader.XMLReaderExc) e; + throw new ProducerConfigFailure("'" + f.getMessage()+"' in " + f.getFilename()+"(line " + f.getLineNr()+", column " + f.getColumnNr() + ")", e); + } + throw new ProducerConfigFailure( e ); + } + } + + + public class RootSectionHandler extends XMLReader.AbstractSectionHandler { + private List producers; + + public RootSectionHandler(List aProducers) { + producers = aProducers; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("producers")) { + return new ProducersSectionHandler(producers); + } + else + throw new XMLReader.XMLReaderExc("Tag 'producers' expected, tag '"+aTag+"' found"); + } + + public void endElement(XMLReader.SectionHandler aHandler) { + } + + public void finishSection() { + } + } + + + private final static String PRODUCER_NAME_ATTRIBUTE = "name"; + private final static String[] PRODUCER_REQUIRED_ATTRIBUTES = { PRODUCER_NAME_ATTRIBUTE }; + private final static String[] PRODUCER_OPTIONAL_ATTRIBUTES = { }; + + private final static String NODE_DEFINITION_NAME_ATTRIBUTE = "name"; + private final static String[] NODE_DEFINITION_REQUIRED_ATTRIBUTES = { NODE_DEFINITION_NAME_ATTRIBUTE }; + private final static String[] NODE_DEFINITION_OPTIONAL_ATTRIBUTES = { }; + + public class ProducersSectionHandler extends XMLReader.AbstractSectionHandler { + private List producers; + private Set producerNames; + private String name; + + public ProducersSectionHandler(List aProducers) { + producers = aProducers; + producerNames = new HashSet(); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("producer")) { + XMLReaderTool.checkAttributes(anAttributes, + PRODUCER_REQUIRED_ATTRIBUTES, + PRODUCER_OPTIONAL_ATTRIBUTES); + + name = (String) anAttributes.get(PRODUCER_NAME_ATTRIBUTE); + XMLReaderTool.checkValidIdentifier(name); + + if (producerNames.contains(name)) + throw new XMLReader.XMLReaderExc("Duplicate producer name: '" + + name + "'"); + + name = (String) anAttributes.get(PRODUCER_NAME_ATTRIBUTE); + + return new ProducerSectionHandler(name); + } + else if (aTag.equals("nodedefinition")) { + XMLReaderTool.checkAttributes(anAttributes, + NODE_DEFINITION_REQUIRED_ATTRIBUTES, + NODE_DEFINITION_OPTIONAL_ATTRIBUTES); + + name = (String) anAttributes.get(NODE_DEFINITION_NAME_ATTRIBUTE); + XMLReaderTool.checkValidIdentifier(name); + + name = (String) anAttributes.get(NODE_DEFINITION_NAME_ATTRIBUTE); + + return new NodeDefinitionSectionHandler(name); + } + throw new XMLReader.XMLReaderExc("Unexpected tag: " + aTag); + } + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (aHandler instanceof ProducerSectionHandler) { + producers.add(((ProducerSectionHandler) aHandler).getProducerFactory()); + producerNames.add(((ProducerSectionHandler) aHandler).getProducerFactory().getName()); + } + else if (aHandler instanceof NodeDefinitionSectionHandler) { + scriptedNodeBuilderLibrary.registerFactory(name, + new DefaultProducerNodeBuilders.ScriptedProducerNodeBuilder.factory( + ((NodeDefinitionSectionHandler) aHandler).getDefinition())); + } + else throw new XMLReader.XMLReaderExc("ProducersSectionHandler.endElement Internal error: Unexpected handler: " + aHandler.getClass().getName()); + } + + public void finishSection() { + } + } + + public class ProducerSectionHandler extends XMLReader.AbstractSectionHandler { + private ProducerFactory producerFactory; + private String factoryName; + + private ProducerNode body; + private Map verbNodes; + private List verbs; + private String defaultVerb; + + public ProducerSectionHandler(String aName) { + factoryName = aName; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("verbs")) { + if (verbs!=null) + throw new XMLReader.XMLReaderExc("Verbs already processed"); + if (body!=null) + throw new XMLReader.XMLReaderExc("Verbs should come before body"); + else + return new ProducerVerbsSectionHandler(); + } + else if (aTag.equals("body")) { + if (body==null) + return new ProducerNodeSectionHandler(); + else + throw new XMLReader.XMLReaderExc("Body already processed"); + } + throw new XMLReader.XMLReaderExc("Unexpected tag: '"+aTag+"'"); + } + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (aHandler instanceof ProducerNodeSectionHandler) { + body = ((ProducerNodeSectionHandler) aHandler).getProducerNode(); + } + else if (aHandler instanceof ProducerVerbsSectionHandler) + { + verbs = ((ProducerVerbsSectionHandler) aHandler).getVerbs(); + verbNodes = ((ProducerVerbsSectionHandler) aHandler).getVerbNodes(); + defaultVerb = ((ProducerVerbsSectionHandler) aHandler).getDefaultVerb(); + } + else throw new XMLReader.XMLReaderExc("ProducerSectionHandler.endElement Internal error: Unexpected handler: " + aHandler.getClass().getName()); + } + + public void finishSection() throws XMLReader.XMLReaderExc { + if (verbs==null) + throw new XMLReader.XMLReaderExc("No verbs defined"); + + if (body==null) + throw new XMLReader.XMLReaderExc("No body defined"); + + producerFactory = new ScriptedProducerFactory(factoryName, verbs, verbNodes, body, defaultVerb); + } + + public ProducerFactory getProducerFactory() { + return producerFactory; + } + } + + private final static String PRODUCER_VERB_NAME_ATTRIBUTE = "name"; + private final static String PRODUCER_VERB_DESCRIPTION_ATTRIBUTE = "description"; + private final static String PRODUCER_VERB_DEFAULT_ATTRIBUTE = "default"; + private final static String[] PRODUCER_VERB_REQUIRED_ATTRIBUTES = { PRODUCER_VERB_NAME_ATTRIBUTE }; + private final static String[] PRODUCER_VERB_OPTIONAL_ATTRIBUTES = { PRODUCER_VERB_DEFAULT_ATTRIBUTE, PRODUCER_VERB_DESCRIPTION_ATTRIBUTE }; + + public class ProducerVerbsSectionHandler extends XMLReader.AbstractSectionHandler { + private Map verbNodes; + private List verbs; + private String defaultVerb; + private String currentVerb; + private String currentVerbDescription; + + public ProducerVerbsSectionHandler() { + verbNodes = new HashMap(); + verbs = new Vector(); + defaultVerb = null; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("verb")) { + XMLReaderTool.checkAttributes(anAttributes, + PRODUCER_VERB_REQUIRED_ATTRIBUTES, + PRODUCER_VERB_OPTIONAL_ATTRIBUTES); + currentVerb = (String) anAttributes.get(PRODUCER_VERB_NAME_ATTRIBUTE); + + XMLReaderTool.checkValidIdentifier(currentVerb); + + if (verbNodes.containsKey(currentVerb)) + throw new XMLReader.XMLReaderExc("Duplicate definition of verb '" + + currentVerb + "'"); + + if (anAttributes.containsKey(PRODUCER_VERB_DEFAULT_ATTRIBUTE)) { + if (defaultVerb != null) + throw new XMLReader.XMLReaderExc("Default verb already declared"); + + defaultVerb = currentVerb; + } + + if (anAttributes.containsKey(PRODUCER_VERB_DESCRIPTION_ATTRIBUTE)) + currentVerbDescription = (String) anAttributes.get( + PRODUCER_VERB_DESCRIPTION_ATTRIBUTE); + else + currentVerbDescription = ""; + + return new ProducerNodeSectionHandler(); + } + else + throw new XMLReader.XMLReaderExc("Only 'verb' tags allowed here, '" + + aTag + "' encountered."); + } + + public void endElement(XMLReader.SectionHandler aHandler) { + verbNodes.put(currentVerb, ((ProducerNodeSectionHandler) aHandler).getProducerNode()); + verbs.add(new SimpleProducerVerb(currentVerb, currentVerbDescription)); + } + + public void finishSection() { + } + + public String getDefaultVerb() { + return defaultVerb; + } + + public List getVerbs() { + return verbs; + } + + public Map getVerbNodes() { + return verbNodes; + } + } + + public class EmptySectionHandler extends XMLReader.AbstractSectionHandler { + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + throw new XMLReader.XMLReaderExc("No tags are allowed here"); + } + + public void endElement(XMLReader.SectionHandler aHandler) { + } + + public void finishSection() { + } + } + + public class MultiProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler { + private Map nodeParameters; + private Set validNodeParameters; + private String currentNodeParameter; + private String scriptedNodeName; + private Set allowedNodeParameterReferences; + + public MultiProducerNodeSectionHandler(String aScriptedNodeName, Set anAllowedNodeParameterReferences, Set aValidNodeParameters) { + allowedNodeParameterReferences = anAllowedNodeParameterReferences; + scriptedNodeName = aScriptedNodeName; + validNodeParameters = aValidNodeParameters; + nodeParameters = new HashMap(); + } + public MultiProducerNodeSectionHandler(Set aValidNodeParameters) { + this("", new HashSet(), aValidNodeParameters); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (!validNodeParameters.contains(aTag)) + throw new XMLReader.XMLReaderExc("Invalid node parameter: '" + aTag + "'"); + else if (nodeParameters.containsKey(aTag)) + throw new XMLReader.XMLReaderExc("Node parameter: '" + aTag + "' already specified"); + else if (anAttributes.size()>0) + throw new XMLReader.XMLReaderExc("No parameters are allowed here"); + + currentNodeParameter = aTag; + + return new ProducerNodeSectionHandler(scriptedNodeName, validNodeParameters); + } + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (aHandler instanceof ProducerNodeSectionHandler) { + nodeParameters.put(currentNodeParameter, ((ProducerNodeSectionHandler) aHandler).getProducerNode()); + } + else { + throw new XMLReader.XMLReaderExc("Internal error: unknown section handler '" + aHandler.getClass().getName() + "'" ); + } + } + + public Map getNodeParameters() { + return nodeParameters; + } + + public void finishSection() { + } + } + + public class ProducerNodeSectionHandler extends XMLReader.AbstractSectionHandler { + private CompositeProducerNode producerNode; + private ProducerNodeBuilder currentBuilder; + private String scriptedNodeName; + private Set allowedNodeParameterReferences; + + public ProducerNodeSectionHandler(String aScriptedNodeName, Set anAllowedNodeParameterReferences) { + producerNode = new CompositeProducerNode(); + scriptedNodeName = aScriptedNodeName; + allowedNodeParameterReferences = anAllowedNodeParameterReferences; + } + + public ProducerNodeSectionHandler() { + this("", new HashSet()); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + try { + if (allowedNodeParameterReferences.contains( (aTag))) { + if (!anAttributes.isEmpty()) { + throw new XMLReader.XMLReaderExc("No attributes allowed"); + } + + currentBuilder = new DefaultProducerNodeBuilders. + ScriptedProducerParameterNodeBuilder(scriptedNodeName, aTag); + return new EmptySectionHandler(); + } + else if (scriptedNodeBuilderLibrary.hasBuilderForName(aTag) || + builderLibrary.hasBuilderForName( (aTag))) { + + if (scriptedNodeBuilderLibrary.hasBuilderForName(aTag)) + currentBuilder = scriptedNodeBuilderLibrary.constructBuilder(aTag); + else + currentBuilder = builderLibrary.constructBuilder(aTag); + + currentBuilder.setAttributes(anAttributes); + if (currentBuilder.getAvailableSubNodes().isEmpty()) { + return new EmptySectionHandler(); + } + if (currentBuilder.getAvailableSubNodes().size() > 1) + return new MultiProducerNodeSectionHandler(scriptedNodeName, + allowedNodeParameterReferences, + currentBuilder.getAvailableSubNodes()); + else if (currentBuilder.getAvailableSubNodes().size() < 1) + return new EmptySectionHandler(); + else { + return new ProducerNodeSectionHandler(scriptedNodeName, + allowedNodeParameterReferences); + } + } + else + throw new XMLReader.XMLReaderExc("Unknown producer node tag: '" + + aTag + "'"); + } + catch (Throwable t) { + throw new XMLReader.XMLReaderFailure(t); + } + } + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + try { + if (aHandler instanceof ProducerNodeSectionHandler) { + currentBuilder.setSubNode( + (String) (currentBuilder.getAvailableSubNodes().iterator().next()), + ((ProducerNodeSectionHandler) aHandler).getProducerNode()); + } + else if (aHandler instanceof MultiProducerNodeSectionHandler) { + Iterator i; + Map nodeParameters; + Map.Entry entry; + + nodeParameters = ( (MultiProducerNodeSectionHandler) aHandler). + getNodeParameters(); + i = nodeParameters.entrySet().iterator(); + while (i.hasNext()) { + entry = (Map.Entry) i.next(); + currentBuilder.setSubNode( (String) entry.getKey(), + (ProducerNode) entry.getValue()); + } + } + else if (aHandler instanceof EmptySectionHandler) { + // deliberately empty: nothing expected, so nothing to process + } + else { + throw new XMLReader.XMLReaderExc( + "Internal error: unknown section handler '" + + aHandler.getClass().getName() + "'"); + } + + producerNode.addSubNode(currentBuilder.constructNode()); + currentBuilder = null; + } + catch (Throwable t) { + throw new XMLReader.XMLReaderFailure(t); + } + } + + public ProducerNode getProducerNode() { + if (producerNode.getNrSubNodes()==1) { + return producerNode.getSubNode(0); + } + else { + return producerNode; + } + } + + public void finishSection() { + } + } + + public class NodeDefinitionSectionHandler extends XMLReader.AbstractSectionHandler { + private ScriptedProducerNodeDefinition nodeDefinition; + private ProducerNode body; + private Map stringParameters; + private Map integerParameters; + private Map nodeParameters; + private String name; + + public NodeDefinitionSectionHandler(String aName) { + body = null; + nodeParameters = null; + stringParameters = null; + integerParameters = null; + name = aName; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("parameters")) { + if (!anAttributes.isEmpty()) { + throw new XMLReader.XMLReaderExc( "No attributes allowed for tag 'parameters'" ); + } + if (nodeParameters!=null) { + throw new XMLReader.XMLReaderExc( "Parameters have already been declared" ); + } + if (body!=null) { + throw new XMLReader.XMLReaderExc( "Parameters should come before definition in nodedefinition '" + name +"'" ); + } + + return new NodeDefinitionParametersSectionHandler(); + } + else if (aTag.equals("definition")) { + if (nodeParameters==null) + throw new XMLReader.XMLReaderExc( "Parameters should come before definition in nodedefinition '" + name +"'" ); + + return new ProducerNodeSectionHandler(name, nodeParameters.keySet()); + } + else throw new XMLReader.XMLReaderExc("Only 'definition' or 'parameters' tags allowed here, '" + aTag + "' encountered."); + } + + public void endElement(XMLReader.SectionHandler aHandler) { + if (aHandler instanceof NodeDefinitionParametersSectionHandler) { + stringParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getStringParameters(); + integerParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getIntegerParameters(); + nodeParameters = ((NodeDefinitionParametersSectionHandler) aHandler).getNodeParameters(); + } + else if (aHandler instanceof ProducerNodeSectionHandler) { + body = ((ProducerNodeSectionHandler) aHandler).getProducerNode(); + } + } + + public void finishSection() throws XMLReader.XMLReaderExc { + Iterator i; + if (body == null) + throw new XMLReader.XMLReaderExc( "Definition missing" ); + + nodeDefinition = new ScriptedProducerNodeDefinition(name); + + nodeDefinition.setBody(body); + + i = nodeParameters.keySet().iterator(); + while (i.hasNext()) { + nodeDefinition.addNodeParameter((String) i.next()); + } + + i = stringParameters.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + nodeDefinition.addStringParameter((String) entry.getKey(), (String) entry.getValue()); + } + + i = integerParameters.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + nodeDefinition.addIntegerParameter((String) entry.getKey(), (String) entry.getValue()); + } + } + + public ScriptedProducerNodeDefinition getDefinition() { + return nodeDefinition; + } + } + + private final static String NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE = "name"; + private final static String NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE = "defaultvalue"; + private final static String[] NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES = { NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE }; + private final static String[] NODE_DEFINITION_PARAMETER_OPTIONAL_ATTRIBUTES = { NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE }; + private final static String[] NODE_DEFINITION_NODE_PARAMETER_OPTIONAL_ATTRIBUTES = { }; + + public class NodeDefinitionParametersSectionHandler extends XMLReader.AbstractSectionHandler { + private Map nodeParameters; + private Map stringParameters; + private Map integerParameters; + + public NodeDefinitionParametersSectionHandler() { + nodeParameters = new HashMap(); + stringParameters = new HashMap(); + integerParameters = new HashMap(); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + String parameterName; + String defaultValue; + + if (aTag.equals("node")) { + XMLReaderTool.checkAttributes(anAttributes, + NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES, + NODE_DEFINITION_NODE_PARAMETER_OPTIONAL_ATTRIBUTES); + parameterName = (String) anAttributes.get( + NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE); + + if (nodeParameters.containsKey(parameterName)) + throw new XMLReader.XMLReaderExc("Duplicate parameter name: '" + + parameterName + "'"); + + XMLReaderTool.checkValidIdentifier(parameterName); + + nodeParameters.put(parameterName, parameterName); + + return new EmptySectionHandler(); + } + else if (aTag.equals("string") || aTag.equals("integer")) { + XMLReaderTool.checkAttributes(anAttributes, + NODE_DEFINITION_PARAMETER_REQUIRED_ATTRIBUTES, + NODE_DEFINITION_PARAMETER_OPTIONAL_ATTRIBUTES); + parameterName = (String) anAttributes.get( + NODE_DEFINITION_PARAMETER_NAME_ATTRIBUTE); + + if (stringParameters.containsKey(parameterName) || + integerParameters.containsKey(parameterName)) + throw new XMLReader.XMLReaderExc("Duplicate parameter name: '" + + parameterName + "'"); + + XMLReaderTool.checkValidIdentifier(parameterName); + + defaultValue = (String) anAttributes.get( + NODE_DEFINITION_PARAMETER_DEFAULTVALUE_ATTRIBUTE); + + if (aTag.equals("string")) + stringParameters.put(parameterName, defaultValue); + else + integerParameters.put(parameterName, defaultValue); + + return new EmptySectionHandler(); + } + else + throw new XMLReader.XMLReaderExc( + "Only 'string', 'integer' and 'node' tags allowed here, '" + aTag + "' encountered."); + } + + public void endElement(XMLReader.SectionHandler aHandler) { + } + + public void finishSection() { + } + + public Map getNodeParameters() { + return nodeParameters; + } + + public Map getStringParameters() { + return stringParameters; + } + + public Map getIntegerParameters() { + return integerParameters; + } + } +} diff --git a/source/mir/rss/RSSData.java b/source/mir/rss/RSSData.java index 5f243996..c5d4f1fb 100755 --- a/source/mir/rss/RSSData.java +++ b/source/mir/rss/RSSData.java @@ -1,70 +1,70 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.rss; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -public class RSSData { - private List items; - private Map item; - private RSSChannel channel; - - protected RSSData() { - items = new Vector(); - item = new HashMap(); - channel = null; - } - - protected void addItem(RSSItem anItem) { - items.add(anItem); - item.put(anItem.getIdentifier(), anItem); - }; - - public void setChannel(RSSChannel aChannel) { - channel = aChannel; - } - - public RSSChannel getChannel() { - return channel; - } - - public List getItems() { - return items; - } - - public Map getItem() { - return item; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.rss; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +public class RSSData { + private List items; + private Map item; + private RSSChannel channel; + + protected RSSData() { + items = new Vector(); + item = new HashMap(); + channel = null; + } + + protected void addItem(RSSItem anItem) { + items.add(anItem); + item.put(anItem.getIdentifier(), anItem); + }; + + public void setChannel(RSSChannel aChannel) { + channel = aChannel; + } + + public RSSChannel getChannel() { + return channel; + } + + public List getItems() { + return items; + } + + public Map getItem() { + return item; + } +} diff --git a/source/mir/rss/RSSReader.java b/source/mir/rss/RSSReader.java index 45fbe4f3..86d9ec61 100755 --- a/source/mir/rss/RSSReader.java +++ b/source/mir/rss/RSSReader.java @@ -1,389 +1,389 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.rss; - -import java.io.InputStream; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import mir.util.XMLReader; -import mir.util.XMLReaderTool; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class RSSReader { - public RSSReader() { - } - - public RSSData parseInputStream(InputStream aStream) throws RSSExc, RSSFailure { - try { - XMLReader xmlReader = new XMLReader(); - RSSData result = new RSSData(); - xmlReader.parseInputStream(aStream, new RootSectionHandler(result)); - - return result; - } - catch (Throwable t) { - throw new RSSFailure(t); - } - } - - public RSSData parseUrl(String anUrl) throws RSSExc, RSSFailure { - try { - InputStream inputStream = (InputStream) new URL(anUrl).getContent(new Class[] {InputStream.class}); - - if (inputStream==null) - throw new RSSExc("RSSChannel.parseUrl: Can't get url content"); - - return parseInputStream(inputStream); - } - catch (Throwable t) { - throw new RSSFailure(t); - } - } - - private static class RootSectionHandler extends XMLReader.AbstractSectionHandler { - private RSSData data; - - public RootSectionHandler(RSSData aData) { - data = aData; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (XMLReaderTool.getLocalNameFromQualifiedName(aTag).equals("RDF")) { - return new RDFSectionHandler(data); - } - else - throw new XMLReader.XMLReaderFailure(new RSSExc("'RDF' tag expected")); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - if (aCharacters.trim().length()>0) - throw new XMLReader.XMLReaderExc("No character data allowed here"); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - } - - private static class RDFSectionHandler extends XMLReader.AbstractSectionHandler { - private RSSData data; - - public RDFSectionHandler(RSSData aData) { - data = aData; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - String identifier = (String) anAttributes.get("rdf:about"); - - if (aTag.equals("channel")) { - if (identifier==null) - throw new XMLReader.XMLReaderFailure(new RSSExc("Missing rdf:about")); - else - return new ChannelSectionHandler(identifier); - } - else if (aTag.equals("item")) { - if (identifier==null) - throw new XMLReader.XMLReaderFailure(new RSSExc("Missing rdf:about")); - else - return new ItemSectionHandler(identifier); - } - else - return new DiscardingSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (aHandler instanceof ItemSectionHandler) { - data.addItem(((ItemSectionHandler) aHandler).getItem()); - } - else if (aHandler instanceof ChannelSectionHandler) { - data.setChannel(((ChannelSectionHandler) aHandler).getChannel()); - } - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - if (aCharacters.trim().length()>0) - throw new XMLReader.XMLReaderExc("No character data allowed here"); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - } - - private static class ChannelSectionHandler extends XMLReader.AbstractSectionHandler { - private String image; - private String currentTag; - private RSSChannel channel; - - public ChannelSectionHandler(String anIdentifier) { - channel = new RSSChannel(anIdentifier); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - currentTag = aTag; - if (currentTag.equals("items")) { - return new ChannelItemsSectionHandler(); - } - else if (currentTag.equals("description") || - currentTag.equals("link") || - currentTag.equals("title")) { - return new PCDATASectionHandler(); - } - - return new DiscardingSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (currentTag.equals("items")) { - channel.setItems(((ChannelItemsSectionHandler) aHandler).getItems()); - } - if (currentTag.equals("description")) { - channel.setDescription(((PCDATASectionHandler) aHandler).getData()); - } - else if (currentTag.equals("title")) { - channel.setTitle(((PCDATASectionHandler) aHandler).getData()); - } - else if (currentTag.equals("link")) { - channel.setLink(((PCDATASectionHandler) aHandler).getData()); - } - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - if (aCharacters.trim().length()>0) - throw new XMLReader.XMLReaderExc("No character data allowed here"); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - - public RSSChannel getChannel () { - return channel; - } - } - - private static class ChannelItemsSectionHandler extends XMLReader.AbstractSectionHandler { - private List items; - - public ChannelItemsSectionHandler() { - items = new Vector(); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("rdf:Seq")) - return new RDFSequenceSectionHandler(); - else - return new DiscardingSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (aHandler instanceof RDFSequenceSectionHandler) { - items.addAll(((RDFSequenceSectionHandler) aHandler).getItems()); - } - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - if (aCharacters.trim().length()>0) - throw new XMLReader.XMLReaderExc("No character data allowed here"); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - - public List getItems() { - return items; - } - } - - private static class ItemSectionHandler extends XMLReader.AbstractSectionHandler { - private String currentTag; - private RSSItem item; - - public ItemSectionHandler(String anIdentifier) { - item = new RSSItem(anIdentifier); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - currentTag = aTag; - - if (currentTag.equals("description") || - currentTag.equals("link") || - currentTag.equals("title")) { - return new PCDATASectionHandler(); - } - - return new DiscardingSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (currentTag.equals("description")) { - item.setDescription(((PCDATASectionHandler) aHandler).getData()); - } - else if (currentTag.equals("title")) { - item.setTitle(((PCDATASectionHandler) aHandler).getData()); - } - else if (currentTag.equals("link")) { - item.setLink(((PCDATASectionHandler) aHandler).getData()); - } - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - if (aCharacters.trim().length()>0) - throw new XMLReader.XMLReaderExc("No character data allowed here"); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - - public RSSItem getItem() { - return item; - }; - } - - private static class PCDATASectionHandler extends XMLReader.AbstractSectionHandler { - private StringBuffer data; - - public PCDATASectionHandler() { - data = new StringBuffer(); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - throw new XMLReader.XMLReaderFailure(new RSSExc("No subtags allowed here")); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - data.append(aCharacters); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - - public String getData() { - return data.toString(); - } - } - - - private static class RDFSequenceSectionHandler extends XMLReader.AbstractSectionHandler { - private List items; - - public RDFSequenceSectionHandler() { - items = new Vector(); - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - if (aTag.equals("rdf:li")) { - String item = (String) anAttributes.get("rdf:resource"); - - if (item!=null) - items.add(item); - } - - return new DiscardingSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - - public List getItems() { - return items; - } - } - - private static class RDFLiteralSectionHandler extends XMLReader.AbstractSectionHandler { - private StringBuffer data; - private String tag; - - public RDFLiteralSectionHandler() { - data = new StringBuffer(); - } - - protected StringBuffer getData() { - return data; - } - - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - tag=aTag; - data.append("<"+tag+">"); - - return new RDFLiteralSectionHandler(); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - data.append(((RDFLiteralSectionHandler) aHandler).getData()); - data.append(""); - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - data.append(aCharacters); - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - } - - private static class DiscardingSectionHandler extends XMLReader.AbstractSectionHandler { - public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - return this; - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - }; - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - }; - - public void finishSection() throws XMLReader.XMLReaderExc { - }; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.rss; + +import java.io.InputStream; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.util.XMLReader; +import mir.util.XMLReaderTool; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class RSSReader { + public RSSReader() { + } + + public RSSData parseInputStream(InputStream aStream) throws RSSExc, RSSFailure { + try { + XMLReader xmlReader = new XMLReader(); + RSSData result = new RSSData(); + xmlReader.parseInputStream(aStream, new RootSectionHandler(result)); + + return result; + } + catch (Throwable t) { + throw new RSSFailure(t); + } + } + + public RSSData parseUrl(String anUrl) throws RSSExc, RSSFailure { + try { + InputStream inputStream = (InputStream) new URL(anUrl).getContent(new Class[] {InputStream.class}); + + if (inputStream==null) + throw new RSSExc("RSSChannel.parseUrl: Can't get url content"); + + return parseInputStream(inputStream); + } + catch (Throwable t) { + throw new RSSFailure(t); + } + } + + private static class RootSectionHandler extends XMLReader.AbstractSectionHandler { + private RSSData data; + + public RootSectionHandler(RSSData aData) { + data = aData; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (XMLReaderTool.getLocalNameFromQualifiedName(aTag).equals("RDF")) { + return new RDFSectionHandler(data); + } + else + throw new XMLReader.XMLReaderFailure(new RSSExc("'RDF' tag expected")); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + if (aCharacters.trim().length()>0) + throw new XMLReader.XMLReaderExc("No character data allowed here"); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + } + + private static class RDFSectionHandler extends XMLReader.AbstractSectionHandler { + private RSSData data; + + public RDFSectionHandler(RSSData aData) { + data = aData; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + String identifier = (String) anAttributes.get("rdf:about"); + + if (aTag.equals("channel")) { + if (identifier==null) + throw new XMLReader.XMLReaderFailure(new RSSExc("Missing rdf:about")); + else + return new ChannelSectionHandler(identifier); + } + else if (aTag.equals("item")) { + if (identifier==null) + throw new XMLReader.XMLReaderFailure(new RSSExc("Missing rdf:about")); + else + return new ItemSectionHandler(identifier); + } + else + return new DiscardingSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (aHandler instanceof ItemSectionHandler) { + data.addItem(((ItemSectionHandler) aHandler).getItem()); + } + else if (aHandler instanceof ChannelSectionHandler) { + data.setChannel(((ChannelSectionHandler) aHandler).getChannel()); + } + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + if (aCharacters.trim().length()>0) + throw new XMLReader.XMLReaderExc("No character data allowed here"); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + } + + private static class ChannelSectionHandler extends XMLReader.AbstractSectionHandler { + private String image; + private String currentTag; + private RSSChannel channel; + + public ChannelSectionHandler(String anIdentifier) { + channel = new RSSChannel(anIdentifier); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + currentTag = aTag; + if (currentTag.equals("items")) { + return new ChannelItemsSectionHandler(); + } + else if (currentTag.equals("description") || + currentTag.equals("link") || + currentTag.equals("title")) { + return new PCDATASectionHandler(); + } + + return new DiscardingSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (currentTag.equals("items")) { + channel.setItems(((ChannelItemsSectionHandler) aHandler).getItems()); + } + if (currentTag.equals("description")) { + channel.setDescription(((PCDATASectionHandler) aHandler).getData()); + } + else if (currentTag.equals("title")) { + channel.setTitle(((PCDATASectionHandler) aHandler).getData()); + } + else if (currentTag.equals("link")) { + channel.setLink(((PCDATASectionHandler) aHandler).getData()); + } + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + if (aCharacters.trim().length()>0) + throw new XMLReader.XMLReaderExc("No character data allowed here"); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + + public RSSChannel getChannel () { + return channel; + } + } + + private static class ChannelItemsSectionHandler extends XMLReader.AbstractSectionHandler { + private List items; + + public ChannelItemsSectionHandler() { + items = new Vector(); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("rdf:Seq")) + return new RDFSequenceSectionHandler(); + else + return new DiscardingSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (aHandler instanceof RDFSequenceSectionHandler) { + items.addAll(((RDFSequenceSectionHandler) aHandler).getItems()); + } + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + if (aCharacters.trim().length()>0) + throw new XMLReader.XMLReaderExc("No character data allowed here"); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + + public List getItems() { + return items; + } + } + + private static class ItemSectionHandler extends XMLReader.AbstractSectionHandler { + private String currentTag; + private RSSItem item; + + public ItemSectionHandler(String anIdentifier) { + item = new RSSItem(anIdentifier); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + currentTag = aTag; + + if (currentTag.equals("description") || + currentTag.equals("link") || + currentTag.equals("title")) { + return new PCDATASectionHandler(); + } + + return new DiscardingSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (currentTag.equals("description")) { + item.setDescription(((PCDATASectionHandler) aHandler).getData()); + } + else if (currentTag.equals("title")) { + item.setTitle(((PCDATASectionHandler) aHandler).getData()); + } + else if (currentTag.equals("link")) { + item.setLink(((PCDATASectionHandler) aHandler).getData()); + } + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + if (aCharacters.trim().length()>0) + throw new XMLReader.XMLReaderExc("No character data allowed here"); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + + public RSSItem getItem() { + return item; + }; + } + + private static class PCDATASectionHandler extends XMLReader.AbstractSectionHandler { + private StringBuffer data; + + public PCDATASectionHandler() { + data = new StringBuffer(); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + throw new XMLReader.XMLReaderFailure(new RSSExc("No subtags allowed here")); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + data.append(aCharacters); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + + public String getData() { + return data.toString(); + } + } + + + private static class RDFSequenceSectionHandler extends XMLReader.AbstractSectionHandler { + private List items; + + public RDFSequenceSectionHandler() { + items = new Vector(); + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + if (aTag.equals("rdf:li")) { + String item = (String) anAttributes.get("rdf:resource"); + + if (item!=null) + items.add(item); + } + + return new DiscardingSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + + public List getItems() { + return items; + } + } + + private static class RDFLiteralSectionHandler extends XMLReader.AbstractSectionHandler { + private StringBuffer data; + private String tag; + + public RDFLiteralSectionHandler() { + data = new StringBuffer(); + } + + protected StringBuffer getData() { + return data; + } + + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + tag=aTag; + data.append("<"+tag+">"); + + return new RDFLiteralSectionHandler(); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + data.append(((RDFLiteralSectionHandler) aHandler).getData()); + data.append(""); + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + data.append(aCharacters); + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + } + + private static class DiscardingSectionHandler extends XMLReader.AbstractSectionHandler { + public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + return this; + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + }; + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + }; + + public void finishSection() throws XMLReader.XMLReaderExc { + }; + } +} diff --git a/source/mir/rss/RSSToMapConverter.java b/source/mir/rss/RSSToMapConverter.java index 36b8461a..2aa25433 100755 --- a/source/mir/rss/RSSToMapConverter.java +++ b/source/mir/rss/RSSToMapConverter.java @@ -1,77 +1,77 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.rss; - -import java.util.*; - -public class RSSToMapConverter { - private RSSToMapConverter() { - } - - public static Map convertRSSItem(RSSItem anItem) { - Map result = new HashMap(); - - result.put("title", anItem.getTitle()); - result.put("description", anItem.getDescription()); - result.put("link", anItem.getLink()); - - return result; - } - - public static Map convertRSSData(RSSData anRSSData) { - Map result = new HashMap(); - - Map channel = null; - if (anRSSData.getChannel()!=null) { - channel = new HashMap(); - channel.put("title", anRSSData.getChannel().getTitle()); - channel.put("description", anRSSData.getChannel().getDescription()); - channel.put("link", anRSSData.getChannel().getLink()); - - List items = new Vector(); - Iterator i = anRSSData.getChannel().getItems().iterator(); - - while (i.hasNext()) { - RSSItem item = (RSSItem) anRSSData.getItem().get(i.next()); - if (item!=null) { - items.add(convertRSSItem(item)); - } - } - - channel.put("items", items); - } - result.put("channel", channel); - result.put("data", anRSSData); - - return result; - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.rss; + +import java.util.*; + +public class RSSToMapConverter { + private RSSToMapConverter() { + } + + public static Map convertRSSItem(RSSItem anItem) { + Map result = new HashMap(); + + result.put("title", anItem.getTitle()); + result.put("description", anItem.getDescription()); + result.put("link", anItem.getLink()); + + return result; + } + + public static Map convertRSSData(RSSData anRSSData) { + Map result = new HashMap(); + + Map channel = null; + if (anRSSData.getChannel()!=null) { + channel = new HashMap(); + channel.put("title", anRSSData.getChannel().getTitle()); + channel.put("description", anRSSData.getChannel().getDescription()); + channel.put("link", anRSSData.getChannel().getLink()); + + List items = new Vector(); + Iterator i = anRSSData.getChannel().getItems().iterator(); + + while (i.hasNext()) { + RSSItem item = (RSSItem) anRSSData.getItem().get(i.next()); + if (item!=null) { + items.add(convertRSSItem(item)); + } + } + + channel.put("items", items); + } + result.put("channel", channel); + result.put("data", anRSSData); + + return result; + } } \ No newline at end of file diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index ecae5357..f114804d 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -1,495 +1,493 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.servlet; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import freemarker.template.SimpleHash; -import freemarker.template.TemplateModelRoot; -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.LineFilterWriter; -import mir.module.AbstractModule; -import mir.storage.StorageObject; -import mir.util.HTTPRequestParser; - - - - -/** - * Abstract class ServletModule provides the base functionality for servlets. - * Deriving a class from ServletModule enables class to insert/edit/update/delete - * and list Entity from a Database via mainModule. - * - * - * Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der - * abgeleiteten ServletModule zur Verf?gung. - * - * @version 28.6.1999 - * @author RK - */ - -public abstract class ServletModule { - - public String defaultAction; - protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; - protected AbstractModule mainModule; - protected String templateListString; - protected String templateObjektString; - protected String templateConfirmString; - - - public ServletModule(){ - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException("Can't get configuration: " + e.getMessage()); - } - } - - - /** - * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden. - * @return ServletModule - */ - public static ServletModule getInstance() { - return null; - } - - /** - * get the module name to be used for generic operations like delete. - */ - protected String getOperationModuleName() { - return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length()); - } - - /** - * get the session binded language - */ - public String getLanguage(HttpServletRequest req) { - HttpSession session = req.getSession(false); - String language = (String) session.getAttribute("language"); - if (language == null) { - language = configuration.getString("StandardLanguage"); - } - return language; - } - - /** - * get the locale either from the session or the accept-language header ot the request - * this supersedes getLanguage for the new i18n - */ - public Locale getLocale(HttpServletRequest req) { - Locale loc = null; - HttpSession session = req.getSession(false); - if (session != null) { - // session can be null in case of logout - loc = (Locale) session.getAttribute("locale"); - } - // if there is nothing in the session get it fron the accept-language - if (loc == null) { - loc = req.getLocale(); - } - return loc; - } - - public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { - try { - aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); - } - } - - /** - * list(req,res) - generische Listmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void list(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - EntityList theList; - String offsetParam = req.getParameter("offset"); - int offset = 0; - PrintWriter out = res.getWriter(); - - // hier offsetcode bearbeiten - if (offsetParam != null && !offsetParam.equals("")) { - offset = Integer.parseInt(offsetParam); - } - if (req.getParameter("next") != null) { - offset = Integer.parseInt(req.getParameter("nextoffset")); - } - else { - if (req.getParameter("prev") != null) { - offset = Integer.parseInt(req.getParameter("prevoffset")); - } - } - theList = mainModule.getByWhereClause(null, offset); - - HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req)); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * add(req,res) - generische Addmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void add(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - - try { - SimpleHash mergeData = new SimpleHash(); - mergeData.put("new", "1"); - deliver(req, res, mergeData, templateObjektString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * insert(req,res) - generische Insertmethode, folgt auf add. - * Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void insert(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); - logger.debug("--trying to add..."); - String id = mainModule.add(withValues); - logger.debug("--trying to deliver..." + id); - list(req, res); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * delete(req,res) - generic delete method. Can be overridden in subclasses. - * - */ - - public void delete(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - String idParam = req.getParameter("id"); - - if (idParam == null) - throw new ServletModuleExc("Invalid call to delete: no id supplied"); - - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - if (confirmParam == null && cancelParam == null) { - SimpleHash mergeData = new SimpleHash(); - - mergeData.put("module", getOperationModuleName()); - mergeData.put("infoString", getOperationModuleName() + ": " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - // this stuff is to be compatible with the other more advanced - // search method used for media and comments - mergeData.put("query_media_folder", req.getParameter("query_media_folder")); - mergeData.put("query_is_published", req.getParameter("query_is_published")); - mergeData.put("query_text", req.getParameter("query_text")); - mergeData.put("query_field", req.getParameter("query_field")); - - deliver(req, res, mergeData, templateConfirmString); - } - else { - if (confirmParam != null && !confirmParam.equals("")) { - //theLog.printInfo("delete confirmed!"); - mainModule.deleteById(idParam); - list(req, res); // back to list - } - else { - if (req.getParameter("where") != null) - list(req, res); - else - edit(req, res); - } - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void edit(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - edit(req, res, req.getParameter("id")); - } - - /** - * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * update(req,res) - generische Updatemethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - - public void update(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - String idParam = req.getParameter("id"); - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); - - String id = mainModule.set(withValues); - String whereParam = req.getParameter("where"); - String orderParam = req.getParameter("order"); - - if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) { - list(req, res); - } - else { - edit(req, res); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, - TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure { - if (rtm == null) - rtm = new SimpleHash(); - - try { - PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req)); - - // we default to admin bundles here, which is not exactly beautiful... - // but this whole producer stuff is going to be rewritten soon. - // ServletModuleOpenIndy overwrites deliver() to use open bundles - // (br1) - out.close(); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure { - deliver(req, res, rtm, null, templateFilename); - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver_compressed(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { - if (rtm == null) rtm = new SimpleHash(); - try { - PrintWriter out = new LineFilterWriter(res.getWriter()); - //PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req)); - out.close(); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen. - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { - try { - HTMLTemplateProcessor.process(res, templateFilename, rtm, out, - getLocale(req)); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem - * Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des - * doParameters ausgefuehrt. - * - * @return Name der Default-Action - */ - public String defaultAction() { - return defaultAction; - } - - /** - * Gets the fields from a httprequest and matches them with the metadata from - * the storage object. Returns the keys that match, with their values. - * - * @return Map with the values - */ - public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage) - throws ServletModuleExc, ServletModuleFailure { - - try { - HTTPRequestParser parser; - List theFieldList; - - logger.debug("using charset: " + req.getParameter("charset")); - logger.debug("using method: " + req.getParameter("do")); - if (req.getParameter("charset") != null) { - parser = new HTTPRequestParser(req, req.getParameter("charset")); - logger.debug("using charset: " + req.getParameter("charset")); - logger.debug("original charset: " + req.getCharacterEncoding()); - } - else { - parser = new HTTPRequestParser(req); - } - - theFieldList = theStorage.getFields(); - - Map withValues = new HashMap(); - String aField, aValue; - - for (int i = 0; i < theFieldList.size(); i++) { - aField = (String) theFieldList.get(i); - - logger.debug("field " + aField + " = " + parser.getParameter(aField)); - - aValue = parser.getParameter(aField); - if (aValue != null) - withValues.put(aField, aValue); - } - return withValues; - } - catch (Throwable e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e); - } - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.servlet; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import freemarker.template.SimpleHash; +import freemarker.template.TemplateModelRoot; +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration$PropertiesConfigExc; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.misc.LineFilterWriter; +import mir.module.AbstractModule; +import mir.storage.StorageObject; +import mir.util.HTTPRequestParser; + + + + +/** + * Abstract class ServletModule provides the base functionality for servlets. + * Deriving a class from ServletModule enables class to insert/edit/update/delete + * and list Entity from a Database via mainModule. + * + * + * Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der + * abgeleiteten ServletModule zur Verf?gung. + * + * @version 28.6.1999 + * @author RK + */ + +public abstract class ServletModule { + + public String defaultAction; + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected AbstractModule mainModule; + protected Locale fallbackLocale; + protected String templateListString; + protected String templateObjektString; + protected String templateConfirmString; + + + public ServletModule(){ + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new RuntimeException("Can't get configuration: " + e.getMessage()); + } + + fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), ""); + } + + + /** + * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden. + * @return ServletModule + */ + public static ServletModule getInstance() { + return null; + } + + /** + * get the module name to be used for generic operations like delete. + */ + protected String getOperationModuleName() { + return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length()); + } + + /** + * get the locale either from the session or the accept-language header ot the request + * this supersedes getLanguage for the new i18n + */ + public Locale getLocale(HttpServletRequest req) { + Locale loc = null; + HttpSession session = req.getSession(false); + if (session != null) { + // session can be null in case of logout + loc = (Locale) session.getAttribute("locale"); + } + // if there is nothing in the session get it fron the accept-language + if (loc == null) { + loc = req.getLocale(); + } + return loc; + } + + /** + * get the locale either from the session or the accept-language header ot the request + * this supersedes getLanguage for the new i18n + */ + public Locale getFallbackLocale(HttpServletRequest req) { + return fallbackLocale; + } + + public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { + try { + aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery); + } + catch (Throwable t) { + throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); + } + } + + /** + * list(req,res) - generische Listmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void list(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + EntityList theList; + String offsetParam = req.getParameter("offset"); + int offset = 0; + PrintWriter out = res.getWriter(); + + // hier offsetcode bearbeiten + if (offsetParam != null && !offsetParam.equals("")) { + offset = Integer.parseInt(offsetParam); + } + if (req.getParameter("next") != null) { + offset = Integer.parseInt(req.getParameter("nextoffset")); + } + else { + if (req.getParameter("prev") != null) { + offset = Integer.parseInt(req.getParameter("prevoffset")); + } + } + theList = mainModule.getByWhereClause(null, offset); + + HTMLTemplateProcessor.process(res, templateListString, theList, null, null, out, getLocale(req), getFallbackLocale(req)); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * add(req,res) - generische Addmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void add(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + + try { + SimpleHash mergeData = new SimpleHash(); + mergeData.put("new", "1"); + deliver(req, res, mergeData, templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * insert(req,res) - generische Insertmethode, folgt auf add. + * Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void insert(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); + logger.debug("--trying to add..."); + String id = mainModule.add(withValues); + logger.debug("--trying to deliver..." + id); + list(req, res); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * delete(req,res) - generic delete method. Can be overridden in subclasses. + * + */ + + public void delete(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + String idParam = req.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("Invalid call to delete: no id supplied"); + + String confirmParam = req.getParameter("confirm"); + String cancelParam = req.getParameter("cancel"); + if (confirmParam == null && cancelParam == null) { + SimpleHash mergeData = new SimpleHash(); + + mergeData.put("module", getOperationModuleName()); + mergeData.put("infoString", getOperationModuleName() + ": " + idParam); + mergeData.put("id", idParam); + mergeData.put("where", req.getParameter("where")); + mergeData.put("order", req.getParameter("order")); + mergeData.put("offset", req.getParameter("offset")); + // this stuff is to be compatible with the other more advanced + // search method used for media and comments + mergeData.put("query_media_folder", req.getParameter("query_media_folder")); + mergeData.put("query_is_published", req.getParameter("query_is_published")); + mergeData.put("query_text", req.getParameter("query_text")); + mergeData.put("query_field", req.getParameter("query_field")); + + deliver(req, res, mergeData, templateConfirmString); + } + else { + if (confirmParam != null && !confirmParam.equals("")) { + //theLog.printInfo("delete confirmed!"); + mainModule.deleteById(idParam); + list(req, res); // back to list + } + else { + if (req.getParameter("where") != null) + list(req, res); + else + edit(req, res); + } + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void edit(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + edit(req, res, req.getParameter("id")); + } + + /** + * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * update(req,res) - generische Updatemethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + + public void update(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + String idParam = req.getParameter("id"); + Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); + + String id = mainModule.set(withValues); + String whereParam = req.getParameter("where"); + String orderParam = req.getParameter("order"); + + if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) { + list(req, res); + } + else { + edit(req, res); + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, + TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure { + if (rtm == null) + rtm = new SimpleHash(); + + try { + PrintWriter out = res.getWriter(); + HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req), getFallbackLocale(req)); + + // we default to admin bundles here, which is not exactly beautiful... + // but this whole producer stuff is going to be rewritten soon. + // ServletModuleOpenIndy overwrites deliver() to use open bundles + // (br1) + out.close(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure { + deliver(req, res, rtm, null, templateFilename); + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver_compressed(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, String templateFilename) + throws ServletModuleFailure { + if (rtm == null) rtm = new SimpleHash(); + try { + PrintWriter out = new LineFilterWriter(res.getWriter()); + //PrintWriter out = res.getWriter(); + HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req)); + out.close(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen. + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out, + TemplateModelRoot rtm, String templateFilename) + throws ServletModuleFailure { + try { + HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req)); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem + * Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des + * doParameters ausgefuehrt. + * + * @return Name der Default-Action + */ + public String defaultAction() { + return defaultAction; + } + + /** + * Gets the fields from a httprequest and matches them with the metadata from + * the storage object. Returns the keys that match, with their values. + * + * @return Map with the values + */ + public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage) + throws ServletModuleExc, ServletModuleFailure { + + try { + HTTPRequestParser parser; + List theFieldList; + + logger.debug("using charset: " + req.getParameter("charset")); + logger.debug("using method: " + req.getParameter("do")); + if (req.getParameter("charset") != null) { + parser = new HTTPRequestParser(req, req.getParameter("charset")); + logger.debug("using charset: " + req.getParameter("charset")); + logger.debug("original charset: " + req.getCharacterEncoding()); + } + else { + parser = new HTTPRequestParser(req); + } + + theFieldList = theStorage.getFields(); + + Map withValues = new HashMap(); + String aField, aValue; + + for (int i = 0; i < theFieldList.size(); i++) { + aField = (String) theFieldList.get(i); + + logger.debug("field " + aField + " = " + parser.getParameter(aField)); + + aValue = parser.getParameter(aField); + if (aValue != null) + withValues.put(aField, aValue); + } + return withValues; + } + catch (Throwable e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e); + } + } + +} diff --git a/source/mir/servlet/ServletModuleShow.java b/source/mir/servlet/ServletModuleShow.java index d3d376d5..7d7f8ba2 100755 --- a/source/mir/servlet/ServletModuleShow.java +++ b/source/mir/servlet/ServletModuleShow.java @@ -1,105 +1,105 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.servlet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import freemarker.template.TemplateModelRoot; - - -/** - * Standard ServletModule, dass eine Template anzeigt, und nicht - * mit Daten mischt. Damit ist es moeglich, einfache HTML-Seiten - * als templates zu benutzen. Damit kann auf einfache Weise die - * Funktionalitaet der Freemarker-Bibliothek (beispielsweise Navigationen - * per include einzubauen) benutzt werden. Die Templates - * werden aus dem per Konfiguration angegebenem template-Verzeichnis - * im Ordner "/html" genommen. - * - * @author RK - */ -public class ServletModuleShow extends ServletModule { - private static ServletModuleShow instance = new ServletModuleShow(); - - /** - * Ein ServletModuleShow-Objekt wird ?ber getInstance geliefert. Es gibt zur - * Laufzeit nur ein Objekt (Singleton) - * @return ServletModuleShow - */ - public static ServletModule getInstance() { - return instance; - } - - /** - * Initialisierung leer. - */ - private ServletModuleShow() { - } - - /** - * defaultAction (s.a ServletModule) - * @return "show" - */ - public String defaultAction() { - return "show"; - } - - /** - * Standardmethode, die die Funktionalitaet des ServletModules implementiert. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @return String fuer Logfile - * @exception ServletModuleException - */ - public void show(HttpServletRequest req, HttpServletResponse res) throws - ServletModuleExc { - try { - String idParam = req.getParameter("tmpl"); - if (! (idParam == null || idParam.equals(""))) { - deliver(req, res, (TemplateModelRoot)null, - "html/" + idParam + ".template"); - } - else { - throw new ServletModuleExc("Invalid template: " + idParam); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } -} - - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.servlet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import freemarker.template.TemplateModelRoot; + + +/** + * Standard ServletModule, dass eine Template anzeigt, und nicht + * mit Daten mischt. Damit ist es moeglich, einfache HTML-Seiten + * als templates zu benutzen. Damit kann auf einfache Weise die + * Funktionalitaet der Freemarker-Bibliothek (beispielsweise Navigationen + * per include einzubauen) benutzt werden. Die Templates + * werden aus dem per Konfiguration angegebenem template-Verzeichnis + * im Ordner "/html" genommen. + * + * @author RK + */ +public class ServletModuleShow extends ServletModule { + private static ServletModuleShow instance = new ServletModuleShow(); + + /** + * Ein ServletModuleShow-Objekt wird ?ber getInstance geliefert. Es gibt zur + * Laufzeit nur ein Objekt (Singleton) + * @return ServletModuleShow + */ + public static ServletModule getInstance() { + return instance; + } + + /** + * Initialisierung leer. + */ + private ServletModuleShow() { + } + + /** + * defaultAction (s.a ServletModule) + * @return "show" + */ + public String defaultAction() { + return "show"; + } + + /** + * Standardmethode, die die Funktionalitaet des ServletModules implementiert. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @return String fuer Logfile + * @exception ServletModuleException + */ + public void show(HttpServletRequest req, HttpServletResponse res) throws + ServletModuleExc { + try { + String idParam = req.getParameter("tmpl"); + if (! (idParam == null || idParam.equals(""))) { + deliver(req, res, (TemplateModelRoot)null, + "html/" + idParam + ".template"); + } + else { + throw new ServletModuleExc("Invalid template: " + idParam); + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } +} + + + + diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index 66211910..16b88e56 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -1,1451 +1,1451 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ -package mir.storage; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.entity.StorableObjectEntity; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; -import mir.storage.store.ObjectStore; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; -import mir.util.JDBCStringRoutines; - -import com.codestudio.util.SQLManager; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - - -/** - * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. - * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. - * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. - * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten - * Treiber, Host, User und Passwort, ueber den der Zugriff auf die - * Datenbank erfolgt. - * - * @version $Id: Database.java,v 1.36 2003/03/05 19:23:15 idfx Exp $ - * @author rk - * - */ -public class Database implements StorageObject { - private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; - private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; - - - private static SimpleHash POPUP_EMPTYLINE = new SimpleHash(); - protected static final ObjectStore o_store = ObjectStore.getInstance(); - private static final int _millisPerHour = 60 * 60 * 1000; - private static final int _millisPerMinute = 60 * 1000; - - static { - // always same object saves a little space - POPUP_EMPTYLINE.put("key", ""); - POPUP_EMPTYLINE.put("value", "--"); - } - - protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; - protected String theTable; - protected String theCoreTable = null; - protected String thePKeyName = "id"; - protected int thePKeyType; - protected int thePKeyIndex; - protected boolean evaluatedMetaData = false; - protected ArrayList metadataFields; - protected ArrayList metadataLabels; - protected ArrayList metadataNotNullFields; - protected int[] metadataTypes; - protected Class theEntityClass; - protected StorageObject myselfDatabase; - protected SimpleList popupCache = null; - protected boolean hasPopupCache = false; - protected SimpleHash hashCache = null; - protected boolean hasTimestamp = true; - private String database_driver; - private String database_url; - private int defaultLimit; - protected DatabaseAdaptor theAdaptor; - private SimpleDateFormat _dateFormatterOut = - new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - private SimpleDateFormat _dateFormatterIn = - new SimpleDateFormat("yyyy-MM-dd HH:mm"); - private Calendar _cal = new GregorianCalendar(); - - /** - * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. - * Aus diesem file werden Database.Logfile, - * Database.Username,Database.Password, - * Database.Host und Database.Adaptor - * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank - * erzeugt. - * - * @param String confFilename Dateiname der Konfigurationsdatei - */ - public Database() throws StorageObjectFailure { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new StorageObjectFailure(e); - } - logger = new LoggerWrapper("Database"); - - String theAdaptorName = configuration.getString("Database.Adaptor"); - defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); - - try { - theEntityClass = GENERIC_ENTITY_CLASS; - theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance(); - } - catch (Throwable e) { - logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); - throw new StorageObjectFailure("Error in Database() constructor.", e); - } - } - - /** - * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt - * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, - * wird eine mir.entity.GenericEntity erzeugt. - * - * @return Class-Objekt der Entity - */ - public java.lang.Class getEntityClass() { - return theEntityClass; - } - - /** - * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also - * wieviel Datens?tze per Default selektiert werden. - * - * @return Standard-Anzahl der Datens?tze - */ - public int getLimit() { - return defaultLimit; - } - - /** - * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von - * der erbenden Klasse ?berschrieben, so ist der Wert PKEY - * @return Name des Primary-Keys - */ - public String getIdName() { - return thePKeyName; - } - - /** - * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. - * - * @return Name der Tabelle - */ - public String getTableName() { - return theTable; - } - - /* - * Dient dazu vererbte Tabellen bei objectrelationalen DBMS - * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet - * wird. - * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst - * the Table - */ - public String getCoreTable() { - if (theCoreTable != null) { - return theCoreTable; - } else { - return theTable; - } - } - - /** - * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) - * @return int-Array mit den Typen der Felder - * @exception StorageObjectException - */ - public int[] getTypes() throws StorageObjectFailure { - if (metadataTypes == null) { - get_meta_data(); - } - - return metadataTypes; - } - - /** - * Liefert eine Liste der Labels der Tabellenfelder - * @return ArrayListe mit Labeln - * @exception StorageObjectException - */ - public List getLabels() throws StorageObjectFailure { - if (metadataLabels == null) { - get_meta_data(); - } - - return metadataLabels; - } - - /** - * Liefert eine Liste der Felder der Tabelle - * @return ArrayList mit Feldern - * @exception StorageObjectException - */ - public List getFields() throws StorageObjectFailure { - if (metadataFields == null) { - get_meta_data(); - } - - return metadataFields; - } - - /* - * Gets value out of ResultSet according to type and converts to String - * @param inValue Wert aus ResultSet. - * @param aType Datenbanktyp. - * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich - * dann /unsupported value/ - */ - private String getValueAsString(ResultSet rs, int valueIndex, int aType) - throws StorageObjectFailure { - String outValue = null; - - if (rs != null) { - try { - switch (aType) { - case java.sql.Types.BIT: - outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; - - break; - - case java.sql.Types.INTEGER: - case java.sql.Types.SMALLINT: - case java.sql.Types.TINYINT: - case java.sql.Types.BIGINT: - - int out = rs.getInt(valueIndex); - - if (!rs.wasNull()) { - outValue = new Integer(out).toString(); - } - - break; - - case java.sql.Types.NUMERIC: - - /** @todo Numeric can be float or double depending upon - * metadata.getScale() / especially with oracle */ - long outl = rs.getLong(valueIndex); - - if (!rs.wasNull()) { - outValue = new Long(outl).toString(); - } - - break; - - case java.sql.Types.REAL: - - float tempf = rs.getFloat(valueIndex); - - if (!rs.wasNull()) { - tempf *= 10; - tempf += 0.5; - - int tempf_int = (int) tempf; - tempf = (float) tempf_int; - tempf /= 10; - outValue = "" + tempf; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.DOUBLE: - - double tempd = rs.getDouble(valueIndex); - - if (!rs.wasNull()) { - tempd *= 10; - tempd += 0.5; - - int tempd_int = (int) tempd; - tempd = (double) tempd_int; - tempd /= 10; - outValue = "" + tempd; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.CHAR: - case java.sql.Types.VARCHAR: - case java.sql.Types.LONGVARCHAR: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.LONGVARBINARY: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.TIMESTAMP: - - // it's important to use Timestamp here as getting it - // as a string is undefined and is only there for debugging - // according to the API. we can make it a string through formatting. - // -mh - Timestamp timestamp = (rs.getTimestamp(valueIndex)); - - if (!rs.wasNull()) { - java.util.Date date = new java.util.Date(timestamp.getTime()); - outValue = _dateFormatterOut.format(date); - _cal.setTime(date); - - int offset = - _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET); - String tzOffset = - StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2); - outValue = outValue + "+" + tzOffset; - } - - break; - - default: - outValue = ""; - logger.warn( "Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); - } - } catch (SQLException e) { - throw new StorageObjectFailure("Could not get Value out of Resultset -- ", - e); - } - } - - return outValue; - } - - /* - * select-Operator um einen Datensatz zu bekommen. - * @param id Primaerschluessel des Datensatzes. - * @return liefert EntityObject des gefundenen Datensatzes oder null. - */ - public Entity selectById(String id) throws StorageObjectExc { - if ((id == null) || id.equals("")) { - throw new StorageObjectExc("Database.selectById: Missing id"); - } - - // ask object store for object - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId); - logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString()); - - Entity hit = (Entity) o_store.use(search_sid); - - if (hit != null) { - return hit; - } - } - - Statement stmt = null; - Connection con = getPooledCon(); - Entity returnEntity = null; - - try { - ResultSet rs; - - /** @todo better prepared statement */ - String selectSql = - "select * from " + theTable + " where " + thePKeyName + "=" + id; - stmt = con.createStatement(); - rs = executeSql(stmt, selectSql); - - if (rs != null) { - if (evaluatedMetaData == false) { - evalMetaData(rs.getMetaData()); - } - - if (rs.next()) { - returnEntity = makeEntityFromResultSet(rs); - } - else { - logger.debug("No data for id: " + id + " in table " + theTable); - } - - rs.close(); - } - else { - logger.debug("No Data for Id " + id + " in Table " + theTable); - } - } - catch (SQLException sqe) { - throwSQLException(sqe, "selectById"); - return null; - } - catch (NumberFormatException e) { - logger.error("ID is no number: " + id); - } - finally { - freeConnection(con, stmt); - } - - return returnEntity; - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { - return selectByFieldValue(aField, aValue, 0); - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { - return selectByWhereClause(aField + "=" + aValue, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * - * @param wc where-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where) - throws StorageObjectFailure { - return selectByWhereClause(where, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param offset ab welchem Datensatz. - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, int offset) - throws StorageObjectFailure { - return selectByWhereClause(whereClause, null, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where, String order) - throws StorageObjectFailure { - return selectByWhereClause(where, order, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @param offset ab welchem Datensatz - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, String orderBy, - int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * @param wc where-Clause - * @param ob orderBy-Clause - * @param offset ab welchem Datensatz - * @param limit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String wc, String ob, int offset, - int limit) throws StorageObjectFailure { - // check o_store for entitylist - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST, - StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset, - limit)); - EntityList hit = (EntityList) o_store.use(search_sid); - - if (hit != null) { - logger.debug("CACHE (hit): " + search_sid.toString()); - - return hit; - } - } - - // local - EntityList theReturnList = null; - Connection con = null; - Statement stmt = null; - ResultSet rs; - int offsetCount = 0; - int count = 0; - - // build sql-statement - - /** @todo count sql string should only be assembled if we really count - * see below at the end of method //rk */ - if ((wc != null) && (wc.trim().length() == 0)) { - wc = null; - } - - StringBuffer countSql = - new StringBuffer("select count(*) from ").append(theTable); - StringBuffer selectSql = - new StringBuffer("select * from ").append(theTable); - - if (wc != null) { - selectSql.append(" where ").append(wc); - countSql.append(" where ").append(wc); - } - - if ((ob != null) && !(ob.trim().length() == 0)) { - selectSql.append(" order by ").append(ob); - } - - if (theAdaptor.hasLimit()) { - if ((limit > -1) && (offset > -1)) { - selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); - } - } - - // execute sql - try { - con = getPooledCon(); - stmt = con.createStatement(); - - // selecting... - rs = executeSql(stmt, selectSql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - evalMetaData(rs.getMetaData()); - } - - theReturnList = new EntityList(); - - Entity theResultEntity; - - while (rs.next()) { - theResultEntity = makeEntityFromResultSet(rs); - theReturnList.add(theResultEntity); - offsetCount++; - } - - rs.close(); - } - - // making entitylist infos - if (!(theAdaptor.hasLimit())) { - count = offsetCount; - } - - if (theReturnList != null) { - // now we decide if we have to know an overall count... - count = offsetCount; - - if ((limit > -1) && (offset > -1)) { - if (offsetCount == limit) { - /** @todo counting should be deffered to entitylist - * getSize() should be used */ - rs = executeSql(stmt, countSql.toString()); - - if (rs != null) { - if (rs.next()) { - count = rs.getInt(1); - } - - rs.close(); - } - else { - logger.error("Could not count: " + countSql); - } - } - } - - theReturnList.setCount(count); - theReturnList.setOffset(offset); - theReturnList.setWhere(wc); - theReturnList.setOrder(ob); - theReturnList.setStorage(this); - theReturnList.setLimit(limit); - - if (offset >= limit) { - theReturnList.setPrevBatch(offset - limit); - } - - if ((offset + offsetCount) < count) { - theReturnList.setNextBatch(offset + limit); - } - - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier sid = theReturnList.getStoreIdentifier(); - logger.debug("CACHE (add): " + sid.toString()); - o_store.add(sid); - } - } - } catch (SQLException sqe) { - throwSQLException(sqe, "selectByWhereClause"); - } finally { - try { - if (con != null) { - freeConnection(con, stmt); - } - } catch (Throwable t) { - } - } - - return theReturnList; - } - - /** - * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. - * - * @param rs Das ResultSetObjekt. - * @return Entity Die Entity. - */ - private Entity makeEntityFromResultSet(ResultSet rs) - throws StorageObjectFailure { - /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ - Map theResultHash = new HashMap(); - String theResult = null; - int theType; - Entity returnEntity = null; - - try { - int size = metadataFields.size(); - - for (int i = 0; i < size; i++) { - // alle durchlaufen bis nix mehr da - theType = metadataTypes[i]; - - if (theType == java.sql.Types.LONGVARBINARY) { - InputStreamReader is = - (InputStreamReader) rs.getCharacterStream(i + 1); - - if (is != null) { - char[] data = new char[32768]; - StringBuffer theResultString = new StringBuffer(); - int len; - - while ((len = is.read(data)) > 0) { - theResultString.append(data, 0, len); - } - - is.close(); - theResult = theResultString.toString(); - } else { - theResult = null; - } - } else { - theResult = getValueAsString(rs, (i + 1), theType); - } - - if (theResult != null) { - theResultHash.put(metadataFields.get(i), theResult); - } - } - - if (theEntityClass != null) { - returnEntity = (Entity) theEntityClass.newInstance(); - returnEntity.setValues(theResultHash); - returnEntity.setStorage(myselfDatabase); - - if (returnEntity instanceof StorableObject) { - logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable); - o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); - } - } else { - throwStorageObjectException("Internal Error: theEntityClass not set!"); - } - } catch (IllegalAccessException e) { - throwStorageObjectException("No access! -- " + e.getMessage()); - } catch (IOException e) { - throwStorageObjectException("IOException! -- " + e.getMessage()); - } catch (InstantiationException e) { - throwStorageObjectException("No Instatiation! -- " + e.getMessage()); - } catch (SQLException sqe) { - throwSQLException(sqe, "makeEntityFromResultSet"); - - return null; - } - - return returnEntity; - } - - /** - * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE - * wird automatisch mit dem aktuellen Datum gefuellt. - * - * @param theEntity - * @return der Wert des Primary-keys der eingef?gten Entity - */ - public String insert(Entity theEntity) throws StorageObjectFailure { - //cache - invalidatePopupCache(); - - // invalidating all EntityLists corresponding with theEntityClass - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - String returnId = null; - Connection con = null; - PreparedStatement pstmt = null; - - try { - List streamedInput = theEntity.streamedInput(); - StringBuffer f = new StringBuffer(); - StringBuffer v = new StringBuffer(); - String aField; - String aValue; - boolean firstField = true; - - // make sql-string - for (int i = 0; i < getFields().size(); i++) { - aField = (String) getFields().get(i); - - if (!aField.equals(thePKeyName)) { - aValue = null; - - // exceptions - if (aField.equals("webdb_create") || - aField.equals("webdb_lastchange")) { - aValue = "NOW()"; - } else { - if ((streamedInput != null) && streamedInput.contains(aField)) { - aValue = "?"; - } else { - if (theEntity.hasValueForField(aField)) { - aValue = - "'" + - JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue( - aField)) + "'"; - } - } - } - - // wenn Wert gegeben, dann einbauen - if (aValue != null) { - if (firstField == false) { - f.append(","); - v.append(","); - } - else { - firstField = false; - } - - f.append(aField); - v.append(aValue); - } - } - } - // end for - - // insert into db - StringBuffer sqlBuf = - new StringBuffer("insert into ").append(theTable).append("(").append(f) - .append(") values (").append(v).append(")"); - String sql = sqlBuf.toString(); - - //theLog.printInfo("INSERT: " + sql); - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - (String) theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - int ret = pstmt.executeUpdate(); - - if (ret == 0) { - //insert failed - return null; - } - - pstmt = - con.prepareStatement(theAdaptor.getLastInsertSQL( - (Database) myselfDatabase)); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - returnId = rs.getString(1); - theEntity.setId(returnId); - } - catch (SQLException sqe) { - throwSQLException(sqe, "insert"); - } - finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - } - - freeConnection(con, pstmt); - } - - /** @todo store entity in o_store */ - return returnId; - } - - /** - * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE - * wird automatisch mit dem aktuellen Datum gefuellt. - * - * @param theEntity - */ - public void update(Entity theEntity) throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - - /** @todo this is stupid: why do we prepare statement, when we - * throw it away afterwards. should be regular statement - * update/insert could better be one routine called save() - * that chooses to either insert or update depending if we - * have a primary key in the entity. i don't know if we - * still need the streamed input fields. // rk */ - /** @todo extension: check if Entity did change, otherwise we don't need - * the roundtrip to the database */ - /** invalidating corresponding entitylists in o_store*/ - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - List streamedInput = theEntity.streamedInput(); - String id = theEntity.getId(); - String aField; - StringBuffer fv = new StringBuffer(); - boolean firstField = true; - - //cache - invalidatePopupCache(); - - // build sql statement - for (int i = 0; i < getFields().size(); i++) { - aField = (String) metadataFields.get(i); - - // only normal cases - if ( !(aField.equals(thePKeyName) || - aField.equals("webdb_create") || - aField.equals("webdb_lastchange") || - ((streamedInput != null) && streamedInput.contains(aField)))) { - if (theEntity.hasValueForField(aField)) { - if (firstField == false) { - fv.append(", "); - } - else { - firstField = false; - } - - fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'"); - - // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); - } - } - } - - StringBuffer sql = - new StringBuffer("update ").append(theTable).append(" set ").append(fv); - - // exceptions - if (metadataFields.contains("webdb_lastchange")) { - sql.append(",webdb_lastchange=NOW()"); - } - - // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm - // format so anything extra will be ignored. -mh - if (metadataFields.contains("webdb_create") && - theEntity.hasValueForField("webdb_create")) { - // minimum of 10 (yyyy-mm-dd)... - if (theEntity.getValue("webdb_create").length() >= 10) { - String dateString = theEntity.getValue("webdb_create"); - - // if only 10, then add 00:00 so it doesn't throw a ParseException - if (dateString.length() == 10) { - dateString = dateString + " 00:00"; - } - - // TimeStamp stuff - try { - java.util.Date d = _dateFormatterIn.parse(dateString); - Timestamp tStamp = new Timestamp(d.getTime()); - sql.append(",webdb_create='" + tStamp.toString() + "'"); - } catch (ParseException e) { - throw new StorageObjectFailure(e); - } - } - } - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - sql.append(",").append(streamedInput.get(i)).append("=?"); - } - } - - sql.append(" where id=").append(id); - - //theLog.printInfo("UPDATE: " + sql); - // execute sql - try { - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - pstmt.executeUpdate(); - } catch (SQLException sqe) { - throwSQLException(sqe, "update"); - } finally { - try { - con.setAutoCommit(true); - } catch (Exception e) { - ; - } - - freeConnection(con, pstmt); - } - } - - /* - * delete-Operator - * @param id des zu loeschenden Datensatzes - * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. - */ - public boolean delete(String id) throws StorageObjectFailure { - invalidatePopupCache(); - - // ostore send notification - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - logger.debug("CACHE: (del) " + id); - - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITY, uniqueId); - o_store.invalidate(search_sid); - } - - /** @todo could be prepared Statement */ - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; - - //theLog.printInfo("DELETE " + sql); - try { - con = getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } catch (SQLException sqe) { - throwSQLException(sqe, "delete"); - } finally { - freeConnection(con, stmt); - } - - return (res > 0) ? true : false; - } - - /* noch nicht implementiert. - * @return immer false - */ - public boolean delete(EntityList theEntityList) { - invalidatePopupCache(); - - return false; - } - - /** - * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse - * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll. - * @return null - */ - public SimpleList getPopupData() throws StorageObjectFailure { - return null; - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, String where) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, where, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @param order Gibt ein Feld als Sortierkriterium an. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, - String where, String order) throws StorageObjectFailure { - // caching - if (hasPopupCache && (popupCache != null)) { - return popupCache; - } - - SimpleList simpleList = null; - Connection con = null; - Statement stmt = null; - - // build sql - StringBuffer sql = - new StringBuffer("select ").append(thePKeyName).append(",").append(name) - .append(" from ").append(theTable); - - if ((where != null) && !(where.length() == 0)) { - sql.append(" where ").append(where); - } - - sql.append(" order by "); - - if ((order != null) && !(order.length() == 0)) { - sql.append(order); - } else { - sql.append(name); - } - - // execute sql - try { - con = getPooledCon(); - } catch (Exception e) { - throw new StorageObjectFailure(e); - } - - try { - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - get_meta_data(); - } - - simpleList = new SimpleList(); - - // if popup has null-selector - if (hasNullValue) { - simpleList.add(POPUP_EMPTYLINE); - } - - SimpleHash popupDict; - - while (rs.next()) { - popupDict = new SimpleHash(); - popupDict.put("key", getValueAsString(rs, 1, thePKeyType)); - popupDict.put("value", rs.getString(2)); - simpleList.add(popupDict); - } - - rs.close(); - } - } - catch (Exception e) { - logger.error("getPopupData: " + e.getMessage()); - throw new StorageObjectFailure(e); - } finally { - freeConnection(con, stmt); - } - - if (hasPopupCache) { - popupCache = simpleList; - } - - return simpleList; - } - - /** - * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt, - * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen - * Tabellen Verwendung finden. - * @return SimpleHash mit den Tabellezeilen. - */ - public SimpleHash getHashData() { - /** @todo dangerous! this should have a flag to be enabled, otherwise - * very big Hashes could be returned */ - if (hashCache == null) { - try { - hashCache = - HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1)); - } - catch (StorageObjectFailure e) { - logger.debug(e.getMessage()); - } - } - - return hashCache; - } - - /* invalidates the popupCache - */ - protected void invalidatePopupCache() { - /** @todo invalidates toooo much */ - popupCache = null; - hashCache = null; - } - - /** - * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. - * @param stmt Statemnt - * @param sql Sql-String - * @return ResultSet - * @exception StorageObjectException - */ - public ResultSet executeSql(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - ResultSet rs; - long startTime = System.currentTimeMillis(); - - try { - rs = stmt.executeQuery(sql); - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - } - catch (SQLException e) { - logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } - - /** - * returns the number of rows in the table - */ - public int getSize(String where) throws SQLException, StorageObjectFailure { - long startTime = System.currentTimeMillis(); - String sql = "SELECT Count(*) FROM " + theTable; - - if ((where != null) && !(where.length() == 0)) { - sql = sql + " where " + where; - } - - Connection con = null; - Statement stmt = null; - int result = 0; - - try { - con = getPooledCon(); - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql); - - while (rs.next()) { - result = rs.getInt(1); - } - } - catch (SQLException e) { - logger.error("Database.getSize: " + e.getMessage()); - } - finally { - freeConnection(con, stmt); - } - - //theLog.printInfo(theTable + " has "+ result +" rows where " + where); - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - - return result; - } - - public int executeUpdate(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - int rs; - long startTime = System.currentTimeMillis(); - - try { - rs = stmt.executeUpdate(sql); - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - } - catch (SQLException e) { - logger.debug("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } - - public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException { - int result = -1; - long startTime = System.currentTimeMillis(); - Connection con = null; - PreparedStatement pstmt = null; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - result = pstmt.executeUpdate(); - } - catch (Throwable e) { - logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage()); - throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); - } - finally { - freeConnection(con, pstmt); - } - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - return result; - } - - /** - * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend - * @param md ResultSetMetaData - * @exception StorageObjectException - */ - private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { - this.evaluatedMetaData = true; - this.metadataFields = new ArrayList(); - this.metadataLabels = new ArrayList(); - this.metadataNotNullFields = new ArrayList(); - - try { - int numFields = md.getColumnCount(); - this.metadataTypes = new int[numFields]; - - String aField; - int aType; - - for (int i = 1; i <= numFields; i++) { - aField = md.getColumnName(i); - metadataFields.add(aField); - metadataLabels.add(md.getColumnLabel(i)); - aType = md.getColumnType(i); - metadataTypes[i - 1] = aType; - - if (aField.equals(thePKeyName)) { - thePKeyType = aType; - thePKeyIndex = i; - } - - if (md.isNullable(i) == ResultSetMetaData.columnNullable) { - metadataNotNullFields.add(aField); - } - } - } - catch (SQLException e) { - throwSQLException(e, "evalMetaData"); - } - } - - /** - * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, - * um die alle Columns und Typen einer Tabelle zu ermitteln. - */ - private void get_meta_data() throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - String sql = "select * from " + theTable + " where 0=1"; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - - logger.debug("METADATA: " + sql); - ResultSet rs = pstmt.executeQuery(); - evalMetaData(rs.getMetaData()); - rs.close(); - } - catch (SQLException e) { - throwSQLException(e, "get_meta_data"); - } - finally { - freeConnection(con, pstmt); - } - } - - public Connection getPooledCon() throws StorageObjectFailure { - Connection con = null; - - try { - con = SQLManager.getInstance().requestConnection(); - } - catch (SQLException e) { - logger.error("could not connect to the database " + e.getMessage()); - - throw new StorageObjectFailure("Could not connect to the database", e); - } - - return con; - } - - public void freeConnection(Connection con, Statement stmt) - throws StorageObjectFailure { - SQLManager.closeStatement(stmt); - SQLManager.getInstance().returnConnection(con); - } - - /** - * Wertet SQLException aus und wirft dannach eine StorageObjectException - * @param sqe SQLException - * @param wo Funktonsname, in der die SQLException geworfen wurde - * @exception StorageObjectException - */ - protected void throwSQLException(SQLException sqe, String aFunction) - throws StorageObjectFailure { - String state = ""; - String message = ""; - int vendor = 0; - - if (sqe != null) { - state = sqe.getSQLState(); - message = sqe.getMessage(); - vendor = sqe.getErrorCode(); - } - - String information = - "SQL Error: " + - "state= " + state + - ", vendor= " + vendor + - ", message=" + message + - ", function= " + aFunction; - - logger.error(information); - - throw new StorageObjectFailure(information, sqe); - } - - protected void _throwStorageObjectException(Exception e, String aFunction) - throws StorageObjectFailure { - - if (e != null) { - logger.error(e.getMessage() + aFunction); - throw new StorageObjectFailure(aFunction, e); - } - } - - /** - * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach - * eine StorageObjectException - * @param message Nachricht mit dem Fehler - * @exception StorageObjectException - */ - void throwStorageObjectException(String aMessage) throws StorageObjectFailure { - logger.error(aMessage); - throw new StorageObjectFailure(aMessage, null); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ +package mir.storage; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.entity.Entity; +import mir.entity.EntityList; +import mir.entity.StorableObjectEntity; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.misc.StringUtil; +import mir.storage.store.ObjectStore; +import mir.storage.store.StorableObject; +import mir.storage.store.StoreContainerType; +import mir.storage.store.StoreIdentifier; +import mir.storage.store.StoreUtil; +import mir.util.JDBCStringRoutines; + +import com.codestudio.util.SQLManager; + +import freemarker.template.SimpleHash; +import freemarker.template.SimpleList; + + +/** + * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. + * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. + * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. + * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten + * Treiber, Host, User und Passwort, ueber den der Zugriff auf die + * Datenbank erfolgt. + * + * @version $Id: Database.java,v 1.37 2003/04/09 02:06:07 zapata Exp $ + * @author rk + * + */ +public class Database implements StorageObject { + private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + + + private static SimpleHash POPUP_EMPTYLINE = new SimpleHash(); + protected static final ObjectStore o_store = ObjectStore.getInstance(); + private static final int _millisPerHour = 60 * 60 * 1000; + private static final int _millisPerMinute = 60 * 1000; + + static { + // always same object saves a little space + POPUP_EMPTYLINE.put("key", ""); + POPUP_EMPTYLINE.put("value", "--"); + } + + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected String theTable; + protected String theCoreTable = null; + protected String thePKeyName = "id"; + protected int thePKeyType; + protected int thePKeyIndex; + protected boolean evaluatedMetaData = false; + protected ArrayList metadataFields; + protected ArrayList metadataLabels; + protected ArrayList metadataNotNullFields; + protected int[] metadataTypes; + protected Class theEntityClass; + protected StorageObject myselfDatabase; + protected SimpleList popupCache = null; + protected boolean hasPopupCache = false; + protected SimpleHash hashCache = null; + protected boolean hasTimestamp = true; + private String database_driver; + private String database_url; + private int defaultLimit; + protected DatabaseAdaptor theAdaptor; + private SimpleDateFormat _dateFormatterOut = + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private SimpleDateFormat _dateFormatterIn = + new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private Calendar _cal = new GregorianCalendar(); + + /** + * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. + * Aus diesem file werden Database.Logfile, + * Database.Username,Database.Password, + * Database.Host und Database.Adaptor + * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank + * erzeugt. + * + * @param String confFilename Dateiname der Konfigurationsdatei + */ + public Database() throws StorageObjectFailure { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new StorageObjectFailure(e); + } + logger = new LoggerWrapper("Database"); + + String theAdaptorName = configuration.getString("Database.Adaptor"); + defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); + + try { + theEntityClass = GENERIC_ENTITY_CLASS; + theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance(); + } + catch (Throwable e) { + logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); + throw new StorageObjectFailure("Error in Database() constructor.", e); + } + } + + /** + * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt + * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, + * wird eine mir.entity.GenericEntity erzeugt. + * + * @return Class-Objekt der Entity + */ + public java.lang.Class getEntityClass() { + return theEntityClass; + } + + /** + * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also + * wieviel Datens?tze per Default selektiert werden. + * + * @return Standard-Anzahl der Datens?tze + */ + public int getLimit() { + return defaultLimit; + } + + /** + * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von + * der erbenden Klasse ?berschrieben, so ist der Wert PKEY + * @return Name des Primary-Keys + */ + public String getIdName() { + return thePKeyName; + } + + /** + * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. + * + * @return Name der Tabelle + */ + public String getTableName() { + return theTable; + } + + /* + * Dient dazu vererbte Tabellen bei objectrelationalen DBMS + * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet + * wird. + * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst + * the Table + */ + public String getCoreTable() { + if (theCoreTable != null) { + return theCoreTable; + } else { + return theTable; + } + } + + /** + * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) + * @return int-Array mit den Typen der Felder + * @exception StorageObjectException + */ + public int[] getTypes() throws StorageObjectFailure { + if (metadataTypes == null) { + get_meta_data(); + } + + return metadataTypes; + } + + /** + * Liefert eine Liste der Labels der Tabellenfelder + * @return ArrayListe mit Labeln + * @exception StorageObjectException + */ + public List getLabels() throws StorageObjectFailure { + if (metadataLabels == null) { + get_meta_data(); + } + + return metadataLabels; + } + + /** + * Liefert eine Liste der Felder der Tabelle + * @return ArrayList mit Feldern + * @exception StorageObjectException + */ + public List getFields() throws StorageObjectFailure { + if (metadataFields == null) { + get_meta_data(); + } + + return metadataFields; + } + + /* + * Gets value out of ResultSet according to type and converts to String + * @param inValue Wert aus ResultSet. + * @param aType Datenbanktyp. + * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich + * dann /unsupported value/ + */ + private String getValueAsString(ResultSet rs, int valueIndex, int aType) + throws StorageObjectFailure { + String outValue = null; + + if (rs != null) { + try { + switch (aType) { + case java.sql.Types.BIT: + outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; + + break; + + case java.sql.Types.INTEGER: + case java.sql.Types.SMALLINT: + case java.sql.Types.TINYINT: + case java.sql.Types.BIGINT: + + int out = rs.getInt(valueIndex); + + if (!rs.wasNull()) { + outValue = new Integer(out).toString(); + } + + break; + + case java.sql.Types.NUMERIC: + + /** @todo Numeric can be float or double depending upon + * metadata.getScale() / especially with oracle */ + long outl = rs.getLong(valueIndex); + + if (!rs.wasNull()) { + outValue = new Long(outl).toString(); + } + + break; + + case java.sql.Types.REAL: + + float tempf = rs.getFloat(valueIndex); + + if (!rs.wasNull()) { + tempf *= 10; + tempf += 0.5; + + int tempf_int = (int) tempf; + tempf = (float) tempf_int; + tempf /= 10; + outValue = "" + tempf; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.DOUBLE: + + double tempd = rs.getDouble(valueIndex); + + if (!rs.wasNull()) { + tempd *= 10; + tempd += 0.5; + + int tempd_int = (int) tempd; + tempd = (double) tempd_int; + tempd /= 10; + outValue = "" + tempd; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.LONGVARBINARY: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.TIMESTAMP: + + // it's important to use Timestamp here as getting it + // as a string is undefined and is only there for debugging + // according to the API. we can make it a string through formatting. + // -mh + Timestamp timestamp = (rs.getTimestamp(valueIndex)); + + if (!rs.wasNull()) { + java.util.Date date = new java.util.Date(timestamp.getTime()); + outValue = _dateFormatterOut.format(date); + _cal.setTime(date); + + int offset = + _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET); + String tzOffset = + StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2); + outValue = outValue + "+" + tzOffset; + } + + break; + + default: + outValue = ""; + logger.warn( "Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); + } + } catch (SQLException e) { + throw new StorageObjectFailure("Could not get Value out of Resultset -- ", + e); + } + } + + return outValue; + } + + /* + * select-Operator um einen Datensatz zu bekommen. + * @param id Primaerschluessel des Datensatzes. + * @return liefert EntityObject des gefundenen Datensatzes oder null. + */ + public Entity selectById(String id) throws StorageObjectExc { + if ((id == null) || id.equals("")) { + throw new StorageObjectExc("Database.selectById: Missing id"); + } + + // ask object store for object + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId); + logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString()); + + Entity hit = (Entity) o_store.use(search_sid); + + if (hit != null) { + return hit; + } + } + + Statement stmt = null; + Connection con = getPooledCon(); + Entity returnEntity = null; + + try { + ResultSet rs; + + /** @todo better prepared statement */ + String selectSql = + "select * from " + theTable + " where " + thePKeyName + "=" + id; + stmt = con.createStatement(); + rs = executeSql(stmt, selectSql); + + if (rs != null) { + if (evaluatedMetaData == false) { + evalMetaData(rs.getMetaData()); + } + + if (rs.next()) { + returnEntity = makeEntityFromResultSet(rs); + } + else { + logger.debug("No data for id: " + id + " in table " + theTable); + } + + rs.close(); + } + else { + logger.debug("No Data for Id " + id + " in Table " + theTable); + } + } + catch (SQLException sqe) { + throwSQLException(sqe, "selectById"); + return null; + } + catch (NumberFormatException e) { + logger.error("ID is no number: " + id); + } + finally { + freeConnection(con, stmt); + } + + return returnEntity; + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { + return selectByFieldValue(aField, aValue, 0); + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { + return selectByWhereClause(aField + "=" + aValue, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * + * @param wc where-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where) + throws StorageObjectFailure { + return selectByWhereClause(where, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param offset ab welchem Datensatz. + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, int offset) + throws StorageObjectFailure { + return selectByWhereClause(whereClause, null, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where, String order) + throws StorageObjectFailure { + return selectByWhereClause(where, order, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @param offset ab welchem Datensatz + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, String orderBy, + int offset) throws StorageObjectFailure { + return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * @param wc where-Clause + * @param ob orderBy-Clause + * @param offset ab welchem Datensatz + * @param limit wieviele Datens?tze + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String wc, String ob, int offset, + int limit) throws StorageObjectFailure { + // check o_store for entitylist + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier search_sid = + new StoreIdentifier(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST, + StoreUtil.getEntityListUniqueIdentifierFor(theTable, wc, ob, offset, + limit)); + EntityList hit = (EntityList) o_store.use(search_sid); + + if (hit != null) { + logger.debug("CACHE (hit): " + search_sid.toString()); + + return hit; + } + } + + // local + EntityList theReturnList = null; + Connection con = null; + Statement stmt = null; + ResultSet rs; + int offsetCount = 0; + int count = 0; + + // build sql-statement + + /** @todo count sql string should only be assembled if we really count + * see below at the end of method //rk */ + if ((wc != null) && (wc.trim().length() == 0)) { + wc = null; + } + + StringBuffer countSql = + new StringBuffer("select count(*) from ").append(theTable); + StringBuffer selectSql = + new StringBuffer("select * from ").append(theTable); + + if (wc != null) { + selectSql.append(" where ").append(wc); + countSql.append(" where ").append(wc); + } + + if ((ob != null) && !(ob.trim().length() == 0)) { + selectSql.append(" order by ").append(ob); + } + + if (theAdaptor.hasLimit()) { + if ((limit > -1) && (offset > -1)) { + selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); + } + } + + // execute sql + try { + con = getPooledCon(); + stmt = con.createStatement(); + + // selecting... + rs = executeSql(stmt, selectSql.toString()); + + if (rs != null) { + if (!evaluatedMetaData) { + evalMetaData(rs.getMetaData()); + } + + theReturnList = new EntityList(); + + Entity theResultEntity; + + while (rs.next()) { + theResultEntity = makeEntityFromResultSet(rs); + theReturnList.add(theResultEntity); + offsetCount++; + } + + rs.close(); + } + + // making entitylist infos + if (!(theAdaptor.hasLimit())) { + count = offsetCount; + } + + if (theReturnList != null) { + // now we decide if we have to know an overall count... + count = offsetCount; + + if ((limit > -1) && (offset > -1)) { + if (offsetCount == limit) { + /** @todo counting should be deffered to entitylist + * getSize() should be used */ + rs = executeSql(stmt, countSql.toString()); + + if (rs != null) { + if (rs.next()) { + count = rs.getInt(1); + } + + rs.close(); + } + else { + logger.error("Could not count: " + countSql); + } + } + } + + theReturnList.setCount(count); + theReturnList.setOffset(offset); + theReturnList.setWhere(wc); + theReturnList.setOrder(ob); + theReturnList.setStorage(this); + theReturnList.setLimit(limit); + + if (offset >= limit) { + theReturnList.setPrevBatch(offset - limit); + } + + if ((offset + offsetCount) < count) { + theReturnList.setNextBatch(offset + limit); + } + + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier sid = theReturnList.getStoreIdentifier(); + logger.debug("CACHE (add): " + sid.toString()); + o_store.add(sid); + } + } + } catch (SQLException sqe) { + throwSQLException(sqe, "selectByWhereClause"); + } finally { + try { + if (con != null) { + freeConnection(con, stmt); + } + } catch (Throwable t) { + } + } + + return theReturnList; + } + + /** + * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. + * + * @param rs Das ResultSetObjekt. + * @return Entity Die Entity. + */ + private Entity makeEntityFromResultSet(ResultSet rs) + throws StorageObjectFailure { + /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ + Map theResultHash = new HashMap(); + String theResult = null; + int theType; + Entity returnEntity = null; + + try { + int size = metadataFields.size(); + + for (int i = 0; i < size; i++) { + // alle durchlaufen bis nix mehr da + theType = metadataTypes[i]; + + if (theType == java.sql.Types.LONGVARBINARY) { + InputStreamReader is = + (InputStreamReader) rs.getCharacterStream(i + 1); + + if (is != null) { + char[] data = new char[32768]; + StringBuffer theResultString = new StringBuffer(); + int len; + + while ((len = is.read(data)) > 0) { + theResultString.append(data, 0, len); + } + + is.close(); + theResult = theResultString.toString(); + } else { + theResult = null; + } + } else { + theResult = getValueAsString(rs, (i + 1), theType); + } + + if (theResult != null) { + theResultHash.put(metadataFields.get(i), theResult); + } + } + + if (theEntityClass != null) { + returnEntity = (Entity) theEntityClass.newInstance(); + returnEntity.setValues(theResultHash); + returnEntity.setStorage(myselfDatabase); + + if (returnEntity instanceof StorableObject) { + logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable); + o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); + } + } else { + throwStorageObjectException("Internal Error: theEntityClass not set!"); + } + } catch (IllegalAccessException e) { + throwStorageObjectException("No access! -- " + e.getMessage()); + } catch (IOException e) { + throwStorageObjectException("IOException! -- " + e.getMessage()); + } catch (InstantiationException e) { + throwStorageObjectException("No Instatiation! -- " + e.getMessage()); + } catch (SQLException sqe) { + throwSQLException(sqe, "makeEntityFromResultSet"); + + return null; + } + + return returnEntity; + } + + /** + * insert-Operator: f?gt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE + * wird automatisch mit dem aktuellen Datum gefuellt. + * + * @param theEntity + * @return der Wert des Primary-keys der eingef?gten Entity + */ + public String insert(Entity theEntity) throws StorageObjectFailure { + //cache + invalidatePopupCache(); + + // invalidating all EntityLists corresponding with theEntityClass + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + String returnId = null; + Connection con = null; + PreparedStatement pstmt = null; + + try { + List streamedInput = theEntity.streamedInput(); + StringBuffer f = new StringBuffer(); + StringBuffer v = new StringBuffer(); + String aField; + String aValue; + boolean firstField = true; + + // make sql-string + for (int i = 0; i < getFields().size(); i++) { + aField = (String) getFields().get(i); + + if (!aField.equals(thePKeyName)) { + aValue = null; + + // exceptions + if (aField.equals("webdb_create") || + aField.equals("webdb_lastchange")) { + aValue = "NOW()"; + } else { + if ((streamedInput != null) && streamedInput.contains(aField)) { + aValue = "?"; + } else { + if (theEntity.hasValueForField(aField)) { + aValue = + "'" + + JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue( + aField)) + "'"; + } + } + } + + // wenn Wert gegeben, dann einbauen + if (aValue != null) { + if (firstField == false) { + f.append(","); + v.append(","); + } + else { + firstField = false; + } + + f.append(aField); + v.append(aValue); + } + } + } + // end for + + // insert into db + StringBuffer sqlBuf = + new StringBuffer("insert into ").append(theTable).append("(").append(f) + .append(") values (").append(v).append(")"); + String sql = sqlBuf.toString(); + + //theLog.printInfo("INSERT: " + sql); + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + (String) theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + int ret = pstmt.executeUpdate(); + + if (ret == 0) { + //insert failed + return null; + } + + pstmt = + con.prepareStatement(theAdaptor.getLastInsertSQL( + (Database) myselfDatabase)); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + returnId = rs.getString(1); + theEntity.setId(returnId); + } + catch (SQLException sqe) { + throwSQLException(sqe, "insert"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + } + + freeConnection(con, pstmt); + } + + /** @todo store entity in o_store */ + return returnId; + } + + /** + * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE + * wird automatisch mit dem aktuellen Datum gefuellt. + * + * @param theEntity + */ + public void update(Entity theEntity) throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + + /** @todo this is stupid: why do we prepare statement, when we + * throw it away afterwards. should be regular statement + * update/insert could better be one routine called save() + * that chooses to either insert or update depending if we + * have a primary key in the entity. i don't know if we + * still need the streamed input fields. // rk */ + /** @todo extension: check if Entity did change, otherwise we don't need + * the roundtrip to the database */ + /** invalidating corresponding entitylists in o_store*/ + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + List streamedInput = theEntity.streamedInput(); + String id = theEntity.getId(); + String aField; + StringBuffer fv = new StringBuffer(); + boolean firstField = true; + + //cache + invalidatePopupCache(); + + // build sql statement + for (int i = 0; i < getFields().size(); i++) { + aField = (String) metadataFields.get(i); + + // only normal cases + if ( !(aField.equals(thePKeyName) || + aField.equals("webdb_create") || + aField.equals("webdb_lastchange") || + ((streamedInput != null) && streamedInput.contains(aField)))) { + if (theEntity.hasValueForField(aField)) { + if (firstField == false) { + fv.append(", "); + } + else { + firstField = false; + } + + fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'"); + + // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); + } + } + } + + StringBuffer sql = + new StringBuffer("update ").append(theTable).append(" set ").append(fv); + + // exceptions + if (metadataFields.contains("webdb_lastchange")) { + sql.append(",webdb_lastchange=NOW()"); + } + + // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm + // format so anything extra will be ignored. -mh + if (metadataFields.contains("webdb_create") && + theEntity.hasValueForField("webdb_create")) { + // minimum of 10 (yyyy-mm-dd)... + if (theEntity.getValue("webdb_create").length() >= 10) { + String dateString = theEntity.getValue("webdb_create"); + + // if only 10, then add 00:00 so it doesn't throw a ParseException + if (dateString.length() == 10) { + dateString = dateString + " 00:00"; + } + + // TimeStamp stuff + try { + java.util.Date d = _dateFormatterIn.parse(dateString); + Timestamp tStamp = new Timestamp(d.getTime()); + sql.append(",webdb_create='" + tStamp.toString() + "'"); + } catch (ParseException e) { + throw new StorageObjectFailure(e); + } + } + } + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + sql.append(",").append(streamedInput.get(i)).append("=?"); + } + } + + sql.append(" where id=").append(id); + + //theLog.printInfo("UPDATE: " + sql); + // execute sql + try { + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql.toString()); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + pstmt.executeUpdate(); + } catch (SQLException sqe) { + throwSQLException(sqe, "update"); + } finally { + try { + con.setAutoCommit(true); + } catch (Exception e) { + ; + } + + freeConnection(con, pstmt); + } + } + + /* + * delete-Operator + * @param id des zu loeschenden Datensatzes + * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. + */ + public boolean delete(String id) throws StorageObjectFailure { + invalidatePopupCache(); + + // ostore send notification + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + logger.debug("CACHE: (del) " + id); + + StoreIdentifier search_sid = + new StoreIdentifier(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITY, uniqueId); + o_store.invalidate(search_sid); + } + + /** @todo could be prepared Statement */ + Statement stmt = null; + Connection con = null; + int res = 0; + String sql = + "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; + + //theLog.printInfo("DELETE " + sql); + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } catch (SQLException sqe) { + throwSQLException(sqe, "delete"); + } finally { + freeConnection(con, stmt); + } + + return (res > 0) ? true : false; + } + + /* noch nicht implementiert. + * @return immer false + */ + public boolean delete(EntityList theEntityList) { + invalidatePopupCache(); + + return false; + } + + /** + * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse + * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll. + * @return null + */ + public SimpleList getPopupData() throws StorageObjectFailure { + return null; + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue) + throws StorageObjectFailure { + return getPopupData(name, hasNullValue, null); + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @param where Schraenkt die Selektion der Datensaetze ein. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue, String where) + throws StorageObjectFailure { + return getPopupData(name, hasNullValue, where, null); + } + + /** + * Holt Daten fuer Popups. + * @param name Name des Feldes. + * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. + * @param where Schraenkt die Selektion der Datensaetze ein. + * @param order Gibt ein Feld als Sortierkriterium an. + * @return SimpleList Gibt freemarker.template.SimpleList zurueck. + */ + public SimpleList getPopupData(String name, boolean hasNullValue, + String where, String order) throws StorageObjectFailure { + // caching + if (hasPopupCache && (popupCache != null)) { + return popupCache; + } + + SimpleList simpleList = null; + Connection con = null; + Statement stmt = null; + + // build sql + StringBuffer sql = + new StringBuffer("select ").append(thePKeyName).append(",").append(name) + .append(" from ").append(theTable); + + if ((where != null) && !(where.length() == 0)) { + sql.append(" where ").append(where); + } + + sql.append(" order by "); + + if ((order != null) && !(order.length() == 0)) { + sql.append(order); + } else { + sql.append(name); + } + + // execute sql + try { + con = getPooledCon(); + } catch (Exception e) { + throw new StorageObjectFailure(e); + } + + try { + stmt = con.createStatement(); + + ResultSet rs = executeSql(stmt, sql.toString()); + + if (rs != null) { + if (!evaluatedMetaData) { + get_meta_data(); + } + + simpleList = new SimpleList(); + + // if popup has null-selector + if (hasNullValue) { + simpleList.add(POPUP_EMPTYLINE); + } + + SimpleHash popupDict; + + while (rs.next()) { + popupDict = new SimpleHash(); + popupDict.put("key", getValueAsString(rs, 1, thePKeyType)); + popupDict.put("value", rs.getString(2)); + simpleList.add(popupDict); + } + + rs.close(); + } + } + catch (Exception e) { + logger.error("getPopupData: " + e.getMessage()); + throw new StorageObjectFailure(e); + } finally { + freeConnection(con, stmt); + } + + if (hasPopupCache) { + popupCache = simpleList; + } + + return simpleList; + } + + /** + * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt, + * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen + * Tabellen Verwendung finden. + * @return SimpleHash mit den Tabellezeilen. + */ + public SimpleHash getHashData() { + /** @todo dangerous! this should have a flag to be enabled, otherwise + * very big Hashes could be returned */ + if (hashCache == null) { + try { + hashCache = + HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1)); + } + catch (StorageObjectFailure e) { + logger.debug(e.getMessage()); + } + } + + return hashCache; + } + + /* invalidates the popupCache + */ + protected void invalidatePopupCache() { + /** @todo invalidates toooo much */ + popupCache = null; + hashCache = null; + } + + /** + * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. + * @param stmt Statemnt + * @param sql Sql-String + * @return ResultSet + * @exception StorageObjectException + */ + public ResultSet executeSql(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + ResultSet rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeQuery(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } + + /** + * returns the number of rows in the table + */ + public int getSize(String where) throws SQLException, StorageObjectFailure { + long startTime = System.currentTimeMillis(); + String sql = "SELECT Count(*) FROM " + theTable; + + if ((where != null) && !(where.length() == 0)) { + sql = sql + " where " + where; + } + + Connection con = null; + Statement stmt = null; + int result = 0; + + try { + con = getPooledCon(); + stmt = con.createStatement(); + + ResultSet rs = executeSql(stmt, sql); + + while (rs.next()) { + result = rs.getInt(1); + } + } + catch (SQLException e) { + logger.error("Database.getSize: " + e.getMessage()); + } + finally { + freeConnection(con, stmt); + } + + //theLog.printInfo(theTable + " has "+ result +" rows where " + where); + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + + return result; + } + + public int executeUpdate(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + int rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeUpdate(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.debug("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } + + public int executeUpdate(String sql) + throws StorageObjectFailure, SQLException { + int result = -1; + long startTime = System.currentTimeMillis(); + Connection con = null; + PreparedStatement pstmt = null; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + result = pstmt.executeUpdate(); + } + catch (Throwable e) { + logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage()); + throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); + } + finally { + freeConnection(con, pstmt); + } + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + return result; + } + + /** + * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend + * @param md ResultSetMetaData + * @exception StorageObjectException + */ + private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { + this.evaluatedMetaData = true; + this.metadataFields = new ArrayList(); + this.metadataLabels = new ArrayList(); + this.metadataNotNullFields = new ArrayList(); + + try { + int numFields = md.getColumnCount(); + this.metadataTypes = new int[numFields]; + + String aField; + int aType; + + for (int i = 1; i <= numFields; i++) { + aField = md.getColumnName(i); + metadataFields.add(aField); + metadataLabels.add(md.getColumnLabel(i)); + aType = md.getColumnType(i); + metadataTypes[i - 1] = aType; + + if (aField.equals(thePKeyName)) { + thePKeyType = aType; + thePKeyIndex = i; + } + + if (md.isNullable(i) == ResultSetMetaData.columnNullable) { + metadataNotNullFields.add(aField); + } + } + } + catch (SQLException e) { + throwSQLException(e, "evalMetaData"); + } + } + + /** + * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, + * um die alle Columns und Typen einer Tabelle zu ermitteln. + */ + private void get_meta_data() throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + String sql = "select * from " + theTable + " where 0=1"; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + + logger.debug("METADATA: " + sql); + ResultSet rs = pstmt.executeQuery(); + evalMetaData(rs.getMetaData()); + rs.close(); + } + catch (SQLException e) { + throwSQLException(e, "get_meta_data"); + } + finally { + freeConnection(con, pstmt); + } + } + + public Connection getPooledCon() throws StorageObjectFailure { + Connection con = null; + + try { + con = SQLManager.getInstance().requestConnection(); + } + catch (SQLException e) { + logger.error("could not connect to the database " + e.getMessage()); + + throw new StorageObjectFailure("Could not connect to the database", e); + } + + return con; + } + + public void freeConnection(Connection con, Statement stmt) + throws StorageObjectFailure { + SQLManager.closeStatement(stmt); + SQLManager.getInstance().returnConnection(con); + } + + /** + * Wertet SQLException aus und wirft dannach eine StorageObjectException + * @param sqe SQLException + * @param wo Funktonsname, in der die SQLException geworfen wurde + * @exception StorageObjectException + */ + protected void throwSQLException(SQLException sqe, String aFunction) + throws StorageObjectFailure { + String state = ""; + String message = ""; + int vendor = 0; + + if (sqe != null) { + state = sqe.getSQLState(); + message = sqe.getMessage(); + vendor = sqe.getErrorCode(); + } + + String information = + "SQL Error: " + + "state= " + state + + ", vendor= " + vendor + + ", message=" + message + + ", function= " + aFunction; + + logger.error(information); + + throw new StorageObjectFailure(information, sqe); + } + + protected void _throwStorageObjectException(Exception e, String aFunction) + throws StorageObjectFailure { + + if (e != null) { + logger.error(e.getMessage() + aFunction); + throw new StorageObjectFailure(aFunction, e); + } + } + + /** + * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach + * eine StorageObjectException + * @param message Nachricht mit dem Fehler + * @exception StorageObjectException + */ + void throwStorageObjectException(String aMessage) throws StorageObjectFailure { + logger.error(aMessage); + throw new StorageObjectFailure(aMessage, null); + } +} diff --git a/source/mir/storage/store/ObjectStore.java b/source/mir/storage/store/ObjectStore.java index de9803a1..c23f7866 100755 --- a/source/mir/storage/store/ObjectStore.java +++ b/source/mir/storage/store/ObjectStore.java @@ -1,286 +1,286 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.storage.store; - -/** - * Title: ObjectStore for StorableObjects - * Description: ObjectStore holds a Map of @see StoreContainer for all possible - * @see StoreIdentifier. - * - * @see StorageIdentifier - identitfies one object in the ObjectStore - * i.e. in its apropriate bucket. It holds a unique identifier - * of a StorableObject and a reference on the StorableObject. - * - * @see StoreContainer - "Buckets" to store different types of Objects - * in one Container. These buckets are cofigurable via - * config.properties. - * - * @see StoreContainerType - is a signature for all StoreContainer - * and StoreIdentifier. - * - * @see StorableObjects - Interface Object have to implement to - * be handled by the ObjectStore - * - * @see ServletStoreInfo - Maintenance Servlet for ObjectStore. - * Displays information about current content of the - * ObjectStore. - * - * - * Copyright: Copyright (c) 2002 - * Company: indy - * @author rk - * @version 1.0 - */ - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.Properties; - -import javax.servlet.http.HttpServletRequest; - -import mir.config.MirPropertiesConfiguration; -import mir.log.LoggerWrapper; - -public class ObjectStore { - - private final static ObjectStore INSTANCE = new ObjectStore(); - private final static Map containerMap = new HashMap(); // StoreContainerType/StoreContainer - private static long storeHit = 0, storeMiss = 0; - private Properties ostoreConf; - private LoggerWrapper logger; - - private ObjectStore() { - String confName = null; - - logger = new LoggerWrapper("Database.ObjectStore"); - Properties conf = new Properties(); - - try { - confName = - MirPropertiesConfiguration.instance().getString("Home") + - "etc/objectstore.properties"; - conf.load(new BufferedInputStream(new FileInputStream(confName))); - } - catch (java.io.FileNotFoundException fnfe) { - logger.error("could not read config file. not found: " + confName); - } - catch (Throwable t) { - logger.error("could not get config: " + t.getMessage()); - } - ostoreConf = conf; - } - - public static ObjectStore getInstance() { - return INSTANCE; - } - - /** - * Method: use - * Description: The ObjectStore tries to find the @see StoreIdentifier sid - * and returns the stored Object. - * - * @return StorableObject is null when no StorableObject for the - * StoreIdentifier sid is found. - */ - public StorableObject use(StoreIdentifier sid) { - if (sid != null) { - StorableObject storeObject = null; - StoreContainer stoc = getStoreContainerForSid(sid); - if (stoc != null) - storeObject = stoc.use(sid); - else - logger.warn("container not found for: " + sid.toString()); - if (storeObject != null) { - storeHit++; - return storeObject; - } - } - storeMiss++; - return null; - - } - - /** - * Method: add - * Description: A StoreIdentifier is added to the ObjectStore, if it - * contains a reference to a @see StorableObject. - */ - public void add(StoreIdentifier sid) { - if (sid != null && sid.hasReference()) { - // find the right StoreContainer for sid - StoreContainer stoc = getStoreContainerForSid(sid); - if (stoc == null) { - // we have to make new StoreContainer - StoreContainerType stocType = sid.getStoreContainerType(); - stoc = new StoreContainer(stocType); - containerMap.put(stocType, stoc); - } - stoc.add(sid); - } - } - - /** - * Method: invalidate(StorableObject sto) - * Description: ObjectStore is notified of change of a @see StorableObject - * sto and invalidates all relevant cache entries. - */ - - public void invalidate(StoreIdentifier sid) { - // propagate invalidation to StoreContainer - if (sid != null) { - StoreContainer stoc = getStoreContainerForSid(sid); - stoc.invalidate(sid); - } - } - - /** - * Method: invalidate(StoreContainerType) - * Description: serves to invalidate a whole StoreContainer - * - * @return - */ - public void invalidate(StoreContainerType stoc_type) { - if (stoc_type != null) { - /** @todo invalidates too much: - * improvement: if instanceof StoreContainerEntity && EntityList - * then invalidate only StoreIdentifier matching the right table - */ - StoreContainer stoc = getStoreContainerForStocType(stoc_type); - if (stoc != null) - stoc.invalidate(); - } - - } - - // internal methods for StoreContainer managment - - /** - * Method: getStoreContainerForSid - * Description: private method to find the right @see StoreContainer for - * the @see StoreIdentifier sid. - * - * @return StoreContainer is null when no Container is found. - */ - private StoreContainer getStoreContainerForSid(StoreIdentifier sid) { - // find apropriate container for a specific sid - if (sid != null) { - StoreContainerType stoc_type = sid.getStoreContainerType(); - return getStoreContainerForStocType(stoc_type); - } - return null; - } - - private StoreContainer getStoreContainerForStocType(StoreContainerType - stoc_type) { - if (stoc_type != null && containerMap.containsKey(stoc_type)) - return (StoreContainer) containerMap.get(stoc_type); - return null; - } - - private boolean has(StoreIdentifier sid) { - StoreContainer stoc = getStoreContainerForSid(sid); - return (stoc != null && stoc.has(sid)) ? true : false; - } - - public String getConfProperty(String name) { - if (name != null) { - String returnValue = ""; - try { - return ostoreConf.getProperty(name); - } - catch (MissingResourceException e) { - logger.error("getConfProperty: " + e.toString()); - } - } - return null; - } - - /** - * Method: toString() - * Description: Displays statistical information about the ObjectStore. - * Further information is gathered from all @see StoreContainer - * - * @return String - */ - public String toString() { - return toHtml(null); - } - - public String toHtml(HttpServletRequest req) { - float hitRatio = 0; - long divisor = storeHit + storeMiss; - if (divisor > 0) - hitRatio = (float) storeHit / (float) divisor; - hitRatio *= 100; - - StringBuffer sb = new StringBuffer("Mir-ObjectStore "); - sb.append( ( (req != null) ? html_version() : version())).append("\n"); - sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit); - sb.append("/").append(storeMiss).append("/").append(hitRatio); - sb.append("%\nCurrently ").append(containerMap.size()); - sb.append(" StoreContainer in use - listing information:\n"); - - // ask container for information - StoreContainer currentStoc; - for (Iterator it = containerMap.keySet().iterator(); it.hasNext(); ) { - currentStoc = (StoreContainer) containerMap.get(it.next()); - sb.append(currentStoc.toHtml(req)); - } - - return sb.toString(); - } - - /** - * Method: html_version() - * Description: returns ObjectStore version as String for HTML representation - * - * @return String - */ - private String html_version() { - return "" + version() + ""; - } - - /** - * Method: version() - * Description: returns ObjectStore version as String - * - * @return String - */ - private String version() { - return "v_sstart3__1.0"; - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.storage.store; + +/** + * Title: ObjectStore for StorableObjects + * Description: ObjectStore holds a Map of @see StoreContainer for all possible + * @see StoreIdentifier. + * + * @see StorageIdentifier - identitfies one object in the ObjectStore + * i.e. in its apropriate bucket. It holds a unique identifier + * of a StorableObject and a reference on the StorableObject. + * + * @see StoreContainer - "Buckets" to store different types of Objects + * in one Container. These buckets are cofigurable via + * config.properties. + * + * @see StoreContainerType - is a signature for all StoreContainer + * and StoreIdentifier. + * + * @see StorableObjects - Interface Object have to implement to + * be handled by the ObjectStore + * + * @see ServletStoreInfo - Maintenance Servlet for ObjectStore. + * Displays information about current content of the + * ObjectStore. + * + * + * Copyright: Copyright (c) 2002 + * Company: indy + * @author rk + * @version 1.0 + */ + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Properties; + +import javax.servlet.http.HttpServletRequest; + +import mir.config.MirPropertiesConfiguration; +import mir.log.LoggerWrapper; + +public class ObjectStore { + + private final static ObjectStore INSTANCE = new ObjectStore(); + private final static Map containerMap = new HashMap(); // StoreContainerType/StoreContainer + private static long storeHit = 0, storeMiss = 0; + private Properties ostoreConf; + private LoggerWrapper logger; + + private ObjectStore() { + String confName = null; + + logger = new LoggerWrapper("Database.ObjectStore"); + Properties conf = new Properties(); + + try { + confName = + MirPropertiesConfiguration.instance().getString("Home") + + "etc/objectstore.properties"; + conf.load(new BufferedInputStream(new FileInputStream(confName))); + } + catch (java.io.FileNotFoundException fnfe) { + logger.error("could not read config file. not found: " + confName); + } + catch (Throwable t) { + logger.error("could not get config: " + t.getMessage()); + } + ostoreConf = conf; + } + + public static ObjectStore getInstance() { + return INSTANCE; + } + + /** + * Method: use + * Description: The ObjectStore tries to find the @see StoreIdentifier sid + * and returns the stored Object. + * + * @return StorableObject is null when no StorableObject for the + * StoreIdentifier sid is found. + */ + public StorableObject use(StoreIdentifier sid) { + if (sid != null) { + StorableObject storeObject = null; + StoreContainer stoc = getStoreContainerForSid(sid); + if (stoc != null) + storeObject = stoc.use(sid); + else + logger.warn("container not found for: " + sid.toString()); + if (storeObject != null) { + storeHit++; + return storeObject; + } + } + storeMiss++; + return null; + + } + + /** + * Method: add + * Description: A StoreIdentifier is added to the ObjectStore, if it + * contains a reference to a @see StorableObject. + */ + public void add(StoreIdentifier sid) { + if (sid != null && sid.hasReference()) { + // find the right StoreContainer for sid + StoreContainer stoc = getStoreContainerForSid(sid); + if (stoc == null) { + // we have to make new StoreContainer + StoreContainerType stocType = sid.getStoreContainerType(); + stoc = new StoreContainer(stocType); + containerMap.put(stocType, stoc); + } + stoc.add(sid); + } + } + + /** + * Method: invalidate(StorableObject sto) + * Description: ObjectStore is notified of change of a @see StorableObject + * sto and invalidates all relevant cache entries. + */ + + public void invalidate(StoreIdentifier sid) { + // propagate invalidation to StoreContainer + if (sid != null) { + StoreContainer stoc = getStoreContainerForSid(sid); + stoc.invalidate(sid); + } + } + + /** + * Method: invalidate(StoreContainerType) + * Description: serves to invalidate a whole StoreContainer + * + * @return + */ + public void invalidate(StoreContainerType stoc_type) { + if (stoc_type != null) { + /** @todo invalidates too much: + * improvement: if instanceof StoreContainerEntity && EntityList + * then invalidate only StoreIdentifier matching the right table + */ + StoreContainer stoc = getStoreContainerForStocType(stoc_type); + if (stoc != null) + stoc.invalidate(); + } + + } + + // internal methods for StoreContainer managment + + /** + * Method: getStoreContainerForSid + * Description: private method to find the right @see StoreContainer for + * the @see StoreIdentifier sid. + * + * @return StoreContainer is null when no Container is found. + */ + private StoreContainer getStoreContainerForSid(StoreIdentifier sid) { + // find apropriate container for a specific sid + if (sid != null) { + StoreContainerType stoc_type = sid.getStoreContainerType(); + return getStoreContainerForStocType(stoc_type); + } + return null; + } + + private StoreContainer getStoreContainerForStocType(StoreContainerType + stoc_type) { + if (stoc_type != null && containerMap.containsKey(stoc_type)) + return (StoreContainer) containerMap.get(stoc_type); + return null; + } + + private boolean has(StoreIdentifier sid) { + StoreContainer stoc = getStoreContainerForSid(sid); + return (stoc != null && stoc.has(sid)) ? true : false; + } + + public String getConfProperty(String name) { + if (name != null) { + String returnValue = ""; + try { + return ostoreConf.getProperty(name); + } + catch (MissingResourceException e) { + logger.error("getConfProperty: " + e.toString()); + } + } + return null; + } + + /** + * Method: toString() + * Description: Displays statistical information about the ObjectStore. + * Further information is gathered from all @see StoreContainer + * + * @return String + */ + public String toString() { + return toHtml(null); + } + + public String toHtml(HttpServletRequest req) { + float hitRatio = 0; + long divisor = storeHit + storeMiss; + if (divisor > 0) + hitRatio = (float) storeHit / (float) divisor; + hitRatio *= 100; + + StringBuffer sb = new StringBuffer("Mir-ObjectStore "); + sb.append( ( (req != null) ? html_version() : version())).append("\n"); + sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit); + sb.append("/").append(storeMiss).append("/").append(hitRatio); + sb.append("%\nCurrently ").append(containerMap.size()); + sb.append(" StoreContainer in use - listing information:\n"); + + // ask container for information + StoreContainer currentStoc; + for (Iterator it = containerMap.keySet().iterator(); it.hasNext(); ) { + currentStoc = (StoreContainer) containerMap.get(it.next()); + sb.append(currentStoc.toHtml(req)); + } + + return sb.toString(); + } + + /** + * Method: html_version() + * Description: returns ObjectStore version as String for HTML representation + * + * @return String + */ + private String html_version() { + return "" + version() + ""; + } + + /** + * Method: version() + * Description: returns ObjectStore version as String + * + * @return String + */ + private String version() { + return "v_sstart3__1.0"; + } + } \ No newline at end of file diff --git a/source/mir/storage/store/StoreContainerType.java b/source/mir/storage/store/StoreContainerType.java index dde90a69..d4df0a22 100755 --- a/source/mir/storage/store/StoreContainerType.java +++ b/source/mir/storage/store/StoreContainerType.java @@ -1,128 +1,128 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.storage.store; - -/** - * Title: StoreContainerType - * - * Description: StoreContainerTypes are uniqe Objects and are generated - * via @see valueOf(Class stocClass, int stocType). - * For every combination of stocClass and stocType there is - * only one Object instantiated. - * - * Copyright: Copyright (c) 2002 - * Company: indy - * - * @author rk - * @version 1.0 - */ - -import java.util.HashMap; -import java.util.Map; - -import mir.misc.StringUtil; - -public class StoreContainerType { - - public final static int STOC_TYPE_UNKNOWN = -1; - public final static int STOC_TYPE_ENTITY = 0; - public final static int STOC_TYPE_ENTITYLIST = 1; - public final static int STOC_TYPE_MAX = STOC_TYPE_ENTITYLIST; - - private static Map[] uniqueTypes = new HashMap[STOC_TYPE_MAX + 1]; - private static ObjectStore o_store = ObjectStore.getInstance(); - private Class stocClass = null; - private int stocType = STOC_TYPE_UNKNOWN; - - static { - uniqueTypes[STOC_TYPE_ENTITY] = new HashMap(); - uniqueTypes[STOC_TYPE_ENTITYLIST] = new HashMap(); - } - - private StoreContainerType() {} - - private StoreContainerType(Class stocClass, int stocType) { - this.stocClass = stocClass; - this.stocType = stocType; - } - - public static StoreContainerType valueOf(Class stoc_class, int stoc_type) { - StoreContainerType returnStocType = null; - if (stoc_type >= 0 && stoc_type <= STOC_TYPE_MAX) { - Map current = uniqueTypes[stoc_type]; - if (current.containsKey(stoc_class)) - returnStocType = (StoreContainerType) current.get(stoc_class); - else { - returnStocType = new StoreContainerType(stoc_class, stoc_type); - current.put(stoc_class, returnStocType); - } - } - return returnStocType; - } - - public int getStocType() { - return stocType; - } - - public Class getStocClass() { - return stocClass; - } - - public String getConfPrefix() { - return StoreUtil.getPropNameFor(stocClass) + "." + - stringForStoreType(stocType); - } - - public int getDefaultSize() { - String confProperty = "StoreContainer." + stringForStoreType(stocType) + - ".DefaultSize"; - return - StringUtil.parseInt(o_store.getConfProperty(confProperty), 10); - } - - public String toString() { - StringBuffer sb = new StringBuffer(this.stocClass.toString()); - sb.append("@").append(stringForStoreType(stocType)); - return sb.toString(); - } - - private static String stringForStoreType(int stocType) { - switch (stocType) { - case STOC_TYPE_ENTITY: - return "Entity"; - case STOC_TYPE_ENTITYLIST: - return "EntityList"; - default: - return "UNKNOWN"; - } - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.storage.store; + +/** + * Title: StoreContainerType + * + * Description: StoreContainerTypes are uniqe Objects and are generated + * via @see valueOf(Class stocClass, int stocType). + * For every combination of stocClass and stocType there is + * only one Object instantiated. + * + * Copyright: Copyright (c) 2002 + * Company: indy + * + * @author rk + * @version 1.0 + */ + +import java.util.HashMap; +import java.util.Map; + +import mir.misc.StringUtil; + +public class StoreContainerType { + + public final static int STOC_TYPE_UNKNOWN = -1; + public final static int STOC_TYPE_ENTITY = 0; + public final static int STOC_TYPE_ENTITYLIST = 1; + public final static int STOC_TYPE_MAX = STOC_TYPE_ENTITYLIST; + + private static Map[] uniqueTypes = new HashMap[STOC_TYPE_MAX + 1]; + private static ObjectStore o_store = ObjectStore.getInstance(); + private Class stocClass = null; + private int stocType = STOC_TYPE_UNKNOWN; + + static { + uniqueTypes[STOC_TYPE_ENTITY] = new HashMap(); + uniqueTypes[STOC_TYPE_ENTITYLIST] = new HashMap(); + } + + private StoreContainerType() {} + + private StoreContainerType(Class stocClass, int stocType) { + this.stocClass = stocClass; + this.stocType = stocType; + } + + public static StoreContainerType valueOf(Class stoc_class, int stoc_type) { + StoreContainerType returnStocType = null; + if (stoc_type >= 0 && stoc_type <= STOC_TYPE_MAX) { + Map current = uniqueTypes[stoc_type]; + if (current.containsKey(stoc_class)) + returnStocType = (StoreContainerType) current.get(stoc_class); + else { + returnStocType = new StoreContainerType(stoc_class, stoc_type); + current.put(stoc_class, returnStocType); + } + } + return returnStocType; + } + + public int getStocType() { + return stocType; + } + + public Class getStocClass() { + return stocClass; + } + + public String getConfPrefix() { + return StoreUtil.getPropNameFor(stocClass) + "." + + stringForStoreType(stocType); + } + + public int getDefaultSize() { + String confProperty = "StoreContainer." + stringForStoreType(stocType) + + ".DefaultSize"; + return + StringUtil.parseInt(o_store.getConfProperty(confProperty), 10); + } + + public String toString() { + StringBuffer sb = new StringBuffer(this.stocClass.toString()); + sb.append("@").append(stringForStoreType(stocType)); + return sb.toString(); + } + + private static String stringForStoreType(int stocType) { + switch (stocType) { + case STOC_TYPE_ENTITY: + return "Entity"; + case STOC_TYPE_ENTITYLIST: + return "EntityList"; + default: + return "UNKNOWN"; + } + } } \ No newline at end of file diff --git a/source/mir/storage/store/StoreIdentifier.java b/source/mir/storage/store/StoreIdentifier.java index 91949aa7..e5fa9271 100755 --- a/source/mir/storage/store/StoreIdentifier.java +++ b/source/mir/storage/store/StoreIdentifier.java @@ -1,187 +1,187 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.storage.store; - -/** - * Title: Class StoreIdentifier - * Description: StoreIdentifier has two functions. - * A) StoreIdenfier holds a reference to a @see StorableObject - * or B) StoreIdentifier is used too search for a @see StorableObject - * in the @see StoreContainer that matches its - * - * Copyright: Copyright (c) 2002 - * Company: indy - * @author rk - * @version 1.0 - */ -import java.util.Iterator; -import java.util.Set; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; - -public class StoreIdentifier { - - /** @todo check if invalidating already to avoid deadlocks - * what about concurrency? */ - - private static ObjectStore o_store = ObjectStore.getInstance(); - - private StoreContainerType stocType = null; - private StorableObject reference = null; - private String uniqueIdentifier = null; // id for Entity & sql for EntityList - private long timesUsed; - private boolean invalidating = false; - - protected LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore"); - - /** @todo initialize logfile */ - - private StoreIdentifier() {} - - public StoreIdentifier(StorableObject reference, int storeType, - String uniqueIdentifier) { - Class theClass; - if (reference instanceof EntityList) - theClass = ( (EntityList) reference).getStorage().getEntityClass(); - else - theClass = reference.getClass(); - this.uniqueIdentifier = uniqueIdentifier; - this.stocType = StoreContainerType.valueOf(theClass, storeType); - this.reference = reference; - } - - public StoreIdentifier(StorableObject reference, String uniqueIdentifier) { - this(reference, StoreContainerType.STOC_TYPE_ENTITY, uniqueIdentifier); - } - - public StoreIdentifier(Class theClass, String uniqueIdentifier) { - this(theClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueIdentifier); - } - - public StoreIdentifier(Class theClass, int storeType, String uniqueIdentifier) { - this.uniqueIdentifier = uniqueIdentifier; - this.stocType = StoreContainerType.valueOf(theClass, storeType); - } - - /** - * Method: ivalidate - * Description: - * - * @return - */ - public void invalidate() { - logger.info("Invalidating: " + toString()); - // avoid deadlock due to propagation. - if (!invalidating) { - invalidating = true; - if (stocType != null && - stocType.getStocType() == StoreContainerType.STOC_TYPE_ENTITY) { - logger.info("Propagating invalidation to EntityList for " + toString()); - // we should invalidate related ENTITY_LIST - StoreContainerType entityListStocType = - StoreContainerType.valueOf(stocType.getStocClass(), - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(entityListStocType); - } - - // propagate invalidation to Set - Set set = reference.getNotifyOnReleaseSet(); - if (set != null) { - for (Iterator it = set.iterator(); it.hasNext(); ) { - Object o = it.next(); - if (o instanceof StoreIdentifier) { - logger.info("Propagating invalidation to StoreIdentifier: " + o.toString()); - // propagate invalidation to a specific StoreIdentifier in cache - o_store.invalidate( (StoreIdentifier) o); - } - else if (o instanceof StoreContainerType) { - logger.info("Propagating invalidation to StoreContainer: " + o.toString()); - // propagate invalidation to a whole StoreContainer - o_store.invalidate( (StoreContainerType) o); - } - - } - } - release(); - } - } - - public void release() { - this.reference = null; - this.uniqueIdentifier = null; - this.stocType = null; - } - - public StorableObject use() { - timesUsed++; - return reference; - } - - /** - * Method equals for comparison between two identifier - * - * @return true if yes otherwise false - * - */ - public boolean equals(Object sid) { - if (! (sid instanceof StoreIdentifier)) - return false; - if ( ( (StoreIdentifier) sid).getStoreContainerType() == stocType && - ( (StoreIdentifier) sid).getUniqueIdentifier().equals(uniqueIdentifier)) { - return true; - } - return false; - } - - public StoreContainerType getStoreContainerType() { - return stocType; - } - - public String getUniqueIdentifier() { - return uniqueIdentifier; - } - - public boolean hasReference() { - return (reference == null) ? false : true; - } - - public String toString() { - StringBuffer id = new StringBuffer(uniqueIdentifier); - id.append("@storetype: ").append(stocType.toString()); - if (reference != null) - id.append(" (" + timesUsed).append(") times used."); - return id.toString(); - } - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.storage.store; + +/** + * Title: Class StoreIdentifier + * Description: StoreIdentifier has two functions. + * A) StoreIdenfier holds a reference to a @see StorableObject + * or B) StoreIdentifier is used too search for a @see StorableObject + * in the @see StoreContainer that matches its + * + * Copyright: Copyright (c) 2002 + * Company: indy + * @author rk + * @version 1.0 + */ +import java.util.Iterator; +import java.util.Set; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; + +public class StoreIdentifier { + + /** @todo check if invalidating already to avoid deadlocks + * what about concurrency? */ + + private static ObjectStore o_store = ObjectStore.getInstance(); + + private StoreContainerType stocType = null; + private StorableObject reference = null; + private String uniqueIdentifier = null; // id for Entity & sql for EntityList + private long timesUsed; + private boolean invalidating = false; + + protected LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore"); + + /** @todo initialize logfile */ + + private StoreIdentifier() {} + + public StoreIdentifier(StorableObject reference, int storeType, + String uniqueIdentifier) { + Class theClass; + if (reference instanceof EntityList) + theClass = ( (EntityList) reference).getStorage().getEntityClass(); + else + theClass = reference.getClass(); + this.uniqueIdentifier = uniqueIdentifier; + this.stocType = StoreContainerType.valueOf(theClass, storeType); + this.reference = reference; + } + + public StoreIdentifier(StorableObject reference, String uniqueIdentifier) { + this(reference, StoreContainerType.STOC_TYPE_ENTITY, uniqueIdentifier); + } + + public StoreIdentifier(Class theClass, String uniqueIdentifier) { + this(theClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueIdentifier); + } + + public StoreIdentifier(Class theClass, int storeType, String uniqueIdentifier) { + this.uniqueIdentifier = uniqueIdentifier; + this.stocType = StoreContainerType.valueOf(theClass, storeType); + } + + /** + * Method: ivalidate + * Description: + * + * @return + */ + public void invalidate() { + logger.info("Invalidating: " + toString()); + // avoid deadlock due to propagation. + if (!invalidating) { + invalidating = true; + if (stocType != null && + stocType.getStocType() == StoreContainerType.STOC_TYPE_ENTITY) { + logger.info("Propagating invalidation to EntityList for " + toString()); + // we should invalidate related ENTITY_LIST + StoreContainerType entityListStocType = + StoreContainerType.valueOf(stocType.getStocClass(), + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(entityListStocType); + } + + // propagate invalidation to Set + Set set = reference.getNotifyOnReleaseSet(); + if (set != null) { + for (Iterator it = set.iterator(); it.hasNext(); ) { + Object o = it.next(); + if (o instanceof StoreIdentifier) { + logger.info("Propagating invalidation to StoreIdentifier: " + o.toString()); + // propagate invalidation to a specific StoreIdentifier in cache + o_store.invalidate( (StoreIdentifier) o); + } + else if (o instanceof StoreContainerType) { + logger.info("Propagating invalidation to StoreContainer: " + o.toString()); + // propagate invalidation to a whole StoreContainer + o_store.invalidate( (StoreContainerType) o); + } + + } + } + release(); + } + } + + public void release() { + this.reference = null; + this.uniqueIdentifier = null; + this.stocType = null; + } + + public StorableObject use() { + timesUsed++; + return reference; + } + + /** + * Method equals for comparison between two identifier + * + * @return true if yes otherwise false + * + */ + public boolean equals(Object sid) { + if (! (sid instanceof StoreIdentifier)) + return false; + if ( ( (StoreIdentifier) sid).getStoreContainerType() == stocType && + ( (StoreIdentifier) sid).getUniqueIdentifier().equals(uniqueIdentifier)) { + return true; + } + return false; + } + + public StoreContainerType getStoreContainerType() { + return stocType; + } + + public String getUniqueIdentifier() { + return uniqueIdentifier; + } + + public boolean hasReference() { + return (reference == null) ? false : true; + } + + public String toString() { + StringBuffer id = new StringBuffer(uniqueIdentifier); + id.append("@storetype: ").append(stocType.toString()); + if (reference != null) + id.append(" (" + timesUsed).append(") times used."); + return id.toString(); + } + + } \ No newline at end of file diff --git a/source/mir/util/FileFunctions.java b/source/mir/util/FileFunctions.java index bdca26ac..20d20e5c 100755 --- a/source/mir/util/FileFunctions.java +++ b/source/mir/util/FileFunctions.java @@ -1,109 +1,109 @@ -package mir.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.FilenameFilter; - -import gnu.regexp.RE; - -public class FileFunctions { - protected static final int FILE_COPY_BUFFER_SIZE = 65536; - - private FileFunctions() { - } - - public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException { - FileInputStream inputStream; - FileOutputStream outputStream; - int nrBytesRead; - byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE]; - - inputStream = new FileInputStream(aSourceFile); - try { - File directory = new File(aDestinationFile.getParent()); - if (directory!=null && !directory.exists()){ - directory.mkdirs(); - } - outputStream = new FileOutputStream(aDestinationFile); - try { - do { - nrBytesRead = inputStream.read(buffer); - if (nrBytesRead>0) - outputStream.write(buffer, 0, nrBytesRead); - } - while (nrBytesRead>=0); - } - finally { - outputStream.close(); - } - } - finally { - inputStream.close(); - } - } - - public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException { - int i; - File sourceFile; - File destinationFile; - File[] files = aSourceDirectory.listFiles(); - - if (!aDestinationDirectory.exists()) - aDestinationDirectory.mkdirs(); - - for (i=0; i0) + outputStream.write(buffer, 0, nrBytesRead); + } + while (nrBytesRead>=0); + } + finally { + outputStream.close(); + } + } + finally { + inputStream.close(); + } + } + + public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException { + int i; + File sourceFile; + File destinationFile; + File[] files = aSourceDirectory.listFiles(); + + if (!aDestinationDirectory.exists()) + aDestinationDirectory.mkdirs(); + + for (i=0; i', '"' }; - final String[] ESCAPE_CODES = { "&", "<", ">", """ }; - - return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES); - } - - public static String encodeXML(String aText) { - final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"', '\'' }; - final String[] ESCAPE_CODES = { "&", "<", ">", """, "'" }; - - return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES); - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.util; + +import java.net.URLEncoder; + +public class HTMLRoutines { + + public static String encodeURL(String aString) { + return URLEncoder.encode(aString); + } + + /** + * + * + * @param aString + * @param anEncoding the encoding to use (Note: JDK 1.3 does not seem to support custom + * encodings, so this parameter is ignored for now) + * @return + */ + + public static String encodeURL(String aString, String anEncoding) { + try { + return URLEncoder.encode(aString); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + + public static String encodeHTML(String aText) { + final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"' }; + final String[] ESCAPE_CODES = { "&", "<", ">", """ }; + + return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES); + } + + public static String encodeXML(String aText) { + final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"', '\'' }; + final String[] ESCAPE_CODES = { "&", "<", ">", """, "'" }; + + return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES); + } } \ No newline at end of file diff --git a/source/mir/util/HTTPRequestParser.java b/source/mir/util/HTTPRequestParser.java index 5303102f..20bfd910 100755 --- a/source/mir/util/HTTPRequestParser.java +++ b/source/mir/util/HTTPRequestParser.java @@ -1,58 +1,58 @@ -package mir.util; - -import javax.servlet.http.HttpServletRequest; - -public class HTTPRequestParser { - private HttpServletRequest request; - private String encoding; - - public HTTPRequestParser(HttpServletRequest aRequest) { - this(aRequest, aRequest.getCharacterEncoding()); - } - - public HTTPRequestParser(HttpServletRequest aRequest, String anEncoding) { - request = aRequest; - encoding = anEncoding; - } - - public boolean hasParameter(String aName) { - return request.getParameter(aName)!=null; - } - - public String getParameterWithDefault(String aName, String aDefault) { - if (hasParameter(aName)) - return getParameter(aName); - else - return aDefault; - } - - public String getParameter(String aName) { - try { - String result = request.getParameter(aName); - String requestEncoding = request.getCharacterEncoding(); - if (requestEncoding==null) - requestEncoding = "ISO-8859-1"; - - if (result != null && encoding!=null && !encoding.equals(requestEncoding)) { - result = new String(result.getBytes(requestEncoding), encoding); - } - - return result; - } - catch (Throwable t) { - throw new RuntimeException("HTTPRequestParser.getParameter: " + t.getMessage()); - } - } - - public int getIntegerWithDefault(String aName, int aDefault) { - int result = aDefault; - String value = getParameter(aName); - - try { - result = Integer.parseInt(value); - } - catch (Throwable t) { - } - return result; - } +package mir.util; + +import javax.servlet.http.HttpServletRequest; + +public class HTTPRequestParser { + private HttpServletRequest request; + private String encoding; + + public HTTPRequestParser(HttpServletRequest aRequest) { + this(aRequest, aRequest.getCharacterEncoding()); + } + + public HTTPRequestParser(HttpServletRequest aRequest, String anEncoding) { + request = aRequest; + encoding = anEncoding; + } + + public boolean hasParameter(String aName) { + return request.getParameter(aName)!=null; + } + + public String getParameterWithDefault(String aName, String aDefault) { + if (hasParameter(aName)) + return getParameter(aName); + else + return aDefault; + } + + public String getParameter(String aName) { + try { + String result = request.getParameter(aName); + String requestEncoding = request.getCharacterEncoding(); + if (requestEncoding==null) + requestEncoding = "ISO-8859-1"; + + if (result != null && encoding!=null && !encoding.equals(requestEncoding)) { + result = new String(result.getBytes(requestEncoding), encoding); + } + + return result; + } + catch (Throwable t) { + throw new RuntimeException("HTTPRequestParser.getParameter: " + t.getMessage()); + } + } + + public int getIntegerWithDefault(String aName, int aDefault) { + int result = aDefault; + String value = getParameter(aName); + + try { + result = Integer.parseInt(value); + } + catch (Throwable t) { + } + return result; + } } \ No newline at end of file diff --git a/source/mir/util/PropertiesManipulator.java b/source/mir/util/PropertiesManipulator.java index 31bd19e3..a60a8ca3 100755 --- a/source/mir/util/PropertiesManipulator.java +++ b/source/mir/util/PropertiesManipulator.java @@ -1,290 +1,290 @@ -package mir.util; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; -import java.io.OutputStream; -import java.io.*; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import multex.Exc; -import multex.Failure; - -public class PropertiesManipulator { - private List entries; - private Map values; - - public PropertiesManipulator() { - entries = new Vector(); - values = new HashMap(); - } - - public void addEmptyLine() { - entries.add(new EmptyLine()); - } - - public void addComment(String aComment) { - entries.add(new Comment(aComment)); - } - - public void addEntry(String aKey, String aValue) { - entries.add(new Entry(aKey, aValue)); - values.put(aKey, aValue); - } - - public Iterator getEntries() { - return entries.iterator(); - } - - public String get(String aKey) { - return (String) values.get(aKey); - } - - public boolean containsKey(String aKey) { - return values.containsKey(aKey); - } - - public static class Comment { - private String comment; - - public Comment(String aComment) { - comment = aComment; - } - - public String getComment() { - return comment; - } - } - - public static class EmptyLine { - public EmptyLine() { - } - } - - public static class Entry { - private String key; - private String value; - - public Entry(String aKey, String aValue) { - key = aKey; - value = aValue; - } - - public String getKey() { - return key; - } - - public String getValue() { - return value; - } - } - - private final static String PLAIN= "[^\\\\]*"; - private final static String ESCAPE= "\\\\[ tn]"; - private final static String UNICODE= "\\\\u[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]"; - - - private static String decode(String aValue) { - try { - SimpleParser parser = new SimpleParser(aValue); - StringBuffer result = new StringBuffer(); - - while (!parser.isAtEnd()) { - result.append(parser.parse(PLAIN)); - - if (!parser.isAtEnd()) { - if (parser.parses(UNICODE)) { - String unicode = parser.parse(UNICODE); - - result.append((char) Integer.parseInt(unicode.substring(2,6), 16)); - } - else if (parser.parses(ESCAPE)) { - String escape = parser.parse(ESCAPE); - result.append(escape.substring(1)); - } - else - throw new PropertiesManipulatorExc("Invalid escape code: " + parser.remainingData()); - } - } - - return result.toString(); - } - catch (Throwable t) { - throw new PropertiesManipulatorFailure(t); - } - } - - private static String encode(String aValue, boolean aUseUnicodeEscapes) { - try { - StringBuffer result = new StringBuffer(); - boolean leadingspace=true; - - for (int i = 0; i0x7e)) { - String code=Integer.toHexString(c); - result.append("\\u"); - for (int j=0; j<4-code.length(); j++) - result.append("0"); - result.append(code); - } - else if (c=='\\') - { - result.append("\\\\"); - } - else if (c=='\n') - { - result.append("\\n"); - } - else if (c=='\r') - { - result.append("\\r"); - } - else if (c=='\t') - { - result.append("\\t"); - } - else if (c==' ' && leadingspace) { - result.append("\\ "); - } - else { - result.append(c); - } - - leadingspace = leadingspace && c ==' '; - } - - return result.toString(); - } - catch (Throwable t) { - throw new PropertiesManipulatorFailure(t); - } - } - - // ML: to be fixed - private final static String SPACE = "[\t\n\r ]*"; - private final static String KEY = "(([\\\\].)|([^\\\\=: \t\n\r]))*"; - private final static String SEPARATOR = "[\t\n\r ]*[:=]?[\t\n\r ]*"; - private final static String VALUE = "(([\\\\].)|([^\\\\]))*"; - - - public static PropertiesManipulator readProperties(InputStream anInputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { - return readProperties(anInputStream, "ISO-8859-1"); - } - - public static PropertiesManipulator readProperties(InputStream anInputStream, String anEncoding) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { - try { - PropertiesManipulator result = new PropertiesManipulator(); - LineNumberReader reader = new LineNumberReader(new InputStreamReader(anInputStream, anEncoding)); - - String line = reader.readLine(); - - while (line != null) { - String trimmedLine = line.trim(); - - if (trimmedLine.length() == 0) { - result.addEmptyLine(); - } - else if (trimmedLine.startsWith("!") || trimmedLine.startsWith("#")) { - result.addComment(line); - } - else { - SimpleParser parser = new SimpleParser(line); - parser.skip(SPACE); - String key = parser.parse(KEY); - parser.skip(SEPARATOR); - String value = parser.parse(VALUE); - while (parser.remainingData().length()>0) { - if (!parser.remainingData().equals("\\")) - throw new PropertiesManipulatorExc("internal error: remainingData = " + parser.remainingData()); - - line = reader.readLine(); - if (line==null) { - throw new PropertiesManipulatorExc("Unexpected end of file"); - } - parser = new SimpleParser(line); - parser.skip(SPACE); - value = value + parser.parse(VALUE); - } - - result.addEntry(decode(key), decode(value)); - } - line = reader.readLine(); - } - - reader.close(); - - return result; - } - catch (PropertiesManipulatorExc t) { - throw t; - } - catch (Throwable t) { - throw new PropertiesManipulatorFailure(t); - } - } - - public static void writeProperties(PropertiesManipulator aProperties, OutputStream anOutputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { - writeProperties(aProperties, anOutputStream, "ISO-8859-1", true); - } - - public static void writeProperties(PropertiesManipulator aProperties, OutputStream anOutputStream, String anEncoding, boolean aUseUnicodeEscapes) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { - try { - PrintWriter p = new PrintWriter(new OutputStreamWriter(anOutputStream, anEncoding)); - - try { - Iterator i = aProperties.getEntries(); - - while (i.hasNext()) { - Object entry = i.next(); - - if (entry instanceof EmptyLine) { - p.println(); - } - else if (entry instanceof Comment) { - p.println(((Comment) entry).getComment()); - } - else if (entry instanceof Entry) { - String key = encode( ( (Entry) entry).getKey(), aUseUnicodeEscapes); - String value = ""; - if ( ( (Entry) entry).getValue() != null) - value = encode( ( (Entry) entry).getValue(), aUseUnicodeEscapes); - - String line = key + " = " + value; - - p.println(line); - - } - else throw new PropertiesManipulatorExc("Unknown entry class: " +entry.getClass().getName()); - } - } - finally { - p.close(); - } - } - catch (Throwable t) { - throw new PropertiesManipulatorFailure(t); - } - } - - public static class PropertiesManipulatorFailure extends Failure { - public PropertiesManipulatorFailure(Throwable aThrowable) { - super(aThrowable.getMessage(), aThrowable); - } - - public PropertiesManipulatorFailure(String aMessage, Throwable aThrowable) { - super(aMessage, aThrowable); - } - } - - public static class PropertiesManipulatorExc extends Exc { - public PropertiesManipulatorExc(String aMessage) { - super(aMessage); - } - } +package mir.util; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.OutputStream; +import java.io.*; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import multex.Exc; +import multex.Failure; + +public class PropertiesManipulator { + private List entries; + private Map values; + + public PropertiesManipulator() { + entries = new Vector(); + values = new HashMap(); + } + + public void addEmptyLine() { + entries.add(new EmptyLine()); + } + + public void addComment(String aComment) { + entries.add(new Comment(aComment)); + } + + public void addEntry(String aKey, String aValue) { + entries.add(new Entry(aKey, aValue)); + values.put(aKey, aValue); + } + + public Iterator getEntries() { + return entries.iterator(); + } + + public String get(String aKey) { + return (String) values.get(aKey); + } + + public boolean containsKey(String aKey) { + return values.containsKey(aKey); + } + + public static class Comment { + private String comment; + + public Comment(String aComment) { + comment = aComment; + } + + public String getComment() { + return comment; + } + } + + public static class EmptyLine { + public EmptyLine() { + } + } + + public static class Entry { + private String key; + private String value; + + public Entry(String aKey, String aValue) { + key = aKey; + value = aValue; + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + } + + private final static String PLAIN= "[^\\\\]*"; + private final static String ESCAPE= "\\\\[ tn]"; + private final static String UNICODE= "\\\\u[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]"; + + + private static String decode(String aValue) { + try { + SimpleParser parser = new SimpleParser(aValue); + StringBuffer result = new StringBuffer(); + + while (!parser.isAtEnd()) { + result.append(parser.parse(PLAIN)); + + if (!parser.isAtEnd()) { + if (parser.parses(UNICODE)) { + String unicode = parser.parse(UNICODE); + + result.append((char) Integer.parseInt(unicode.substring(2,6), 16)); + } + else if (parser.parses(ESCAPE)) { + String escape = parser.parse(ESCAPE); + result.append(escape.substring(1)); + } + else + throw new PropertiesManipulatorExc("Invalid escape code: " + parser.remainingData()); + } + } + + return result.toString(); + } + catch (Throwable t) { + throw new PropertiesManipulatorFailure(t); + } + } + + private static String encode(String aValue, boolean aUseUnicodeEscapes) { + try { + StringBuffer result = new StringBuffer(); + boolean leadingspace=true; + + for (int i = 0; i0x7e)) { + String code=Integer.toHexString(c); + result.append("\\u"); + for (int j=0; j<4-code.length(); j++) + result.append("0"); + result.append(code); + } + else if (c=='\\') + { + result.append("\\\\"); + } + else if (c=='\n') + { + result.append("\\n"); + } + else if (c=='\r') + { + result.append("\\r"); + } + else if (c=='\t') + { + result.append("\\t"); + } + else if (c==' ' && leadingspace) { + result.append("\\ "); + } + else { + result.append(c); + } + + leadingspace = leadingspace && c ==' '; + } + + return result.toString(); + } + catch (Throwable t) { + throw new PropertiesManipulatorFailure(t); + } + } + + // ML: to be fixed + private final static String SPACE = "[\t\n\r ]*"; + private final static String KEY = "(([\\\\].)|([^\\\\=: \t\n\r]))*"; + private final static String SEPARATOR = "[\t\n\r ]*[:=]?[\t\n\r ]*"; + private final static String VALUE = "(([\\\\].)|([^\\\\]))*"; + + + public static PropertiesManipulator readProperties(InputStream anInputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { + return readProperties(anInputStream, "ISO-8859-1"); + } + + public static PropertiesManipulator readProperties(InputStream anInputStream, String anEncoding) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { + try { + PropertiesManipulator result = new PropertiesManipulator(); + LineNumberReader reader = new LineNumberReader(new InputStreamReader(anInputStream, anEncoding)); + + String line = reader.readLine(); + + while (line != null) { + String trimmedLine = line.trim(); + + if (trimmedLine.length() == 0) { + result.addEmptyLine(); + } + else if (trimmedLine.startsWith("!") || trimmedLine.startsWith("#")) { + result.addComment(line); + } + else { + SimpleParser parser = new SimpleParser(line); + parser.skip(SPACE); + String key = parser.parse(KEY); + parser.skip(SEPARATOR); + String value = parser.parse(VALUE); + while (parser.remainingData().length()>0) { + if (!parser.remainingData().equals("\\")) + throw new PropertiesManipulatorExc("internal error: remainingData = " + parser.remainingData()); + + line = reader.readLine(); + if (line==null) { + throw new PropertiesManipulatorExc("Unexpected end of file"); + } + parser = new SimpleParser(line); + parser.skip(SPACE); + value = value + parser.parse(VALUE); + } + + result.addEntry(decode(key), decode(value)); + } + line = reader.readLine(); + } + + reader.close(); + + return result; + } + catch (PropertiesManipulatorExc t) { + throw t; + } + catch (Throwable t) { + throw new PropertiesManipulatorFailure(t); + } + } + + public static void writeProperties(PropertiesManipulator aProperties, OutputStream anOutputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { + writeProperties(aProperties, anOutputStream, "ISO-8859-1", true); + } + + public static void writeProperties(PropertiesManipulator aProperties, OutputStream anOutputStream, String anEncoding, boolean aUseUnicodeEscapes) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { + try { + PrintWriter p = new PrintWriter(new OutputStreamWriter(anOutputStream, anEncoding)); + + try { + Iterator i = aProperties.getEntries(); + + while (i.hasNext()) { + Object entry = i.next(); + + if (entry instanceof EmptyLine) { + p.println(); + } + else if (entry instanceof Comment) { + p.println(((Comment) entry).getComment()); + } + else if (entry instanceof Entry) { + String key = encode( ( (Entry) entry).getKey(), aUseUnicodeEscapes); + String value = ""; + if ( ( (Entry) entry).getValue() != null) + value = encode( ( (Entry) entry).getValue(), aUseUnicodeEscapes); + + String line = key + " = " + value; + + p.println(line); + + } + else throw new PropertiesManipulatorExc("Unknown entry class: " +entry.getClass().getName()); + } + } + finally { + p.close(); + } + } + catch (Throwable t) { + throw new PropertiesManipulatorFailure(t); + } + } + + public static class PropertiesManipulatorFailure extends Failure { + public PropertiesManipulatorFailure(Throwable aThrowable) { + super(aThrowable.getMessage(), aThrowable); + } + + public PropertiesManipulatorFailure(String aMessage, Throwable aThrowable) { + super(aMessage, aThrowable); + } + } + + public static class PropertiesManipulatorExc extends Exc { + public PropertiesManipulatorExc(String aMessage) { + super(aMessage); + } + } } \ No newline at end of file diff --git a/source/mir/util/ResourceBundleGeneratorFunction.java b/source/mir/util/ResourceBundleGeneratorFunction.java index 5571c310..e27ce230 100755 --- a/source/mir/util/ResourceBundleGeneratorFunction.java +++ b/source/mir/util/ResourceBundleGeneratorFunction.java @@ -1,89 +1,94 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.util; - -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Vector; - -import mir.generator.Generator; -import mir.generator.GeneratorExc; - -import org.apache.struts.util.MessageResources; - -public class ResourceBundleGeneratorFunction implements Generator.GeneratorFunction { - private List messages; - private Locale locale; - - public ResourceBundleGeneratorFunction(Locale aLocale, MessageResources aMessages) { - this(aLocale, new MessageResources[] {aMessages} ); - } - - public ResourceBundleGeneratorFunction(Locale aLocale, MessageResources aMessages1, MessageResources aMessages2) { - this(aLocale, new MessageResources[] {aMessages1, aMessages2} ); - } - - public ResourceBundleGeneratorFunction(Locale aLocale, MessageResources[] aMessages) { - locale = aLocale; - messages = new Vector(); - - for(int i=0; iTitle:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class SimpleParser { - private String data; - private int position; - - /** - * - * @param aData - */ - - public SimpleParser(String aData) { - data=aData; - position=0; - } - - /** - * - * @param aRegularExpression - * @return - * @throws SimpleParserExc - */ - - public boolean parses(RE aRegularExpression) throws SimpleParserExc { - REMatch match = aRegularExpression.getMatch(data, position); - - return (match!=null && match.getStartIndex()==position) ; - } - - /** - * - * @param aRegularExpression - * @param aMessage - * @return - * @throws SimpleParserExc - */ - - public String parse(RE aRegularExpression, String aMessage) throws SimpleParserExc { - REMatch match = aRegularExpression.getMatch(data, position); - - if (match==null || match.getStartIndex()!=position) - throw new SimpleParserExc(aMessage+" at position "+position+" in '"+data+"'"); - - position=match.getEndIndex(); - - return match.toString(); - } - - /** - * - * @param aRegularExpression - * @return - * @throws SimpleParserExc - */ - - public String parse(RE aRegularExpression) throws SimpleParserExc { - return parse( aRegularExpression, "No match found for '"+aRegularExpression.toString()+"'"); - } - - /** - * - * @param aRegularExpression - * @throws SimpleParserExc - */ - - public void skip(RE aRegularExpression) throws SimpleParserExc { - REMatch match = aRegularExpression.getMatch(data, position); - - if (match!=null && match.getStartIndex()==position) - position=match.getEndIndex(); - } - - /** - * - * @param anExpression - * @return - * @throws SimpleParserExc - */ - - public boolean parses(String anExpression) throws SimpleParserExc { - try { - return parses(new RE(anExpression)); - } - catch (SimpleParserExc e) { - throw e; - } - catch (REException e) { - throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); - } - catch (Throwable t) { - throw new SimpleParserFailure( t ); - } - } - - /** - * - * @param anExpression - * @return - * @throws SimpleParserExc - * @throws SimpleParserFailure - */ - - public String parse(String anExpression) throws SimpleParserExc, SimpleParserFailure { - try { - return parse(new RE(anExpression)); - } - catch (SimpleParserExc e) { - throw e; - } - catch (REException e) { - throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); - } - catch (Throwable t) { - throw new SimpleParserFailure( t ); - } - } - - /** - * - * @param anExpression - * @param aMessage - * @return - * @throws SimpleParserExc - * @throws SimpleParserFailure - */ - - public String parse(String anExpression, String aMessage) throws SimpleParserExc, SimpleParserFailure { - try { - return parse(new RE(anExpression), aMessage); - } - catch (SimpleParserExc e) { - throw e; - } - catch (REException e) { - throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); - } - catch (Throwable t) { - throw new SimpleParserFailure( t ); - } - } - - /** - * - * @param anExpression - * @throws SimpleParserExc - * @throws SimpleParserFailure - */ - - public void skip(String anExpression) throws SimpleParserExc, SimpleParserFailure { - try { - skip(new RE(anExpression)); - } - catch (SimpleParserExc e) { - throw e; - } - catch (REException e) { - throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); - } - catch (Throwable t) { - throw new SimpleParserFailure( t ); - } - } - - /** - * - * @return true if the parser is at the end of the data - */ - - public boolean isAtEnd() { - return position>=data.length(); - } - - /** - * - * @return - */ - public String remainingData() { - return data.substring(position); - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - - public static class SimpleParserFailure extends Failure { - public SimpleParserFailure(Throwable aThrowable) { - super(aThrowable.getMessage(), aThrowable); - } - - public SimpleParserFailure(String aMessage, Throwable aThrowable) { - super(aMessage, aThrowable); - } - } - - public static class SimpleParserExc extends Exc { - public SimpleParserExc(String aMessage) { - super(aMessage); - } - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.util; + +import gnu.regexp.RE; +import gnu.regexp.REException; +import gnu.regexp.REMatch; +import multex.Exc; +import multex.Failure; + +/** + * a class to do some basic, regexp based parsing of character data + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class SimpleParser { + private String data; + private int position; + + /** + * + * @param aData + */ + + public SimpleParser(String aData) { + data=aData; + position=0; + } + + /** + * + * @param aRegularExpression + * @return + * @throws SimpleParserExc + */ + + public boolean parses(RE aRegularExpression) throws SimpleParserExc { + REMatch match = aRegularExpression.getMatch(data, position); + + return (match!=null && match.getStartIndex()==position) ; + } + + /** + * + * @param aRegularExpression + * @param aMessage + * @return + * @throws SimpleParserExc + */ + + public String parse(RE aRegularExpression, String aMessage) throws SimpleParserExc { + REMatch match = aRegularExpression.getMatch(data, position); + + if (match==null || match.getStartIndex()!=position) + throw new SimpleParserExc(aMessage+" at position "+position+" in '"+data+"'"); + + position=match.getEndIndex(); + + return match.toString(); + } + + /** + * + * @param aRegularExpression + * @return + * @throws SimpleParserExc + */ + + public String parse(RE aRegularExpression) throws SimpleParserExc { + return parse( aRegularExpression, "No match found for '"+aRegularExpression.toString()+"'"); + } + + /** + * + * @param aRegularExpression + * @throws SimpleParserExc + */ + + public void skip(RE aRegularExpression) throws SimpleParserExc { + REMatch match = aRegularExpression.getMatch(data, position); + + if (match!=null && match.getStartIndex()==position) + position=match.getEndIndex(); + } + + /** + * + * @param anExpression + * @return + * @throws SimpleParserExc + */ + + public boolean parses(String anExpression) throws SimpleParserExc { + try { + return parses(new RE(anExpression)); + } + catch (SimpleParserExc e) { + throw e; + } + catch (REException e) { + throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); + } + catch (Throwable t) { + throw new SimpleParserFailure( t ); + } + } + + /** + * + * @param anExpression + * @return + * @throws SimpleParserExc + * @throws SimpleParserFailure + */ + + public String parse(String anExpression) throws SimpleParserExc, SimpleParserFailure { + try { + return parse(new RE(anExpression)); + } + catch (SimpleParserExc e) { + throw e; + } + catch (REException e) { + throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); + } + catch (Throwable t) { + throw new SimpleParserFailure( t ); + } + } + + /** + * + * @param anExpression + * @param aMessage + * @return + * @throws SimpleParserExc + * @throws SimpleParserFailure + */ + + public String parse(String anExpression, String aMessage) throws SimpleParserExc, SimpleParserFailure { + try { + return parse(new RE(anExpression), aMessage); + } + catch (SimpleParserExc e) { + throw e; + } + catch (REException e) { + throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); + } + catch (Throwable t) { + throw new SimpleParserFailure( t ); + } + } + + /** + * + * @param anExpression + * @throws SimpleParserExc + * @throws SimpleParserFailure + */ + + public void skip(String anExpression) throws SimpleParserExc, SimpleParserFailure { + try { + skip(new RE(anExpression)); + } + catch (SimpleParserExc e) { + throw e; + } + catch (REException e) { + throw new SimpleParserFailure( "Error compiling regular expression '" + anExpression + "': " + e.getMessage(), e); + } + catch (Throwable t) { + throw new SimpleParserFailure( t ); + } + } + + /** + * + * @return true if the parser is at the end of the data + */ + + public boolean isAtEnd() { + return position>=data.length(); + } + + /** + * + * @return + */ + public String remainingData() { + return data.substring(position); + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + + public static class SimpleParserFailure extends Failure { + public SimpleParserFailure(Throwable aThrowable) { + super(aThrowable.getMessage(), aThrowable); + } + + public SimpleParserFailure(String aMessage, Throwable aThrowable) { + super(aMessage, aThrowable); + } + } + + public static class SimpleParserExc extends Exc { + public SimpleParserExc(String aMessage) { + super(aMessage); + } + } } \ No newline at end of file diff --git a/source/mir/util/XMLReader.java b/source/mir/util/XMLReader.java index b8bc9e35..23e08234 100755 --- a/source/mir/util/XMLReader.java +++ b/source/mir/util/XMLReader.java @@ -1,298 +1,298 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.StringReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import multex.Exc; -import multex.Failure; - -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -public class XMLReader { - private Locator locator; - private String filename; - private boolean namespaceAware; - - public XMLReader() { - this(false); - } - - public XMLReader(boolean aNameSpaceAware) { - namespaceAware = aNameSpaceAware; - filename=""; - } - - public void parseFile(String aFileName, SectionHandler aRootHandler) throws XMLReaderFailure, XMLReaderExc { - filename= aFileName; - try { - parseInputStream(new FileInputStream(aFileName), aRootHandler); - } - catch (Throwable t) { - throw new XMLReaderFailure(t); - } - } - - public void parseInputStream(InputStream anInputStream, SectionHandler aRootHandler) throws XMLReaderFailure, XMLReaderExc { - try { - SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - - parserFactory.setNamespaceAware(namespaceAware); - parserFactory.setValidating(true); - - XMLReaderHandler handler = new XMLReaderHandler(parserFactory, aRootHandler); - - handler.processInputStream(anInputStream); - } - catch (Throwable e) { - Throwable t = ExceptionFunctions.traceCauseException(e); - - if (t instanceof XMLReaderExc) { - if (locator!=null && filename!=null) - ((XMLReaderExc) t).setLocation(filename, locator.getLineNumber(), locator.getColumnNumber()); - throw (XMLReaderExc) t; - } - - if (t instanceof XMLReaderFailure) { - throw (XMLReaderFailure) t; - } - - throw new XMLReaderFailure(t); - } - } - - private class XMLReaderHandler extends DefaultHandler { - private SAXParserFactory parserFactory; - private SectionsManager manager; - private InputSource inputSource; - - public XMLReaderHandler(SAXParserFactory aParserFactory, SectionHandler aRootHandler) { - super(); - - parserFactory=aParserFactory; - manager = new SectionsManager(); - manager.pushHandler(aRootHandler); - } - - public void setDocumentLocator(Locator aLocator) { - locator=aLocator; - } - - private void processInputStream(InputStream anInputStream) throws XMLReaderExc, XMLReaderFailure { - try { - SAXParser parser=parserFactory.newSAXParser(); - - inputSource = new InputSource(anInputStream); - parser.parse(inputSource, this); - } - catch (ParserConfigurationException e) { - throw new XMLReaderExc("Internal exception: "+e.getMessage()); - } - catch (Throwable e) { - throw new XMLReaderFailure(e); - } - } - - public void startElement(String aUri, String aTag, String aQualifiedName, Attributes anAttributes) throws SAXException { - Map attributesMap; - int i; - - try { - attributesMap = new HashMap(); - for (i=0; i 0) { - throw new XMLReaderExc("Text not allowed"); - } - } - } - - public static class XMLReaderExc extends Exc { - private boolean hasLocation; - private String filename; - private int lineNr; - private int columnNr; - - public XMLReaderExc(String aMessage) { - super(aMessage); - hasLocation = false; - } - - protected void setLocation(String aFilename, int aLineNr, int aColumnNr) { - filename = aFilename; - lineNr = aLineNr; - columnNr = aColumnNr; - hasLocation = true; - } - - public boolean getHasLocation() { - return hasLocation; - } - - public int getLineNr() { - return lineNr; - } - - public int getColumnNr() { - return columnNr; - } - - public String getFilename() { - return filename; - } - } - - public static class XMLReaderFailure extends Failure { - public XMLReaderFailure(String aMessage, Throwable aCause) { - super(aMessage, aCause); - } - - public XMLReaderFailure(Throwable aCause) { - super(aCause.getMessage(), aCause); - } - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.StringReader; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Stack; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import multex.Exc; +import multex.Failure; + +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +public class XMLReader { + private Locator locator; + private String filename; + private boolean namespaceAware; + + public XMLReader() { + this(false); + } + + public XMLReader(boolean aNameSpaceAware) { + namespaceAware = aNameSpaceAware; + filename=""; + } + + public void parseFile(String aFileName, SectionHandler aRootHandler) throws XMLReaderFailure, XMLReaderExc { + filename= aFileName; + try { + parseInputStream(new FileInputStream(aFileName), aRootHandler); + } + catch (Throwable t) { + throw new XMLReaderFailure(t); + } + } + + public void parseInputStream(InputStream anInputStream, SectionHandler aRootHandler) throws XMLReaderFailure, XMLReaderExc { + try { + SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + + parserFactory.setNamespaceAware(namespaceAware); + parserFactory.setValidating(true); + + XMLReaderHandler handler = new XMLReaderHandler(parserFactory, aRootHandler); + + handler.processInputStream(anInputStream); + } + catch (Throwable e) { + Throwable t = ExceptionFunctions.traceCauseException(e); + + if (t instanceof XMLReaderExc) { + if (locator!=null && filename!=null) + ((XMLReaderExc) t).setLocation(filename, locator.getLineNumber(), locator.getColumnNumber()); + throw (XMLReaderExc) t; + } + + if (t instanceof XMLReaderFailure) { + throw (XMLReaderFailure) t; + } + + throw new XMLReaderFailure(t); + } + } + + private class XMLReaderHandler extends DefaultHandler { + private SAXParserFactory parserFactory; + private SectionsManager manager; + private InputSource inputSource; + + public XMLReaderHandler(SAXParserFactory aParserFactory, SectionHandler aRootHandler) { + super(); + + parserFactory=aParserFactory; + manager = new SectionsManager(); + manager.pushHandler(aRootHandler); + } + + public void setDocumentLocator(Locator aLocator) { + locator=aLocator; + } + + private void processInputStream(InputStream anInputStream) throws XMLReaderExc, XMLReaderFailure { + try { + SAXParser parser=parserFactory.newSAXParser(); + + inputSource = new InputSource(anInputStream); + parser.parse(inputSource, this); + } + catch (ParserConfigurationException e) { + throw new XMLReaderExc("Internal exception: "+e.getMessage()); + } + catch (Throwable e) { + throw new XMLReaderFailure(e); + } + } + + public void startElement(String aUri, String aTag, String aQualifiedName, Attributes anAttributes) throws SAXException { + Map attributesMap; + int i; + + try { + attributesMap = new HashMap(); + for (i=0; i 0) { + throw new XMLReaderExc("Text not allowed"); + } + } + } + + public static class XMLReaderExc extends Exc { + private boolean hasLocation; + private String filename; + private int lineNr; + private int columnNr; + + public XMLReaderExc(String aMessage) { + super(aMessage); + hasLocation = false; + } + + protected void setLocation(String aFilename, int aLineNr, int aColumnNr) { + filename = aFilename; + lineNr = aLineNr; + columnNr = aColumnNr; + hasLocation = true; + } + + public boolean getHasLocation() { + return hasLocation; + } + + public int getLineNr() { + return lineNr; + } + + public int getColumnNr() { + return columnNr; + } + + public String getFilename() { + return filename; + } + } + + public static class XMLReaderFailure extends Failure { + public XMLReaderFailure(String aMessage, Throwable aCause) { + super(aMessage, aCause); + } + + public XMLReaderFailure(Throwable aCause) { + super(aCause.getMessage(), aCause); + } + } + } \ No newline at end of file diff --git a/source/mircoders/entity/EntityAudio.java b/source/mircoders/entity/EntityAudio.java index 768e8ebd..3a46eed9 100755 --- a/source/mircoders/entity/EntityAudio.java +++ b/source/mircoders/entity/EntityAudio.java @@ -1,67 +1,67 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -import java.sql.SQLException; -import java.util.Map; - -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -/** - * This class handles storage of audio data and meta data - * - * @author mh - * @version $Id: EntityAudio.java,v 1.9 2003/03/16 19:54:45 zapata Exp $ - */ - - -public class EntityAudio extends EntityUploadedMedia -{ - public EntityAudio() { - super(); - } - - public EntityAudio(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (!theStringValues.containsKey("is_published")) - theStringValues.put("is_published", "0"); - } - super.setValues(theStringValues); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.entity; + +import java.sql.SQLException; +import java.util.Map; + +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * This class handles storage of audio data and meta data + * + * @author mh + * @version $Id: EntityAudio.java,v 1.10 2003/04/09 02:06:08 zapata Exp $ + */ + + +public class EntityAudio extends EntityUploadedMedia +{ + public EntityAudio() { + super(); + } + + public EntityAudio(StorageObject theStorage) { + this(); + setStorage(theStorage); + } + + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (!theStringValues.containsKey("is_published")) + theStringValues.put("is_published", "0"); + } + super.setValues(theStringValues); + } + +} diff --git a/source/mircoders/entity/EntityOther.java b/source/mircoders/entity/EntityOther.java index a470850f..4a72359f 100755 --- a/source/mircoders/entity/EntityOther.java +++ b/source/mircoders/entity/EntityOther.java @@ -1,67 +1,67 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -import java.sql.SQLException; -import java.util.Map; - -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -/** - * This class handles storage of other data and meta data - * - * @author mh - * @version 11.11.2000 - */ - - -public class EntityOther extends EntityUploadedMedia -{ - public EntityOther() { - super(); - } - - public EntityOther(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (!theStringValues.containsKey("is_published")) - theStringValues.put("is_published", "0"); - } - super.setValues(theStringValues); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.entity; + +import java.sql.SQLException; +import java.util.Map; + +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * This class handles storage of other data and meta data + * + * @author mh + * @version 11.11.2000 + */ + + +public class EntityOther extends EntityUploadedMedia +{ + public EntityOther() { + super(); + } + + public EntityOther(StorageObject theStorage) { + this(); + setStorage(theStorage); + } + + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (!theStringValues.containsKey("is_published")) + theStringValues.put("is_published", "0"); + } + super.setValues(theStringValues); + } + +} diff --git a/source/mircoders/entity/EntityVideo.java b/source/mircoders/entity/EntityVideo.java index b16d3d6c..8497fc95 100755 --- a/source/mircoders/entity/EntityVideo.java +++ b/source/mircoders/entity/EntityVideo.java @@ -1,70 +1,70 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -import java.sql.SQLException; -import java.util.Map; - -import mir.log.LoggerWrapper; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -/** - * Diese Klasse enth?lt die Daten eines MetaObjekts - * - * @author RK - * @version 11.11.2000 - */ - - -public class EntityVideo extends EntityUploadedMedia -{ - public EntityVideo() { - super(); - - logger = new LoggerWrapper("Entity.UploadedMedia.Video"); - } - - public EntityVideo(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (!theStringValues.containsKey("is_published")) - theStringValues.put("is_published", "0"); - } - super.setValues(theStringValues); - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.entity; + +import java.sql.SQLException; +import java.util.Map; + +import mir.log.LoggerWrapper; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse enth?lt die Daten eines MetaObjekts + * + * @author RK + * @version 11.11.2000 + */ + + +public class EntityVideo extends EntityUploadedMedia +{ + public EntityVideo() { + super(); + + logger = new LoggerWrapper("Entity.UploadedMedia.Video"); + } + + public EntityVideo(StorageObject theStorage) { + this(); + setStorage(theStorage); + } + + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (!theStringValues.containsKey("is_published")) + theStringValues.put("is_published", "0"); + } + super.setValues(theStringValues); + } + } \ No newline at end of file diff --git a/source/mircoders/global/Abuse.java b/source/mircoders/global/Abuse.java index 7ef49c30..0d2e630f 100755 --- a/source/mircoders/global/Abuse.java +++ b/source/mircoders/global/Abuse.java @@ -1,601 +1,601 @@ -package mircoders.global; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Vector; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.collections.ExtendedProperties; - -import gnu.regexp.RE; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.util.DateToMapAdapter; -import mir.util.InternetFunctions; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.localizer.MirAdminInterfaceLocalizer; - - -public class Abuse { - private List filters; - private int maxIdentifier; - private LoggerWrapper logger; - private int logSize; - private boolean logEnabled; - private boolean openPostingDisabled; - private boolean openPostingPassword; - private boolean cookieOnBlock; - private String articleBlockAction; - private String commentBlockAction; - private List log; - private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config"); - - - private static final String IP_FILTER_TYPE="ip"; - private static final String REGEXP_FILTER_TYPE="regexp"; - private static String cookieName=MirGlobal.config().getString("Abuse.CookieName"); - private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge"); - - public Abuse() { - logger = new LoggerWrapper("Global.Abuse"); - filters = new Vector(); - maxIdentifier = 0; - log = new Vector(); - - logSize = 100; - logEnabled = false; - articleBlockAction = ""; - commentBlockAction = ""; - openPostingPassword = false; - openPostingDisabled = false; - cookieOnBlock = false; - - load(); - } - - public boolean checkIpFilter(String anIpAddress) { - synchronized (filters) { - Iterator i = filters.iterator(); - - while (i.hasNext()) { - Filter filter = (Filter) i.next(); - - try { - if ( (filter.getType().equals(IP_FILTER_TYPE)) && - InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) { - logger.debug("ip match on " + filter.getExpression()); - return true; - } - } - catch (Throwable t) { - logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage()); - } - } - - return false; - } - } - - private boolean checkRegExpFilter(Entity anEntity) { - synchronized (filters) { - Iterator i = filters.iterator(); - - while (i.hasNext()) { - Filter filter = (Filter) i.next(); - - if (filter.getType().equals(REGEXP_FILTER_TYPE)) { - try { - RE regularExpression = new RE(filter.getExpression()); - - Iterator j = anEntity.getFields().iterator(); - while (j.hasNext()) { - String field = anEntity.getValue( (String) j.next()); - - if (field != null && regularExpression.isMatch(field.toLowerCase())) { - logger.debug("regexp match on " + filter.getExpression()); - return true; - } - } - } - catch (Throwable t) { - logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage()); - } - } - } - - return false; - } - } - - private void setCookie(HttpServletResponse aResponse) { - Random random = new Random(); - - Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000))); - cookie.setMaxAge(cookieMaxAge); - cookie.setPath("/"); - aResponse.addCookie(cookie); - } - - private boolean checkCookie(List aCookies) { - if (getCookieOnBlock()) { - Iterator i = aCookies.iterator(); - - while (i.hasNext()) { - Cookie cookie = (Cookie) i.next(); - - if (cookie.getName().equals(cookieName)) { - logger.debug("cookie match"); - return true; - } - } - } - - return false; - } - - public void checkComment(EntityComment aComment, HttpServletRequest aRequest, HttpServletResponse aResponse) { - try { - long time = System.currentTimeMillis(); - - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction); - - if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(aComment)) { - operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment)); - setCookie(aResponse); - } - - logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms"); - - } - catch (Throwable t) { - logger.error("Abuse.checkComment: " + t.toString()); - } - } - - public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) { - try { - long time = System.currentTimeMillis(); - - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction); - - if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) { - operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle)); - setCookie(aResponse); - } - - logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms"); - } - catch (Throwable t) { - logger.error("Abuse.checkArticle: " + t.toString()); - } - } - - public boolean getLogEnabled() { - return logEnabled; - } - - public void setLogEnabled(boolean anEnabled) { - logEnabled = anEnabled; - truncateLog(); - } - - public int getLogSize() { - return logSize; - } - - public void setLogSize(int aSize) { - logSize = aSize; - truncateLog(); - } - - public boolean getOpenPostingDisabled() { - return openPostingDisabled; - } - - public void setOpenPostingDisabled(boolean anOpenPostingDisabled) { - openPostingDisabled = anOpenPostingDisabled; - } - - public boolean getOpenPostingPassword() { - return openPostingPassword; - } - - public void setOpenPostingPassword(boolean anOpenPostingPassword) { - openPostingPassword = anOpenPostingPassword; - } - - public boolean getCookieOnBlock() { - return cookieOnBlock; - } - - public void setCookieOnBlock(boolean aCookieOnBlock) { - cookieOnBlock = aCookieOnBlock; - } - - public String getArticleBlockAction() { - return articleBlockAction; - } - - public void setArticleBlockAction(String anAction) { - articleBlockAction = anAction; - } - - public String getCommentBlockAction() { - return commentBlockAction; - } - - public void setCommentBlockAction(String anAction) { - commentBlockAction = anAction; - } - - - public List getLog() { - synchronized(log) { - List result = new Vector(); - - Iterator i = log.iterator(); - while (i.hasNext()) { - LogEntry logEntry = (LogEntry) i.next(); - Map entry = new HashMap(); - - entry.put("ip", logEntry.getIpNumber()); - entry.put("id", logEntry.getId()); - entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp())); - if (logEntry.getIsArticle()) - entry.put("type", "content"); - else - entry.put("type", "comment"); - entry.put("browser", logEntry.getBrowserString()); - - result.add(entry); - } - - return result; - } - } - - public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) { - appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false)); - } - - public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) { - appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true)); - } - - public void load() { - try { - ExtendedProperties configuration = new ExtendedProperties(); - - try { - configuration = new ExtendedProperties(configFile); - } - catch (FileNotFoundException e) { - } - - getFilterConfig(filters, "abuse.filter", configuration); - - setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1")); - setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1")); - setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1")); - setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1")); - setLogSize(configuration.getInt("abuse.logSize", 10)); - setArticleBlockAction(configuration.getString("abuse.articleBlockAction", "")); - setCommentBlockAction(configuration.getString("abuse.commentBlockAction", "")); - } - catch (Throwable t) { - throw new RuntimeException(t.toString()); - } - } - public void save() { - try { - ExtendedProperties configuration = new ExtendedProperties(); - - setFilterConfig(filters, "abuse.filter", configuration); - - configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0"); - configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0"); - configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0"); - configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0"); - configuration.addProperty("abuse.logSize", Integer.toString(getLogSize())); - configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction()); - configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction()); - - configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration"); - } - catch (Throwable t) { - throw new RuntimeException(t.toString()); - } - } - - public List getFilterTypes() { - List result = new Vector(); - - Map entry = new HashMap(); - entry.put("resource", "abuse.filtertype.ip"); - entry.put("id", IP_FILTER_TYPE); - result.add(entry); - - entry = new HashMap(); - entry.put("resource", "abuse.filtertype.regexp"); - entry.put("id", REGEXP_FILTER_TYPE); - result.add(entry); - - return result; - } - - public List getArticleActions() { - try { - List result = new Vector(); - - Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator(); - while (i.hasNext()) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = - (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); - - Map action = new HashMap(); - action.put("resource", "content.operation."+operation.getName()); - action.put("identifier", operation.getName()); - - result.add(action); - } - - return result; - } - catch (Throwable t) { - throw new RuntimeException("can't get article actions"); - } - } - - public List getCommentActions() { - try { - List result = new Vector(); - - Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator(); - while (i.hasNext()) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = - (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); - - Map action = new HashMap(); - action.put("resource", "comment.operation."+operation.getName()); - action.put("identifier", operation.getName()); - - result.add(action); - } - - return result; - } - catch (Throwable t) { - throw new RuntimeException("can't get comment actions"); - } - } - - public List getFilters() { - return getFiltersAsMaps(filters); - } - - public void addFilter(String aType, String anExpression) { - addFilter(filters, aType, anExpression); - } - - public void setFilter(String anIdentifier, String aType, String anExpression) { - setFilter(filters, anIdentifier, aType, anExpression); - } - - public void deleteFilter(String anIdentifier) { - deleteFilter(filters, anIdentifier); - } - - public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception { - } - - private List getFiltersAsMaps(List aFilters) { - synchronized(aFilters) { - List result = new Vector(); - - Iterator i = aFilters.iterator(); - while (i.hasNext()) { - Filter filter = (Filter) i.next(); - Map map = new HashMap(); - - map.put("id", filter.getId()); - map.put("expression", filter.getExpression()); - map.put("type", filter.getType()); - - result.add(map); - } - return result; - } - } - - private void addFilter(List aFilters, String aType, String anExpression) { - Filter filter = new Filter(); - - filter.setId(generateId()); - filter.setExpression(anExpression); - filter.setType(aType); - - synchronized (aFilters) { - aFilters.add(filter); - } - } - - private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) { - synchronized (aFilters) { - Filter filter = findFilter(aFilters, anIdentifier); - - if (filter!=null) { - filter.setExpression(anExpression); - filter.setType(aType); - } - } - } - - private Filter findFilter(List aFilters, String anIdentifier) { - synchronized (aFilters) { - Iterator i = aFilters.iterator(); - while (i.hasNext()) { - Filter filter = (Filter) i.next(); - - if (filter.getId().equals(anIdentifier)) { - return filter; - } - } - } - - return null; - } - - private void deleteFilter(List aFilters, String anIdentifier) { - synchronized (aFilters) { - Filter filter = findFilter(aFilters, anIdentifier); - - if (filter!=null) { - aFilters.remove(filter); - } - } - } - - private String generateId() { - synchronized(this) { - maxIdentifier = maxIdentifier+1; - - return Integer.toString(maxIdentifier); - } - } - - private static class Filter { - private String identifier; - private String expression; - private String type; - - public Filter() { - expression=""; - type=""; - identifier=""; - } - - public String getId() { - return identifier; - } - - public void setId(String anId) { - identifier = anId; - } - - public String getExpression() { - return expression; - } - - public void setExpression(String anExpression) { - expression = anExpression; - } - - public String getType() { - return type; - } - - public void setType(String aType) { - type = aType; - } - } - - private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) { - synchronized(aFilters) { - Iterator i = aFilters.iterator(); - - while (i.hasNext()) { - Filter filter = (Filter) i.next(); - - aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression()); - } - } - } - - private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) { - synchronized(aFilters) { - aFilters.clear(); - - Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator(); - - while (i.hasNext()) { - String filter = (String) i.next(); - List parts = StringRoutines.separateString(filter, ":"); - - if (parts.size()==2) { - addFilter( (String) parts.get(0), (String) parts.get(1)); - } - } - } - } - - private static class LogEntry { - private String ipNumber; - private String browserString; - private String id; - private Date timeStamp; - private boolean isArticle; - - public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) { - ipNumber = anIpNumber; - browserString = aBrowserString; - id = anId; - isArticle = anIsArticle; - timeStamp=aTimeStamp; - } - - public String getIpNumber() { - return ipNumber; - } - - public String getBrowserString() { - return browserString; - } - - public String getId() { - return id; - } - - public Date getTimeStamp() { - return timeStamp; - } - - public boolean getIsArticle() { - return isArticle; - } - } - - private void truncateLog() { - synchronized(log) { - if (!logEnabled) - log.clear(); - else { - while (log.size()>0 && log.size()>logSize) { - log.remove(0); - } - } - } - }; - - private void appendLog(LogEntry anEntry) { - synchronized (log) { - if (logEnabled) { - log.add(anEntry); - truncateLog(); - } - } - } - +package mircoders.global; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Vector; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.collections.ExtendedProperties; + +import gnu.regexp.RE; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.util.DateToMapAdapter; +import mir.util.InternetFunctions; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.localizer.MirAdminInterfaceLocalizer; + + +public class Abuse { + private List filters; + private int maxIdentifier; + private LoggerWrapper logger; + private int logSize; + private boolean logEnabled; + private boolean openPostingDisabled; + private boolean openPostingPassword; + private boolean cookieOnBlock; + private String articleBlockAction; + private String commentBlockAction; + private List log; + private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config"); + + + private static final String IP_FILTER_TYPE="ip"; + private static final String REGEXP_FILTER_TYPE="regexp"; + private static String cookieName=MirGlobal.config().getString("Abuse.CookieName"); + private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge"); + + public Abuse() { + logger = new LoggerWrapper("Global.Abuse"); + filters = new Vector(); + maxIdentifier = 0; + log = new Vector(); + + logSize = 100; + logEnabled = false; + articleBlockAction = ""; + commentBlockAction = ""; + openPostingPassword = false; + openPostingDisabled = false; + cookieOnBlock = false; + + load(); + } + + public boolean checkIpFilter(String anIpAddress) { + synchronized (filters) { + Iterator i = filters.iterator(); + + while (i.hasNext()) { + Filter filter = (Filter) i.next(); + + try { + if ( (filter.getType().equals(IP_FILTER_TYPE)) && + InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) { + logger.debug("ip match on " + filter.getExpression()); + return true; + } + } + catch (Throwable t) { + logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage()); + } + } + + return false; + } + } + + private boolean checkRegExpFilter(Entity anEntity) { + synchronized (filters) { + Iterator i = filters.iterator(); + + while (i.hasNext()) { + Filter filter = (Filter) i.next(); + + if (filter.getType().equals(REGEXP_FILTER_TYPE)) { + try { + RE regularExpression = new RE(filter.getExpression()); + + Iterator j = anEntity.getFields().iterator(); + while (j.hasNext()) { + String field = anEntity.getValue( (String) j.next()); + + if (field != null && regularExpression.isMatch(field.toLowerCase())) { + logger.debug("regexp match on " + filter.getExpression()); + return true; + } + } + } + catch (Throwable t) { + logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage()); + } + } + } + + return false; + } + } + + private void setCookie(HttpServletResponse aResponse) { + Random random = new Random(); + + Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000))); + cookie.setMaxAge(cookieMaxAge); + cookie.setPath("/"); + aResponse.addCookie(cookie); + } + + private boolean checkCookie(List aCookies) { + if (getCookieOnBlock()) { + Iterator i = aCookies.iterator(); + + while (i.hasNext()) { + Cookie cookie = (Cookie) i.next(); + + if (cookie.getName().equals(cookieName)) { + logger.debug("cookie match"); + return true; + } + } + } + + return false; + } + + public void checkComment(EntityComment aComment, HttpServletRequest aRequest, HttpServletResponse aResponse) { + try { + long time = System.currentTimeMillis(); + + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction); + + if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(aComment)) { + operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment)); + setCookie(aResponse); + } + + logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms"); + + } + catch (Throwable t) { + logger.error("Abuse.checkComment: " + t.toString()); + } + } + + public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) { + try { + long time = System.currentTimeMillis(); + + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction); + + if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) { + operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle)); + setCookie(aResponse); + } + + logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms"); + } + catch (Throwable t) { + logger.error("Abuse.checkArticle: " + t.toString()); + } + } + + public boolean getLogEnabled() { + return logEnabled; + } + + public void setLogEnabled(boolean anEnabled) { + logEnabled = anEnabled; + truncateLog(); + } + + public int getLogSize() { + return logSize; + } + + public void setLogSize(int aSize) { + logSize = aSize; + truncateLog(); + } + + public boolean getOpenPostingDisabled() { + return openPostingDisabled; + } + + public void setOpenPostingDisabled(boolean anOpenPostingDisabled) { + openPostingDisabled = anOpenPostingDisabled; + } + + public boolean getOpenPostingPassword() { + return openPostingPassword; + } + + public void setOpenPostingPassword(boolean anOpenPostingPassword) { + openPostingPassword = anOpenPostingPassword; + } + + public boolean getCookieOnBlock() { + return cookieOnBlock; + } + + public void setCookieOnBlock(boolean aCookieOnBlock) { + cookieOnBlock = aCookieOnBlock; + } + + public String getArticleBlockAction() { + return articleBlockAction; + } + + public void setArticleBlockAction(String anAction) { + articleBlockAction = anAction; + } + + public String getCommentBlockAction() { + return commentBlockAction; + } + + public void setCommentBlockAction(String anAction) { + commentBlockAction = anAction; + } + + + public List getLog() { + synchronized(log) { + List result = new Vector(); + + Iterator i = log.iterator(); + while (i.hasNext()) { + LogEntry logEntry = (LogEntry) i.next(); + Map entry = new HashMap(); + + entry.put("ip", logEntry.getIpNumber()); + entry.put("id", logEntry.getId()); + entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp())); + if (logEntry.getIsArticle()) + entry.put("type", "content"); + else + entry.put("type", "comment"); + entry.put("browser", logEntry.getBrowserString()); + + result.add(entry); + } + + return result; + } + } + + public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) { + appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false)); + } + + public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) { + appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true)); + } + + public void load() { + try { + ExtendedProperties configuration = new ExtendedProperties(); + + try { + configuration = new ExtendedProperties(configFile); + } + catch (FileNotFoundException e) { + } + + getFilterConfig(filters, "abuse.filter", configuration); + + setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1")); + setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1")); + setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1")); + setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1")); + setLogSize(configuration.getInt("abuse.logSize", 10)); + setArticleBlockAction(configuration.getString("abuse.articleBlockAction", "")); + setCommentBlockAction(configuration.getString("abuse.commentBlockAction", "")); + } + catch (Throwable t) { + throw new RuntimeException(t.toString()); + } + } + public void save() { + try { + ExtendedProperties configuration = new ExtendedProperties(); + + setFilterConfig(filters, "abuse.filter", configuration); + + configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0"); + configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0"); + configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0"); + configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0"); + configuration.addProperty("abuse.logSize", Integer.toString(getLogSize())); + configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction()); + configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction()); + + configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration"); + } + catch (Throwable t) { + throw new RuntimeException(t.toString()); + } + } + + public List getFilterTypes() { + List result = new Vector(); + + Map entry = new HashMap(); + entry.put("resource", "abuse.filtertype.ip"); + entry.put("id", IP_FILTER_TYPE); + result.add(entry); + + entry = new HashMap(); + entry.put("resource", "abuse.filtertype.regexp"); + entry.put("id", REGEXP_FILTER_TYPE); + result.add(entry); + + return result; + } + + public List getArticleActions() { + try { + List result = new Vector(); + + Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator(); + while (i.hasNext()) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = + (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); + + Map action = new HashMap(); + action.put("resource", "content.operation."+operation.getName()); + action.put("identifier", operation.getName()); + + result.add(action); + } + + return result; + } + catch (Throwable t) { + throw new RuntimeException("can't get article actions"); + } + } + + public List getCommentActions() { + try { + List result = new Vector(); + + Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator(); + while (i.hasNext()) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = + (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); + + Map action = new HashMap(); + action.put("resource", "comment.operation."+operation.getName()); + action.put("identifier", operation.getName()); + + result.add(action); + } + + return result; + } + catch (Throwable t) { + throw new RuntimeException("can't get comment actions"); + } + } + + public List getFilters() { + return getFiltersAsMaps(filters); + } + + public void addFilter(String aType, String anExpression) { + addFilter(filters, aType, anExpression); + } + + public void setFilter(String anIdentifier, String aType, String anExpression) { + setFilter(filters, anIdentifier, aType, anExpression); + } + + public void deleteFilter(String anIdentifier) { + deleteFilter(filters, anIdentifier); + } + + public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception { + } + + private List getFiltersAsMaps(List aFilters) { + synchronized(aFilters) { + List result = new Vector(); + + Iterator i = aFilters.iterator(); + while (i.hasNext()) { + Filter filter = (Filter) i.next(); + Map map = new HashMap(); + + map.put("id", filter.getId()); + map.put("expression", filter.getExpression()); + map.put("type", filter.getType()); + + result.add(map); + } + return result; + } + } + + private void addFilter(List aFilters, String aType, String anExpression) { + Filter filter = new Filter(); + + filter.setId(generateId()); + filter.setExpression(anExpression); + filter.setType(aType); + + synchronized (aFilters) { + aFilters.add(filter); + } + } + + private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) { + synchronized (aFilters) { + Filter filter = findFilter(aFilters, anIdentifier); + + if (filter!=null) { + filter.setExpression(anExpression); + filter.setType(aType); + } + } + } + + private Filter findFilter(List aFilters, String anIdentifier) { + synchronized (aFilters) { + Iterator i = aFilters.iterator(); + while (i.hasNext()) { + Filter filter = (Filter) i.next(); + + if (filter.getId().equals(anIdentifier)) { + return filter; + } + } + } + + return null; + } + + private void deleteFilter(List aFilters, String anIdentifier) { + synchronized (aFilters) { + Filter filter = findFilter(aFilters, anIdentifier); + + if (filter!=null) { + aFilters.remove(filter); + } + } + } + + private String generateId() { + synchronized(this) { + maxIdentifier = maxIdentifier+1; + + return Integer.toString(maxIdentifier); + } + } + + private static class Filter { + private String identifier; + private String expression; + private String type; + + public Filter() { + expression=""; + type=""; + identifier=""; + } + + public String getId() { + return identifier; + } + + public void setId(String anId) { + identifier = anId; + } + + public String getExpression() { + return expression; + } + + public void setExpression(String anExpression) { + expression = anExpression; + } + + public String getType() { + return type; + } + + public void setType(String aType) { + type = aType; + } + } + + private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) { + synchronized(aFilters) { + Iterator i = aFilters.iterator(); + + while (i.hasNext()) { + Filter filter = (Filter) i.next(); + + aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression()); + } + } + } + + private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) { + synchronized(aFilters) { + aFilters.clear(); + + Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator(); + + while (i.hasNext()) { + String filter = (String) i.next(); + List parts = StringRoutines.separateString(filter, ":"); + + if (parts.size()==2) { + addFilter( (String) parts.get(0), (String) parts.get(1)); + } + } + } + } + + private static class LogEntry { + private String ipNumber; + private String browserString; + private String id; + private Date timeStamp; + private boolean isArticle; + + public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) { + ipNumber = anIpNumber; + browserString = aBrowserString; + id = anId; + isArticle = anIsArticle; + timeStamp=aTimeStamp; + } + + public String getIpNumber() { + return ipNumber; + } + + public String getBrowserString() { + return browserString; + } + + public String getId() { + return id; + } + + public Date getTimeStamp() { + return timeStamp; + } + + public boolean getIsArticle() { + return isArticle; + } + } + + private void truncateLog() { + synchronized(log) { + if (!logEnabled) + log.clear(); + else { + while (log.size()>0 && log.size()>logSize) { + log.remove(0); + } + } + } + }; + + private void appendLog(LogEntry anEntry) { + synchronized (log) { + if (logEnabled) { + log.add(anEntry); + truncateLog(); + } + } + } + } \ No newline at end of file diff --git a/source/mircoders/localizer/MirDataModelLocalizer.java b/source/mircoders/localizer/MirDataModelLocalizer.java index 3b5994c8..54c63c68 100755 --- a/source/mircoders/localizer/MirDataModelLocalizer.java +++ b/source/mircoders/localizer/MirDataModelLocalizer.java @@ -1,38 +1,38 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.localizer; - -import mir.entity.adapter.EntityAdapterModel; - -public interface MirDataModelLocalizer { - public EntityAdapterModel adapterModel() throws MirLocalizerExc, MirLocalizerFailure; +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.localizer; + +import mir.entity.adapter.EntityAdapterModel; + +public interface MirDataModelLocalizer { + public EntityAdapterModel adapterModel() throws MirLocalizerExc, MirLocalizerFailure; } \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index 9d7831da..74e1b3ef 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -1,320 +1,320 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.localizer.basic; - -import java.text.SimpleDateFormat; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import mir.entity.Entity; -import mir.entity.adapter.EntityAdapter; -import mir.misc.StringUtil; -import mir.storage.StorageObjectFailure; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.localizer.MirAdminInterfaceLocalizer; -import mircoders.localizer.MirLocalizerExc; -import mircoders.localizer.MirLocalizerFailure; -import mircoders.storage.DatabaseContent; - - -public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer { - private Vector simpleCommentOperations; - private Vector simpleArticleOperations; - private Map simpleCommentOperationsMap; - private Map simpleArticleOperationsMap; - private static SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); - - public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure, MirLocalizerExc { - simpleCommentOperations = new Vector(); - simpleArticleOperations = new Vector(); - simpleCommentOperationsMap = new HashMap(); - simpleArticleOperationsMap = new HashMap(); - - addSimpleArticleOperation(new ChangeArticleFieldOperation("newswire", "to_article_type", "0", "1", false)); - addSimpleArticleOperation(new ModifyArticleFieldOperation("unhide", "is_published", "1", false)); - addSimpleArticleOperation(new ModifyArticleFieldOperation("hide", "is_published", "0", false)); - - addSimpleCommentOperation(new ModifyCommentFieldOperation("unhide", "is_published", "1")); - addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0")); - } - - public String makePasswordDigest(String aPassword) { - return aPassword; - } - - public void initializeArticle(Map anArticle) { - anArticle.put("is_published", "0"); - anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); - }; - - public List simpleCommentOperations() { - return simpleCommentOperations; - }; - - public List simpleArticleOperations() { - return simpleArticleOperations; - }; - - public MirSimpleEntityOperation simpleArticleOperationForName(String aName) { - return (MirSimpleEntityOperation) simpleArticleOperationsMap.get(aName); - }; - - public MirSimpleEntityOperation simpleCommentOperationForName(String aName) { - return (MirSimpleEntityOperation) simpleCommentOperationsMap.get(aName); - }; - - public void removeSimpleArticleOperation(String aName) { - simpleArticleOperations.remove(simpleArticleOperationsMap.get(aName)); - simpleArticleOperationsMap.remove(aName); - } - - public void addSimpleArticleOperation(MirSimpleEntityOperation anOperation) { - removeSimpleArticleOperation(anOperation.getName()); - simpleArticleOperationsMap.put(anOperation.getName(), anOperation); - simpleArticleOperations.add(anOperation); - } - - public void removeSimpleCommentOperation(String aName) { - simpleCommentOperations.remove(simpleCommentOperationsMap.get(aName)); - simpleCommentOperationsMap.remove(aName); - } - - public void addSimpleCommentOperation(MirSimpleEntityOperation anOperation) { - removeSimpleCommentOperation(anOperation.getName()); - simpleCommentOperationsMap.put(anOperation.getName(), anOperation); - simpleCommentOperations.add(anOperation); - } - - protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation { - private String name; - - protected EntityModifyingOperation(String aName) { - name = aName; - } - - public String getName() { - return name; - }; - - public boolean isAvailable(EntityAdapter anEntity) { - try { - Entity entity = anEntity.getEntity(); - return isAvailable(entity); - } - catch (Throwable t) { - return false; - } - }; - - public void perform(EntityAdapter aUser, EntityAdapter anEntity) { - Entity entity = anEntity.getEntity(); - try { - performModification(aUser, entity); - entity.update(); - } - catch (Throwable t) { - } - }; - - protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ; - protected abstract void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure ; - } - - public static abstract class CommentModifyingOperation extends EntityModifyingOperation { - public CommentModifyingOperation(String aName) { - super(aName); - } - - protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { - return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity); - } - - protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { - performModification(aUser, (EntityComment) anEntity); - DatabaseContent.getInstance().setUnproduced("id="+anEntity.getValue("to_media")); - }; - - protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ; - protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ; - } - - public static abstract class ArticleModifyingOperation extends EntityModifyingOperation { - private boolean logOperation; - - public ArticleModifyingOperation(String aName, boolean aLogOperation) { - super(aName); - - logOperation = aLogOperation; - } - - protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { - return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity); - } - - protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { - performModification(aUser, (EntityContent) anEntity); - anEntity.setValueForProperty("is_produced", "0"); - - if (logOperation) { - StringBuffer comment = new StringBuffer(); - try { - comment.append(StringRoutines.interpretAsString(anEntity.getValue("comment"))); - } - catch (Throwable t) { - } - if (comment.length()>0 && comment.charAt(comment.length()-1)!='\n') { - comment.append('\n'); - } - comment.append(dateFormatter.format((new GregorianCalendar()).getTime())); - comment.append(" "); - try { - comment.append(StringRoutines.interpretAsString(aUser.get("login"))); - } - catch (Throwable t) { - } - comment.append(" "); - comment.append(getName()); - anEntity.setValueForProperty("comment", comment.toString()); - } - }; - - protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ; - protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ; - } - - protected static class SetCommentFieldOperation extends CommentModifyingOperation { - private String field; - private String value; - - public SetCommentFieldOperation(String aName, String aField, String aValue) { - super(aName); - - field = aField; - value = aValue; - } - - protected boolean isAvailable(EntityComment aComment) { - return true; - } - - protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { - aComment.setValueForProperty(field, value); - } - } - - protected static class ModifyCommentFieldOperation extends CommentModifyingOperation { - private String field; - private String value; - - public ModifyCommentFieldOperation(String aName, String aField, String aValue) { - super(aName); - - field = aField; - value = aValue; - } - - protected boolean isAvailable(EntityComment aComment) { - return aComment.getValue(field) == null || !aComment.getValue(field).equals(value); - } - - protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { - aComment.setValueForProperty(field, value); - } - } - - protected static class SetArticleFieldOperation extends ArticleModifyingOperation { - private String field; - private String value; - - public SetArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) { - super(aName, aLogOperation); - - field = aField; - value = aValue; - } - - protected boolean isAvailable(EntityContent anArticle) { - return true; - } - - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { - anArticle.setValueForProperty(field, value); - } - } - - protected static class ModifyArticleFieldOperation extends ArticleModifyingOperation { - private String field; - private String value; - - public ModifyArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) { - super(aName, aLogOperation); - - field = aField; - value = aValue; - } - - protected boolean isAvailable(EntityContent anArticle) { - return anArticle.getValue(field) == null || !anArticle.getValue(field).equals(value); - } - - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { - anArticle.setValueForProperty(field, value); - } - } - - protected static class ChangeArticleFieldOperation extends ArticleModifyingOperation { - private String field; - private String oldValue; - private String newValue; - - public ChangeArticleFieldOperation(String aName, String aField, String anOldValue, String aNewValue, boolean aLogOperation) { - super(aName, aLogOperation); - - field = aField; - newValue = aNewValue; - oldValue = anOldValue; - } - - protected boolean isAvailable(EntityContent anArticle) { - return anArticle.getValue(field) != null && anArticle.getValue(field).equals(oldValue); - } - - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { - anArticle.setValueForProperty(field, newValue); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.localizer.basic; + +import java.text.SimpleDateFormat; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.entity.adapter.EntityAdapter; +import mir.misc.StringUtil; +import mir.storage.StorageObjectFailure; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.localizer.MirAdminInterfaceLocalizer; +import mircoders.localizer.MirLocalizerExc; +import mircoders.localizer.MirLocalizerFailure; +import mircoders.storage.DatabaseContent; + + +public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer { + private Vector simpleCommentOperations; + private Vector simpleArticleOperations; + private Map simpleCommentOperationsMap; + private Map simpleArticleOperationsMap; + private static SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + + public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure, MirLocalizerExc { + simpleCommentOperations = new Vector(); + simpleArticleOperations = new Vector(); + simpleCommentOperationsMap = new HashMap(); + simpleArticleOperationsMap = new HashMap(); + + addSimpleArticleOperation(new ChangeArticleFieldOperation("newswire", "to_article_type", "0", "1", false)); + addSimpleArticleOperation(new ModifyArticleFieldOperation("unhide", "is_published", "1", false)); + addSimpleArticleOperation(new ModifyArticleFieldOperation("hide", "is_published", "0", false)); + + addSimpleCommentOperation(new ModifyCommentFieldOperation("unhide", "is_published", "1")); + addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0")); + } + + public String makePasswordDigest(String aPassword) { + return aPassword; + } + + public void initializeArticle(Map anArticle) { + anArticle.put("is_published", "0"); + anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); + }; + + public List simpleCommentOperations() { + return simpleCommentOperations; + }; + + public List simpleArticleOperations() { + return simpleArticleOperations; + }; + + public MirSimpleEntityOperation simpleArticleOperationForName(String aName) { + return (MirSimpleEntityOperation) simpleArticleOperationsMap.get(aName); + }; + + public MirSimpleEntityOperation simpleCommentOperationForName(String aName) { + return (MirSimpleEntityOperation) simpleCommentOperationsMap.get(aName); + }; + + public void removeSimpleArticleOperation(String aName) { + simpleArticleOperations.remove(simpleArticleOperationsMap.get(aName)); + simpleArticleOperationsMap.remove(aName); + } + + public void addSimpleArticleOperation(MirSimpleEntityOperation anOperation) { + removeSimpleArticleOperation(anOperation.getName()); + simpleArticleOperationsMap.put(anOperation.getName(), anOperation); + simpleArticleOperations.add(anOperation); + } + + public void removeSimpleCommentOperation(String aName) { + simpleCommentOperations.remove(simpleCommentOperationsMap.get(aName)); + simpleCommentOperationsMap.remove(aName); + } + + public void addSimpleCommentOperation(MirSimpleEntityOperation anOperation) { + removeSimpleCommentOperation(anOperation.getName()); + simpleCommentOperationsMap.put(anOperation.getName(), anOperation); + simpleCommentOperations.add(anOperation); + } + + protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation { + private String name; + + protected EntityModifyingOperation(String aName) { + name = aName; + } + + public String getName() { + return name; + }; + + public boolean isAvailable(EntityAdapter anEntity) { + try { + Entity entity = anEntity.getEntity(); + return isAvailable(entity); + } + catch (Throwable t) { + return false; + } + }; + + public void perform(EntityAdapter aUser, EntityAdapter anEntity) { + Entity entity = anEntity.getEntity(); + try { + performModification(aUser, entity); + entity.update(); + } + catch (Throwable t) { + } + }; + + protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ; + protected abstract void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure ; + } + + public static abstract class CommentModifyingOperation extends EntityModifyingOperation { + public CommentModifyingOperation(String aName) { + super(aName); + } + + protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { + return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity); + } + + protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { + performModification(aUser, (EntityComment) anEntity); + DatabaseContent.getInstance().setUnproduced("id="+anEntity.getValue("to_media")); + }; + + protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ; + protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ; + } + + public static abstract class ArticleModifyingOperation extends EntityModifyingOperation { + private boolean logOperation; + + public ArticleModifyingOperation(String aName, boolean aLogOperation) { + super(aName); + + logOperation = aLogOperation; + } + + protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { + return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity); + } + + protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { + performModification(aUser, (EntityContent) anEntity); + anEntity.setValueForProperty("is_produced", "0"); + + if (logOperation) { + StringBuffer comment = new StringBuffer(); + try { + comment.append(StringRoutines.interpretAsString(anEntity.getValue("comment"))); + } + catch (Throwable t) { + } + if (comment.length()>0 && comment.charAt(comment.length()-1)!='\n') { + comment.append('\n'); + } + comment.append(dateFormatter.format((new GregorianCalendar()).getTime())); + comment.append(" "); + try { + comment.append(StringRoutines.interpretAsString(aUser.get("login"))); + } + catch (Throwable t) { + } + comment.append(" "); + comment.append(getName()); + anEntity.setValueForProperty("comment", comment.toString()); + } + }; + + protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ; + protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ; + } + + protected static class SetCommentFieldOperation extends CommentModifyingOperation { + private String field; + private String value; + + public SetCommentFieldOperation(String aName, String aField, String aValue) { + super(aName); + + field = aField; + value = aValue; + } + + protected boolean isAvailable(EntityComment aComment) { + return true; + } + + protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { + aComment.setValueForProperty(field, value); + } + } + + protected static class ModifyCommentFieldOperation extends CommentModifyingOperation { + private String field; + private String value; + + public ModifyCommentFieldOperation(String aName, String aField, String aValue) { + super(aName); + + field = aField; + value = aValue; + } + + protected boolean isAvailable(EntityComment aComment) { + return aComment.getValue(field) == null || !aComment.getValue(field).equals(value); + } + + protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { + aComment.setValueForProperty(field, value); + } + } + + protected static class SetArticleFieldOperation extends ArticleModifyingOperation { + private String field; + private String value; + + public SetArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) { + super(aName, aLogOperation); + + field = aField; + value = aValue; + } + + protected boolean isAvailable(EntityContent anArticle) { + return true; + } + + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + anArticle.setValueForProperty(field, value); + } + } + + protected static class ModifyArticleFieldOperation extends ArticleModifyingOperation { + private String field; + private String value; + + public ModifyArticleFieldOperation(String aName, String aField, String aValue, boolean aLogOperation) { + super(aName, aLogOperation); + + field = aField; + value = aValue; + } + + protected boolean isAvailable(EntityContent anArticle) { + return anArticle.getValue(field) == null || !anArticle.getValue(field).equals(value); + } + + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + anArticle.setValueForProperty(field, value); + } + } + + protected static class ChangeArticleFieldOperation extends ArticleModifyingOperation { + private String field; + private String oldValue; + private String newValue; + + public ChangeArticleFieldOperation(String aName, String aField, String anOldValue, String aNewValue, boolean aLogOperation) { + super(aName, aLogOperation); + + field = aField; + newValue = aNewValue; + oldValue = anOldValue; + } + + protected boolean isAvailable(EntityContent anArticle) { + return anArticle.getValue(field) != null && anArticle.getValue(field).equals(oldValue); + } + + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + anArticle.setValueForProperty(field, newValue); + } + } +} diff --git a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java index fd9bf478..859da23a 100755 --- a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java @@ -1,439 +1,439 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.localizer.basic; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import mir.entity.Entity; -import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityAdapterDefinition; -import mir.entity.adapter.EntityAdapterModel; -import mir.log.LoggerWrapper; -import mir.media.MediaHelper; -import mir.media.MirMedia; -import mir.util.RewindableIterator; -import mircoders.entity.EntityUploadedMedia; -import mircoders.global.MirGlobal; -import mircoders.localizer.MirAdminInterfaceLocalizer; -import mircoders.localizer.MirDataModelLocalizer; -import mircoders.localizer.MirLocalizerFailure; -import mircoders.storage.DatabaseArticleType; -import mircoders.storage.DatabaseAudio; -import mircoders.storage.DatabaseBreaking; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseCommentStatus; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseImageType; -import mircoders.storage.DatabaseImages; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseMedia; -import mircoders.storage.DatabaseMediaType; -import mircoders.storage.DatabaseMediafolder; -import mircoders.storage.DatabaseMessages; -import mircoders.storage.DatabaseOther; -import mircoders.storage.DatabaseTopics; -import mircoders.storage.DatabaseUploadedMedia; -import mircoders.storage.DatabaseUsers; -import mircoders.storage.DatabaseVideo; - -public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { - private EntityAdapterModel model; - protected LoggerWrapper logger; - - public MirBasicDataModelLocalizer() { - model=null; - logger = new LoggerWrapper("Localizer.DataModel"); - } - - public EntityAdapterModel adapterModel() throws MirLocalizerFailure { - if (model==null) - model = buildModel(); - - return model; - }; - - protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure { - try { - anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create"); - anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange"); - anEntityAdapterDefinition.addMirDateField("date", "date"); - anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField()); - anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField()); - anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField()); - - anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'")); - anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField("")); - - anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" )); - anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" )); - anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" )); - anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" )); - anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" )); - anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField()); - - anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField()); - - anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); - anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data")); - - anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField()); - anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField()); - - anEntityAdapterDefinition.addCalculatedField("operations", - new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations())); - } - catch (Throwable t) { - throw new MirLocalizerFailure(t.getMessage(), t); - } - } - - protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure { - try { - anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create"); - anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField()); - anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField()); - - anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); - anEntityAdapterDefinition.addCalculatedField("operations", - new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations())); - } - catch (Throwable t) { - throw new MirLocalizerFailure(t.getMessage(), t); - } - } - - protected EntityAdapterModel buildModel() throws MirLocalizerFailure { - EntityAdapterModel result = new EntityAdapterModel(); - - try { - EntityAdapterDefinition definition; - - definition = new EntityAdapterDefinition(); - constructContentAdapterDefinition( definition ); - result.addMapping( "content", DatabaseContent.getInstance(), definition); - - definition = new EntityAdapterDefinition(); - constructCommentAdapterDefinition( definition ); - result.addMapping( "comment", DatabaseComment.getInstance(), definition); - - result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition()); - - definition = new EntityAdapterDefinition(); - definition.addDBDateField("creationdate", "webdb_create"); - result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition); - - result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "internalMessage", DatabaseMessages.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "media", DatabaseMedia.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "image", DatabaseImages.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "audio", DatabaseAudio.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "video", DatabaseVideo.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition()); - } - catch (Throwable t) { - throw new MirLocalizerFailure(t.getMessage(), t); - } - - return result; - } - - protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getToOneRelation( - "id="+anEntityAdapter.get("to_media"), - "id", - "content" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getToOneRelation( - "id="+anEntityAdapter.get("to_comment_status"), - "id", - "commentStatus" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField { - private List operations; - - public EntityToSimpleOperationsField(List anOperations) { - operations = anOperations; - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - Iterator i = operations.iterator(); - List availableOperations = new Vector(); - - while (i.hasNext()) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = - (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); - - if (operation.isAvailable(anEntityAdapter)) { - availableOperations.add(operation.getName()); - } - }; - - return availableOperations; - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class FilteredField implements EntityAdapterDefinition.CalculatedField { - String fieldName; - - public FilteredField(String aFieldName) { - fieldName = aFieldName; - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) { - return anEntityAdapter.get(fieldName); - } - else { - return MirGlobal.localizer().producerAssistant().filterText((String) anEntityAdapter.get(fieldName)); - } - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - logger.debug("ContentToParentField.getValue"); - return anEntityAdapter.getToOneRelation( - "id="+anEntityAdapter.get("to_content"), - "id", - "content" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getRelation( - "to_content="+anEntityAdapter.get("id"), - "id", - "content" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getToOneRelation( - "id="+anEntityAdapter.get("to_language"), - "id", - "language" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getToOneRelation( - "id="+anEntityAdapter.get("to_article_type"), - "id", - "articleType" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getRelation( - "to_media="+anEntityAdapter.get("id")+" and is_published='1'", - "webdb_create", - "comment" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getRelation( - "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)", - "title", - "topic" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField { - String definition; - - public ContentToMediaField(String aDefinition) { - definition = aDefinition; - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return anEntityAdapter.getRelation( - "is_published='t' and exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)", - "id", - definition); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - EntityAdapter media; - Entity mediaType; - RewindableIterator iterator; - Map result; - MirMedia mediaHandler; - String tinyIcon; - String iconAlt; - - try { - iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media")); - iterator.rewind(); - - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText"); - iconAlt = "Text"; - - if (iterator.hasNext()) { - media = (EntityAdapter) iterator.next(); - - mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType(); - mediaHandler = MediaHelper.getHandler( mediaType ); - - if (mediaHandler.isVideo()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo"); - iconAlt = "Video"; - } - else if (mediaHandler.isAudio()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio"); - iconAlt = "Audio"; - } - else if (mediaHandler.isImage()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage"); - iconAlt = "Image"; - } - else { - tinyIcon = mediaHandler.getTinyIconName(); - iconAlt = mediaHandler.getIconAltName(); - } - - } - } - catch (Throwable t) { - logger.error("ContentToIconField: " +t.getMessage()); - throw new RuntimeException(t.getMessage()); - } - - result = new HashMap(); - result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon); - result.put("icon_alt", iconAlt); - - return result; - } - } - - protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField { - private String extraCondition; - - public ContentCommentCountField(String anExtraCondition) { - super(); - - extraCondition = anExtraCondition; - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return Integer.toString( - DatabaseComment.getInstance().getSize( - "to_media="+anEntityAdapter.get("id")+" " + extraCondition)); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.localizer.basic; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.entity.adapter.EntityAdapter; +import mir.entity.adapter.EntityAdapterDefinition; +import mir.entity.adapter.EntityAdapterModel; +import mir.log.LoggerWrapper; +import mir.media.MediaHelper; +import mir.media.MirMedia; +import mir.util.RewindableIterator; +import mircoders.entity.EntityUploadedMedia; +import mircoders.global.MirGlobal; +import mircoders.localizer.MirAdminInterfaceLocalizer; +import mircoders.localizer.MirDataModelLocalizer; +import mircoders.localizer.MirLocalizerFailure; +import mircoders.storage.DatabaseArticleType; +import mircoders.storage.DatabaseAudio; +import mircoders.storage.DatabaseBreaking; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseCommentStatus; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseImageType; +import mircoders.storage.DatabaseImages; +import mircoders.storage.DatabaseLanguage; +import mircoders.storage.DatabaseMedia; +import mircoders.storage.DatabaseMediaType; +import mircoders.storage.DatabaseMediafolder; +import mircoders.storage.DatabaseMessages; +import mircoders.storage.DatabaseOther; +import mircoders.storage.DatabaseTopics; +import mircoders.storage.DatabaseUploadedMedia; +import mircoders.storage.DatabaseUsers; +import mircoders.storage.DatabaseVideo; + +public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { + private EntityAdapterModel model; + protected LoggerWrapper logger; + + public MirBasicDataModelLocalizer() { + model=null; + logger = new LoggerWrapper("Localizer.DataModel"); + } + + public EntityAdapterModel adapterModel() throws MirLocalizerFailure { + if (model==null) + model = buildModel(); + + return model; + }; + + protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure { + try { + anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create"); + anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange"); + anEntityAdapterDefinition.addMirDateField("date", "date"); + anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField()); + anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField()); + anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField()); + + anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'")); + anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField("")); + + anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" )); + anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" )); + anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" )); + anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField()); + + anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField()); + + anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); + anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data")); + + anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField()); + anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField()); + + anEntityAdapterDefinition.addCalculatedField("operations", + new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations())); + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + } + + protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure { + try { + anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create"); + anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField()); + anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField()); + + anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); + anEntityAdapterDefinition.addCalculatedField("operations", + new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations())); + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + } + + protected EntityAdapterModel buildModel() throws MirLocalizerFailure { + EntityAdapterModel result = new EntityAdapterModel(); + + try { + EntityAdapterDefinition definition; + + definition = new EntityAdapterDefinition(); + constructContentAdapterDefinition( definition ); + result.addMapping( "content", DatabaseContent.getInstance(), definition); + + definition = new EntityAdapterDefinition(); + constructCommentAdapterDefinition( definition ); + result.addMapping( "comment", DatabaseComment.getInstance(), definition); + + result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition()); + + definition = new EntityAdapterDefinition(); + definition.addDBDateField("creationdate", "webdb_create"); + result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition); + + result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "internalMessage", DatabaseMessages.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "media", DatabaseMedia.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "image", DatabaseImages.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "audio", DatabaseAudio.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "video", DatabaseVideo.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition()); + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + + return result; + } + + protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_media"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_comment_status"), + "id", + "commentStatus" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField { + private List operations; + + public EntityToSimpleOperationsField(List anOperations) { + operations = anOperations; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + Iterator i = operations.iterator(); + List availableOperations = new Vector(); + + while (i.hasNext()) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = + (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); + + if (operation.isAvailable(anEntityAdapter)) { + availableOperations.add(operation.getName()); + } + }; + + return availableOperations; + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class FilteredField implements EntityAdapterDefinition.CalculatedField { + String fieldName; + + public FilteredField(String aFieldName) { + fieldName = aFieldName; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) { + return anEntityAdapter.get(fieldName); + } + else { + return MirGlobal.localizer().producerAssistant().filterText((String) anEntityAdapter.get(fieldName)); + } + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + logger.debug("ContentToParentField.getValue"); + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_content"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "to_content="+anEntityAdapter.get("id"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_language"), + "id", + "language" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_article_type"), + "id", + "articleType" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "to_media="+anEntityAdapter.get("id")+" and is_published='1'", + "webdb_create", + "comment" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)", + "title", + "topic" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField { + String definition; + + public ContentToMediaField(String aDefinition) { + definition = aDefinition; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "is_published='t' and exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)", + "id", + definition); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + EntityAdapter media; + Entity mediaType; + RewindableIterator iterator; + Map result; + MirMedia mediaHandler; + String tinyIcon; + String iconAlt; + + try { + iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media")); + iterator.rewind(); + + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText"); + iconAlt = "Text"; + + if (iterator.hasNext()) { + media = (EntityAdapter) iterator.next(); + + mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType(); + mediaHandler = MediaHelper.getHandler( mediaType ); + + if (mediaHandler.isVideo()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo"); + iconAlt = "Video"; + } + else if (mediaHandler.isAudio()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio"); + iconAlt = "Audio"; + } + else if (mediaHandler.isImage()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage"); + iconAlt = "Image"; + } + else { + tinyIcon = mediaHandler.getTinyIconName(); + iconAlt = mediaHandler.getIconAltName(); + } + + } + } + catch (Throwable t) { + logger.error("ContentToIconField: " +t.getMessage()); + throw new RuntimeException(t.getMessage()); + } + + result = new HashMap(); + result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon); + result.put("icon_alt", iconAlt); + + return result; + } + } + + protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField { + private String extraCondition; + + public ContentCommentCountField(String anExtraCondition) { + super(); + + extraCondition = anExtraCondition; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return Integer.toString( + DatabaseComment.getInstance().getSize( + "to_media="+anEntityAdapter.get("id")+" " + extraCondition)); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } +} diff --git a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java index 6c9720fb..625eae24 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java @@ -1,140 +1,140 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.localizer.basic; - -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.util.DateToMapAdapter; -import mir.util.GeneratorHTMLFunctions; -import mir.util.GeneratorIntegerFunctions; -import mir.util.GeneratorListFunctions; -import mir.util.GeneratorStringFunctions; -import mircoders.global.MirGlobal; -import mircoders.localizer.MirProducerAssistantLocalizer; - -public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer { - protected LoggerWrapper logger; - - public void initializeGenerationValueSet(Map aValueSet) { - try { - Iterator i; - - Map configMap = new HashMap(); - Map utilityMap = new HashMap(); - - logger = new LoggerWrapper("Localizer.ProducerAssistant"); - -// obsolete: - configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot")); - configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot")); - configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost")); - configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction")); - configMap.put("docRoot", MirGlobal.config().getString("RootUri")); - configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir"); - configMap.put("now", new DateToMapAdapter( (new GregorianCalendar()).getTime())); - configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host")); - configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host")); - configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host")); - configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path")); - configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version")); - configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding")); - -// "new": - configMap.putAll(MirPropertiesConfiguration.instance().allSettings()); - - utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace()); - utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction()); - utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction()); - utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction()); - utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction()); - utilityMap.put("subList", new GeneratorListFunctions.subListFunction()); - utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction()); - utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction()); - - aValueSet.put("config", configMap); - aValueSet.put("utility", utilityMap); - - aValueSet.put("languages", - new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language")); - - aValueSet.put("topics", - new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); - - Map articleTypeMap = new HashMap(); - articleTypeMap.put("openposting", "0"); - articleTypeMap.put("newswire", "1"); - articleTypeMap.put("feature", "2"); - articleTypeMap.put("topicspecial", "3"); - articleTypeMap.put("startspecial", "4"); - - i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType"); - while (i.hasNext()) { - EntityAdapter articleType = (EntityAdapter) i.next(); - - articleTypeMap.put(articleType.get("name"), articleType.get("id")); - } - aValueSet.put("articletype", articleTypeMap); - - Map commentStatusMap = new HashMap(); - i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"); - while (i.hasNext()) { - EntityAdapter commentStatus = (EntityAdapter) i.next(); - - commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id")); - } - aValueSet.put("commentstatus", commentStatusMap); - } - catch (Throwable t) { - logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage()); - throw new RuntimeException(t.getMessage()); - } - - }; - - public String filterText(String aText) { - return StringUtil.createHTML( - StringUtil.deleteForbiddenTags(aText), - MirGlobal.config().getString("Producer.ImageRoot"), - MirGlobal.config().getString("Producer.MailLinkName"), - MirGlobal.config().getString("Producer.ExtLinkName"), - MirGlobal.config().getString("Producer.IntLinkName") - ); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.localizer.basic; + +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.adapter.EntityAdapter; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.util.DateToMapAdapter; +import mir.util.GeneratorHTMLFunctions; +import mir.util.GeneratorIntegerFunctions; +import mir.util.GeneratorListFunctions; +import mir.util.GeneratorStringFunctions; +import mircoders.global.MirGlobal; +import mircoders.localizer.MirProducerAssistantLocalizer; + +public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer { + protected LoggerWrapper logger; + + public void initializeGenerationValueSet(Map aValueSet) { + try { + Iterator i; + + Map configMap = new HashMap(); + Map utilityMap = new HashMap(); + + logger = new LoggerWrapper("Localizer.ProducerAssistant"); + +// obsolete: + configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot")); + configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot")); + configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost")); + configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction")); + configMap.put("docRoot", MirGlobal.config().getString("RootUri")); + configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir"); + configMap.put("now", new DateToMapAdapter( (new GregorianCalendar()).getTime())); + configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host")); + configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host")); + configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host")); + configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path")); + configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version")); + configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding")); + +// "new": + configMap.putAll(MirPropertiesConfiguration.instance().allSettings()); + + utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace()); + utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction()); + utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction()); + utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction()); + utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction()); + utilityMap.put("subList", new GeneratorListFunctions.subListFunction()); + utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction()); + utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction()); + + aValueSet.put("config", configMap); + aValueSet.put("utility", utilityMap); + + aValueSet.put("languages", + new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language")); + + aValueSet.put("topics", + new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + + Map articleTypeMap = new HashMap(); + articleTypeMap.put("openposting", "0"); + articleTypeMap.put("newswire", "1"); + articleTypeMap.put("feature", "2"); + articleTypeMap.put("topicspecial", "3"); + articleTypeMap.put("startspecial", "4"); + + i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType"); + while (i.hasNext()) { + EntityAdapter articleType = (EntityAdapter) i.next(); + + articleTypeMap.put(articleType.get("name"), articleType.get("id")); + } + aValueSet.put("articletype", articleTypeMap); + + Map commentStatusMap = new HashMap(); + i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"); + while (i.hasNext()) { + EntityAdapter commentStatus = (EntityAdapter) i.next(); + + commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id")); + } + aValueSet.put("commentstatus", commentStatusMap); + } + catch (Throwable t) { + logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage()); + throw new RuntimeException(t.getMessage()); + } + + }; + + public String filterText(String aText) { + return StringUtil.createHTML( + StringUtil.deleteForbiddenTags(aText), + MirGlobal.config().getString("Producer.ImageRoot"), + MirGlobal.config().getString("Producer.MailLinkName"), + MirGlobal.config().getString("Producer.ExtLinkName"), + MirGlobal.config().getString("Producer.IntLinkName") + ); + } +} diff --git a/source/mircoders/media/MediaHandlerImagesExtern.java b/source/mircoders/media/MediaHandlerImagesExtern.java index a885d2fa..1f01ee57 100755 --- a/source/mircoders/media/MediaHandlerImagesExtern.java +++ b/source/mircoders/media/MediaHandlerImagesExtern.java @@ -1,176 +1,176 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.media; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; -import mir.misc.StringUtil; -import mircoders.storage.DatabaseUploadedMedia; - - -/** - * Image handler that stores images outside of the database. Will be replaced by the new - * media handling system. - * @author Zapata - * @version 1.0 - */ - -public class MediaHandlerImagesExtern extends MediaHandlerGeneric -{ - public MediaHandlerImagesExtern() { - logger = new LoggerWrapper("Media.Images.Extern"); - } - - public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure { - try { - String date = anImageEntity.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String ext = "." + mediaTypeEnt.getValue("name"); - String filePath = datePath + anImageEntity.getId() + ext; - String iconFilePath = MirPropertiesConfiguration.instance().getString("Producer.StorageRoot") + getIconStoragePath() + filePath; - String imageFilePath = getStoragePath() + File.separator + filePath; - int maxIconSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxIconSize"); - - File imageFile = new File(imageFilePath); - File iconFile = new File(iconFilePath); - - if (!imageFile.exists()) { - throw new MediaExc("error in MediaHandlerImagesExtern.produce(): " + filePath + " does not exist!"); - } - else { - ImageProcessor processor = new ImageProcessor(imageFile, "JPEG"); - - processor.descaleImage(maxIconSize, 0.2F); - File dir = new File(iconFile.getParent()); - if (dir!=null && !dir.exists()){ - dir.mkdirs(); - } - processor.writeScaledData(iconFile); - - logger.info(processor.getWidth()+"x"+processor.getHeight()); - - anImageEntity.setValueForProperty("img_height", new Integer(processor.getHeight()).toString()); - anImageEntity.setValueForProperty("img_width", new Integer(processor.getWidth()).toString()); - - anImageEntity.setValueForProperty("icon_height", new Integer(processor.getScaledHeight()).toString()); - anImageEntity.setValueForProperty("icon_width", new Integer(processor.getScaledWidth()).toString()); - - anImageEntity.setValueForProperty("icon_path", getIconStoragePath()+filePath); - anImageEntity.setValueForProperty("publish_path", filePath); - - anImageEntity.update(); - } - } - catch(Throwable t) { - logger.error("MediaHandlerImagesExtern.produce: " + t.getMessage()); - t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - throw new MediaFailure(t.getMessage(), t); - } - } - - - public InputStream getIcon(Entity anImageEntity) throws MediaExc, MediaFailure { - try { - Entity mediaType = DatabaseUploadedMedia.getInstance().getMediaType( - anImageEntity); - - String date = anImageEntity.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String ext = "." + mediaType.getValue("name"); - String filePath = MirPropertiesConfiguration.instance().getString("Producer.StorageRoot") + - getIconStoragePath() + datePath + anImageEntity.getId() + ext; - - return new FileInputStream(new File(filePath)); - } - catch (Throwable t) { - throw new MediaFailure(t); - } - } - - public String getStoragePath() - { - return configuration.getString("Producer.Image.Path"); - } - - public String getIconStoragePath() - { - return configuration.getString("Producer.Image.IconPath"); - } - - public String getPublishHost() - { - return StringUtil.removeSlash(configuration.getString("Producer.Image.Host")); - } - - public String getTinyIconName() - { - return configuration.getString("Producer.Icon.TinyImage"); - } - - public String getBigIconName() - { - return configuration.getString("Producer.Icon.BigImage"); - } - - public String getIconAltName() - { - return "Image"; - } - - public boolean isVideo() - { - return false; - } - - public boolean isAudio() - { - return false; - } - - public boolean isImage () - { - return true; - } - - public String getDescr(Entity mediaType) - { - return "image/jpeg"; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.media; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.misc.StringUtil; +import mircoders.storage.DatabaseUploadedMedia; + + +/** + * Image handler that stores images outside of the database. Will be replaced by the new + * media handling system. + * @author Zapata + * @version 1.0 + */ + +public class MediaHandlerImagesExtern extends MediaHandlerGeneric +{ + public MediaHandlerImagesExtern() { + logger = new LoggerWrapper("Media.Images.Extern"); + } + + public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure { + try { + String date = anImageEntity.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String ext = "." + mediaTypeEnt.getValue("name"); + String filePath = datePath + anImageEntity.getId() + ext; + String iconFilePath = MirPropertiesConfiguration.instance().getString("Producer.StorageRoot") + getIconStoragePath() + filePath; + String imageFilePath = getStoragePath() + File.separator + filePath; + int maxIconSize = MirPropertiesConfiguration.instance().getInt("Producer.Image.MaxIconSize"); + + File imageFile = new File(imageFilePath); + File iconFile = new File(iconFilePath); + + if (!imageFile.exists()) { + throw new MediaExc("error in MediaHandlerImagesExtern.produce(): " + filePath + " does not exist!"); + } + else { + ImageProcessor processor = new ImageProcessor(imageFile, "JPEG"); + + processor.descaleImage(maxIconSize, 0.2F); + File dir = new File(iconFile.getParent()); + if (dir!=null && !dir.exists()){ + dir.mkdirs(); + } + processor.writeScaledData(iconFile); + + logger.info(processor.getWidth()+"x"+processor.getHeight()); + + anImageEntity.setValueForProperty("img_height", new Integer(processor.getHeight()).toString()); + anImageEntity.setValueForProperty("img_width", new Integer(processor.getWidth()).toString()); + + anImageEntity.setValueForProperty("icon_height", new Integer(processor.getScaledHeight()).toString()); + anImageEntity.setValueForProperty("icon_width", new Integer(processor.getScaledWidth()).toString()); + + anImageEntity.setValueForProperty("icon_path", getIconStoragePath()+filePath); + anImageEntity.setValueForProperty("publish_path", filePath); + + anImageEntity.update(); + } + } + catch(Throwable t) { + logger.error("MediaHandlerImagesExtern.produce: " + t.getMessage()); + t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + throw new MediaFailure(t.getMessage(), t); + } + } + + + public InputStream getIcon(Entity anImageEntity) throws MediaExc, MediaFailure { + try { + Entity mediaType = DatabaseUploadedMedia.getInstance().getMediaType( + anImageEntity); + + String date = anImageEntity.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String ext = "." + mediaType.getValue("name"); + String filePath = MirPropertiesConfiguration.instance().getString("Producer.StorageRoot") + + getIconStoragePath() + datePath + anImageEntity.getId() + ext; + + return new FileInputStream(new File(filePath)); + } + catch (Throwable t) { + throw new MediaFailure(t); + } + } + + public String getStoragePath() + { + return configuration.getString("Producer.Image.Path"); + } + + public String getIconStoragePath() + { + return configuration.getString("Producer.Image.IconPath"); + } + + public String getPublishHost() + { + return StringUtil.removeSlash(configuration.getString("Producer.Image.Host")); + } + + public String getTinyIconName() + { + return configuration.getString("Producer.Icon.TinyImage"); + } + + public String getBigIconName() + { + return configuration.getString("Producer.Icon.BigImage"); + } + + public String getIconAltName() + { + return "Image"; + } + + public boolean isVideo() + { + return false; + } + + public boolean isAudio() + { + return false; + } + + public boolean isImage () + { + return true; + } + + public String getDescr(Entity mediaType) + { + return "image/jpeg"; + } +} diff --git a/source/mircoders/media/MediaHandlerVideo.java b/source/mircoders/media/MediaHandlerVideo.java index 5e020f24..195205e4 100755 --- a/source/mircoders/media/MediaHandlerVideo.java +++ b/source/mircoders/media/MediaHandlerVideo.java @@ -1,73 +1,73 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.media; - -import mir.media.MirMedia; - - -/** - * Handles video media, like mpeg, av, and qt - * It is like MediaHandlerAudio with different icons. - * It is MediaHandlerGeneric with different icons. - * - * @see mir.media.MediaHandlerGeneric - * @see mir.media.MirMedia - * @author john - * @version $Id: MediaHandlerVideo.java,v 1.7 2003/02/23 05:00:14 zapata Exp $ - */ - -public class MediaHandlerVideo extends MediaHandlerGeneric implements MirMedia -{ - private static String tinyIcon; - private static String bigIcon; - - static { - tinyIcon = configuration.getString("Producer.Icon.TinyVideo"); - bigIcon = configuration.getString("Producer.Icon.BigVideo"); - } - - public String getTinyIcon() { - return tinyIcon; - } - - public String getBigIconName() { - return bigIcon; - } - - public String getIconAlt() { - return "Video"; - } - - public boolean isVideo() { - return true; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.media; + +import mir.media.MirMedia; + + +/** + * Handles video media, like mpeg, av, and qt + * It is like MediaHandlerAudio with different icons. + * It is MediaHandlerGeneric with different icons. + * + * @see mir.media.MediaHandlerGeneric + * @see mir.media.MirMedia + * @author john + * @version $Id: MediaHandlerVideo.java,v 1.8 2003/04/09 02:06:09 zapata Exp $ + */ + +public class MediaHandlerVideo extends MediaHandlerGeneric implements MirMedia +{ + private static String tinyIcon; + private static String bigIcon; + + static { + tinyIcon = configuration.getString("Producer.Icon.TinyVideo"); + bigIcon = configuration.getString("Producer.Icon.BigVideo"); + } + + public String getTinyIcon() { + return tinyIcon; + } + + public String getBigIconName() { + return bigIcon; + } + + public String getIconAlt() { + return "Video"; + } + + public boolean isVideo() { + return true; + } +} diff --git a/source/mircoders/module/ModuleUsers.java b/source/mircoders/module/ModuleUsers.java index 8c97894e..0e401058 100755 --- a/source/mircoders/module/ModuleUsers.java +++ b/source/mircoders/module/ModuleUsers.java @@ -1,140 +1,140 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.module; - -import java.util.HashMap; -import java.util.Map; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; -import mir.util.JDBCStringRoutines; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; - - -/* - * Users Module - - * - * - * @author RK - */ - -public class ModuleUsers extends AbstractModule -{ - static LoggerWrapper logger = new LoggerWrapper("Module.Users"); - - public ModuleUsers(StorageObject theStorage) - { - if (theStorage == null) - logger.warn("ModuleUsers(): StorageObject was null!"); - - this.theStorage = theStorage; - } - - /** - * Authenticate and lookup a user - * - * @param user The user to lookup - * @param password The password - * @return The authenticated user, or null if the user - * doesn't exist, or the supplied password is invalid. - * @throws ModuleException - */ - - public EntityUsers getUserForLogin(String user, String password) throws ModuleExc, ModuleFailure { - try { - String whereString = - "login='" + JDBCStringRoutines.escapeStringLiteral(user) + "' " + - "and password='" + JDBCStringRoutines.escapeStringLiteral( - MirGlobal.localizer().adminInterface().makePasswordDigest(password)) + - "' " + - "and is_admin='1'"; - - EntityList userList = getByWhereClause(whereString, -1); - - if (userList != null && userList.getCount() == 1) - return (EntityUsers) userList.elementAt(0); - else - return null; - } - catch (Throwable t) { - throw new ModuleFailure(t); - } - } - - private Map digestPassword(Map aValues) throws ModuleExc, ModuleFailure { - Map result = aValues; - - try { - if (aValues.containsKey("password")) { - result = new HashMap(); - result.putAll(aValues); - result.put("password", - MirGlobal.localizer().adminInterface(). - makePasswordDigest( (String) aValues.get("password"))); - } - } - catch (Throwable t) { - throw new ModuleFailure("ModuleUsers.add: " + t.getMessage(), t); - } - - return result; - } - - public String add (Map theValues) throws ModuleExc, ModuleFailure { - try { - return super.add(digestPassword(theValues)); - } - catch (Throwable t) { - throw new ModuleFailure(t); - } - } - - /** - * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren - * @param theValues Hash mit Spalte/Wert-Paaren - * @return Id des eingef?gten Objekts - * @exception ModuleException - */ - public String set (Map theValues) throws ModuleExc, ModuleFailure { - try { - return super.set(digestPassword(theValues)); - } - catch (Throwable t) { - throw new ModuleFailure(t); - } - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.module; + +import java.util.HashMap; +import java.util.Map; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; +import mir.util.JDBCStringRoutines; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; + + +/* + * Users Module - + * + * + * @author RK + */ + +public class ModuleUsers extends AbstractModule +{ + static LoggerWrapper logger = new LoggerWrapper("Module.Users"); + + public ModuleUsers(StorageObject theStorage) + { + if (theStorage == null) + logger.warn("ModuleUsers(): StorageObject was null!"); + + this.theStorage = theStorage; + } + + /** + * Authenticate and lookup a user + * + * @param user The user to lookup + * @param password The password + * @return The authenticated user, or null if the user + * doesn't exist, or the supplied password is invalid. + * @throws ModuleException + */ + + public EntityUsers getUserForLogin(String user, String password) throws ModuleExc, ModuleFailure { + try { + String whereString = + "login='" + JDBCStringRoutines.escapeStringLiteral(user) + "' " + + "and password='" + JDBCStringRoutines.escapeStringLiteral( + MirGlobal.localizer().adminInterface().makePasswordDigest(password)) + + "' " + + "and is_admin='1'"; + + EntityList userList = getByWhereClause(whereString, -1); + + if (userList != null && userList.getCount() == 1) + return (EntityUsers) userList.elementAt(0); + else + return null; + } + catch (Throwable t) { + throw new ModuleFailure(t); + } + } + + private Map digestPassword(Map aValues) throws ModuleExc, ModuleFailure { + Map result = aValues; + + try { + if (aValues.containsKey("password")) { + result = new HashMap(); + result.putAll(aValues); + result.put("password", + MirGlobal.localizer().adminInterface(). + makePasswordDigest( (String) aValues.get("password"))); + } + } + catch (Throwable t) { + throw new ModuleFailure("ModuleUsers.add: " + t.getMessage(), t); + } + + return result; + } + + public String add (Map theValues) throws ModuleExc, ModuleFailure { + try { + return super.add(digestPassword(theValues)); + } + catch (Throwable t) { + throw new ModuleFailure(t); + } + } + + /** + * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren + * @param theValues Hash mit Spalte/Wert-Paaren + * @return Id des eingef?gten Objekts + * @exception ModuleException + */ + public String set (Map theValues) throws ModuleExc, ModuleFailure { + try { + return super.set(digestPassword(theValues)); + } + catch (Throwable t) { + throw new ModuleFailure(t); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletHelper.java b/source/mircoders/servlet/ServletHelper.java index c3e4b85c..efe8dbce 100755 --- a/source/mircoders/servlet/ServletHelper.java +++ b/source/mircoders/servlet/ServletHelper.java @@ -6,7 +6,6 @@ import java.util.Locale; import java.util.Map; import org.apache.struts.util.MessageResources; - import mir.entity.adapter.EntityIteratorAdapter; import mir.generator.Generator; import mir.servlet.ServletModuleExc; @@ -14,21 +13,20 @@ import mir.servlet.ServletModuleFailure; import mir.util.CachingRewindableIterator; import mir.util.NullWriter; import mir.util.ResourceBundleGeneratorFunction; - import mircoders.global.MirGlobal; public class ServletHelper { - static Map makeGenerationData(Locale aLocale) throws ServletModuleExc { - return makeGenerationData(aLocale, "bundles.adminlocal", "bundles.admin"); + public static Map makeGenerationData(Locale[] aLocales) throws ServletModuleExc { + return makeGenerationData(aLocales, "bundles.adminlocal", "bundles.admin"); } - static Map makeGenerationData(Locale aLocale, String aBundle) throws ServletModuleExc { - return makeGenerationData(aLocale, aBundle, aBundle); + public static Map makeGenerationData(Locale[] aLocales, String aBundle) throws ServletModuleExc { + return makeGenerationData(aLocales, aBundle, aBundle); } - static Map makeGenerationData(Locale aLocale, String aBundle, String aDefaultBundle) throws ServletModuleExc { + public static Map makeGenerationData(Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc { try { Map result = new HashMap(); @@ -62,9 +60,9 @@ public class ServletHelper { result.put("topics", topics); result.put( "lang", - new ResourceBundleGeneratorFunction( aLocale, - MessageResources.getMessageResources(aBundle), - MessageResources.getMessageResources(aDefaultBundle))); + new ResourceBundleGeneratorFunction( aLocales, + new MessageResources[] { MessageResources.getMessageResources(aBundle), + MessageResources.getMessageResources(aDefaultBundle)})); return result; } @@ -73,7 +71,7 @@ public class ServletHelper { } } - static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { + public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { Generator generator; try { @@ -86,7 +84,7 @@ public class ServletHelper { } } - static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { + public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { Generator generator; try { diff --git a/source/mircoders/servlet/ServletModuleAbuse.java b/source/mircoders/servlet/ServletModuleAbuse.java index 1cf01251..e2d955b0 100755 --- a/source/mircoders/servlet/ServletModuleAbuse.java +++ b/source/mircoders/servlet/ServletModuleAbuse.java @@ -1,150 +1,150 @@ -package mircoders.servlet; - +package mircoders.servlet; + +import java.util.Locale; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleFailure; -import mir.util.URLBuilder; import mir.util.HTTPRequestParser; -import mircoders.global.*; - -public class ServletModuleAbuse extends ServletModule { - private static ServletModuleAbuse instance = new ServletModuleAbuse(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleAbuse() { - logger = new LoggerWrapper("ServletModule.Abuse"); - defaultAction = "showsettings"; - } - - public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String type=requestParser.getParameterWithDefault("type", ""); - String id=requestParser.getParameterWithDefault("id", ""); - String expression=requestParser.getParameterWithDefault("expression", ""); - - if (id.equals("")) { - MirGlobal.abuse().addFilter(type, expression); - } - else { - MirGlobal.abuse().setFilter(id, type, expression); - } - - MirGlobal.abuse().save(); - - showfilters(aRequest, aResponse); - } - - public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String id=requestParser.getParameterWithDefault("id", ""); - MirGlobal.abuse().deleteFilter(id); - - MirGlobal.abuse().save(); - - showfilters(aRequest, aResponse); - } - - public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - - urlBuilder.setValue("module", "Abuse"); - urlBuilder.setValue("do", "showfilters"); - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("filters", MirGlobal.abuse().getFilters()); - responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.filters.template"); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - - public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - - urlBuilder.setValue("module", "Abuse"); - urlBuilder.setValue("do", "showsettings"); - - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); - responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); - - responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled())); - responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword())); - responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled())); - responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize())); - responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock())); - responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction()); - responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.template"); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { - try { - HTTPRequestParser parser = new HTTPRequestParser(aRequest); - - MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1")); - MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1")); - MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1")); - - try { - MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize())); - } - catch (Throwable t) { - } - - MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1")); - - MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction")); - MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction")); - - MirGlobal.abuse().save(); - - showsettings(aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - urlBuilder.setValue("module", "Abuse"); - urlBuilder.setValue("do", "showlog"); - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("log", MirGlobal.abuse().getLog()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.log.template"); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } +import mir.util.URLBuilder; +import mircoders.global.MirGlobal; + +public class ServletModuleAbuse extends ServletModule { + private static ServletModuleAbuse instance = new ServletModuleAbuse(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleAbuse() { + logger = new LoggerWrapper("ServletModule.Abuse"); + defaultAction = "showsettings"; + } + + public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String type=requestParser.getParameterWithDefault("type", ""); + String id=requestParser.getParameterWithDefault("id", ""); + String expression=requestParser.getParameterWithDefault("expression", ""); + + if (id.equals("")) { + MirGlobal.abuse().addFilter(type, expression); + } + else { + MirGlobal.abuse().setFilter(id, type, expression); + } + + MirGlobal.abuse().save(); + + showfilters(aRequest, aResponse); + } + + public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().deleteFilter(id); + + MirGlobal.abuse().save(); + + showfilters(aRequest, aResponse); + } + + public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showfilters"); + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("filters", MirGlobal.abuse().getFilters()); + responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.filters.template"); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + + public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showsettings"); + + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); + responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); + + responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled())); + responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword())); + responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled())); + responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize())); + responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock())); + responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction()); + responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.template"); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { + try { + HTTPRequestParser parser = new HTTPRequestParser(aRequest); + + MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1")); + MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1")); + MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1")); + + try { + MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize())); + } + catch (Throwable t) { + } + + MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1")); + + MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction")); + MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction")); + + MirGlobal.abuse().save(); + + showsettings(aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showlog"); + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("log", MirGlobal.abuse().getLog()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.log.template"); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleAdmin.java b/source/mircoders/servlet/ServletModuleAdmin.java index eb4ae4d9..533ff79c 100755 --- a/source/mircoders/servlet/ServletModuleAdmin.java +++ b/source/mircoders/servlet/ServletModuleAdmin.java @@ -1,71 +1,71 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleFailure; -import mir.util.URLBuilder; - -public class ServletModuleAdmin extends ServletModule -{ - private static ServletModuleAdmin instance = new ServletModuleAdmin(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleAdmin() { - logger = new LoggerWrapper("ServletModule.Admin"); - defaultAction = "showSuperUserMenu"; - } - - public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - urlBuilder.setValue("module", "Admin"); - urlBuilder.setValue("do", "superusermenu"); - - responseData.put("thisurl" , urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template"); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleFailure; +import mir.util.URLBuilder; + +public class ServletModuleAdmin extends ServletModule +{ + private static ServletModuleAdmin instance = new ServletModuleAdmin(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleAdmin() { + logger = new LoggerWrapper("ServletModule.Admin"); + defaultAction = "showSuperUserMenu"; + } + + public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + urlBuilder.setValue("module", "Admin"); + urlBuilder.setValue("do", "superusermenu"); + + responseData.put("thisurl" , urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template"); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index b752549c..6a7afa60 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -31,20 +31,19 @@ package mircoders.servlet; -import java.net.URLEncoder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleFailure; -import mircoders.module.ModuleBreaking; +import java.net.URLEncoder; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import freemarker.template.SimpleHash; +import mir.config.MirPropertiesConfiguration; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleFailure; +import mircoders.module.ModuleBreaking; import mircoders.storage.DatabaseBreaking; -import freemarker.template.SimpleHash; /* * ServletModuleBreaking - @@ -102,7 +101,7 @@ public class ServletModuleBreaking extends ServletModule mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); // raus damit - HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req)); + HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req)); } catch (Exception e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleComment.java b/source/mircoders/servlet/ServletModuleComment.java index 510b9844..50173476 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -32,6 +32,7 @@ package mircoders.servlet; import java.util.Map; +import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -201,7 +202,7 @@ public class ServletModuleComment extends ServletModule int count; try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); model = MirGlobal.localizer().dataModel().adapterModel(); Object commentList = diff --git a/source/mircoders/servlet/ServletModuleCommentStatus.java b/source/mircoders/servlet/ServletModuleCommentStatus.java index ffe91690..d2adaac5 100755 --- a/source/mircoders/servlet/ServletModuleCommentStatus.java +++ b/source/mircoders/servlet/ServletModuleCommentStatus.java @@ -31,10 +31,10 @@ package mircoders.servlet; -import mir.config.MirPropertiesConfiguration; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mircoders.module.ModuleCommentStatus; +import mir.config.MirPropertiesConfiguration; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mircoders.module.ModuleCommentStatus; import mircoders.storage.DatabaseCommentStatus; public class ServletModuleCommentStatus extends ServletModule diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index 048959b0..3c168514 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -1,554 +1,555 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.lucene.index.IndexReader; -import freemarker.template.SimpleHash; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.CachingRewindableIterator; -import mir.util.HTTPRequestParser; -import mir.util.JDBCStringRoutines; -import mir.util.SQLQueryBuilder; -import mir.util.URLBuilder; - -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleContent; -import mircoders.search.IndexUtil; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseContentToMedia; - -/* - * ServletModuleContent - - * deliver html for the article admin form. - * - * @version $Id: ServletModuleContent.java,v 1.46 2003/03/27 20:11:35 zapata Exp $ - * @author rk, mir-coders - * - */ - -public class ServletModuleContent extends ServletModule -{ - private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; - private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); - - private static ServletModuleContent instance = new ServletModuleContent(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleContent() { - super(); - logger = new LoggerWrapper("ServletModule.Content"); - try { - - templateListString = configuration.getString("ServletModule.Content.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); - - mainModule = new ModuleContent(DatabaseContent.getInstance()); - } - catch (Throwable e) { - logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); - } - } - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String where = requestParser.getParameter("where"); - String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); - int offset = requestParser.getIntegerWithDefault("offset", 0); - String selectArticleUrl = requestParser.getParameter("selectarticleurl"); - - returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl); - } - - public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); - String searchField = requestParser.getParameterWithDefault("searchfield", ""); - String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim(); - String searchOrder = requestParser.getParameterWithDefault("searchorder", ""); - String searchispublished = requestParser.getParameterWithDefault("searchispublished", ""); - String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); - String selectArticleUrl = requestParser.getParameter("selectarticleurl"); - - if (searchValue.length()>0) { - if (searchField.equals("id")) - queryBuilder.appendAndCondition( - "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'"); - else if (searchField.equals("contents")) - queryBuilder.appendAndCondition( - "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ - " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); - else - queryBuilder.appendAndCondition( - "lower("+ searchField + ") like " + - "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); - } - - if (searchispublished.length()>0) { - if (searchispublished.equals("0")) - queryBuilder.appendAndCondition("is_published='f'"); - else - queryBuilder.appendAndCondition("is_published='t'"); - } - - if (searchArticleType.length()>0) { - queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType)); - } - - if (searchOrder.length()>0) { - if (searchOrder.equals("datedesc")) - queryBuilder.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) - queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("title")) - queryBuilder.appendDescendingOrder("title"); - else if (searchOrder.equals("creator")) - queryBuilder.appendDescendingOrder("creator"); - } - - returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { - _showObject(null, req, res); - } - - - public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { -//theLog.printDebugInfo(":: content :: trying to insert"); - try { - EntityUsers user = _getUser(req); - Map withValues = getIntersectingValues(req, DatabaseContent.getInstance()); - - String now = StringUtil.date2webdbDate(new GregorianCalendar()); - withValues.put("date", now); - withValues.put("publish_path", StringUtil.webdbDate2path(now)); - withValues.put("to_publisher", user.getId()); - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String id = mainModule.add(withValues); - DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); - - _showObject(id, req, res); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - EntityUsers user = _getUser(req); - - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleExc("Invalid call: id missing"); - - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - - logger.info("where = " + req.getParameter("where")); - - if (confirmParam == null && cancelParam == null) { - - SimpleHash mergeData = new SimpleHash(); - mergeData.put("module", "Content"); - mergeData.put("infoString", "Content: " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - deliver(req, res, mergeData, templateConfirmString); - } - else { - if (confirmParam!= null && !confirmParam.equals("")) { - try { - mainModule.deleteById(idParam); - - /** @todo the following two should be implied in - * DatabaseContent */ - DatabaseContentToTopics.getInstance().deleteByContentId(idParam); - DatabaseComment.getInstance().deleteByContentId(idParam); - DatabaseContentToMedia.getInstance().deleteByContentId(idParam); - - - //delete from lucene index, if any - String index = configuration.getString("IndexPath"); - if (IndexReader.indexExists(index)){ - IndexUtil.unindexID(idParam,index); - } - - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - list(req,res); - } - else { - // Datensatz anzeigen - _showObject(idParam, req, res); - } - } - } - - public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String idParam = req.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Invalid call: id not supplied "); - _showObject(idParam, req, res); - } - -// methods for attaching media file - public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String mediaIdParam = req.getParameter("mid"); - String idParam = req.getParameter("cid"); - if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(idParam); - entContent.attach(mediaIdParam); - } - catch(Throwable e) { - logger.error("smod content :: attach :: could not get entityContent"); - } - - _showObject(idParam, req, res); - } - - public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String cidParam = req.getParameter("cid"); - String midParam = req.getParameter("mid"); - if (cidParam == null) - throw new ServletModuleExc("smod content :: dettach :: cid missing"); - if (midParam == null) - throw new ServletModuleExc("smod content :: dettach :: mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(cidParam); - entContent.dettach(cidParam,midParam); - } - catch(Throwable e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - - _showObject(cidParam, req, res); - } - - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String returnUrl = requestParser.getParameter("returnurl"); - - String idParam = aRequest.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Wrong call: (id) is missing"); - - Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); - String[] topic_id = aRequest.getParameterValues("to_topic"); - String content_id = aRequest.getParameter("id"); - - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String id = mainModule.set(withValues); - DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id); - - String whereParam = aRequest.getParameter("where"); - String orderParam = aRequest.getParameter("order"); - - if (returnUrl!=null){ - redirect(aResponse, returnUrl); - } - else - _showObject(idParam, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - -/* - * HelperMethod shows the basic article editing form. - * - * if the "id" parameter is null, it means show an empty form to add a new - * article. -*/ - public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); - Map article; - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "edit"); - urlBuilder.setValue("id", id); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - if (id!=null) { - responseData.put("new", Boolean.FALSE); - article = model.makeEntityAdapter("content", mainModule.getById(id)); - } - else { - List fields = DatabaseContent.getInstance().getFields(); - responseData.put("new", Boolean.TRUE); - article = new HashMap(); - Iterator i = fields.iterator(); - while (i.hasNext()) { - article.put(i.next(), null); - } - - article.put("to_topics", null); - - MirGlobal.localizer().adminInterface().initializeArticle(article); - } - responseData.put("article", article); - - responseData.put("topics", - new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"), - 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); - - - - responseData.put("returnurl", requestParser.getParameter("returnurl")); - responseData.put("thisurl", urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void returnArticleList( - HttpServletRequest aRequest, - HttpServletResponse aResponse, - String aWhereClause, - String anOrderByClause, - int anOffset, - String aSelectArticleUrl) throws ServletModuleExc { - - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - URLBuilder urlBuilder = new URLBuilder(); - EntityAdapterModel model; - int nrArticlesPerPage = 20; - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object articleList = - new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset) - ); - - responseData.put("nexturl", null); - responseData.put("prevurl", null); - - count=mainModule.getSize(aWhereClause); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "list"); - urlBuilder.setValue("where", aWhereClause); - urlBuilder.setValue("order", anOrderByClause); - - - urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); - urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue")); - urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); - urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); - urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype")); - urlBuilder.setValue("selectarticleurl", aSelectArticleUrl); - - responseData.put("searchfield", requestParser.getParameter("searchfield")); - responseData.put("searchvalue", requestParser.getParameter("searchvalue")); - responseData.put("searchispublished", requestParser.getParameter("searchispublished")); - responseData.put("searchorder", requestParser.getParameter("searchorder")); - responseData.put("searcharticletype", requestParser.getParameter("searcharticletype")); - responseData.put("selectarticleurl", aSelectArticleUrl); - - urlBuilder.setValue("offset", anOffset); - responseData.put("offset" , new Integer(anOffset).toString()); - responseData.put("thisurl" , urlBuilder.getQuery()); - - if (count>=anOffset+nrArticlesPerPage) { - urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage)); - responseData.put("nexturl" , urlBuilder.getQuery()); - } - - if (anOffset>0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0)); - responseData.put("prevurl" , urlBuilder.getQuery()); - } - - responseData.put("articles", articleList); - - responseData.put("from" , Integer.toString(anOffset+1)); - responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count))); - responseData.put("offset" , Integer.toString(anOffset)); - responseData.put("order", anOrderByClause); - responseData.put("where" , aWhereClause); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "setparent"); - urlBuilder.setValue("childid", requestParser.getParameter("id")); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery()); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = requestParser.getParameter("article_id"); - - if (articleId == null) - throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!"); - - returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = aRequest.getParameter("childid"); - String parentId = aRequest.getParameter("id"); - String returnUrl = aRequest.getParameter("returnurl"); - - try { - EntityContent article = (EntityContent) mainModule.getById(articleId); - article.setValueForProperty("to_content", parentId); - article.setProduced(false); - article.update(); - } - catch(Throwable e) { - logger.error("ServletModuleContent.setparent: " + e.getMessage()); - throw new ServletModuleFailure(e); - } - - redirect(aResponse, returnUrl); - } - - public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = requestParser.getParameter("id"); - String returnUrl = requestParser.getParameter("returnurl"); - - try { - EntityContent article = (EntityContent) mainModule.getById(articleId); - article.setValueForProperty("to_content", ""); - article.setProduced(false); - article.update(); - } - catch(Throwable e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - logger.error("ServletModuleContent.clearparent: " + e.getMessage()); - - throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e); - } - - redirect(aResponse, returnUrl); - } - - private EntityUsers _getUser(HttpServletRequest req) - { - HttpSession session=req.getSession(false); - - return (EntityUsers)session.getAttribute("login.uid"); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.lucene.index.IndexReader; +import freemarker.template.SimpleHash; +import mir.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.CachingRewindableIterator; +import mir.util.HTTPRequestParser; +import mir.util.JDBCStringRoutines; +import mir.util.SQLQueryBuilder; +import mir.util.URLBuilder; + +import mircoders.entity.EntityContent; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleContent; +import mircoders.search.IndexUtil; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToTopics; +import mircoders.storage.DatabaseContentToMedia; + +/* + * ServletModuleContent - + * deliver html for the article admin form. + * + * @version $Id: ServletModuleContent.java,v 1.47 2003/04/09 02:06:09 zapata Exp $ + * @author rk, mir-coders + * + */ + +public class ServletModuleContent extends ServletModule +{ + private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; + private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); + + private static ServletModuleContent instance = new ServletModuleContent(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleContent() { + super(); + logger = new LoggerWrapper("ServletModule.Content"); + try { + + templateListString = configuration.getString("ServletModule.Content.ListTemplate"); + templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); + templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); + + mainModule = new ModuleContent(DatabaseContent.getInstance()); + } + catch (Throwable e) { + logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); + } + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String where = requestParser.getParameter("where"); + String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); + int offset = requestParser.getIntegerWithDefault("offset", 0); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl); + } + + public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); + String searchField = requestParser.getParameterWithDefault("searchfield", ""); + String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim(); + String searchOrder = requestParser.getParameterWithDefault("searchorder", ""); + String searchispublished = requestParser.getParameterWithDefault("searchispublished", ""); + String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + if (searchValue.length()>0) { + if (searchField.equals("id")) + queryBuilder.appendAndCondition( + "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'"); + else if (searchField.equals("contents")) + queryBuilder.appendAndCondition( + "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ + " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); + else + queryBuilder.appendAndCondition( + "lower("+ searchField + ") like " + + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); + } + + if (searchispublished.length()>0) { + if (searchispublished.equals("0")) + queryBuilder.appendAndCondition("is_published='f'"); + else + queryBuilder.appendAndCondition("is_published='t'"); + } + + if (searchArticleType.length()>0) { + queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType)); + } + + if (searchOrder.length()>0) { + if (searchOrder.equals("datedesc")) + queryBuilder.appendAscendingOrder("webdb_create"); + else if (searchOrder.equals("dateasc")) + queryBuilder.appendDescendingOrder("webdb_create"); + else if (searchOrder.equals("title")) + queryBuilder.appendDescendingOrder("title"); + else if (searchOrder.equals("creator")) + queryBuilder.appendDescendingOrder("creator"); + } + + returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { + _showObject(null, req, res); + } + + + public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { +//theLog.printDebugInfo(":: content :: trying to insert"); + try { + EntityUsers user = _getUser(req); + Map withValues = getIntersectingValues(req, DatabaseContent.getInstance()); + + String now = StringUtil.date2webdbDate(new GregorianCalendar()); + withValues.put("date", now); + withValues.put("publish_path", StringUtil.webdbDate2path(now)); + withValues.put("to_publisher", user.getId()); + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String id = mainModule.add(withValues); + DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); + + _showObject(id, req, res); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + EntityUsers user = _getUser(req); + + String idParam = req.getParameter("id"); + if (idParam == null) throw new ServletModuleExc("Invalid call: id missing"); + + String confirmParam = req.getParameter("confirm"); + String cancelParam = req.getParameter("cancel"); + + logger.info("where = " + req.getParameter("where")); + + if (confirmParam == null && cancelParam == null) { + + SimpleHash mergeData = new SimpleHash(); + mergeData.put("module", "Content"); + mergeData.put("infoString", "Content: " + idParam); + mergeData.put("id", idParam); + mergeData.put("where", req.getParameter("where")); + mergeData.put("order", req.getParameter("order")); + mergeData.put("offset", req.getParameter("offset")); + deliver(req, res, mergeData, templateConfirmString); + } + else { + if (confirmParam!= null && !confirmParam.equals("")) { + try { + mainModule.deleteById(idParam); + + /** @todo the following two should be implied in + * DatabaseContent */ + DatabaseContentToTopics.getInstance().deleteByContentId(idParam); + DatabaseComment.getInstance().deleteByContentId(idParam); + DatabaseContentToMedia.getInstance().deleteByContentId(idParam); + + + //delete from lucene index, if any + String index = configuration.getString("IndexPath"); + if (IndexReader.indexExists(index)){ + IndexUtil.unindexID(idParam,index); + } + + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + list(req,res); + } + else { + // Datensatz anzeigen + _showObject(idParam, req, res); + } + } + } + + public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String idParam = req.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Invalid call: id not supplied "); + _showObject(idParam, req, res); + } + +// methods for attaching media file + public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String mediaIdParam = req.getParameter("mid"); + String idParam = req.getParameter("cid"); + if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(idParam); + entContent.attach(mediaIdParam); + } + catch(Throwable e) { + logger.error("smod content :: attach :: could not get entityContent"); + } + + _showObject(idParam, req, res); + } + + public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String cidParam = req.getParameter("cid"); + String midParam = req.getParameter("mid"); + if (cidParam == null) + throw new ServletModuleExc("smod content :: dettach :: cid missing"); + if (midParam == null) + throw new ServletModuleExc("smod content :: dettach :: mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(cidParam); + entContent.dettach(cidParam,midParam); + } + catch(Throwable e) { + logger.error("smod content :: dettach :: could not get entityContent"); + } + + _showObject(cidParam, req, res); + } + + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); + String[] topic_id = aRequest.getParameterValues("to_topic"); + String content_id = aRequest.getParameter("id"); + + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String id = mainModule.set(withValues); + DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id); + + String whereParam = aRequest.getParameter("where"); + String orderParam = aRequest.getParameter("order"); + + if (returnUrl!=null){ + redirect(aResponse, returnUrl); + } + else + _showObject(idParam, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + +/* + * HelperMethod shows the basic article editing form. + * + * if the "id" parameter is null, it means show an empty form to add a new + * article. +*/ + public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); + Map article; + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "edit"); + urlBuilder.setValue("id", id); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + if (id!=null) { + responseData.put("new", Boolean.FALSE); + article = model.makeEntityAdapter("content", mainModule.getById(id)); + } + else { + List fields = DatabaseContent.getInstance().getFields(); + responseData.put("new", Boolean.TRUE); + article = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + article.put(i.next(), null); + } + + article.put("to_topics", null); + + MirGlobal.localizer().adminInterface().initializeArticle(article); + } + responseData.put("article", article); + + responseData.put("topics", + new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"), + 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + + + + responseData.put("returnurl", requestParser.getParameter("returnurl")); + responseData.put("thisurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void returnArticleList( + HttpServletRequest aRequest, + HttpServletResponse aResponse, + String aWhereClause, + String anOrderByClause, + int anOffset, + String aSelectArticleUrl) throws ServletModuleExc { + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + EntityAdapterModel model; + int nrArticlesPerPage = 20; + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object articleList = + new CachingRewindableIterator( + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, + MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset) + ); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + + count=mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "list"); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + + urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); + urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue")); + urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); + urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); + urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype")); + urlBuilder.setValue("selectarticleurl", aSelectArticleUrl); + + responseData.put("searchfield", requestParser.getParameter("searchfield")); + responseData.put("searchvalue", requestParser.getParameter("searchvalue")); + responseData.put("searchispublished", requestParser.getParameter("searchispublished")); + responseData.put("searchorder", requestParser.getParameter("searchorder")); + responseData.put("searcharticletype", requestParser.getParameter("searcharticletype")); + responseData.put("selectarticleurl", aSelectArticleUrl); + + urlBuilder.setValue("offset", anOffset); + responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("thisurl" , urlBuilder.getQuery()); + + if (count>=anOffset+nrArticlesPerPage) { + urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage)); + responseData.put("nexturl" , urlBuilder.getQuery()); + } + + if (anOffset>0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0)); + responseData.put("prevurl" , urlBuilder.getQuery()); + } + + responseData.put("articles", articleList); + + responseData.put("from" , Integer.toString(anOffset+1)); + responseData.put("count", Integer.toString(count)); + responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count))); + responseData.put("offset" , Integer.toString(anOffset)); + responseData.put("order", anOrderByClause); + responseData.put("where" , aWhereClause); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "setparent"); + urlBuilder.setValue("childid", requestParser.getParameter("id")); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery()); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("article_id"); + + if (articleId == null) + throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!"); + + returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = aRequest.getParameter("childid"); + String parentId = aRequest.getParameter("id"); + String returnUrl = aRequest.getParameter("returnurl"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setValueForProperty("to_content", parentId); + article.setProduced(false); + article.update(); + } + catch(Throwable e) { + logger.error("ServletModuleContent.setparent: " + e.getMessage()); + throw new ServletModuleFailure(e); + } + + redirect(aResponse, returnUrl); + } + + public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("id"); + String returnUrl = requestParser.getParameter("returnurl"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setValueForProperty("to_content", ""); + article.setProduced(false); + article.update(); + } + catch(Throwable e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + logger.error("ServletModuleContent.clearparent: " + e.getMessage()); + + throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e); + } + + redirect(aResponse, returnUrl); + } + + private EntityUsers _getUser(HttpServletRequest req) + { + HttpSession session=req.getSession(false); + + return (EntityUsers)session.getAttribute("login.uid"); + } +} diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java index 862fe6e0..1698666f 100755 --- a/source/mircoders/servlet/ServletModuleFileEdit.java +++ b/source/mircoders/servlet/ServletModuleFileEdit.java @@ -1,248 +1,249 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.FilenameFilter; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.FileFunctions; -import mir.util.HTTPRequestParser; -import mir.util.URLBuilder; - -/* - * ServletModuleFileEdit - - * Allows one to do a basic edit of a file in a directory specified - * in the config file. - * - * @author $Author: zapata $ - * @version $Revision: 1.8 $ $Date: 2003/03/17 20:47:04 $ - * - */ - -public class ServletModuleFileEdit extends ServletModule -{ - private static ServletModuleFileEdit instance = new ServletModuleFileEdit(); - public static ServletModule getInstance() { return instance; } - - private File rootDirectory; - private FilenameFilter filter; - private FilenameFilter dirFilter; - private boolean recurse; - - private ServletModuleFileEdit() { - super(); - - logger = new LoggerWrapper("ServletModule.FileEdit"); - - rootDirectory = new File(configuration.getString("ServletModule.FileEdit.FileDirectory")); - recurse = configuration.getString("ServletModule.FileEdit.Recursive", "").equals("1"); - - filter = new FileFunctions.RegExpFileFilter(configuration.getString("ServletModule.FileEdit.ExtFilter")); - dirFilter = new FileFunctions.DirectoryFilter(); - - templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate"); - templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate"); - templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate"); - } - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - listSubDirectory("/", aRequest, aResponse); - } - - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String filename = requestParser.getParameter("filename"); - String subDirectory = requestParser.getParameterWithDefault("subdirectory", ""); - - if (filename == null) - throw new ServletModuleExc("No filename specified"); - - editFile(filename, subDirectory, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String directoryName = requestParser.getParameter("directory"); - String subDirectoryName = requestParser.getParameter("subdirectory"); - - if (directoryName==null | subDirectoryName==null) - throw new ServletModuleExc("No directory/subDirectory specified"); - - listSubDirectory(subDirectoryName+File.separator+directoryName, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String filename = aRequest.getParameter("filename"); - String subDirectory = aRequest.getParameter("subdirectory"); - String text = aRequest.getParameter("text"); - - try { - File f = new File(new File(rootDirectory, subDirectory), filename); - - if (validateDirectory(f)) { - StringReader in = new StringReader(text); - FileWriter out = new FileWriter(f); - - int c; - while ( (c = in.read()) != -1) - out.write(c); - in.close(); - out.close(); - - editFile(filename, subDirectory, aRequest, aResponse); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void listSubDirectory(String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - File dir = new File(rootDirectory, aSubDirectory); - - if (!validateDirectory(dir) || !dir.isDirectory()) { - dir = rootDirectory; - aSubDirectory = ""; - } - - responseData.put("filelist", Arrays.asList(dir.list(filter))); - - if (recurse) { - List dirs = new Vector(); - if (!dir.getCanonicalPath().equals(rootDirectory.getCanonicalPath())) - responseData.put("updir", new File(aSubDirectory).getParent()); - - dirs.addAll(Arrays.asList(dir.list(dirFilter))); - - responseData.put("dirlist", dirs); - } - else { - responseData.put("dirlist", null); - responseData.put("updir", null); - } - - responseData.put("subdirectory", aSubDirectory); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void editFile(String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - File f = new File(new File(rootDirectory, aSubDirectory), aFileName); - - if (!validateDirectory(f) || f.isDirectory() || !validateFile(f)) { - listSubDirectory("", aRequest, aResponse); - } - else { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "FileEdit"); - urlBuilder.setValue("do", "enter"); - urlBuilder.setValue("directory", ""); - urlBuilder.setValue("subdirectory", aSubDirectory); - - FileReader in = new FileReader(f); - StringWriter out = new StringWriter(); - - int c; - while ( (c = in.read()) != -1) - out.write(c); - in.close(); - out.close(); - - responseData.put("text", out.toString()); - responseData.put("filename", aFileName); - responseData.put("subdirectory", aSubDirectory); - responseData.put("returnurl", urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - protected boolean validateDirectory(File aFile) { - try { - return (aFile.getCanonicalPath().startsWith(rootDirectory.getCanonicalPath())); - } - catch (Throwable t) { - return false; - } - } - - protected boolean validateFile(File aFile) { - try { - return filter.accept(aFile.getParentFile(), aFile.getName()); - } - catch (Throwable t) { - return false; - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Vector; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.FileFunctions; +import mir.util.HTTPRequestParser; +import mir.util.URLBuilder; + +/* + * ServletModuleFileEdit - + * Allows one to do a basic edit of a file in a directory specified + * in the config file. + * + * @author $Author: zapata $ + * @version $Revision: 1.9 $ $Date: 2003/04/09 02:06:09 $ + * + */ + +public class ServletModuleFileEdit extends ServletModule +{ + private static ServletModuleFileEdit instance = new ServletModuleFileEdit(); + public static ServletModule getInstance() { return instance; } + + private File rootDirectory; + private FilenameFilter filter; + private FilenameFilter dirFilter; + private boolean recurse; + + private ServletModuleFileEdit() { + super(); + + logger = new LoggerWrapper("ServletModule.FileEdit"); + + rootDirectory = new File(configuration.getString("ServletModule.FileEdit.FileDirectory")); + recurse = configuration.getString("ServletModule.FileEdit.Recursive", "").equals("1"); + + filter = new FileFunctions.RegExpFileFilter(configuration.getString("ServletModule.FileEdit.ExtFilter")); + dirFilter = new FileFunctions.DirectoryFilter(); + + templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate"); + templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate"); + templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate"); + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + listSubDirectory("/", aRequest, aResponse); + } + + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String filename = requestParser.getParameter("filename"); + String subDirectory = requestParser.getParameterWithDefault("subdirectory", ""); + + if (filename == null) + throw new ServletModuleExc("No filename specified"); + + editFile(filename, subDirectory, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String directoryName = requestParser.getParameter("directory"); + String subDirectoryName = requestParser.getParameter("subdirectory"); + + if (directoryName==null | subDirectoryName==null) + throw new ServletModuleExc("No directory/subDirectory specified"); + + listSubDirectory(subDirectoryName+File.separator+directoryName, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String filename = aRequest.getParameter("filename"); + String subDirectory = aRequest.getParameter("subdirectory"); + String text = aRequest.getParameter("text"); + + try { + File f = new File(new File(rootDirectory, subDirectory), filename); + + if (validateDirectory(f)) { + StringReader in = new StringReader(text); + FileWriter out = new FileWriter(f); + + int c; + while ( (c = in.read()) != -1) + out.write(c); + in.close(); + out.close(); + + editFile(filename, subDirectory, aRequest, aResponse); + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void listSubDirectory(String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + File dir = new File(rootDirectory, aSubDirectory); + + if (!validateDirectory(dir) || !dir.isDirectory()) { + dir = rootDirectory; + aSubDirectory = ""; + } + + responseData.put("filelist", Arrays.asList(dir.list(filter))); + + if (recurse) { + List dirs = new Vector(); + if (!dir.getCanonicalPath().equals(rootDirectory.getCanonicalPath())) + responseData.put("updir", new File(aSubDirectory).getParent()); + + dirs.addAll(Arrays.asList(dir.list(dirFilter))); + + responseData.put("dirlist", dirs); + } + else { + responseData.put("dirlist", null); + responseData.put("updir", null); + } + + responseData.put("subdirectory", aSubDirectory); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void editFile(String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + File f = new File(new File(rootDirectory, aSubDirectory), aFileName); + + if (!validateDirectory(f) || f.isDirectory() || !validateFile(f)) { + listSubDirectory("", aRequest, aResponse); + } + else { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "FileEdit"); + urlBuilder.setValue("do", "enter"); + urlBuilder.setValue("directory", ""); + urlBuilder.setValue("subdirectory", aSubDirectory); + + FileReader in = new FileReader(f); + StringWriter out = new StringWriter(); + + int c; + while ( (c = in.read()) != -1) + out.write(c); + in.close(); + out.close(); + + responseData.put("text", out.toString()); + responseData.put("filename", aFileName); + responseData.put("subdirectory", aSubDirectory); + responseData.put("returnurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString); + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + protected boolean validateDirectory(File aFile) { + try { + return (aFile.getCanonicalPath().startsWith(rootDirectory.getCanonicalPath())); + } + catch (Throwable t) { + return false; + } + } + + protected boolean validateFile(File aFile) { + try { + return filter.accept(aFile.getParentFile(), aFile.getName()); + } + catch (Throwable t) { + return false; + } + } +} diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java index b7a63584..6da2e3cc 100755 --- a/source/mircoders/servlet/ServletModuleHidden.java +++ b/source/mircoders/servlet/ServletModuleHidden.java @@ -115,7 +115,7 @@ public class ServletModuleHidden extends ServletModule } } // raus damit - HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req)); + HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req)); } catch (Throwable e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleLinksImcs.java b/source/mircoders/servlet/ServletModuleLinksImcs.java index e854dcd5..4cca2063 100755 --- a/source/mircoders/servlet/ServletModuleLinksImcs.java +++ b/source/mircoders/servlet/ServletModuleLinksImcs.java @@ -100,7 +100,7 @@ public class ServletModuleLinksImcs extends ServletModule { modelRoot.put("languagelist", theLanguageList); if (theParentList == null || theParentList.getCount() == 0 || theParentList.getCount() > 1) { - HTMLTemplateProcessor.process(res, templateObjektString, modelRoot, res.getWriter(), getLocale(req)); + HTMLTemplateProcessor.process(res, templateObjektString, modelRoot, res.getWriter(), getLocale(req), getFallbackLocale(req)); } else { deliver(req, res, modelRoot, templateObjektString); @@ -134,7 +134,6 @@ public class ServletModuleLinksImcs extends ServletModule { modelRoot.put("to_parent_id", parent); String language = req.getParameter("to_language"); modelRoot.put("to_language", language); - modelRoot.put("language", getLanguage(req)); String whereClause = ""; boolean isFirst = true; @@ -184,7 +183,7 @@ public class ServletModuleLinksImcs extends ServletModule { if (theImcsList.hasPrevBatch()) modelRoot.put("prev", (new Integer(theImcsList.getPrevBatch())).toString()); - HTMLTemplateProcessor.process(res, templateListString, modelRoot, res.getWriter(), getLocale(req)); + HTMLTemplateProcessor.process(res, templateListString, modelRoot, res.getWriter(), getLocale(req), getFallbackLocale(req)); } catch (Throwable e) { diff --git a/source/mircoders/servlet/ServletModuleLocalizer.java b/source/mircoders/servlet/ServletModuleLocalizer.java index 363af6cf..aa973b34 100755 --- a/source/mircoders/servlet/ServletModuleLocalizer.java +++ b/source/mircoders/servlet/ServletModuleLocalizer.java @@ -1,198 +1,198 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.localizer.MirAdminInterfaceLocalizer; -import mircoders.module.ModuleComment; -import mircoders.module.ModuleContent; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; - -public class ServletModuleLocalizer extends ServletModule { - private static ServletModuleLocalizer instance = new ServletModuleLocalizer(); - public static ServletModule getInstance() { return instance; } - - private ModuleContent contentModule; - private ModuleComment commentModule; - - private ServletModuleLocalizer() { - try { - contentModule = new ModuleContent(DatabaseContent.getInstance()); - commentModule = new ModuleComment(DatabaseComment.getInstance()); - - logger = new LoggerWrapper("ServletModule.Localizer"); - } - catch (Exception e) { - logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage()); - } - } - - private EntityAdapter getActiveUser(HttpServletRequest aRequest) throws ServletModuleExc { - try { - HttpSession session = aRequest.getSession(false); - return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter - ("user", (EntityUsers) session.getAttribute("login.uid")); - } - catch (Throwable e) { - throw new ServletModuleFailure("ServletModuleLocalizer.getActiveUser: " + e.getMessage(), e); - } - } - - public void performCommentOperation(EntityAdapter aUser, String anId, String anOperation) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; - EntityAdapter comment; - EntityComment entity; - - try { - entity = (EntityComment) commentModule.getById(anId); - - if (entity != null) { - comment = MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", entity); - operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(anOperation); - operation.perform(aUser, comment); - logger.info("Operation " + anOperation + " successfully performed on comment " + anId); - } - logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null"); - } - catch (Throwable e) { - logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage()); - } - } - - public void commentoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - String commentIdString = aRequest.getParameter("id"); - String operationString = aRequest.getParameter("operation"); - String returnUrlString = aRequest.getParameter("returnurl"); - - performCommentOperation(getActiveUser(aRequest), commentIdString, operationString); - - redirect(aResponse, returnUrlString); - } - - public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - String returnUrlString = aRequest.getParameter("returnurl"); - - String[] operations = aRequest.getParameterValues("operation"); - - for (int i=0; i0) { - List parts = StringRoutines.splitString(operations[i], ";"); - - if (parts.size() != 2) { - logger.error("commentoperationbatch: operation string invalid: " + - operations[i]); - } - else { - String commentIdString = (String) parts.get(0); - String operationString = (String) parts.get(1); - - performCommentOperation(getActiveUser(aRequest), commentIdString, operationString); - } - } - } - - redirect(aResponse, returnUrlString); - } - - public void performArticleOperation(EntityAdapter aUser, String anId, String anOperation) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; - EntityAdapter article; - EntityContent entity; - - try { - entity = (EntityContent) contentModule.getById(anId); - - if (entity != null) { - article = MirGlobal.localizer().dataModel().adapterModel(). - makeEntityAdapter("content", entity); - operation = MirGlobal.localizer().adminInterface(). - simpleArticleOperationForName(anOperation); - operation.perform(aUser, article); - logger.info("Operation " + anOperation + " successfully performed on article " + anId); - } - logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null"); - } - catch (Throwable e) { - logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage()); - } - } - - public void articleoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - String articleIdString = aRequest.getParameter("articleid"); - String operationString = aRequest.getParameter("operation"); - String returnUrlString = aRequest.getParameter("returnurl"); - - performArticleOperation(getActiveUser(aRequest), articleIdString, operationString); - redirect(aResponse, returnUrlString); - } - - public void articleoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - String returnUrlString = aRequest.getParameter("returnurl"); - - String[] operations = aRequest.getParameterValues("operation"); - - for (int i=0; i0) { - List parts = StringRoutines.splitString(operations[i], ";"); - - if (parts.size() != 2) { - logger.error("articleoperationbatch: operation string invalid: " + operations[i]); - } - else { - String articleIdString = (String) parts.get(0); - String operationString = (String) parts.get(1); - - performArticleOperation(getActiveUser(aRequest), articleIdString, operationString); - } - } - } - - redirect(aResponse, returnUrlString); - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.entity.adapter.EntityAdapter; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.localizer.MirAdminInterfaceLocalizer; +import mircoders.module.ModuleComment; +import mircoders.module.ModuleContent; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseContent; + +public class ServletModuleLocalizer extends ServletModule { + private static ServletModuleLocalizer instance = new ServletModuleLocalizer(); + public static ServletModule getInstance() { return instance; } + + private ModuleContent contentModule; + private ModuleComment commentModule; + + private ServletModuleLocalizer() { + try { + contentModule = new ModuleContent(DatabaseContent.getInstance()); + commentModule = new ModuleComment(DatabaseComment.getInstance()); + + logger = new LoggerWrapper("ServletModule.Localizer"); + } + catch (Exception e) { + logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage()); + } + } + + private EntityAdapter getActiveUser(HttpServletRequest aRequest) throws ServletModuleExc { + try { + HttpSession session = aRequest.getSession(false); + return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter + ("user", (EntityUsers) session.getAttribute("login.uid")); + } + catch (Throwable e) { + throw new ServletModuleFailure("ServletModuleLocalizer.getActiveUser: " + e.getMessage(), e); + } + } + + public void performCommentOperation(EntityAdapter aUser, String anId, String anOperation) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; + EntityAdapter comment; + EntityComment entity; + + try { + entity = (EntityComment) commentModule.getById(anId); + + if (entity != null) { + comment = MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", entity); + operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(anOperation); + operation.perform(aUser, comment); + logger.info("Operation " + anOperation + " successfully performed on comment " + anId); + } + logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null"); + } + catch (Throwable e) { + logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage()); + } + } + + public void commentoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String commentIdString = aRequest.getParameter("id"); + String operationString = aRequest.getParameter("operation"); + String returnUrlString = aRequest.getParameter("returnurl"); + + performCommentOperation(getActiveUser(aRequest), commentIdString, operationString); + + redirect(aResponse, returnUrlString); + } + + public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String returnUrlString = aRequest.getParameter("returnurl"); + + String[] operations = aRequest.getParameterValues("operation"); + + for (int i=0; i0) { + List parts = StringRoutines.splitString(operations[i], ";"); + + if (parts.size() != 2) { + logger.error("commentoperationbatch: operation string invalid: " + + operations[i]); + } + else { + String commentIdString = (String) parts.get(0); + String operationString = (String) parts.get(1); + + performCommentOperation(getActiveUser(aRequest), commentIdString, operationString); + } + } + } + + redirect(aResponse, returnUrlString); + } + + public void performArticleOperation(EntityAdapter aUser, String anId, String anOperation) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; + EntityAdapter article; + EntityContent entity; + + try { + entity = (EntityContent) contentModule.getById(anId); + + if (entity != null) { + article = MirGlobal.localizer().dataModel().adapterModel(). + makeEntityAdapter("content", entity); + operation = MirGlobal.localizer().adminInterface(). + simpleArticleOperationForName(anOperation); + operation.perform(aUser, article); + logger.info("Operation " + anOperation + " successfully performed on article " + anId); + } + logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null"); + } + catch (Throwable e) { + logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage()); + } + } + + public void articleoperation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String articleIdString = aRequest.getParameter("articleid"); + String operationString = aRequest.getParameter("operation"); + String returnUrlString = aRequest.getParameter("returnurl"); + + performArticleOperation(getActiveUser(aRequest), articleIdString, operationString); + redirect(aResponse, returnUrlString); + } + + public void articleoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String returnUrlString = aRequest.getParameter("returnurl"); + + String[] operations = aRequest.getParameterValues("operation"); + + for (int i=0; i0) { + List parts = StringRoutines.splitString(operations[i], ";"); + + if (parts.size() != 2) { + logger.error("articleoperationbatch: operation string invalid: " + operations[i]); + } + else { + String articleIdString = (String) parts.get(0); + String operationString = (String) parts.get(1); + + performArticleOperation(getActiveUser(aRequest), articleIdString, operationString); + } + } + } + + redirect(aResponse, returnUrlString); + } + } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleMessage.java b/source/mircoders/servlet/ServletModuleMessage.java index cedb77a5..8d10cf47 100755 --- a/source/mircoders/servlet/ServletModuleMessage.java +++ b/source/mircoders/servlet/ServletModuleMessage.java @@ -1,117 +1,116 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.net.URLEncoder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mircoders.module.ModuleMessage; -import mircoders.storage.DatabaseMessages; -import freemarker.template.SimpleHash; - -/** - * Title: ServletModuleMessage - * Description: - * Copyright: Copyright (c) 2001-2002 - * Company: mir-coders - * @author - * @version 1.0 - */ - - -public class ServletModuleMessage extends ServletModule -{ - - // Singelton / Kontruktor - - private static ServletModuleMessage instance = new ServletModuleMessage(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleMessage() { - super(); - logger = new LoggerWrapper("ServletModule.Messages"); - - templateListString = configuration.getString("ServletModule.Messages.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Messages.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Messages.ConfirmTemplate"); - - try { - mainModule = new ModuleMessage(DatabaseMessages.getInstance()); - } - catch (StorageObjectFailure e) { - logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage()); - - throw new ServletModuleFailure(e); - } - } - - public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { -// fetch and deliver - try { - SimpleHash mergeData = new SimpleHash(); - String offset = req.getParameter("offset"); - if (offset==null || offset.equals("")) offset="0"; - mergeData.put("offset",offset); - EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue()); - mergeData.put("contentlist",theList); - if(theList.getOrder()!=null) { - mergeData.put("order", theList.getOrder()); - mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder())); - } - mergeData.put("count", (new Integer(theList.getCount())).toString()); - mergeData.put("from", (new Integer(theList.getFrom())).toString()); - mergeData.put("to", (new Integer(theList.getTo())).toString()); - if (theList.hasNextBatch()) - mergeData.put("next", (new Integer(theList.getNextBatch())).toString()); - if (theList.hasPrevBatch()) - mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); - - HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req)); - - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.net.URLEncoder; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import freemarker.template.SimpleHash; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.storage.StorageObjectFailure; +import mircoders.module.ModuleMessage; +import mircoders.storage.DatabaseMessages; + +/** + * Title: ServletModuleMessage + * Description: + * Copyright: Copyright (c) 2001-2002 + * Company: mir-coders + * @author + * @version 1.0 + */ + + +public class ServletModuleMessage extends ServletModule +{ + + // Singelton / Kontruktor + + private static ServletModuleMessage instance = new ServletModuleMessage(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleMessage() { + super(); + logger = new LoggerWrapper("ServletModule.Messages"); + + templateListString = configuration.getString("ServletModule.Messages.ListTemplate"); + templateObjektString = configuration.getString("ServletModule.Messages.ObjektTemplate"); + templateConfirmString = configuration.getString("ServletModule.Messages.ConfirmTemplate"); + + try { + mainModule = new ModuleMessage(DatabaseMessages.getInstance()); + } + catch (StorageObjectFailure e) { + logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage()); + + throw new ServletModuleFailure(e); + } + } + + public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { +// fetch and deliver + try { + SimpleHash mergeData = new SimpleHash(); + String offset = req.getParameter("offset"); + if (offset==null || offset.equals("")) offset="0"; + mergeData.put("offset",offset); + EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue()); + mergeData.put("contentlist",theList); + if(theList.getOrder()!=null) { + mergeData.put("order", theList.getOrder()); + mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder())); + } + mergeData.put("count", (new Integer(theList.getCount())).toString()); + mergeData.put("from", (new Integer(theList.getFrom())).toString()); + mergeData.put("to", (new Integer(theList.getTo())).toString()); + if (theList.hasNextBatch()) + mergeData.put("next", (new Integer(theList.getNextBatch())).toString()); + if (theList.hasPrevBatch()) + mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); + + HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req)); + + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + +} diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index d15578a5..d2e48110 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -1,1092 +1,1093 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.Vector; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.net.smtp.SMTPClient; -import org.apache.commons.net.smtp.SMTPReply; -import org.apache.fop.apps.Driver; -import org.apache.fop.apps.XSLTInputHandler; -import org.apache.log.Hierarchy; -import org.apache.log.Priority; -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.document.Document; -import org.apache.lucene.queryParser.QueryParser; -import org.apache.lucene.search.Hits; -import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.search.Query; -import org.apache.lucene.search.Searcher; -import org.apache.struts.util.MessageResources; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.generator.Generator; -import mir.log.LoggerWrapper; -import mir.misc.FileHandler; -import mir.misc.StringUtil; -import mir.misc.WebdbMultipartRequest; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.servlet.ServletModuleUserExc; -import mir.storage.StorageObjectFailure; -import mir.util.ExceptionFunctions; -import mir.util.HTTPRequestParser; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.global.MirGlobal; -import mircoders.media.MediaRequest; -import mircoders.media.UnsupportedMediaFormatExc; -import mircoders.module.ModuleComment; -import mircoders.module.ModuleContent; -import mircoders.module.ModuleImages; -import mircoders.module.ModuleTopics; -import mircoders.search.AudioSearchTerm; -import mircoders.search.ContentSearchTerm; -import mircoders.search.ImagesSearchTerm; -import mircoders.search.KeywordSearchTerm; -import mircoders.search.TextSearchTerm; -import mircoders.search.TopicSearchTerm; -import mircoders.search.UnIndexedSearchTerm; -import mircoders.search.VideoSearchTerm; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToMedia; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseImages; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseTopics; - -/* - * ServletModuleOpenIndy - - * is the open-access-servlet, which is responsible for - * adding comments to articles & - * open-postings to the newswire - * - * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.70 2003/04/02 22:15:03 zapata Exp $ - * - */ - -public class ServletModuleOpenIndy extends ServletModule -{ - - private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate; - private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate; - private String searchResultsTemplate; - private String prepareMailTemplate,sentMailTemplate; - private ModuleContent contentModule; - private ModuleComment commentModule; - private ModuleImages imageModule; - private ModuleTopics topicsModule; - private String directOp ="yes"; - // Singelton / Kontruktor - private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleOpenIndy() { - super(); - try { - logger = new LoggerWrapper("ServletModule.OpenIndy"); - - commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate"); - commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate"); - commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate"); - postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate"); - postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate"); - postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate"); - searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate"); - prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate"); - sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate"); - directOp = configuration.getString("DirectOpenposting").toLowerCase(); - mainModule = new ModuleComment(DatabaseComment.getInstance()); - contentModule = new ModuleContent(DatabaseContent.getInstance()); - topicsModule = new ModuleTopics(DatabaseTopics.getInstance()); - imageModule = new ModuleImages(DatabaseImages.getInstance()); - defaultAction="addposting"; - } - catch (StorageObjectFailure e) { - logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); - } - } - - /** - * Method to return an "apology" when open postings are disabled - * - * @param aRequest - * @param aResponse - * @throws ServletModuleExc - * @throws ServletModuleUserExc - * @throws ServletModuleFailure - */ - public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - deliver(aRequest, aResponse, (Map) null, null, - configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate")); - } - - - /** - * Method for making a comment - */ - - public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - if (MirGlobal.abuse().getOpenPostingDisabled()) { - openPostingDisabled(req, res); - - return; - } - - String aid = req.getParameter("aid"); // the article id the comment will belong to -/* - String language = req.getParameter("language"); - */ - - if (aid!=null && !aid.equals("")) { - try { - Map mergeData = new HashMap(); - - // onetimepasswd - if (MirGlobal.abuse().getOpenPostingPassword()) { - String passwd = this.createOneTimePasswd(); - HttpSession session = req.getSession(false); - session.setAttribute("passwd", passwd); - mergeData.put("passwd", passwd); - } - else { - mergeData.put("passwd", (String) null); - } -/* - if (language != null) { - HttpSession session = req.getSession(false); - session.setAttribute("Locale", new Locale(language, "")); - session.setAttribute("language", language); - } -*/ - mergeData.put("aid", aid); - - Map extraInfo = new HashMap(); - extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); - - deliver(req, res, mergeData, extraInfo, commentFormTemplate); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t); - } - } - else throw new ServletModuleExc("aid not set!"); - } - - /** - * Method for inserting a comment into the Database and delivering - * the commentDone Page - */ - - public void inscomment(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - if (MirGlobal.abuse().getOpenPostingDisabled()) { - openPostingDisabled(req, res); - - return; - } - - String aid = req.getParameter("to_media"); // the article id the comment will belong to - if (aid!=null && !aid.equals("")) - { - // ok, collecting data from form - try { - Map withValues = getIntersectingValues(req, DatabaseComment.getInstance()); - - //no html in comments(for now) - for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ - String k=(String)i.next(); - String v=(String)withValues.get(k); - - withValues.put(k,StringUtil.removeHTMLTags(v)); - } - withValues.put("is_published","1"); - withValues.put("to_comment_status","1"); - - //checking the onetimepasswd - HttpSession session = req.getSession(false); - String sessionPasswd = (String) session.getAttribute("passwd"); - if ( sessionPasswd != null){ - String passwd = req.getParameter("passwd"); - if ( passwd == null || passwd.length()==0) { - throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {}); - } - if (!sessionPasswd.equals(passwd)) { - throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {}); - } - session.invalidate(); - } - - String id = mainModule.add(withValues); - - if(id==null){ - deliver(req, res, (Map) null, null, commentFormDupeTemplate); - } - else { - MirGlobal.abuse().logComment(req.getRemoteAddr(), id, new Date(), (String) req.getHeader("User-Agent")); - - DatabaseContent.getInstance().setUnproduced("id="+aid); - - try { - EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id); - MirGlobal.abuse().checkComment(comment, req, res); - MirGlobal.localizer().openPostings().afterCommentPosting(comment); - } - catch (Throwable t) { - throw new ServletModuleExc(t.getMessage()); - } - } - - // redirecting to url - // should implement back to article - Map mergeData = new HashMap(); - deliver(req, res, mergeData, null, commentFormDoneTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - else throw new ServletModuleExc("aid not set!"); - - } - - /** - * Method for delivering the form-Page for open posting - */ - - public void addposting(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - try { - if (MirGlobal.abuse().getOpenPostingDisabled()) { - openPostingDisabled(req, res); - - return; - } - - Map mergeData = new HashMap(); - - // onetimepasswd - if (MirGlobal.abuse().getOpenPostingPassword()) { - String passwd = this.createOneTimePasswd(); - HttpSession session = req.getSession(false); - session.setAttribute("passwd", passwd); - mergeData.put("passwd", passwd); - } - else { - mergeData.put("passwd", (String)null); - } - - String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems"); - String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems"); - String numOfMedia = req.getParameter("medianum"); - - if (numOfMedia == null || numOfMedia.equals("")) { - numOfMedia = defaultMedia; - } - else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) { - numOfMedia = maxMedia; - } - - int mediaNum = Integer.parseInt(numOfMedia); - List mediaFields = new Vector(); - for (int i = 0; i < mediaNum; i++) { - Integer mNum = new Integer(i + 1); - mediaFields.add(mNum.toString()); - } - mergeData.put("medianum", numOfMedia); - mergeData.put("mediafields", mediaFields); - mergeData.put("to_topic", null); - - Map extraInfo = new HashMap(); - extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); - extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList()); - - extraInfo.put("topics", topicsModule.getTopicsList()); - deliver(req, res, mergeData, extraInfo, postingFormTemplate); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - /** - * Method for inserting an open posting into the Database and delivering - * the postingDone Page - */ - - public void insposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - if (MirGlobal.abuse().getOpenPostingDisabled()) { - openPostingDisabled(req, res); - - return; - } - - Map mergeData = new HashMap(); - boolean setMedia=false; - boolean setTopic = false; - - try { - - WebdbMultipartRequest mp = null; - EntityList mediaList = null; - try { - // new MediaRequest, "1" is the id for the openPosting user - MediaRequest mediaReq = new MediaRequest("1", true); - mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq); - mediaList = mediaReq.getEntityList(); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - - Map withValues = mp.getParameters(); - - //checking the onetimepasswd - HttpSession session = req.getSession(false); - String sessionPasswd = (String) session.getAttribute("passwd"); - if (sessionPasswd != null){ - String passwd = (String) withValues.get("passwd"); - - logger.debug("session password = " + sessionPasswd + ", form password = " + passwd); - - if ( passwd == null || passwd.length()==0) { - throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {}); - } - if (!sessionPasswd.equals(passwd)) { - throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {}); - } - session.invalidate(); - } - - if ((((String)withValues.get("title")).length() == 0) || - (((String)withValues.get("description")).length() == 0) || - (((String)withValues.get("content_data")).length() == 0)) - throw new ServletModuleUserExc("posting.error.missingfield", new String[] {}); - - // call the routines that escape html - - for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ - String k=(String)i.next(); - String v=(String)withValues.get(k); - - if (k.equals("content_data")){ - //this doesn't quite work yet, so for now, all html goes - //withValues.put(k,StringUtil.approveHTMLTags(v)); - withValues.put(k,StringUtil.deleteForbiddenTags(v)); - } - else if (k.equals("description")) { - String tmp = StringUtil.deleteForbiddenTags(v); - withValues.put(k,StringUtil.deleteHTMLTableTags(tmp)); - } - else { - withValues.put(k,StringUtil.removeHTMLTags(v)); - } - - } - - withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); - withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date"))); - withValues.put("is_produced", "0"); - withValues.put("is_published","1"); - if (directOp.equals("yes")) - withValues.put("to_article_type","1"); - - withValues.put("to_publisher","1"); - - // inserting content into database - String cid = contentModule.add(withValues); - logger.debug("id: "+cid); - //insert was not successfull - if(cid==null){ - - //How do we know that it was not succesful cause of a - //dupe, what if it failed cause of "No space left on device"? - //Or is there something I am missing? Wouldn't it be better - //to have an explicit dupe check and then insert? I have no - //idea what I am talking about. this comment is in case - //I forget to explicitely ask. -mh - deliver(req, res, mergeData, null, postingFormDupeTemplate); - return; - } - - MirGlobal.abuse().logArticle(req.getRemoteAddr(), cid, new Date(), (String) req.getHeader("User-Agent")); - - String[] to_topicsArr = mp.getParameterValues("to_topic"); - - if (to_topicsArr != null && to_topicsArr.length > 0) { - try{ - DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr); - setTopic = true; - } - catch (Throwable e) { - logger.error("setting content_x_topic failed"); - contentModule.deleteById(cid); - throw new ServletModuleFailure("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString(), e); - } //end try - } //end if - - //if we're here all is ok... associate the media to the article - for(int i=0;i= totalHits) - newPosition=totalHits-1; - session.setAttribute("positionInResults",new Integer(newPosition)); - } - else { - if (searchForwardValue != null){ - int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue(); - int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment; - if (newPosition<0) - newPosition=0; - if (newPosition >= totalHits) - newPosition=totalHits-1; - - session.setAttribute("positionInResults",new Integer(newPosition)); - } - else { - String indexPath=configuration.getString("IndexPath"); - - - String creatorFragment = creatorTerm.makeTerm(req); - if (creatorFragment != null){ - queryString = queryString + " +" + creatorFragment; - } - - // search title, description, and content for something - // the contentTerm uses param "search_boolean" to combine its terms - String contentFragment = contentTerm.makeTerm(req); - if (contentFragment != null){ - logger.debug("contentFragment: " + contentFragment); - queryString = queryString + " +" + contentFragment; - } - - String topicFragment = topicTerm.makeTerm(req); - if (topicFragment != null){ - queryString = queryString + " +" + topicFragment; - } - - String imagesFragment = imagesTerm.makeTerm(req); - if (imagesFragment != null){ - queryString = queryString + " +" + imagesFragment; - } - - String audioFragment = audioTerm.makeTerm(req); - if (audioFragment != null){ - queryString = queryString + " +" + audioFragment; - } - - String videoFragment = videoTerm.makeTerm(req); - if (videoFragment != null){ - queryString = queryString + " +" + videoFragment; - } - - if (queryString == null || queryString == ""){ - queryString = ""; - } - else{ - try{ - Searcher searcher = null; - try { - searcher = new IndexSearcher(indexPath); - } - catch(IOException e) { - logger.debug("Can't open indexPath: " + indexPath); - throw new ServletModuleExc("Problem with Search Index! : "+ e.toString()); - } - - Query query = null; - try { - query = QueryParser.parse(queryString, "content", new StandardAnalyzer()); - } - catch(Exception e) { - searcher.close(); - logger.debug("Query don't parse: " + queryString); - throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')"); - } - - Hits hits = null; - try { - hits = searcher.search(query); - } - catch(IOException e) { - searcher.close(); - logger.debug("Can't get hits: " + e.toString()); - throw new ServletModuleExc("Problem getting hits!"); - } - - int start = 0; - int end = hits.length(); - - String sortBy=req.getParameter("search_sort"); - if (sortBy == null || sortBy.equals("")){ - throw new ServletModuleExc("Please let me sort by something!(missing search_sort)"); - } - - // here is where the documents will go for storage across sessions - ArrayList theDocumentsSorted = new ArrayList(); - - if (sortBy.equals("score")){ - for(int i = start; i < end; i++) { - theDocumentsSorted.add(hits.doc(i)); - } - } - else{ - // then we'll sort by date! - Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be - for(int i = start; i < end; i++) { - String creationDate=(hits.doc(i)).get("creationDate"); - // do a little dance in case two contents created at the same second! - if (dateToPosition.containsKey(creationDate)){ - ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i)); - } - else{ - ArrayList thePositions = new ArrayList(); - thePositions.add(new Integer(i)); - dateToPosition.put(creationDate,thePositions); - } - } - Set keys = dateToPosition.keySet(); - ArrayList keyList= new ArrayList(keys); - Collections.sort(keyList); - if (sortBy.equals("date_desc")){ - Collections.reverse(keyList); - } - else{ - if (!sortBy.equals("date_asc")){ - throw new ServletModuleExc("don't know how to sort by: "+ sortBy); - } - } - ListIterator keyTraverser = keyList.listIterator(); - while (keyTraverser.hasNext()){ - ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next())); - ListIterator positionsTraverser=positions.listIterator(); - while (positionsTraverser.hasNext()){ - theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue())); - } - } - } - - try{ - searcher.close(); - } - catch (IOException e){ - logger.debug("Can't close searcher: " + e.toString()); - throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e); - } - - - session.removeAttribute("numberOfHits"); - session.removeAttribute("theDocumentsSorted"); - session.removeAttribute("positionInResults"); - - session.setAttribute("numberOfHits",new Integer(end)); - session.setAttribute("theDocumentsSorted",theDocumentsSorted); - session.setAttribute("positionInResults",new Integer(0)); - - } - catch (IOException e){ - logger.debug("Can't close searcher: " + e.toString()); - throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e); - } - } - } - } - - try { - ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted"); - if (theDocs != null){ - - mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString()); - List theHits = new Vector(); - int pIR=((Integer)session.getAttribute("positionInResults")).intValue(); - int terminus; - int numHits=((Integer)session.getAttribute("numberOfHits")).intValue(); - - if (!(pIR+increment>=numHits)){ - mergeData.put("hasNext","y"); - } - else { - mergeData.put("hasNext", null); - } - if (pIR>0){ - mergeData.put("hasPrevious","y"); - } - else { - mergeData.put("hasPrevious", null); - } - - if ((pIR+increment)>numHits){ - terminus=numHits; - } - else { - terminus=pIR+increment; - } - for(int i = pIR; i < terminus; i++) { - Map h = new HashMap(); - Document theHit = (Document)theDocs.get(i); - whereTerm.returnMeta(h,theHit); - creatorTerm.returnMeta(h,theHit); - titleTerm.returnMeta(h,theHit); - descriptionTerm.returnMeta(h,theHit); - dateTerm.returnMeta(h,theHit); - imagesTerm.returnMeta(h,theHit); - audioTerm.returnMeta(h,theHit); - videoTerm.returnMeta(h,theHit); - theHits.add(h); - } - mergeData.put("hits",theHits); - } - } - catch (Throwable e) { - logger.error("Can't iterate over hits: " + e.toString()); - - throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e); - } - - mergeData.put("queryString",queryString); - - deliver(req, res, mergeData, null, searchResultsTemplate); - } - catch (NullPointerException n){ - throw new ServletModuleFailure("Null Pointer: "+n.toString(), n); - } - } - - /* - * Method for dynamically generating a pdf from a fo file - */ - public void getpdf(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - String ID_REQUEST_PARAM = "id"; - String language = req.getParameter("language"); - String generateFO=configuration.getString("GenerateFO"); - String generatePDF=configuration.getString("GeneratePDF"); - - - //don't do anything if we are not making FO files, or if we are - //pregenerating PDF's - if (generateFO.equals("yes") && generatePDF.equals("no")){ - //fop complains unless you do the logging this way - org.apache.log.Logger log = null; - Hierarchy hierarchy = Hierarchy.getDefaultHierarchy(); - log = hierarchy.getLoggerFor("fop"); - log.setPriority(Priority.WARN); - - String producerStorageRoot=configuration.getString("Producer.StorageRoot"); - String producerDocRoot=configuration.getString("Producer.DocRoot"); - // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir"); - String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet"); - try { - String idParam = req.getParameter(ID_REQUEST_PARAM); - if (idParam != null) { - EntityContent contentEnt = - (EntityContent)contentModule.getById(idParam); - String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date")); - String foFile; - - if (language == null){ - foFile = producerStorageRoot + producerDocRoot + "/" - + publishPath + idParam + ".fo"; - } - else{ - foFile = producerStorageRoot + producerDocRoot + "/" - + language + publishPath + idParam + ".fo"; - } - logger.debug("USING FILES" + foFile + " and " + xslSheet); - XSLTInputHandler input = new XSLTInputHandler(new File(foFile), - new File(xslSheet)); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - res.setContentType("application/pdf"); - - Driver driver = new Driver(); - driver.setLogger(log); - driver.setRenderer(Driver.RENDER_PDF); - driver.setOutputStream(out); - driver.render(input.getParser(), input.getInputSource()); - - byte[] content = out.toByteArray(); - res.setContentLength(content.length); - res.getOutputStream().write(content); - res.getOutputStream().flush(); - } - else { - throw new ServletModuleExc("Missing id."); - } - } - catch (Throwable t) { - logger.error(t.toString()); - - throw new ServletModuleFailure(t); - } - } - else { - throw new ServletModuleExc("Can't generate a PDF because the config tells me not to."); - } - } - - protected String createOneTimePasswd(){ - Random r = new Random(); - int random = r.nextInt(); - long l = System.currentTimeMillis(); - l = (l*l*l*l)/random; - if(l<0) l = l * -1; - String returnString = ""+l; - - return returnString.substring(5); - } - - - /* this is an overwritten method of ServletModule in order - to use different bundles for open and admin */ -/* public void deliver(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, TemplateModelRoot popups, - String templateFilename) throws ServletModuleFailure - { - } -*/ - public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) - throws ServletModuleFailure { - try { - deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) - throws ServletModuleFailure { - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest), "bundles.open"); - responseData.put("data", aData); - responseData.put("extra", anExtra); - - - Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator); - generator.generate(anOutputWriter, responseData, logger.asPrintWriter(logger.INFO_MESSAGE)); - - anOutputWriter.close(); - } - catch (Throwable e) { - logger.error("Error while generating " + aGenerator + ": " + e.getMessage()); - - throw new ServletModuleFailure(e); - } - } - - public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { - try { - logger.error("error: " + anException); - Map data = new HashMap(); - - data.put("errorstring", anException.getMessage()); - data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar())); - - deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate")); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, - PrintWriter out, ServletModuleUserExc anException) { - try { - logger.warn("user error: " + anException.getMessage()); - Map data = new HashMap(); - - MessageResources messages = MessageResources.getMessageResources("bundles.open"); - data.put("errorstring", - messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) - ); - data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar())); - - deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate")); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - -} - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.Vector; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.net.smtp.SMTPClient; +import org.apache.commons.net.smtp.SMTPReply; +import org.apache.fop.apps.Driver; +import org.apache.fop.apps.XSLTInputHandler; +import org.apache.log.Hierarchy; +import org.apache.log.Priority; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.queryParser.QueryParser; +import org.apache.lucene.search.Hits; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Searcher; +import org.apache.struts.util.MessageResources; +import mir.entity.Entity; +import mir.entity.EntityList; +import mir.generator.Generator; +import mir.log.LoggerWrapper; +import mir.misc.FileHandler; +import mir.misc.StringUtil; +import mir.misc.WebdbMultipartRequest; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.servlet.ServletModuleUserExc; +import mir.storage.StorageObjectFailure; +import mir.util.ExceptionFunctions; +import mir.util.HTTPRequestParser; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.global.MirGlobal; +import mircoders.media.MediaRequest; +import mircoders.media.UnsupportedMediaFormatExc; +import mircoders.module.ModuleComment; +import mircoders.module.ModuleContent; +import mircoders.module.ModuleImages; +import mircoders.module.ModuleTopics; +import mircoders.search.AudioSearchTerm; +import mircoders.search.ContentSearchTerm; +import mircoders.search.ImagesSearchTerm; +import mircoders.search.KeywordSearchTerm; +import mircoders.search.TextSearchTerm; +import mircoders.search.TopicSearchTerm; +import mircoders.search.UnIndexedSearchTerm; +import mircoders.search.VideoSearchTerm; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToMedia; +import mircoders.storage.DatabaseContentToTopics; +import mircoders.storage.DatabaseImages; +import mircoders.storage.DatabaseLanguage; +import mircoders.storage.DatabaseTopics; + +/* + * ServletModuleOpenIndy - + * is the open-access-servlet, which is responsible for + * adding comments to articles & + * open-postings to the newswire + * + * @author mir-coders group + * @version $Id: ServletModuleOpenIndy.java,v 1.71 2003/04/09 02:06:09 zapata Exp $ + * + */ + +public class ServletModuleOpenIndy extends ServletModule +{ + + private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate; + private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate; + private String searchResultsTemplate; + private String prepareMailTemplate,sentMailTemplate; + private ModuleContent contentModule; + private ModuleComment commentModule; + private ModuleImages imageModule; + private ModuleTopics topicsModule; + private String directOp ="yes"; + // Singelton / Kontruktor + private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleOpenIndy() { + super(); + try { + logger = new LoggerWrapper("ServletModule.OpenIndy"); + + commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate"); + commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate"); + commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate"); + postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate"); + postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate"); + postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate"); + searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate"); + prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate"); + sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate"); + directOp = configuration.getString("DirectOpenposting").toLowerCase(); + mainModule = new ModuleComment(DatabaseComment.getInstance()); + contentModule = new ModuleContent(DatabaseContent.getInstance()); + topicsModule = new ModuleTopics(DatabaseTopics.getInstance()); + imageModule = new ModuleImages(DatabaseImages.getInstance()); + defaultAction="addposting"; + } + catch (StorageObjectFailure e) { + logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); + } + } + + /** + * Method to return an "apology" when open postings are disabled + * + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure + */ + public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + deliver(aRequest, aResponse, (Map) null, null, + configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate")); + } + + + /** + * Method for making a comment + */ + + public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + if (MirGlobal.abuse().getOpenPostingDisabled()) { + openPostingDisabled(req, res); + + return; + } + + String aid = req.getParameter("aid"); // the article id the comment will belong to +/* + String language = req.getParameter("language"); + */ + + if (aid!=null && !aid.equals("")) { + try { + Map mergeData = new HashMap(); + + // onetimepasswd + if (MirGlobal.abuse().getOpenPostingPassword()) { + String passwd = this.createOneTimePasswd(); + HttpSession session = req.getSession(false); + session.setAttribute("passwd", passwd); + mergeData.put("passwd", passwd); + } + else { + mergeData.put("passwd", (String) null); + } +/* + if (language != null) { + HttpSession session = req.getSession(false); + session.setAttribute("Locale", new Locale(language, "")); + session.setAttribute("language", language); + } +*/ + mergeData.put("aid", aid); + + Map extraInfo = new HashMap(); + extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); + + deliver(req, res, mergeData, extraInfo, commentFormTemplate); + } + catch (Throwable t) { + throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t); + } + } + else throw new ServletModuleExc("aid not set!"); + } + + /** + * Method for inserting a comment into the Database and delivering + * the commentDone Page + */ + + public void inscomment(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + if (MirGlobal.abuse().getOpenPostingDisabled()) { + openPostingDisabled(req, res); + + return; + } + + String aid = req.getParameter("to_media"); // the article id the comment will belong to + if (aid!=null && !aid.equals("")) + { + // ok, collecting data from form + try { + Map withValues = getIntersectingValues(req, DatabaseComment.getInstance()); + + //no html in comments(for now) + for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ + String k=(String)i.next(); + String v=(String)withValues.get(k); + + withValues.put(k,StringUtil.removeHTMLTags(v)); + } + withValues.put("is_published","1"); + withValues.put("to_comment_status","1"); + + //checking the onetimepasswd + HttpSession session = req.getSession(false); + String sessionPasswd = (String) session.getAttribute("passwd"); + if ( sessionPasswd != null){ + String passwd = req.getParameter("passwd"); + if ( passwd == null || passwd.length()==0) { + throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {}); + } + if (!sessionPasswd.equals(passwd)) { + throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {}); + } + session.invalidate(); + } + + String id = mainModule.add(withValues); + + if(id==null){ + deliver(req, res, (Map) null, null, commentFormDupeTemplate); + } + else { + MirGlobal.abuse().logComment(req.getRemoteAddr(), id, new Date(), (String) req.getHeader("User-Agent")); + + DatabaseContent.getInstance().setUnproduced("id="+aid); + + try { + EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id); + MirGlobal.abuse().checkComment(comment, req, res); + MirGlobal.localizer().openPostings().afterCommentPosting(comment); + } + catch (Throwable t) { + throw new ServletModuleExc(t.getMessage()); + } + } + + // redirecting to url + // should implement back to article + Map mergeData = new HashMap(); + deliver(req, res, mergeData, null, commentFormDoneTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + else throw new ServletModuleExc("aid not set!"); + + } + + /** + * Method for delivering the form-Page for open posting + */ + + public void addposting(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + try { + if (MirGlobal.abuse().getOpenPostingDisabled()) { + openPostingDisabled(req, res); + + return; + } + + Map mergeData = new HashMap(); + + // onetimepasswd + if (MirGlobal.abuse().getOpenPostingPassword()) { + String passwd = this.createOneTimePasswd(); + HttpSession session = req.getSession(false); + session.setAttribute("passwd", passwd); + mergeData.put("passwd", passwd); + } + else { + mergeData.put("passwd", (String)null); + } + + String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems"); + String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems"); + String numOfMedia = req.getParameter("medianum"); + + if (numOfMedia == null || numOfMedia.equals("")) { + numOfMedia = defaultMedia; + } + else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) { + numOfMedia = maxMedia; + } + + int mediaNum = Integer.parseInt(numOfMedia); + List mediaFields = new Vector(); + for (int i = 0; i < mediaNum; i++) { + Integer mNum = new Integer(i + 1); + mediaFields.add(mNum.toString()); + } + mergeData.put("medianum", numOfMedia); + mergeData.put("mediafields", mediaFields); + mergeData.put("to_topic", null); + + Map extraInfo = new HashMap(); + extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); + extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList()); + + extraInfo.put("topics", topicsModule.getTopicsList()); + deliver(req, res, mergeData, extraInfo, postingFormTemplate); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + /** + * Method for inserting an open posting into the Database and delivering + * the postingDone Page + */ + + public void insposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + if (MirGlobal.abuse().getOpenPostingDisabled()) { + openPostingDisabled(req, res); + + return; + } + + Map mergeData = new HashMap(); + boolean setMedia=false; + boolean setTopic = false; + + try { + + WebdbMultipartRequest mp = null; + EntityList mediaList = null; + try { + // new MediaRequest, "1" is the id for the openPosting user + MediaRequest mediaReq = new MediaRequest("1", true); + mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq); + mediaList = mediaReq.getEntityList(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + + Map withValues = mp.getParameters(); + + //checking the onetimepasswd + HttpSession session = req.getSession(false); + String sessionPasswd = (String) session.getAttribute("passwd"); + if (sessionPasswd != null){ + String passwd = (String) withValues.get("passwd"); + + logger.debug("session password = " + sessionPasswd + ", form password = " + passwd); + + if ( passwd == null || passwd.length()==0) { + throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {}); + } + if (!sessionPasswd.equals(passwd)) { + throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {}); + } + session.invalidate(); + } + + if ((((String)withValues.get("title")).length() == 0) || + (((String)withValues.get("description")).length() == 0) || + (((String)withValues.get("content_data")).length() == 0)) + throw new ServletModuleUserExc("posting.error.missingfield", new String[] {}); + + // call the routines that escape html + + for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ + String k=(String)i.next(); + String v=(String)withValues.get(k); + + if (k.equals("content_data")){ + //this doesn't quite work yet, so for now, all html goes + //withValues.put(k,StringUtil.approveHTMLTags(v)); + withValues.put(k,StringUtil.deleteForbiddenTags(v)); + } + else if (k.equals("description")) { + String tmp = StringUtil.deleteForbiddenTags(v); + withValues.put(k,StringUtil.deleteHTMLTableTags(tmp)); + } + else { + withValues.put(k,StringUtil.removeHTMLTags(v)); + } + + } + + withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); + withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date"))); + withValues.put("is_produced", "0"); + withValues.put("is_published","1"); + if (directOp.equals("yes")) + withValues.put("to_article_type","1"); + + withValues.put("to_publisher","1"); + + // inserting content into database + String cid = contentModule.add(withValues); + logger.debug("id: "+cid); + //insert was not successfull + if(cid==null){ + + //How do we know that it was not succesful cause of a + //dupe, what if it failed cause of "No space left on device"? + //Or is there something I am missing? Wouldn't it be better + //to have an explicit dupe check and then insert? I have no + //idea what I am talking about. this comment is in case + //I forget to explicitely ask. -mh + deliver(req, res, mergeData, null, postingFormDupeTemplate); + return; + } + + MirGlobal.abuse().logArticle(req.getRemoteAddr(), cid, new Date(), (String) req.getHeader("User-Agent")); + + String[] to_topicsArr = mp.getParameterValues("to_topic"); + + if (to_topicsArr != null && to_topicsArr.length > 0) { + try{ + DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr); + setTopic = true; + } + catch (Throwable e) { + logger.error("setting content_x_topic failed"); + contentModule.deleteById(cid); + throw new ServletModuleFailure("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString(), e); + } //end try + } //end if + + //if we're here all is ok... associate the media to the article + for(int i=0;i= totalHits) + newPosition=totalHits-1; + session.setAttribute("positionInResults",new Integer(newPosition)); + } + else { + if (searchForwardValue != null){ + int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue(); + int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment; + if (newPosition<0) + newPosition=0; + if (newPosition >= totalHits) + newPosition=totalHits-1; + + session.setAttribute("positionInResults",new Integer(newPosition)); + } + else { + String indexPath=configuration.getString("IndexPath"); + + + String creatorFragment = creatorTerm.makeTerm(req); + if (creatorFragment != null){ + queryString = queryString + " +" + creatorFragment; + } + + // search title, description, and content for something + // the contentTerm uses param "search_boolean" to combine its terms + String contentFragment = contentTerm.makeTerm(req); + if (contentFragment != null){ + logger.debug("contentFragment: " + contentFragment); + queryString = queryString + " +" + contentFragment; + } + + String topicFragment = topicTerm.makeTerm(req); + if (topicFragment != null){ + queryString = queryString + " +" + topicFragment; + } + + String imagesFragment = imagesTerm.makeTerm(req); + if (imagesFragment != null){ + queryString = queryString + " +" + imagesFragment; + } + + String audioFragment = audioTerm.makeTerm(req); + if (audioFragment != null){ + queryString = queryString + " +" + audioFragment; + } + + String videoFragment = videoTerm.makeTerm(req); + if (videoFragment != null){ + queryString = queryString + " +" + videoFragment; + } + + if (queryString == null || queryString == ""){ + queryString = ""; + } + else{ + try{ + Searcher searcher = null; + try { + searcher = new IndexSearcher(indexPath); + } + catch(IOException e) { + logger.debug("Can't open indexPath: " + indexPath); + throw new ServletModuleExc("Problem with Search Index! : "+ e.toString()); + } + + Query query = null; + try { + query = QueryParser.parse(queryString, "content", new StandardAnalyzer()); + } + catch(Exception e) { + searcher.close(); + logger.debug("Query don't parse: " + queryString); + throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')"); + } + + Hits hits = null; + try { + hits = searcher.search(query); + } + catch(IOException e) { + searcher.close(); + logger.debug("Can't get hits: " + e.toString()); + throw new ServletModuleExc("Problem getting hits!"); + } + + int start = 0; + int end = hits.length(); + + String sortBy=req.getParameter("search_sort"); + if (sortBy == null || sortBy.equals("")){ + throw new ServletModuleExc("Please let me sort by something!(missing search_sort)"); + } + + // here is where the documents will go for storage across sessions + ArrayList theDocumentsSorted = new ArrayList(); + + if (sortBy.equals("score")){ + for(int i = start; i < end; i++) { + theDocumentsSorted.add(hits.doc(i)); + } + } + else{ + // then we'll sort by date! + Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be + for(int i = start; i < end; i++) { + String creationDate=(hits.doc(i)).get("creationDate"); + // do a little dance in case two contents created at the same second! + if (dateToPosition.containsKey(creationDate)){ + ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i)); + } + else{ + ArrayList thePositions = new ArrayList(); + thePositions.add(new Integer(i)); + dateToPosition.put(creationDate,thePositions); + } + } + Set keys = dateToPosition.keySet(); + ArrayList keyList= new ArrayList(keys); + Collections.sort(keyList); + if (sortBy.equals("date_desc")){ + Collections.reverse(keyList); + } + else{ + if (!sortBy.equals("date_asc")){ + throw new ServletModuleExc("don't know how to sort by: "+ sortBy); + } + } + ListIterator keyTraverser = keyList.listIterator(); + while (keyTraverser.hasNext()){ + ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next())); + ListIterator positionsTraverser=positions.listIterator(); + while (positionsTraverser.hasNext()){ + theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue())); + } + } + } + + try{ + searcher.close(); + } + catch (IOException e){ + logger.debug("Can't close searcher: " + e.toString()); + throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e); + } + + + session.removeAttribute("numberOfHits"); + session.removeAttribute("theDocumentsSorted"); + session.removeAttribute("positionInResults"); + + session.setAttribute("numberOfHits",new Integer(end)); + session.setAttribute("theDocumentsSorted",theDocumentsSorted); + session.setAttribute("positionInResults",new Integer(0)); + + } + catch (IOException e){ + logger.debug("Can't close searcher: " + e.toString()); + throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e); + } + } + } + } + + try { + ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted"); + if (theDocs != null){ + + mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString()); + List theHits = new Vector(); + int pIR=((Integer)session.getAttribute("positionInResults")).intValue(); + int terminus; + int numHits=((Integer)session.getAttribute("numberOfHits")).intValue(); + + if (!(pIR+increment>=numHits)){ + mergeData.put("hasNext","y"); + } + else { + mergeData.put("hasNext", null); + } + if (pIR>0){ + mergeData.put("hasPrevious","y"); + } + else { + mergeData.put("hasPrevious", null); + } + + if ((pIR+increment)>numHits){ + terminus=numHits; + } + else { + terminus=pIR+increment; + } + for(int i = pIR; i < terminus; i++) { + Map h = new HashMap(); + Document theHit = (Document)theDocs.get(i); + whereTerm.returnMeta(h,theHit); + creatorTerm.returnMeta(h,theHit); + titleTerm.returnMeta(h,theHit); + descriptionTerm.returnMeta(h,theHit); + dateTerm.returnMeta(h,theHit); + imagesTerm.returnMeta(h,theHit); + audioTerm.returnMeta(h,theHit); + videoTerm.returnMeta(h,theHit); + theHits.add(h); + } + mergeData.put("hits",theHits); + } + } + catch (Throwable e) { + logger.error("Can't iterate over hits: " + e.toString()); + + throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e); + } + + mergeData.put("queryString",queryString); + + deliver(req, res, mergeData, null, searchResultsTemplate); + } + catch (NullPointerException n){ + throw new ServletModuleFailure("Null Pointer: "+n.toString(), n); + } + } + + /* + * Method for dynamically generating a pdf from a fo file + */ + public void getpdf(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + String ID_REQUEST_PARAM = "id"; + String language = req.getParameter("language"); + String generateFO=configuration.getString("GenerateFO"); + String generatePDF=configuration.getString("GeneratePDF"); + + + //don't do anything if we are not making FO files, or if we are + //pregenerating PDF's + if (generateFO.equals("yes") && generatePDF.equals("no")){ + //fop complains unless you do the logging this way + org.apache.log.Logger log = null; + Hierarchy hierarchy = Hierarchy.getDefaultHierarchy(); + log = hierarchy.getLoggerFor("fop"); + log.setPriority(Priority.WARN); + + String producerStorageRoot=configuration.getString("Producer.StorageRoot"); + String producerDocRoot=configuration.getString("Producer.DocRoot"); + // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir"); + String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet"); + try { + String idParam = req.getParameter(ID_REQUEST_PARAM); + if (idParam != null) { + EntityContent contentEnt = + (EntityContent)contentModule.getById(idParam); + String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date")); + String foFile; + + if (language == null){ + foFile = producerStorageRoot + producerDocRoot + "/" + + publishPath + idParam + ".fo"; + } + else{ + foFile = producerStorageRoot + producerDocRoot + "/" + + language + publishPath + idParam + ".fo"; + } + logger.debug("USING FILES" + foFile + " and " + xslSheet); + XSLTInputHandler input = new XSLTInputHandler(new File(foFile), + new File(xslSheet)); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + res.setContentType("application/pdf"); + + Driver driver = new Driver(); + driver.setLogger(log); + driver.setRenderer(Driver.RENDER_PDF); + driver.setOutputStream(out); + driver.render(input.getParser(), input.getInputSource()); + + byte[] content = out.toByteArray(); + res.setContentLength(content.length); + res.getOutputStream().write(content); + res.getOutputStream().flush(); + } + else { + throw new ServletModuleExc("Missing id."); + } + } + catch (Throwable t) { + logger.error(t.toString()); + + throw new ServletModuleFailure(t); + } + } + else { + throw new ServletModuleExc("Can't generate a PDF because the config tells me not to."); + } + } + + protected String createOneTimePasswd(){ + Random r = new Random(); + int random = r.nextInt(); + long l = System.currentTimeMillis(); + l = (l*l*l*l)/random; + if(l<0) l = l * -1; + String returnString = ""+l; + + return returnString.substring(5); + } + + + /* this is an overwritten method of ServletModule in order + to use different bundles for open and admin */ +/* public void deliver(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, TemplateModelRoot popups, + String templateFilename) throws ServletModuleFailure + { + } +*/ + public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) + throws ServletModuleFailure { + try { + deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) + throws ServletModuleFailure { + try { + Map responseData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open"); + responseData.put("data", aData); + responseData.put("extra", anExtra); + + + Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator); + generator.generate(anOutputWriter, responseData, logger.asPrintWriter(logger.INFO_MESSAGE)); + + anOutputWriter.close(); + } + catch (Throwable e) { + logger.error("Error while generating " + aGenerator + ": " + e.getMessage()); + + throw new ServletModuleFailure(e); + } + } + + public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { + try { + logger.error("error: " + anException); + Map data = new HashMap(); + + data.put("errorstring", anException.getMessage()); + data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar())); + + deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate")); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, + PrintWriter out, ServletModuleUserExc anException) { + try { + logger.warn("user error: " + anException.getMessage()); + Map data = new HashMap(); + + MessageResources messages = MessageResources.getMessageResources("bundles.open"); + data.put("errorstring", + messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) + ); + data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar())); + + deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate")); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + +} + + + diff --git a/source/mircoders/servlet/ServletModuleProducer.java b/source/mircoders/servlet/ServletModuleProducer.java index 6d4be8e3..c3d41ebf 100755 --- a/source/mircoders/servlet/ServletModuleProducer.java +++ b/source/mircoders/servlet/ServletModuleProducer.java @@ -107,7 +107,7 @@ public class ServletModuleProducer extends ServletModule try { generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template"); - generationData = ServletHelper.makeGenerationData(getLocale(aRequest)); + generationData = ServletHelper.makeGenerationData(new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus"); producersData = new Vector(); diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index d3d29eb0..28ed2793 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -40,11 +40,11 @@ package mircoders.storage; * @version 1.0 */ +import freemarker.template.SimpleList; import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; public class DatabaseArticleType extends Database implements StorageObject{ @@ -52,11 +52,7 @@ public class DatabaseArticleType extends Database implements StorageObject{ private static DatabaseArticleType instance; private static SimpleList articletypePopupData; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseArticleType getInstance() throws - StorageObjectFailure { + public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure { if (instance == null) { instance = new DatabaseArticleType(); instance.myselfDatabase = instance; @@ -74,6 +70,4 @@ public class DatabaseArticleType extends Database implements StorageObject{ public SimpleList getPopupData() throws StorageObjectFailure { return getPopupData("name", false); } - - } diff --git a/source/mircoders/storage/DatabaseAudio.java b/source/mircoders/storage/DatabaseAudio.java index fa98493d..b5aa0b7d 100755 --- a/source/mircoders/storage/DatabaseAudio.java +++ b/source/mircoders/storage/DatabaseAudio.java @@ -1,94 +1,94 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -public class DatabaseAudio extends Database implements StorageObject{ - - private static DatabaseAudio instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseAudio getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseAudio(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseAudio() throws StorageObjectFailure { - super(); - logger = new LoggerWrapper("Database.Audio"); - - hasTimestamp = true; - theTable = "audio"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityAudio.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +public class DatabaseAudio extends Database implements StorageObject{ + + private static DatabaseAudio instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseAudio getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseAudio(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseAudio() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Audio"); + + hasTimestamp = true; + theTable = "audio"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityAudio.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + +} diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index d5eda990..06b8bb48 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -1,104 +1,104 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * This class implements the access to the comment-table for the - * media table. - * - * - */ - -public class DatabaseComment extends Database implements StorageObject{ - - private static DatabaseComment instance; - - public static DatabaseComment getInstance() { - if (instance == null) { - synchronized (DatabaseComment.class) { - if (instance == null) { - instance = new DatabaseComment(); - instance.myselfDatabase = instance; - } - } - } - return instance; - } - - private DatabaseComment() { - super(); - hasTimestamp = false; - theTable = "comment"; - logger = new LoggerWrapper("Database.Comment"); - - this.theEntityClass = mircoders.entity.EntityComment.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public boolean deleteByContentId(String id) throws StorageObjectFailure { - Statement stmt = null; - Connection con = null; - String sql; - int res = 0; - - /** @todo comments and topics should be deleted */ - sql = "delete from " + theTable + " where to_media=" + id; - logger.info("DELETE "+ sql); - - try { - con = getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } - catch (SQLException sqe) { - new StorageObjectFailure(sqe); - return false; - } - finally { - freeConnection(con, stmt); - } - return true; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * This class implements the access to the comment-table for the + * media table. + * + * + */ + +public class DatabaseComment extends Database implements StorageObject{ + + private static DatabaseComment instance; + + public static DatabaseComment getInstance() { + if (instance == null) { + synchronized (DatabaseComment.class) { + if (instance == null) { + instance = new DatabaseComment(); + instance.myselfDatabase = instance; + } + } + } + return instance; + } + + private DatabaseComment() { + super(); + hasTimestamp = false; + theTable = "comment"; + logger = new LoggerWrapper("Database.Comment"); + + this.theEntityClass = mircoders.entity.EntityComment.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public boolean deleteByContentId(String id) throws StorageObjectFailure { + Statement stmt = null; + Connection con = null; + String sql; + int res = 0; + + /** @todo comments and topics should be deleted */ + sql = "delete from " + theTable + " where to_media=" + id; + logger.info("DELETE "+ sql); + + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } + catch (SQLException sqe) { + new StorageObjectFailure(sqe); + return false; + } + finally { + freeConnection(con, stmt); + } + return true; + } +} diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index 83ae0cc8..904cb6cc 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -1,77 +1,77 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @author: - * @version 1.0 - */ - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - - -public class DatabaseCommentStatus extends Database implements StorageObject{ - - private static DatabaseCommentStatus instance; - - public static DatabaseCommentStatus getInstance() throws StorageObjectFailure { - if (instance == null) { - synchronized (DatabaseCommentStatus.class) { - if (instance == null) { - instance = new DatabaseCommentStatus(); - instance.myselfDatabase = instance; - } - } - } - - return instance; - } - - private DatabaseCommentStatus() throws StorageObjectFailure { - super(); - hasTimestamp = false; - theTable = "comment_status"; - logger = new LoggerWrapper("Database.CommentStatus"); - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", false); - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +/** + * Title: + * Description: + * Copyright: Copyright (c) 2001 + * Company: + * @author: + * @version 1.0 + */ + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + + +public class DatabaseCommentStatus extends Database implements StorageObject{ + + private static DatabaseCommentStatus instance; + + public static DatabaseCommentStatus getInstance() throws StorageObjectFailure { + if (instance == null) { + synchronized (DatabaseCommentStatus.class) { + if (instance == null) { + instance = new DatabaseCommentStatus(); + instance.myselfDatabase = instance; + } + } + } + + return instance; + } + + private DatabaseCommentStatus() throws StorageObjectFailure { + super(); + hasTimestamp = false; + theTable = "comment_status"; + logger = new LoggerWrapper("Database.CommentStatus"); + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", false); + } } \ No newline at end of file diff --git a/source/mircoders/storage/DatabaseContentToMedia.java b/source/mircoders/storage/DatabaseContentToMedia.java index f9303973..1572cb28 100755 --- a/source/mircoders/storage/DatabaseContentToMedia.java +++ b/source/mircoders/storage/DatabaseContentToMedia.java @@ -1,562 +1,562 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUploadedMedia; - -/** - * implements abstract DB connection to the content_x_media SQL table - * - * @author RK, mir-coders group - * @version $Id: DatabaseContentToMedia.java,v 1.16 2003/03/09 03:53:12 zapata Exp $ - * - */ - -public class DatabaseContentToMedia extends Database implements StorageObject{ - - private static DatabaseContentToMedia instance; - - public static DatabaseContentToMedia getInstance() { - if (instance == null) { - synchronized (DatabaseContentToMedia.class) { - if (instance == null) { - instance = new DatabaseContentToMedia(); - instance.myselfDatabase = instance; - } - } - } - return instance; - } - - private DatabaseContentToMedia() { - super(); - - logger = new LoggerWrapper("Database.ContentToMedia"); - - hasTimestamp = false; - theTable = "content_x_media"; - theEntityClass = mir.entity.GenericEntity.class; - } - - /** - * get all the media-files belonging to a content entity - * - */ - public EntityList getMedia(EntityContent content) throws StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Throwable e) { - logger.debug("-- get media failed " + e.toString()); - throw new StorageObjectFailure("-- get media failed ", e); - } - } - return returnList; - } - - public boolean hasMedia(EntityContent content) throws StorageObjectFailure, - StorageObjectExc { - if (content != null) { - try { - if (selectByWhereClause("content_id=" + content.getId(), -1).size() == - 0) - return false; - else - return true; - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.hasMedia: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.hasMedia: " + - e.toString(), e); - } - } - else { - logger.error("DatabaseContentToMedia.hasMedia: content == null"); - throw new StorageObjectExc( - "DatabaseContentToMedia.hasMedia: content == null"); - } - } - - /** - * get all the audio belonging to a content entity - * - */ - public EntityList getAudio(EntityContent content) throws StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getAudio: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getAudio: " + - e.toString(), e); - } - } - return returnList; - } - - /** - * get all the video belonging to a content entity - * - */ - public EntityList getVideo(EntityContent content) throws StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getVideo: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getVideo: " + - e.toString(), e); - } - } - return returnList; - } - - /** - * get all the images belonging to a content entity - * - */ - public EntityList getImages(EntityContent content) throws - StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseImages.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getImages: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getImages: " + - e.toString(), e); - } - } - return returnList; - } - - /** - * get all the uploaded/other Media belonging to a content entity - * - */ - public EntityList getOther(EntityContent content) throws StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseOther.getInstance().selectByWhereClause(subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getOther: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getOther: " + e.toString(), e); - } - } - return returnList; - } - - /** - * get all the uploaded/other Media belonging to a content entity - * - */ - public EntityList getUploadedMedia(EntityContent content) throws - StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause( - subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getUploadedMedia: " + e.toString()); - throw new StorageObjectFailure( - "DatabaseContentToMedia.getUploadedMedia: " + e.toString(), e); - } - } - return returnList; - } - - public void setMedia(String contentId, String[] mediaId) throws - StorageObjectFailure { - if (contentId == null) { - return; - } - if (mediaId == null || mediaId[0] == null) { - return; - } - //first delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; - - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, sql); - } - catch (Exception e) { - logger.error("-- set media failed -- delete"); - throw new StorageObjectFailure("-- set media failed -- delete", e); - } - finally { - freeConnection(con, stmt); - } - - //now insert - //first delete all row with content_id=contentId - for (int i = 0; i < mediaId.length; i++) { - sql = "insert into " + theTable + " (content_id,media_id) values (" - + contentId + "," + mediaId[i] + ")"; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - } - catch (Exception e) { - logger.error("-- set topics failed -- insert"); - throw new StorageObjectFailure("-- set topics failed -- insert ", e); - } - finally { - freeConnection(con, stmt); - } - } - } - - public void addMedia(String contentId, String mediaId) throws - StorageObjectFailure { - if (contentId == null && mediaId == null) { - return; - } - - Connection con = null; - Statement stmt = null; - //now insert - - String sql = "insert into " + theTable + " (content_id,media_id) values (" - + contentId + "," + mediaId + ")"; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - } - catch (Exception e) { - logger.error("-- add media failed -- insert"); - throw new StorageObjectFailure("-- add media failed -- insert ", e); - } - finally { - freeConnection(con, stmt); - } - } - - public void setMedia(String contentId, String mediaId) throws - StorageObjectFailure { - if (contentId == null && mediaId == null) { - return; - } - //first delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; - - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - } - catch (Exception e) { - logger.error("-- set media failed -- delete"); - throw new StorageObjectFailure("-- set media failed -- delete ", e); - } - finally { - freeConnection(con, stmt); - } - - //now insert - //first delete all row with content_id=contentId - - sql = "insert into " + theTable + " (content_id,media_id) values (" - + contentId + "," + mediaId + ")"; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - } - catch (Exception e) { - logger.error("-- set media failed -- insert"); - throw new StorageObjectFailure("-- set media failed -- insert ", e); - } - finally { - freeConnection(con, stmt); - } - } - - public void deleteByContentId(String contentId) throws StorageObjectFailure { - if (contentId == null) { - //theLog.printDebugInfo("-- delete topics failed -- no content id"); - return; - } - //delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; - - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - } - catch (Exception e) { - logger.error("-- delete by contentId failed "); - throw new StorageObjectFailure( - "-- delete by content id failed -- delete ", e); - } - finally { - freeConnection(con, stmt); - } - } - - public void deleteByMediaId(String mediaId) throws StorageObjectFailure { - if (mediaId == null) { - //theLog.printDebugInfo("-- delete topics failed -- no topic id"); - return; - } - //delete all row with content_id=contentId - String sql = "delete from " + theTable + " where media_id=" + mediaId; - - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - logger.debug("-- delete media success "); - } - catch (Exception e) { - logger.error("-- delete media failed "); - throw new StorageObjectFailure("-- delete by media id failed -- ", e); - } - finally { - freeConnection(con, stmt); - } - } - - public void delete(String contentId, String mediaId) throws - StorageObjectFailure { - if (mediaId == null || contentId == null) { - logger.debug("-- delete media failed -- missing parameter"); - return; - } - //delete all row with content_id=contentId and media_id=mediaId - String sql = "delete from " + theTable + " where media_id=" + mediaId + - " and content_id= " + contentId; - - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt, sql); - logger.debug("-- delete content_x_media success "); - } - catch (Exception e) { - logger.error("-- delete content_x_media failed "); - throw new StorageObjectFailure("-- delete content_x_media failed -- ", e); - } - finally { - freeConnection(con, stmt); - } - } - - public EntityList getContent(EntityUploadedMedia media) throws - StorageObjectFailure { - EntityList returnList = null; - if (media != null) { - String id = media.getId(); - String select = "select content_id from " + theTable + " where media_id=" + - id; - - // execute select statement - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseContent.getInstance().selectByWhereClause( - mediaSelect, -1); - } - } - catch (Exception e) { - logger.error("-- get content failed"); - throw new StorageObjectFailure("-- get content failed -- ", e); - } - finally { - freeConnection(con, stmt); - } - } - return returnList; - } - - /** - * Returns a EntityList with all content-objects having a relation to a media - */ - - public EntityList getContent() throws StorageObjectFailure { - EntityList returnList = null; - - String select = "select distinct content_id from " + theTable; - // execute select statement - Connection con = null; - Statement stmt = null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseContent.getInstance().selectByWhereClause( - mediaSelect, "webdb_lastchange desc"); - } - } - catch (Exception e) { - logger.error("-- get content failed"); - throw new StorageObjectFailure("-- get content failed -- ", e); - } - finally { - freeConnection(con, stmt); - } - - return returnList; - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityUploadedMedia; + +/** + * implements abstract DB connection to the content_x_media SQL table + * + * @author RK, mir-coders group + * @version $Id: DatabaseContentToMedia.java,v 1.17 2003/04/09 02:06:10 zapata Exp $ + * + */ + +public class DatabaseContentToMedia extends Database implements StorageObject{ + + private static DatabaseContentToMedia instance; + + public static DatabaseContentToMedia getInstance() { + if (instance == null) { + synchronized (DatabaseContentToMedia.class) { + if (instance == null) { + instance = new DatabaseContentToMedia(); + instance.myselfDatabase = instance; + } + } + } + return instance; + } + + private DatabaseContentToMedia() { + super(); + + logger = new LoggerWrapper("Database.ContentToMedia"); + + hasTimestamp = false; + theTable = "content_x_media"; + theEntityClass = mir.entity.GenericEntity.class; + } + + /** + * get all the media-files belonging to a content entity + * + */ + public EntityList getMedia(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Throwable e) { + logger.debug("-- get media failed " + e.toString()); + throw new StorageObjectFailure("-- get media failed ", e); + } + } + return returnList; + } + + public boolean hasMedia(EntityContent content) throws StorageObjectFailure, + StorageObjectExc { + if (content != null) { + try { + if (selectByWhereClause("content_id=" + content.getId(), -1).size() == + 0) + return false; + else + return true; + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.hasMedia: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.hasMedia: " + + e.toString(), e); + } + } + else { + logger.error("DatabaseContentToMedia.hasMedia: content == null"); + throw new StorageObjectExc( + "DatabaseContentToMedia.hasMedia: content == null"); + } + } + + /** + * get all the audio belonging to a content entity + * + */ + public EntityList getAudio(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getAudio: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getAudio: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the video belonging to a content entity + * + */ + public EntityList getVideo(EntityContent content) throws StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getVideo: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getVideo: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the images belonging to a content entity + * + */ + public EntityList getImages(EntityContent content) throws + StorageObjectFailure { + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseImages.getInstance().selectByWhereClause(subselect, + "id", -1); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getImages: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getImages: " + + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the uploaded/other Media belonging to a content entity + * + */ + public EntityList getOther(EntityContent content) throws StorageObjectFailure { + /** @todo this should only fetch published media / rk */ + + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + // media should stay in uploaded order. this is especially important + // for photo stories which require a specific chronologic order. + // this is why we have the the second parameter "id" + returnList = DatabaseOther.getInstance().selectByWhereClause(subselect, + "id"); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getOther: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.getOther: " + e.toString(), e); + } + } + return returnList; + } + + /** + * get all the uploaded/other Media belonging to a content entity + * + */ + public EntityList getUploadedMedia(EntityContent content) throws + StorageObjectFailure { + /** @todo this should only fetch published media / rk */ + + EntityList returnList = null; + if (content != null) { + // get all to_topic from media_x_topic + String id = content.getId(); + //this is not supported by mysql + String subselect = "id in (select media_id from " + theTable + + " where content_id=" + id + ")"; + + try { + returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause( + subselect, + "id"); + } + catch (Exception e) { + logger.error("DatabaseContentToMedia.getUploadedMedia: " + e.toString()); + throw new StorageObjectFailure( + "DatabaseContentToMedia.getUploadedMedia: " + e.toString(), e); + } + } + return returnList; + } + + public void setMedia(String contentId, String[] mediaId) throws + StorageObjectFailure { + if (contentId == null) { + return; + } + if (mediaId == null || mediaId[0] == null) { + return; + } + //first delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- delete"); + throw new StorageObjectFailure("-- set media failed -- delete", e); + } + finally { + freeConnection(con, stmt); + } + + //now insert + //first delete all row with content_id=contentId + for (int i = 0; i < mediaId.length; i++) { + sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId[i] + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set topics failed -- insert"); + throw new StorageObjectFailure("-- set topics failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + } + + public void addMedia(String contentId, String mediaId) throws + StorageObjectFailure { + if (contentId == null && mediaId == null) { + return; + } + + Connection con = null; + Statement stmt = null; + //now insert + + String sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- add media failed -- insert"); + throw new StorageObjectFailure("-- add media failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void setMedia(String contentId, String mediaId) throws + StorageObjectFailure { + if (contentId == null && mediaId == null) { + return; + } + //first delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- delete"); + throw new StorageObjectFailure("-- set media failed -- delete ", e); + } + finally { + freeConnection(con, stmt); + } + + //now insert + //first delete all row with content_id=contentId + + sql = "insert into " + theTable + " (content_id,media_id) values (" + + contentId + "," + mediaId + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- set media failed -- insert"); + throw new StorageObjectFailure("-- set media failed -- insert ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void deleteByContentId(String contentId) throws StorageObjectFailure { + if (contentId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no content id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from " + theTable + " where content_id=" + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + } + catch (Exception e) { + logger.error("-- delete by contentId failed "); + throw new StorageObjectFailure( + "-- delete by content id failed -- delete ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void deleteByMediaId(String mediaId) throws StorageObjectFailure { + if (mediaId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no topic id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from " + theTable + " where media_id=" + mediaId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + logger.debug("-- delete media success "); + } + catch (Exception e) { + logger.error("-- delete media failed "); + throw new StorageObjectFailure("-- delete by media id failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public void delete(String contentId, String mediaId) throws + StorageObjectFailure { + if (mediaId == null || contentId == null) { + logger.debug("-- delete media failed -- missing parameter"); + return; + } + //delete all row with content_id=contentId and media_id=mediaId + String sql = "delete from " + theTable + " where media_id=" + mediaId + + " and content_id= " + contentId; + + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt, sql); + logger.debug("-- delete content_x_media success "); + } + catch (Exception e) { + logger.error("-- delete content_x_media failed "); + throw new StorageObjectFailure("-- delete content_x_media failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + + public EntityList getContent(EntityUploadedMedia media) throws + StorageObjectFailure { + EntityList returnList = null; + if (media != null) { + String id = media.getId(); + String select = "select content_id from " + theTable + " where media_id=" + + id; + + // execute select statement + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, select); + if (rs != null) { + String mediaSelect = "id IN ("; + boolean first = true; + while (rs.next()) { + if (first == false) + mediaSelect += ","; + mediaSelect += rs.getString(1); + first = false; + } + mediaSelect += ")"; + if (first == false) + returnList = DatabaseContent.getInstance().selectByWhereClause( + mediaSelect, -1); + } + } + catch (Exception e) { + logger.error("-- get content failed"); + throw new StorageObjectFailure("-- get content failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + } + return returnList; + } + + /** + * Returns a EntityList with all content-objects having a relation to a media + */ + + public EntityList getContent() throws StorageObjectFailure { + EntityList returnList = null; + + String select = "select distinct content_id from " + theTable; + // execute select statement + Connection con = null; + Statement stmt = null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt, select); + if (rs != null) { + String mediaSelect = "id IN ("; + boolean first = true; + while (rs.next()) { + if (first == false) + mediaSelect += ","; + mediaSelect += rs.getString(1); + first = false; + } + mediaSelect += ")"; + if (first == false) + returnList = DatabaseContent.getInstance().selectByWhereClause( + mediaSelect, "webdb_lastchange desc"); + } + } + catch (Exception e) { + logger.error("-- get content failed"); + throw new StorageObjectFailure("-- get content failed -- ", e); + } + finally { + freeConnection(con, stmt); + } + + return returnList; + } + +} diff --git a/source/mircoders/storage/DatabaseContentToTopics.java b/source/mircoders/storage/DatabaseContentToTopics.java index 3dc31160..9bf65600 100755 --- a/source/mircoders/storage/DatabaseContentToTopics.java +++ b/source/mircoders/storage/DatabaseContentToTopics.java @@ -1,318 +1,318 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityTopics; - -/** - * This class implements the 1-n-relation between - * content and topic - * - */ - -public class DatabaseContentToTopics extends Database implements StorageObject{ - - private static DatabaseContentToTopics instance; - - public static DatabaseContentToTopics getInstance() { - if (instance == null) { - synchronized (DatabaseContentToTopics.class) { - if (instance == null) { - instance = new DatabaseContentToTopics(); - instance.myselfDatabase = instance; - } - } - } - return instance; - } - - private DatabaseContentToTopics() { - super(); - - logger = new LoggerWrapper("Database.ContentToTopics"); - - hasTimestamp = false; - theTable="content_x_topic"; - theEntityClass = mir.entity.GenericEntity.class; - } - - /** - * This class return an EntityList of Topics - * @param EntityContent content - * @returns EntityList - */ - public EntityList getTopics(EntityContent content) { - EntityList returnList=null; - if (content != null) { - // get all to_topic from content_x_topic - String id = content.getId(); - String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")"; - - try { - returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1); - } - catch (Exception e) { - logger.error("-- get topics failed " + e.toString()); - } - } - return returnList; - } - - /** - * Returns a ArrayList of Integer-Objects from a content-id. - * @returns ArrayList - */ - public ArrayList getTopicsOfContent(String contentId) - throws StorageObjectFailure { - ArrayList returnList = new ArrayList(); - - if (contentId != null) { - String sql = "select topic_id from " + theTable + " where content_id=" + contentId; - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); - if(rs!=null){ - while(rs.next()){ - returnList.add(new Integer(rs.getInt("topic_id"))); - } - } - } - catch (Exception e) { - logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage()); - } - finally { - freeConnection(con,stmt); - } - } - return returnList; - } - - /** - * Set new topics - */ - public void setTopics(String contentId, String[] topicId) - throws StorageObjectFailure { - if (contentId == null){ - return; - } - if (topicId==null || topicId[0]==null) { - return; - } - //first check which topics this article has - Collection hasTopics = getTopicsOfContent(contentId); - Collection toSet = new ArrayList(); - Collection toDelete = new ArrayList(); - - if(hasTopics!=null && hasTopics.size()>0){ - //now we check if there are new topics and copy them to an array. - for(int i = 0; i< topicId.length;i++){ - boolean set=false; - int whichTopic = 0; - for(Iterator it=hasTopics.iterator();it.hasNext();){ - Integer topic = (Integer)it.next(); - if(topicId[i].equals(topic.toString())){ - set=true; - } else { - whichTopic = i; - } - } - if(set==false){ - toSet.add(topicId[i]); - logger.debug("to set: "+ topicId[i]); - } - } - //now we check if we have to delete topics - for(Iterator it=hasTopics.iterator();it.hasNext();){ - boolean delete=true; - int whichTopic = 0; - Integer topic = (Integer)it.next(); - for(int i = 0; i< topicId.length;i++){ - if(topicId[i].equals(topic.toString())){ - delete=false; - } else { - whichTopic = i; - } - } - if(delete==true){ - toDelete.add(topic.toString()); - logger.debug("to delete: "+ topic.toString()); - } - } - } else { - //all the topics has to be set, so we copy all to the array - for (int i = 0; i < topicId.length; i++){ - toSet.add(topicId[i]); - } - } - - //first delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where content_id=" + contentId - + " and topic_id in ("; - boolean first=false; - for(Iterator it = toDelete.iterator(); it.hasNext();){ - if(first==false){ - first=true; - } else { - sql+=","; - } - sql+= (String)it.next(); - } - sql+=")"; - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt,sql); - } catch (Exception e) { - logger.error("-- deleting topics failed"); - } finally { - freeConnection(con,stmt); - } - - //now insert - //first delete all row with content_id=contentId - for (Iterator it = toSet.iterator(); it.hasNext();) { - sql = "insert into "+ theTable +" (content_id,topic_id) values (" - + contentId + "," + (String)it.next() + ")"; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - int rs = executeUpdate(stmt,sql); - } - catch (Exception e) { - logger.error("-- set topics failed -- insert laenge topicId" + topicId.length); - } finally { - freeConnection(con,stmt); - } - } - } - - public void deleteByContentId(String contentId) - throws StorageObjectFailure { - if (contentId == null) { - //theLog.printDebugInfo("-- delete topics failed -- no content id"); - return; - } - //delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where content_id=" + contentId; - - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); - } catch (Exception e) { - //theLog.printDebugInfo("-- delete topics failed "); - } finally { - freeConnection(con,stmt); - } - } - - public void deleteByTopicId(String topicId) - throws StorageObjectFailure { - if (topicId == null) { - //theLog.printDebugInfo("-- delete topics failed -- no topic id"); - return; - } - //delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where topic_id=" + topicId; - - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); - } - catch (Exception e) { - logger.error("-- delete topics failed "); - } - finally { - freeConnection(con,stmt); - } - } - - - public EntityList getContent(EntityTopics topic) - throws StorageObjectFailure { - EntityList returnList=null; - if (topic != null) { - String id = topic.getId(); - String select = "select content_id from " + theTable + " where topic_id=" + id; - - // execute select statement - Connection con=null;Statement stmt=null; - try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,select); - if (rs!=null) { - String topicSelect= "id IN ("; - boolean first=true; - while (rs.next()) { - if (first==false) topicSelect+=","; - topicSelect += rs.getString(1); - first=false; - } - topicSelect+=")"; - if (first==false) - returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1); - } - } - catch (Exception e) { - logger.error("-- get contetn failed"); - } - finally { freeConnection(con,stmt);} - } - return returnList; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityTopics; + +/** + * This class implements the 1-n-relation between + * content and topic + * + */ + +public class DatabaseContentToTopics extends Database implements StorageObject{ + + private static DatabaseContentToTopics instance; + + public static DatabaseContentToTopics getInstance() { + if (instance == null) { + synchronized (DatabaseContentToTopics.class) { + if (instance == null) { + instance = new DatabaseContentToTopics(); + instance.myselfDatabase = instance; + } + } + } + return instance; + } + + private DatabaseContentToTopics() { + super(); + + logger = new LoggerWrapper("Database.ContentToTopics"); + + hasTimestamp = false; + theTable="content_x_topic"; + theEntityClass = mir.entity.GenericEntity.class; + } + + /** + * This class return an EntityList of Topics + * @param EntityContent content + * @returns EntityList + */ + public EntityList getTopics(EntityContent content) { + EntityList returnList=null; + if (content != null) { + // get all to_topic from content_x_topic + String id = content.getId(); + String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")"; + + try { + returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1); + } + catch (Exception e) { + logger.error("-- get topics failed " + e.toString()); + } + } + return returnList; + } + + /** + * Returns a ArrayList of Integer-Objects from a content-id. + * @returns ArrayList + */ + public ArrayList getTopicsOfContent(String contentId) + throws StorageObjectFailure { + ArrayList returnList = new ArrayList(); + + if (contentId != null) { + String sql = "select topic_id from " + theTable + " where content_id=" + contentId; + Connection con=null;Statement stmt=null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt,sql); + if(rs!=null){ + while(rs.next()){ + returnList.add(new Integer(rs.getInt("topic_id"))); + } + } + } + catch (Exception e) { + logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage()); + } + finally { + freeConnection(con,stmt); + } + } + return returnList; + } + + /** + * Set new topics + */ + public void setTopics(String contentId, String[] topicId) + throws StorageObjectFailure { + if (contentId == null){ + return; + } + if (topicId==null || topicId[0]==null) { + return; + } + //first check which topics this article has + Collection hasTopics = getTopicsOfContent(contentId); + Collection toSet = new ArrayList(); + Collection toDelete = new ArrayList(); + + if(hasTopics!=null && hasTopics.size()>0){ + //now we check if there are new topics and copy them to an array. + for(int i = 0; i< topicId.length;i++){ + boolean set=false; + int whichTopic = 0; + for(Iterator it=hasTopics.iterator();it.hasNext();){ + Integer topic = (Integer)it.next(); + if(topicId[i].equals(topic.toString())){ + set=true; + } else { + whichTopic = i; + } + } + if(set==false){ + toSet.add(topicId[i]); + logger.debug("to set: "+ topicId[i]); + } + } + //now we check if we have to delete topics + for(Iterator it=hasTopics.iterator();it.hasNext();){ + boolean delete=true; + int whichTopic = 0; + Integer topic = (Integer)it.next(); + for(int i = 0; i< topicId.length;i++){ + if(topicId[i].equals(topic.toString())){ + delete=false; + } else { + whichTopic = i; + } + } + if(delete==true){ + toDelete.add(topic.toString()); + logger.debug("to delete: "+ topic.toString()); + } + } + } else { + //all the topics has to be set, so we copy all to the array + for (int i = 0; i < topicId.length; i++){ + toSet.add(topicId[i]); + } + } + + //first delete all row with content_id=contentId + String sql = "delete from "+ theTable +" where content_id=" + contentId + + " and topic_id in ("; + boolean first=false; + for(Iterator it = toDelete.iterator(); it.hasNext();){ + if(first==false){ + first=true; + } else { + sql+=","; + } + sql+= (String)it.next(); + } + sql+=")"; + Connection con=null;Statement stmt=null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt,sql); + } catch (Exception e) { + logger.error("-- deleting topics failed"); + } finally { + freeConnection(con,stmt); + } + + //now insert + //first delete all row with content_id=contentId + for (Iterator it = toSet.iterator(); it.hasNext();) { + sql = "insert into "+ theTable +" (content_id,topic_id) values (" + + contentId + "," + (String)it.next() + ")"; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + int rs = executeUpdate(stmt,sql); + } + catch (Exception e) { + logger.error("-- set topics failed -- insert laenge topicId" + topicId.length); + } finally { + freeConnection(con,stmt); + } + } + } + + public void deleteByContentId(String contentId) + throws StorageObjectFailure { + if (contentId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no content id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from "+ theTable +" where content_id=" + contentId; + + Connection con=null;Statement stmt=null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt,sql); + } catch (Exception e) { + //theLog.printDebugInfo("-- delete topics failed "); + } finally { + freeConnection(con,stmt); + } + } + + public void deleteByTopicId(String topicId) + throws StorageObjectFailure { + if (topicId == null) { + //theLog.printDebugInfo("-- delete topics failed -- no topic id"); + return; + } + //delete all row with content_id=contentId + String sql = "delete from "+ theTable +" where topic_id=" + topicId; + + Connection con=null;Statement stmt=null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt,sql); + } + catch (Exception e) { + logger.error("-- delete topics failed "); + } + finally { + freeConnection(con,stmt); + } + } + + + public EntityList getContent(EntityTopics topic) + throws StorageObjectFailure { + EntityList returnList=null; + if (topic != null) { + String id = topic.getId(); + String select = "select content_id from " + theTable + " where topic_id=" + id; + + // execute select statement + Connection con=null;Statement stmt=null; + try { + con = getPooledCon(); + // should be a preparedStatement because is faster + stmt = con.createStatement(); + ResultSet rs = executeSql(stmt,select); + if (rs!=null) { + String topicSelect= "id IN ("; + boolean first=true; + while (rs.next()) { + if (first==false) topicSelect+=","; + topicSelect += rs.getString(1); + first=false; + } + topicSelect+=")"; + if (first==false) + returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1); + } + } + catch (Exception e) { + logger.error("-- get contetn failed"); + } + finally { freeConnection(con,stmt);} + } + return returnList; + } +} diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index c611dfc0..6b0bd9e4 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -1,72 +1,72 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageColor extends Database implements StorageObject{ - - private static DatabaseImageColor instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageColor getInstance() { - if (instance == null) { - instance = new DatabaseImageColor(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageColor() { - super(); - logger = new LoggerWrapper("Database.ImageColor"); - hasTimestamp = false; - theTable = "img_color"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageColor extends Database implements StorageObject{ + + private static DatabaseImageColor instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageColor getInstance() { + if (instance == null) { + instance = new DatabaseImageColor(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageColor() { + super(); + logger = new LoggerWrapper("Database.ImageColor"); + hasTimestamp = false; + theTable = "img_color"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } +} diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 217d4c7d..776b679f 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -1,73 +1,73 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageFormat extends Database implements StorageObject{ - - private static DatabaseImageFormat instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageFormat getInstance() { - if (instance == null) { - instance = new DatabaseImageFormat(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageFormat() { - super(); - logger = new LoggerWrapper("Database.ImageFormat"); - hasTimestamp = false; - theTable = "img_format"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageFormat extends Database implements StorageObject{ + + private static DatabaseImageFormat instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageFormat getInstance() { + if (instance == null) { + instance = new DatabaseImageFormat(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageFormat() { + super(); + logger = new LoggerWrapper("Database.ImageFormat"); + hasTimestamp = false; + theTable = "img_format"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index c3bf5765..677e635c 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -1,74 +1,74 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageLayout extends Database implements StorageObject{ - - private static DatabaseImageLayout instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageLayout getInstance() { - if (instance == null) { - instance = new DatabaseImageLayout(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageLayout() { - super(); - - logger = new LoggerWrapper("Database.ImageLayout"); - hasTimestamp = false; - theTable = "img_layout"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageLayout extends Database implements StorageObject{ + + private static DatabaseImageLayout instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageLayout getInstance() { + if (instance == null) { + instance = new DatabaseImageLayout(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageLayout() { + super(); + + logger = new LoggerWrapper("Database.ImageLayout"); + hasTimestamp = false; + theTable = "img_layout"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index e3754fe4..2743ba6e 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -1,72 +1,72 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageType extends Database implements StorageObject{ - private static DatabaseImageType instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageType getInstance() { - if (instance == null) { - instance = new DatabaseImageType(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImageType() { - super(); - logger = new LoggerWrapper("Database.ImageType"); - - hasTimestamp = false; - theTable = "img_type"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImageType extends Database implements StorageObject{ + private static DatabaseImageType instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImageType getInstance() { + if (instance == null) { + instance = new DatabaseImageType(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImageType() { + super(); + logger = new LoggerWrapper("Database.ImageType"); + + hasTimestamp = false; + theTable = "img_type"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseImages.java b/source/mircoders/storage/DatabaseImages.java index e44eb288..0638f333 100755 --- a/source/mircoders/storage/DatabaseImages.java +++ b/source/mircoders/storage/DatabaseImages.java @@ -1,104 +1,104 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImages extends Database implements StorageObject{ - - private static DatabaseImages instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImages getInstance() { - if (instance == null) { - instance = new DatabaseImages(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseImages() { - super(); - - logger = new LoggerWrapper("Database.Images"); - - hasTimestamp = true; - theTable = "images"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityImages.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImages extends Database implements StorageObject{ + + private static DatabaseImages instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseImages getInstance() { + if (instance == null) { + instance = new DatabaseImages(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseImages() { + super(); + + logger = new LoggerWrapper("Database.Images"); + + hasTimestamp = true; + theTable = "images"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityImages.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index 0d2b5859..dddac23f 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -1,81 +1,81 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -/** - * Title: DatabaseLanguage - * Description: - * Copyright: Copyright (c) 2001 - * Company: Indymedia - * @author - * @version 1.0 - */ - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - - -public class DatabaseLanguage extends Database implements StorageObject{ - - private static DatabaseLanguage instance; - private static SimpleList languagePopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseLanguage getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseLanguage(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseLanguage() throws StorageObjectFailure { - super(); - logger = new LoggerWrapper("Database.Language"); - - this.hasTimestamp = false; - this.theTable = "language"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - SimpleList pData = null; - pData = getPopupData("name", false); - - return pData; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +/** + * Title: DatabaseLanguage + * Description: + * Copyright: Copyright (c) 2001 + * Company: Indymedia + * @author + * @version 1.0 + */ + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + + +public class DatabaseLanguage extends Database implements StorageObject{ + + private static DatabaseLanguage instance; + private static SimpleList languagePopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseLanguage getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseLanguage(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseLanguage() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Language"); + + this.hasTimestamp = false; + this.theTable = "language"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + SimpleList pData = null; + pData = getPopupData("name", false); + + return pData; + } +} diff --git a/source/mircoders/storage/DatabaseLinksImcs.java b/source/mircoders/storage/DatabaseLinksImcs.java index 0499acba..3ca88c3f 100755 --- a/source/mircoders/storage/DatabaseLinksImcs.java +++ b/source/mircoders/storage/DatabaseLinksImcs.java @@ -1,250 +1,250 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mir.util.JDBCStringRoutines; - - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ -public class DatabaseLinksImcs extends Database implements StorageObject { - - private static DatabaseLinksImcs instance; - - public static DatabaseLinksImcs getInstance() { - if (instance == null) { - synchronized (DatabaseLinksImcs.class) { - if (instance == null) { - DatabaseLinksImcs newInstance; - - newInstance = new DatabaseLinksImcs(); - newInstance.myselfDatabase = newInstance; - instance = newInstance; - } - } - } - - return instance; - } - - private DatabaseLinksImcs() { - super(); - - logger = new LoggerWrapper("ServletModule.Database.LinksImcs"); - hasTimestamp = false; - theTable = "links_imcs"; - - theEntityClass = mircoders.entity.EntityLinksImcs.class; - } - - /** @todo toooo much copy/paste in this class //rk */ - - public String insert(Entity theEntity) throws StorageObjectFailure { - String returnId = "0"; - Connection con = null; - PreparedStatement pstmt = null; - //cache - invalidatePopupCache(); - try { - Map theEntityValues = theEntity.getValues(); - List streamedInput = theEntity.streamedInput(); - StringBuffer f = new StringBuffer(); - StringBuffer v = new StringBuffer(); - String aField, aValue; - boolean firstField = true; - // make sql-string - for (int i = 0; i < getFields().size(); i++) { - aField = (String) getFields().get(i); - if (!aField.equals(thePKeyName)) { - aValue = null; - // sonderfaelle - if (aField.equals("webdb_create")) { - aValue = "NOW()"; - } - else { - if (streamedInput != null && streamedInput.contains(aField)) { - aValue = "?"; - } - else { - if (theEntityValues.containsKey(aField)) { - if (aField.equals("to_parent_id")) { - aValue = JDBCStringRoutines.escapeStringLiteral((String) theEntityValues.get(aField)); - } - else { - aValue = "'" + JDBCStringRoutines.escapeStringLiteral((String) theEntityValues.get(aField)) + "'"; - } - } - } - } - // wenn Wert gegeben, dann einbauen - if (aValue != null) { - if (firstField == false) { - f.append(","); - v.append(","); - } - else { - firstField = false; - } - f.append(aField); - v.append(aValue); - } - } - } // end for - // insert into db - StringBuffer sqlBuf = - new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")"); - String sql = sqlBuf.toString(); - - logger.info("INSERT: " + sql); - - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql); - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = (String) theEntityValues.get(streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - pstmt.execute(); - pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL( (Database) - myselfDatabase)); - ResultSet rs = pstmt.executeQuery(); - rs.next(); - returnId = rs.getString(1); - theEntity.setId(returnId); - } - catch (SQLException sqe) { - throwSQLException(sqe, "insert"); - } - finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - ; - } - freeConnection(con, pstmt); - } - return returnId; - } - - public void update(Entity theEntity) throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - List streamedInput = theEntity.streamedInput(); - Map theEntityValues = theEntity.getValues(); - String id = theEntity.getId(); - String aField; - StringBuffer fv = new StringBuffer(); - boolean firstField = true; - //cache - invalidatePopupCache(); - // build sql statement - for (int i = 0; i < getFields().size(); i++) { - aField = (String) metadataFields.get(i); - // only normal cases - if (! (aField.equals(thePKeyName) || aField.equals("webdb_create") || - aField.equals("webdb_lastchange") || - (streamedInput != null && streamedInput.contains(aField)))) { - if (theEntityValues.containsKey(aField)) { - if (firstField == false) { - fv.append(", "); - } - else { - firstField = false; - } - if (aField.equals("to_parent_id")) { - fv.append(aField).append("=").append(JDBCStringRoutines.escapeStringLiteral((String)theEntityValues.get(aField))); - } - else { - fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String)theEntityValues.get(aField))).append("'"); - } - } - } - } - StringBuffer sql = new StringBuffer("update ").append(theTable).append( - " set ").append(fv); - // exceptions - if (metadataFields.contains("webdb_lastchange")) { - sql.append(",webdb_lastchange=NOW()"); - } - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - sql.append(",").append(streamedInput.get(i)).append("=?"); - } - } - sql.append(" where id=").append(id); - logger.info("UPDATE: " + sql); - // execute sql - try { - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = (String) theEntityValues.get(streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - pstmt.executeUpdate(); - } - catch (SQLException sqe) { - throwSQLException(sqe, "update"); - } - finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - ; - } - freeConnection(con, pstmt); - } - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mir.util.JDBCStringRoutines; + + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ +public class DatabaseLinksImcs extends Database implements StorageObject { + + private static DatabaseLinksImcs instance; + + public static DatabaseLinksImcs getInstance() { + if (instance == null) { + synchronized (DatabaseLinksImcs.class) { + if (instance == null) { + DatabaseLinksImcs newInstance; + + newInstance = new DatabaseLinksImcs(); + newInstance.myselfDatabase = newInstance; + instance = newInstance; + } + } + } + + return instance; + } + + private DatabaseLinksImcs() { + super(); + + logger = new LoggerWrapper("ServletModule.Database.LinksImcs"); + hasTimestamp = false; + theTable = "links_imcs"; + + theEntityClass = mircoders.entity.EntityLinksImcs.class; + } + + /** @todo toooo much copy/paste in this class //rk */ + + public String insert(Entity theEntity) throws StorageObjectFailure { + String returnId = "0"; + Connection con = null; + PreparedStatement pstmt = null; + //cache + invalidatePopupCache(); + try { + Map theEntityValues = theEntity.getValues(); + List streamedInput = theEntity.streamedInput(); + StringBuffer f = new StringBuffer(); + StringBuffer v = new StringBuffer(); + String aField, aValue; + boolean firstField = true; + // make sql-string + for (int i = 0; i < getFields().size(); i++) { + aField = (String) getFields().get(i); + if (!aField.equals(thePKeyName)) { + aValue = null; + // sonderfaelle + if (aField.equals("webdb_create")) { + aValue = "NOW()"; + } + else { + if (streamedInput != null && streamedInput.contains(aField)) { + aValue = "?"; + } + else { + if (theEntityValues.containsKey(aField)) { + if (aField.equals("to_parent_id")) { + aValue = JDBCStringRoutines.escapeStringLiteral((String) theEntityValues.get(aField)); + } + else { + aValue = "'" + JDBCStringRoutines.escapeStringLiteral((String) theEntityValues.get(aField)) + "'"; + } + } + } + } + // wenn Wert gegeben, dann einbauen + if (aValue != null) { + if (firstField == false) { + f.append(","); + v.append(","); + } + else { + firstField = false; + } + f.append(aField); + v.append(aValue); + } + } + } // end for + // insert into db + StringBuffer sqlBuf = + new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")"); + String sql = sqlBuf.toString(); + + logger.info("INSERT: " + sql); + + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql); + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = (String) theEntityValues.get(streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + pstmt.execute(); + pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL( (Database) + myselfDatabase)); + ResultSet rs = pstmt.executeQuery(); + rs.next(); + returnId = rs.getString(1); + theEntity.setId(returnId); + } + catch (SQLException sqe) { + throwSQLException(sqe, "insert"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + ; + } + freeConnection(con, pstmt); + } + return returnId; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + List streamedInput = theEntity.streamedInput(); + Map theEntityValues = theEntity.getValues(); + String id = theEntity.getId(); + String aField; + StringBuffer fv = new StringBuffer(); + boolean firstField = true; + //cache + invalidatePopupCache(); + // build sql statement + for (int i = 0; i < getFields().size(); i++) { + aField = (String) metadataFields.get(i); + // only normal cases + if (! (aField.equals(thePKeyName) || aField.equals("webdb_create") || + aField.equals("webdb_lastchange") || + (streamedInput != null && streamedInput.contains(aField)))) { + if (theEntityValues.containsKey(aField)) { + if (firstField == false) { + fv.append(", "); + } + else { + firstField = false; + } + if (aField.equals("to_parent_id")) { + fv.append(aField).append("=").append(JDBCStringRoutines.escapeStringLiteral((String)theEntityValues.get(aField))); + } + else { + fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String)theEntityValues.get(aField))).append("'"); + } + } + } + } + StringBuffer sql = new StringBuffer("update ").append(theTable).append( + " set ").append(fv); + // exceptions + if (metadataFields.contains("webdb_lastchange")) { + sql.append(",webdb_lastchange=NOW()"); + } + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + sql.append(",").append(streamedInput.get(i)).append("=?"); + } + } + sql.append(" where id=").append(id); + logger.info("UPDATE: " + sql); + // execute sql + try { + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql.toString()); + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = (String) theEntityValues.get(streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + pstmt.executeUpdate(); + } + catch (SQLException sqe) { + throwSQLException(sqe, "update"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + ; + } + freeConnection(con, pstmt); + } + } + } \ No newline at end of file diff --git a/source/mircoders/storage/DatabaseMessages.java b/source/mircoders/storage/DatabaseMessages.java index 7a9848b5..5457e73a 100755 --- a/source/mircoders/storage/DatabaseMessages.java +++ b/source/mircoders/storage/DatabaseMessages.java @@ -31,8 +31,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; @@ -47,12 +47,8 @@ import mir.storage.StorageObject; public class DatabaseMessages extends Database implements StorageObject{ - private static DatabaseMessages instance; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseMessages getInstance() { if (instance == null) { instance = new DatabaseMessages(); diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index fce632d0..3ed15543 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -1,101 +1,101 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseOther extends Database implements StorageObject{ - private static DatabaseOther instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseOther getInstance() { - if (instance == null) { - instance = new DatabaseOther(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseOther() { - super(); - - logger = new LoggerWrapper("Database.OtherMedia"); - - hasTimestamp = true; - theTable = "other_media"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityOther.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseOther extends Database implements StorageObject{ + private static DatabaseOther instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseOther getInstance() { + if (instance == null) { + instance = new DatabaseOther(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseOther() { + super(); + + logger = new LoggerWrapper("Database.OtherMedia"); + + hasTimestamp = true; + theTable = "other_media"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityOther.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseRights.java b/source/mircoders/storage/DatabaseRights.java index 3c87f892..772c318f 100755 --- a/source/mircoders/storage/DatabaseRights.java +++ b/source/mircoders/storage/DatabaseRights.java @@ -1,74 +1,74 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseRights extends Database implements StorageObject{ - private static DatabaseRights instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseRights getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseRights(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseRights() throws StorageObjectFailure { - super(); - - logger = new LoggerWrapper("Database.Rights"); - - hasTimestamp = false; - theTable = "rights"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseRights extends Database implements StorageObject{ + private static DatabaseRights instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseRights getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseRights(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseRights() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Rights"); + + hasTimestamp = false; + theTable = "rights"; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("name", true); + } + +} diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index 2445eb3a..09a15442 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -1,75 +1,75 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseTopics extends Database implements StorageObject{ - - private static DatabaseTopics instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseTopics getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseTopics(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseTopics() throws StorageObjectFailure { - super(); - - logger = new LoggerWrapper("Database.Topics"); - - hasTimestamp = false; - theTable = "topic"; - theEntityClass = mircoders.entity.EntityTopics.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseTopics extends Database implements StorageObject{ + + private static DatabaseTopics instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseTopics getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseTopics(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseTopics() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Topics"); + + hasTimestamp = false; + theTable = "topic"; + theEntityClass = mircoders.entity.EntityTopics.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } +} diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index edf5d966..5d91315a 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -1,87 +1,87 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.entity.Entity; -import mir.entity.EntityRelation; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -public class DatabaseUploadedMedia extends Database implements StorageObject { - private static DatabaseUploadedMedia instance; - private static EntityRelation relationMediaType; - - public static DatabaseUploadedMedia getInstance() { - if (instance == null ) { - synchronized(DatabaseUploadedMedia.class) { - if (instance == null ) { - instance = new DatabaseUploadedMedia(); - instance.myselfDatabase = instance; - } - } - } - - return instance; - } - - private DatabaseUploadedMedia() { - super(); - - logger = new LoggerWrapper("Database.UploadedMedia"); - - theTable="uploaded_media"; - theCoreTable="media"; - relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); - theEntityClass = mircoders.entity.EntityUploadedMedia.class; - } - - - /** - * returns the media_type that belongs to the media item (via entityrelation) - * where db-flag is_published is true - */ - public Entity getMediaType(Entity ent) throws StorageObjectFailure { - Entity type=null; - try { - type = relationMediaType.getOne(ent); - } - catch (Throwable t) { - logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage()); - - throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", t); - } - return type; - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.entity.Entity; +import mir.entity.EntityRelation; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +public class DatabaseUploadedMedia extends Database implements StorageObject { + private static DatabaseUploadedMedia instance; + private static EntityRelation relationMediaType; + + public static DatabaseUploadedMedia getInstance() { + if (instance == null ) { + synchronized(DatabaseUploadedMedia.class) { + if (instance == null ) { + instance = new DatabaseUploadedMedia(); + instance.myselfDatabase = instance; + } + } + } + + return instance; + } + + private DatabaseUploadedMedia() { + super(); + + logger = new LoggerWrapper("Database.UploadedMedia"); + + theTable="uploaded_media"; + theCoreTable="media"; + relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); + theEntityClass = mircoders.entity.EntityUploadedMedia.class; + } + + + /** + * returns the media_type that belongs to the media item (via entityrelation) + * where db-flag is_published is true + */ + public Entity getMediaType(Entity ent) throws StorageObjectFailure { + Entity type=null; + try { + type = relationMediaType.getOne(ent); + } + catch (Throwable t) { + logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage()); + + throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", t); + } + return type; + } + +} diff --git a/source/mircoders/storage/DatabaseUsers.java b/source/mircoders/storage/DatabaseUsers.java index 1373abb2..580cc260 100755 --- a/source/mircoders/storage/DatabaseUsers.java +++ b/source/mircoders/storage/DatabaseUsers.java @@ -1,75 +1,75 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseUsers extends Database implements StorageObject{ - - private static DatabaseUsers instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseUsers getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseUsers(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseUsers() throws StorageObjectFailure { - super(); - - logger = new LoggerWrapper("Database.Users"); - - hasTimestamp = false; - theTable = "webdb_users"; - theEntityClass = mircoders.entity.EntityUsers.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("login", true); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseUsers extends Database implements StorageObject{ + + private static DatabaseUsers instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseUsers getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseUsers(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseUsers() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Users"); + + hasTimestamp = false; + theTable = "webdb_users"; + theEntityClass = mircoders.entity.EntityUsers.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("login", true); + } +} diff --git a/source/mircoders/storage/DatabaseVideo.java b/source/mircoders/storage/DatabaseVideo.java index e1cdf4e2..0c720e89 100755 --- a/source/mircoders/storage/DatabaseVideo.java +++ b/source/mircoders/storage/DatabaseVideo.java @@ -1,100 +1,100 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseVideo extends Database implements StorageObject{ - - private static DatabaseVideo instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseVideo getInstance() { - if (instance == null) { - instance = new DatabaseVideo(); - instance.myselfDatabase = instance; - } - return instance; - } - - private DatabaseVideo() { - super(); - - logger = new LoggerWrapper("Database.Video"); - - hasTimestamp = true; - theTable = "video"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityVideo.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import freemarker.template.SimpleList; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseVideo extends Database implements StorageObject{ + + private static DatabaseVideo instance; + private static SimpleList publisherPopupData; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseVideo getInstance() { + if (instance == null) { + instance = new DatabaseVideo(); + instance.myselfDatabase = instance; + } + return instance; + } + + private DatabaseVideo() { + super(); + + logger = new LoggerWrapper("Database.Video"); + + hasTimestamp = true; + theTable = "video"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityVideo.class; + } + + public SimpleList getPopupData() throws StorageObjectFailure { + return getPopupData("title", true); + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + +} diff --git a/source/tool/BundleTool.java b/source/tool/BundleTool.java index 1a5edaa3..942a2b24 100755 --- a/source/tool/BundleTool.java +++ b/source/tool/BundleTool.java @@ -101,6 +101,7 @@ public class BundleTool { result = new PropertiesManipulator(); + // skip past the header in the slave bundle Iterator i = slave.getEntries(); while (i.hasNext()) { Object e = i.next(); @@ -130,6 +131,11 @@ public class BundleTool { else if (e instanceof PropertiesManipulator.Entry) { String key = ( (PropertiesManipulator.Entry) e).getKey(); String value = slave.get(key); + + if (value==null || value.length()==0) { + result.addComment("# missing (master value = \"" +master.get(key)+"\")"); + } + result.addEntry(key, value); } @@ -164,11 +170,18 @@ public class BundleTool { try { bundle = PropertiesManipulator.readProperties(new FileInputStream(new File(aSourceFile)), anEncoding); + } + catch (Throwable t) { + Throwable s = ExceptionFunctions.traceCauseException(t); + System.out.println("Unable to read sourcefile: " + s.toString()); + return; + } + try { PropertiesManipulator.writeProperties(bundle, new FileOutputStream(aBundle)); } catch (Throwable t) { - System.out.println("Unable to read master properties: " + t.getMessage()); + System.out.println("Unable to write bundle: " + t.toString()); return; } } diff --git a/templates/admin/FUNCTIONS.template b/templates/admin/FUNCTIONS.template new file mode 100755 index 00000000..296f540e --- /dev/null +++ b/templates/admin/FUNCTIONS.template @@ -0,0 +1,231 @@ +creates a full table incl. edit/delete entry.id + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ${indexVariable} + +   +
+ ${entry[indexVariable]} + + ${lang("delete")} + | ${lang("edit")} +
+ ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} +
+
+ +creates browse links, only called if necessary + +

+ +

+ + + + + + + + + + + + +
+ +

+
+ +extra navigation + +

+ [+] ${lang("add")}   + [<] ${lang("back")}   + [<<<] ${lang("head.start")} +

+
+ + + +4 functions to create Table rows with input-fields + + + + ${label}: + + + + + + + + + + + + ${label}: + + + + + + + + + + + + + + ${label}: + + + + + + + + + + + + ${label}: + + + + + + + + +complete search-form for contenentries, not sure if it works from everywhere + + +
+ + + + + + class="bg_neutral"> + + + + + + + + + + + + + + + +
class="table_head"class="small bg_neutral" valign="bottom"> ${lang("contentsearch.value")}class="table_head"class="small bg_neutral" valign="bottom"> ${lang("contentsearch.field")}class="table_head"class="small bg_neutral" valign="bottom"> ${lang("contentsearch.publishedstate")}class="table_head"class="small bg_neutral" valign="bottom"> ${lang("contentsearch.articletype")}class="table_head"class="small bg_neutral" valign="bottom"> ${lang("contentsearch.order")}class="table_head"class="small bg_neutral" valign="bottom">  
class="listrow2">class="listrow2"> + + class="listrow2"> + + class="listrow2"> + + class="listrow2"> + + class="listrow2"> + +
+
+ +
+ +browse function, only called if necessary + + +

+ + [ < ] ${lang("list.previous")}   + + + ${lang("list.next")} [ > ] + +

+
+
+ +multifunctional help - popup or not - big or small designs + + + + + + + + [ ? ] ${lang("help")}[?] + + + + + + + [ ? ] ${lang("help")} + + [?] + + + diff --git a/templates/admin/FUNCTIONS_media.template b/templates/admin/FUNCTIONS_media.template new file mode 100755 index 00000000..ccd09247 --- /dev/null +++ b/templates/admin/FUNCTIONS_media.template @@ -0,0 +1,143 @@ + + the complete medialist-template in two functions + not used for image-list because imagelist uses other display method + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
${lang("search")}:${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: [+] ${lang("add")}
+ + + + + + + + + + +   +
+ +
+ +
+ + + + + + + + + + + + + + + + + + class="listrow1"class="listrow2" > + + + + + + + + + + + + + + + + + + + + +
+ ${lang("media.icon")} + ${lang("media.title")} + ${lang("media.format")} + ${lang("media.size")} + ${lang("media.mediafolder")} + ${lang("media.creator")} +  
+ + + + ${entry.title}  +
${entry.description}
+
+ ${entry.media_descr}  + + ${entry.human_readable_size}  + + ${data.mediafolderHashdata[entry.to_media_folder]["name"]}  + + ${entry.creator}  +   + + ${lang("attach")} + + ${lang("delete")} + | ${lang("edit")} + +
+ ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} +
+ + ${lang("list.previous")}  + + + ${lang("list.next")} + +
${lang("no_matches_found")}
+ +
diff --git a/templates/admin/abuse.filters.template b/templates/admin/abuse.filters.template index 23b00ace..b8410ad5 100755 --- a/templates/admin/abuse.filters.template +++ b/templates/admin/abuse.filters.template @@ -5,7 +5,7 @@ - + - + - ${lang("delete")} + [${lang("delete")}]   @@ -30,36 +30,44 @@ + + - - ${config["Mir.Name"]} | ${lang("userlist.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("userlist.htmltitle")} + + + + + +

+ [ < ] ${lang("back")}   + ${lang("abuse.showlog")} +

+

+ + + + + + + - - -

- ${lang("back")} -

-
${lang("abuse.filter.type")}${lang("abuse.filter.expression")}  
- - - - - - - - - - - - -
${lang("abuse.filter.type")}${lang("abuse.filter.expression")} 
+ + + + -

- ${lang("back")} -

+ + + +

+ [ < ] ${lang("back")}   + ${lang("abuse.showlog")} +

+ + diff --git a/templates/admin/abuse.log.template b/templates/admin/abuse.log.template index cfe1ecd8..73d15072 100755 --- a/templates/admin/abuse.log.template +++ b/templates/admin/abuse.log.template @@ -6,21 +6,23 @@ -

- ${lang("back")} -

- - + +

+ [ < ] ${lang("back")}   + ${lang("abuse.showfilters")} +
+

+
- - - - + + + + - + + + +
${lang("abuse.log.time")}${lang("abuse.log.address")}${lang("abuse.log.object")}${lang("abuse.log.browser")}${lang("abuse.log.time")}${lang("abuse.log.address")}${lang("abuse.log.object")}${lang("abuse.log.browser")}
${l.timestamp["yyyy-MM-dd HH:mm"]} ${l.ip} @@ -33,10 +35,14 @@ ${l.browser}
 

- ${lang("back")} + [ < ] ${lang("back")}   + ${lang("abuse.showfilters")}

diff --git a/templates/admin/abuse.template b/templates/admin/abuse.template index 34296695..0c82b95e 100755 --- a/templates/admin/abuse.template +++ b/templates/admin/abuse.template @@ -1,108 +1,131 @@ - - ${config["Mir.Name"]} | ${lang("userlist.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("abuse.htmltitle")} + + - - -

- ${lang("back")} -

-

- ${lang("abuse.showlog")} -

-

- ${lang("abuse.showfilters")} -

-

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
${lang("abuse.setting")}${lang("abuse.value")}
- ${lang("abuse.disableopenpostings")} - - checked="1"> -
- ${lang("abuse.openpostingpassword")} - - checked="1"> -
- ${lang("abuse.logpostings")} - - checked="1"> -
- ${lang("abuse.logsize")}' - - -
- ${lang("abuse.cookies")} - - checked="1"> -
- ${lang("abuse.articleaction")} - - -
- ${lang("abuse.commentaction")} - - -
-

- -

+ - ${lang("abuse.showfilters")} -

+ + +

+ [ < ] ${lang("back")} +

-

- ${lang("back")} -

+ + + + + +
- - +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
${lang("abuse.setting")}${lang("abuse.value")}
+ ${lang("abuse.disableopenpostings")} + + checked="1"> +
+ ${lang("abuse.openpostingpassword")} + + checked="1"> +
 
+ ${lang("abuse.logpostings")} + + checked="1"> +
+ ${lang("abuse.logsize")} + + +
 
+ ${lang("abuse.cookies")} + + checked="1"> +
 
+ ${lang("abuse.articleaction")} + + +
+ ${lang("abuse.commentaction")} + + +
+ +
+
+ +
+ +

+ > ${lang("abuse.showlog")}
+ > ${lang("abuse.showfilters")} +

+ +
+ + + +

+ [ < ] ${lang("back")} +

+ + + diff --git a/templates/admin/articletype.template b/templates/admin/articletype.template index 62af13e2..cc7efa45 100755 --- a/templates/admin/articletype.template +++ b/templates/admin/articletype.template @@ -2,50 +2,48 @@ ${config["Mir.Name"]} | ${lang("articletype.htmltitle")} - - - - -
+ + + + + - - - - - - - + + + + + + + - - - - - - - - - - - - -
- ${lang("articletype.id")}: - ${data.id} -
- ${lang("articletype.name")}: - -
- - - - - - - -
+ + + + + + + + + + + + +
+ ${lang("articletype.id")}: + + ${data.id} +
+ + + + + +
+ + - +

[<] ${lang("back")}  

- - + + diff --git a/templates/admin/articletypelist.template b/templates/admin/articletypelist.template index a07d8b14..73556119 100755 --- a/templates/admin/articletypelist.template +++ b/templates/admin/articletypelist.template @@ -4,83 +4,32 @@ + + - - -

- ${lang("add")} | - ${lang("back")} -

+ + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - -
- - ${lang("articletype.id")} - - - - ${lang("articletype.name")} - - -   -
${entry.id} ${entry.name}  -   - ${lang("delete")} - | ${lang("edit")} - -
- - ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} - -  
-

- -

- - - - - - - - - - - - -
-
- + + +

${lang("no_matches_found")}

-

- ${lang("add")} | - ${lang("back")} -

diff --git a/templates/admin/audio.template b/templates/admin/audio.template index 5e431003..215a51a0 100755 --- a/templates/admin/audio.template +++ b/templates/admin/audio.template @@ -11,31 +11,32 @@ function openWin(url) { +
- - - + + + - - - - + + + +
- - ${lang("media.nr_of_media")}
-
-
-   -
+ ${lang("media.nr_of_media")} :
+
+    +
+ +
- - - + + + @@ -45,121 +46,98 @@ function openWin(url) { - - + - - - ${lang("media.created")}: ${data.webdb_create} - / ${lang("media.changed")} ${data.webdb_lastchange}
- ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
- ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
- ${lang("media.size")}: ${data.human_readable_size}
- ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
- +    + + + ${lang("media.created")}: ${data.webdb_create} + / ${lang("media.changed")} ${data.webdb_lastchange}
+ ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
+ ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
+ ${lang("media.size")}: ${data.human_readable_size}
+ ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
+
- - ${lang("media.mediafolder")}: - - - + + ${lang("media.mediafolder")}: + + + + - - - - - ${lang("media.description")}: - - - - - - ${lang("media.date")}: - - - - - - - ${lang("media.location")}: - - - - - - ${lang("media.creator")}: - - - - - - - ${lang("media.keywords")}: - - - - - - ${lang("media.comment")}: - - - - - - ${lang("media.source")}: - - - + + + + + + + + + + +   + + - - ${lang("media.is_published")} checked> - + + ${lang("media.is_published")} : + + + checked> + +   + - - - + + ${lang("media.title")}: - - + + - - - - -
+ + + +   - + +
+ +
- - + + ${lang("media.title")}: - + - + - + ${lang("media.is_published")} checked> - - +    + + +

[<] ${lang("list")}  

+ diff --git a/templates/admin/audiolist.template b/templates/admin/audiolist.template index c01f4013..0a67543a 100755 --- a/templates/admin/audiolist.template +++ b/templates/admin/audiolist.template @@ -7,107 +7,11 @@ + + +

 

+ - - - - - - - - - - - - - - - - class="list1"class="list2" > - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: 
- - - - - - - - -
-
-
- ${lang("media.icon")} - ${lang("media.title")} - ${lang("media.format")} - ${lang("media.size")} - ${lang("media.mediafolder")} - ${lang("media.creator")}
- - ${entry.title}  -
${entry.description}
${entry.media_descr} ${entry.human_readable_size} ${data.mediafolderHashdata[entry.to_media_folder]["name"]} ${entry.creator}   - ${lang("attach")} - - ${lang("delete")} - | ${lang("edit")} - -
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
- - zurueck  - - -weiter - -
${lang("no_matches_found")}
diff --git a/templates/admin/breaking.template b/templates/admin/breaking.template index 8c5e3702..cc2b5da3 100755 --- a/templates/admin/breaking.template +++ b/templates/admin/breaking.template @@ -7,36 +7,46 @@ + + +
+ - - + + + - - + -
- ${lang("breaking.date")}: + + ${lang("breaking.date")}: + ${data.webdb_create_formatted}
- ${lang("breaking.text")}: ${lang("breaking.textinfo")} - + + ${lang("breaking.text")}:
${lang("breaking.textinfo")}
+
- - - - + + + + + +
+ +

[<] ${lang("back")}

diff --git a/templates/admin/breakinglist.template b/templates/admin/breakinglist.template index 34b75cc8..39975cb7 100755 --- a/templates/admin/breakinglist.template +++ b/templates/admin/breakinglist.template @@ -6,43 +6,44 @@ - - - - - - - - - - - class="list1"class="list2" > - - - - - - - - - -
${lang("breaking.date")}${lang("breaking.text")} 
${entry.webdb_create_formatted} ${entry.text}  ${lang("delete")} - | ${lang("edit")}
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
- -

- - ${lang("list.previous")}  - - -${lang("list.next")} - - - -

${lang("no_matches_found")}

-
- + + + + + configure this template here + + + + + + + + + + + + + + +

+ [+] ${lang("add")}   + [<<<] ${lang("head.start")} +

+ + + + +

${lang("no_matches_found")}

+
+ +

+ [+] ${lang("add")}   + [<<<] ${lang("head.start")} +

+ + + diff --git a/templates/admin/comment.template b/templates/admin/comment.template index 408e365c..2673cba7 100755 --- a/templates/admin/comment.template +++ b/templates/admin/comment.template @@ -5,7 +5,8 @@ - + +
@@ -20,20 +21,25 @@ - - + + + + - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - - - - -
+ +
${lang("comment.htmltitle")}
${lang("comment.date")} + ${utility.encodeHTML(utility.encodeHTML(data.webdb_create))}
+ +
${lang("comment.status")} +
- ${lang("comment.title")} - - -
- ${lang("comment.creator")} - - -
- ${lang("comment.url")} - - -
- ${lang("comment.email")} - - -
- ${lang("comment.phone")} - - -
- ${lang("comment.address")} - - -
+ ${lang("comment.language")} +
+ ${lang("comment.text")}
${lang("comment.html")} checked>
+
+ ${lang("comment.published")} checked> @@ -132,6 +93,12 @@
+ +

+ [<] ${lang("list")}   + [<<<] ${lang("head.start")} +

+ diff --git a/templates/admin/commentlist.template b/templates/admin/commentlist.template index 165ab7fd..4675103a 100755 --- a/templates/admin/commentlist.template +++ b/templates/admin/commentlist.template @@ -8,168 +8,186 @@ +
- - + + - - - - - - - - - - +
${lang("commentsearch.field")}${lang("commentsearch.value")}${lang("commentsearch.publishedstate")}${lang("commentsearch.status")}${lang("commentsearch.order")}
- -
+ + + + + + + + - - - - - - -
${lang("commentsearch.field")}${lang("commentsearch.value")}${lang("commentsearch.publishedstate")}${lang("commentsearch.status")}${lang("commentsearch.order")} 
- - - - - - - - - -
+ + + + + + + + + + + + + + + + + + + + +
- -
- - - + + + + + +

+   (${lang("commentlist.activate")}) +

+
-

- -

- + + + + + + -
+ + [ ${lang("list.previous")} ]  + + + [ ${lang("list.next")} ]  + +
- - - - - - - - + + + + + - - class="list1"class="list2"> - - + + class="listrow1"class="listrow2"> + - - ${lang("comment.creator")}: ${entry.creator}
- ${utility.encodeHTML(entry.description)} -
URL: ${entry.main_url}
-
- - - [${lang("comment.operation."+op)}] - - - - - [${lang("comment.operation."+op)}] - - - - - - | - ${lang("edit")} - + + + - - - - - - - - - -
- - ${lang("list.previous")}  - - - ${lang("list.next")}  - -

${lang("comment.date")}

${lang("comment.title")}/ ${lang("comment.creator")}
- ${lang("comment.text")}

 
+ ${lang("comment.date")} + + ${lang("comment.title")}/ ${lang("comment.creator")}
+ ${lang("comment.text")} +
+   +
${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
- ${lang("comment.hidden")}- -
+ ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
+ ${lang("commentlist.hidden")}- +
- ${lang("comment.article")} - - ${utility.encodeHTML(entry.to_content.title)} - - (${lang("articletypes."+entry.to_content.article_type.name)}) -
- [${lang("commentlist.allcomments")}] -
- - ${lang("commentstatus." + entry.status.name)} - - ${entry.title}
+
+ + + + ${lang("comment.article")}: + + ${utility.encodeHTML(entry.to_content.title)} + + (${lang("articletypes."+entry.to_content.article_type.name)})
+ [${lang("commentlist.allcomments")}]
+
+ + ${entry.title}   + + ${lang("by")}: ${entry.creator} + +
+ ${utility.encodeHTML(entry.description)} + +
URL: ${entry.main_url}
+
${lang("commentstatus." + entry.status.name)} -   +
+ + + [ ${lang("comment.operation."+op)} ] + + + + + [ ${lang("comment.operation."+op)} ] + + + + + + | + ${lang("edit")} +
+   + [${lang("delete")}] +
-   - ${lang("delete")} - -
${count} ${lang("records")} / ${lang("show_from_to", from, to)}
- - ${lang("list.previous")}  - - - ${lang("list.next")}  - -
+ + + ${count} ${lang("records")} / ${lang("show_from_to", from, to)} + + + + + + + [ ${lang("list.previous")} ]  + + + [ ${lang("list.next")} ]  + + + + - -

- -

- -
+ +

+   (${lang("commentlist.activate")}) +

+ +
-

${lang("no_matches_found")}

+

${lang("no_matches_found")}

diff --git a/templates/admin/commentstatus.template b/templates/admin/commentstatus.template index 4b4dd64a..7e0539e3 100755 --- a/templates/admin/commentstatus.template +++ b/templates/admin/commentstatus.template @@ -4,7 +4,7 @@ - +
@@ -18,21 +18,16 @@ - - + + + - - - - -
- ${lang("commentstatus.id")}: + + ${lang("commentstatus.id")}: ${data.id}
- ${lang("commentstatus.name")}: - -
+ @@ -45,7 +40,7 @@
- +

[<] ${lang("back")}  

diff --git a/templates/admin/commentstatuslist.template b/templates/admin/commentstatuslist.template index be06706e..3187c891 100755 --- a/templates/admin/commentstatuslist.template +++ b/templates/admin/commentstatuslist.template @@ -4,85 +4,36 @@ - + + + -

- ${lang("add")} | - ${lang("back")} -

+ configure this template here + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - -
- - ${lang("commentstatus.id")} - - - - ${lang("commentstatus.name")} - - -   -
${entry.id} ${entry.name}  -   - ${lang("delete")} - | ${lang("edit")} - -
- - ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} - -  
-

- -

- - - - - - - - - - - - -
-
- -

${lang("no_matches_found")}

+ + + + +

${lang("no_matches_found")}

-

- ${lang("add")} | - ${lang("back")} -

+ + diff --git a/templates/admin/confirm.template b/templates/admin/confirm.template index ccb7e138..4d23f0f9 100755 --- a/templates/admin/confirm.template +++ b/templates/admin/confirm.template @@ -5,18 +5,12 @@ - +
- - - - - -
-

${lang("confirm.really_delete")}

-
-
+ - -
+

${lang("confirm.really_delete")}

+

@@ -28,12 +22,14 @@ - - - -

+
+
+ ${lang("confirm.text")} +

+ +
+ +
diff --git a/templates/admin/content.template b/templates/admin/content.template index 246d5615..85be6bf0 100755 --- a/templates/admin/content.template +++ b/templates/admin/content.template @@ -1,342 +1,329 @@ - - ${lang("content.htmltitle")} - - - + + ${lang("content.htmltitle")} + + -
- - - - - - - - + + + + + + + + - - - - - - +
  - - ${lang("content.comments")} - - - ${lang("content.published")} - checked> - - - - - -
+ + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + - - - - - - - - - - + + + + + + + + + + + + +
+ + [ ${lang("content.comments")} ] + + + ${lang("content.published")} : + checked> + + + + + +
- ${lang("content.import_date")}: - - ${article.date} -  
- ${lang("content.lastchange_date")}: - - ${utility.encodeHTML(article.webdb_lastchange)}
-
 
- ${lang("content.create_date")}: - - ${utility.encodeHTML(article.webdb_create)}

${lang("edit")} (yyyy-mm-dd [HH:mm]): -
-
 
- ${lang("content.articletype")} / - ${lang("content.language")}: - - - -
- ${lang("content.topic")}: - - - - - - - - - - - - - - - - - - -
- checked>${t.title} - -   -
- - -
-
+ id # : + + ${article.id} +
+ ${lang("content.lastchange_date")}: + + ${utility.encodeHTML(article.webdb_lastchange)}
+
- ${lang("content.title")}:  - -
-
- ${lang("content.subtitle")}: 
-
- - -
- ${lang("content.location")}: - - -
- ${lang("content.creator")}: - -
-
- ${lang("content.creator.email")}/${lang("content.creator.url")}: - - - -
- ${lang("content.creator.address")}/${lang("content.creator.telephone")}: - - - -
- ${lang("content.abstract")}: - - -
- ${lang("content.content")}: -
- ${lang("content.html")} - checked>  -
- -
- ${lang("content.comment")}:
- ${lang("content.internal")} -
- -
    - - - - - -
- ${lang("content.family")} -
- ${lang("content.parent")}: - - - ${utility.encodeHTML(article.parent.title)} - ${lang("content.viewparent")} | - ${lang("content.clearparent")} | - - ${lang("content.selectparent")} -
- ${lang("content.children")}: - - ${lang("content.viewchildren")} -
+ ${lang("content.create_date")}: + + ${utility.encodeHTML(article.webdb_create)}
${lang("edit")}: +   (yyyy-mm-dd [HH:mm]) +
- ${lang("content.attachments")} -
+ ${lang("content.articletype")}: + + +
+ ${lang("content.language")} + + +
+ ${lang("content.topic")}: + + + + + + + + + + + + + + + + + + +
+ checked> + ${t.title} + +   +
+ + +
+
- ${lang("content.images")}: - - edit - ${lang("delete")} -
- ${lang("content.images")}: - - ${lang("content.addimage")} | - ${lang("content.uploadimage")} -
+ ${lang("content.abstract")}: + + +
- ${lang("content.audio")}: - - edit - ${lang("delete")} -
- ${lang("content.audio")}: - - ${lang("content.addaudio")} | - ${lang("content.uploadaudio")} -
+ ${lang("content.content")}: +
+ ${lang("content.html")}  + checked>   +
+ +
+ ${lang("content.comment")}:
+ ${lang("content.internal")} +
+ +
+ + + + + +
+ + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ ${lang("content.family")} +
+ ${lang("content.parent")}: + + + ${utility.encodeHTML(article.parent.title)}
+ ${lang("content.viewparent")} | + ${lang("content.clearparent")} | +
+  ${lang("content.selectparent")} +
+ ${lang("content.children")}: + + ${lang("content.viewchildren")} +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ${lang("content.attachments")} +
+ ${lang("content.images")}: + + [+] ${lang("content.addimage")} | + ${lang("content.uploadimage")} +
+ edit  + + [-] ${lang("delete")} +
+ ${lang("content.audio")}: + + [+] ${lang("content.addaudio")} | + ${lang("content.uploadaudio")} +
+ edit  + + [-] ${lang("delete")} +
+ ${lang("content.video")}: + + [+] ${lang("content.addvideo")} | + ${lang("content.uploadvideo")} +
+ edit  + + [-] ${lang("delete")} +
+ ${lang("content.other")}: + + [+] ${lang("content.addother")} | + ${lang("content.uploadother")} +
+ edit  + + [-] ${lang("delete")} +
+ +
- - - - ${lang("content.video")}: - - - edit - ${lang("delete")} - - - - - - ${lang("content.video")}: - - - ${lang("content.addvideo")} | - ${lang("content.uploadvideo")} - - - - - - ${lang("content.other")}: - - - edit - ${lang("delete")} - - - - - - ${lang("content.other")}: - - - ${lang("content.addother")} | - ${lang("content.uploadother")} - - -
- -
- - - + + + + + diff --git a/templates/admin/contentlist.template b/templates/admin/contentlist.template index 2d540056..edfe822c 100755 --- a/templates/admin/contentlist.template +++ b/templates/admin/contentlist.template @@ -3,205 +3,137 @@ - - + + - - + + - - ${config["Mir.Name"]} | ${lang("contentlist.htmltitle")} - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - -
${lang("contentsearch.value")}${lang("contentsearch.field")}${lang("contentsearch.publishedstate")}${lang("contentsearch.articletype")}${lang("contentsearch.order")}
- - - - - - - - - -
-
-
- - - - - -
- - - - -

- -

- - - - - - - - - - - - - - - class="list1"class="list2"> - - - - - - - - - -
- ${lang("content.creationdate")}
- ${lang("content.modificationdate")}
- ${lang("content.status")} -
- ${lang("content.type")} - ${lang("content.title")}
- ${lang("content.creator")} -
- ${lang("content.comment")} -  
- - ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
- ${entry.changedate.formatted["dd.MM.yyyy HH:mm"]}
- F-H- -
-
- - - - ${lang("articletypes." + entry.article_type.name)} - - - ${entry.title} -
- ${entry.creator}
- - - - - [${lang("content.operation."+op)}] - - - - - [${lang("content.operation."+op)}] - - - - - - - | - - ${lang("edit")} | - ${lang("contentlist.comments")} (${entry.commentcount}) - - - ${lang("contentlist.select")} - - -
-
class="list3"class="list4" valign="top"> - - ${entry.comment}  - - - - - ${lang("delete")} - - -
- ${count} ${lang("records")} / ${lang("show_from_to", from, to)} -
- - - -

- -

- -
-
-

- - - - ${lang("list.previous")} - - - ${lang("list.next")} - - - - -

${lang("no_matches_found")}

-
- - - + + ${config["Mir.Name"]} | ${lang("contentlist.htmltitle")} + + + + + + + + + + + + + + + +
+ + + +

+   ( ${lang("commentlist.activate")}) +

+ + + + + + + + + + + + + + + + + class="listrow1"class="listrow2"> + + + + + + + + + +
+ + ${lang("content.creationdate")}
+ ${lang("content.modificationdate")}
+ ${lang("content.status")} +
+
+ ${lang("content.type")} - ${lang("content.title")}
+ ${lang("content.creator")} +
+ ${lang("content.comment")} +  
+ ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
+ ${entry.changedate.formatted["dd.MM.yyyy HH:mm"]}
+ Pub.- HTML- +
+ ${entry.title}
+ ${lang("by")}: ${entry.creator}
+ (${lang("articletypes." + entry.article_type.name)}) + + + + [ ${lang("content.operation."+op)} ] + + + + + [ ${lang("content.operation."+op)} ] + + + + + + | + ${lang("edit")} | + ${lang("contentlist.comments")} (${entry.commentcount}) + + + ${lang("contentlist.select")} + +
class="listrow3"class="listrow4" valign="top"> + ${entry.comment}  + + + [${lang("delete")}] + +
+ ${count} ${lang("records")} / ${lang("show_from_to", from, to)} +
+ + + +

+   ( ${lang("commentlist.activate")}) +

+ +
+
+ + + + + + + +

${lang("no_matches_found")}

+
+ + + diff --git a/templates/admin/error.template b/templates/admin/error.template index 2a0395d0..9c79dc29 100755 --- a/templates/admin/error.template +++ b/templates/admin/error.template @@ -5,33 +5,16 @@ - - - - - - - - - - - - - -
-

${lang("error.title")}

-
-
-

${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])} -

-

-

${data.date} -- ${data.errorstring} -

-

-

- ${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])} -

-

+ +
+ +

${lang("error.title")}

+

${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

+


${data.date} -- ${data.errorstring}

+

${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

+ +
+ diff --git a/templates/admin/fileedit.template b/templates/admin/fileedit.template index 75f57a9f..97cfada5 100755 --- a/templates/admin/fileedit.template +++ b/templates/admin/fileedit.template @@ -8,42 +8,33 @@ -
-${lang("fileedit.filename")} : ${filename} +

+ ${lang("fileedit.filename")} : ${filename}
+ ${lang("fileedit.subdirectory")} : ${subdirectory} +


- - - - - - -
- - - -   - - - + +   + +

+ +

+   +


- -${lang("preview")} - -
- +

${lang("preview")} :

+
${text} - -
+

- diff --git a/templates/admin/fileeditlist.template b/templates/admin/fileeditlist.template index 680fe46c..9ca7fab3 100755 --- a/templates/admin/fileeditlist.template +++ b/templates/admin/fileeditlist.template @@ -1,82 +1,86 @@ ${config["Mir.Name"]} | ${lang("fileeditlist.htmltitle")} - + + + + + + - -

+ + + + +
+ + + + + + + + + + +
+ + + + + + + + + -
${lang("fileeditlist.dirname")} 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
${lang("fileeditlist.dirname")} 
.. ${lang("edit")}
${entry} ${lang("edit")}
+ +
 .. ${lang("edit")}
${entry} ${lang("edit")}
- - + + - - - - + + + + + - - - - - - - - - - - - +
-
${lang("fileeditlist.filename")} 
${entry} ${lang("edit")}
+ + + + + + + + + + + + + + +
${lang("fileeditlist.filename")} 
${entry} ${lang("edit")}
-

+ + +

-

${lang("no_matches_found")}

+

${lang("no_matches_found")}

diff --git a/templates/admin/foot.template b/templates/admin/foot.template index be714bc3..cc328978 100755 --- a/templates/admin/foot.template +++ b/templates/admin/foot.template @@ -1,11 +1,23 @@ - - - - - - - - +
+

- ${lang("foot.top")} - ${config["Mir.Shortname"]} - ${config["Mir.Version"]}
+ + + + + +
+ ${lang("foot.top")} + + |   ${lang("back")} [ < ]   + + + ${config["Mir.Shortname"]} - ${config["Mir.Version"]} +
+ + + + + + + diff --git a/templates/admin/head.template b/templates/admin/head.template index b482efc8..ea79e7c5 100755 --- a/templates/admin/head.template +++ b/templates/admin/head.template @@ -1,22 +1,18 @@ - - - - - - - - - - +
-   - - ${config["Mir.Name"]}
-${lang("back")} - - ${lang("head.start")} | - ${lang("head.logout")} | - ${lang("head.help")} | ${lang("head.search")}
-
+ + + +
+   + ${config["Mir.Name"]} + + + [ < ] ${lang("back")}  | + + ${lang("head.start")} | + ${lang("head.logout")} +
+
diff --git a/templates/admin/head_nonavi.template b/templates/admin/head_nonavi.template index 9019b5a2..0217fd09 100755 --- a/templates/admin/head_nonavi.template +++ b/templates/admin/head_nonavi.template @@ -1,14 +1,18 @@ - - - + + + + + + + - +
-   - - ${config["Mir.Name"]}
- ${login_user.login} ${lang("head.logged_in")} / - ${lang("head.logout")} -
+   + ${config["Mir.Name"]} +
+ ${login_user.login} ${lang("head.logged_in")} | + ${lang("head.logout")} +


diff --git a/templates/admin/hiddenlist.template b/templates/admin/hiddenlist.template index 26357a46..9bc61911 100755 --- a/templates/admin/hiddenlist.template +++ b/templates/admin/hiddenlist.template @@ -2,55 +2,63 @@ ${config["Mir.Name"]} | ${lang("start.content.hidden")} - - - - + diff --git a/templates/admin/image.template b/templates/admin/image.template index 4d34c23c..623e733f 100755 --- a/templates/admin/image.template +++ b/templates/admin/image.template @@ -1,173 +1,147 @@ - - ${config["Mir.Name"]} | ${lang("image.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("image.htmltitle")} + + + - + - - - + + - -
- - - -
+ + + + + + + - + +
+ ${lang("start.content.hidden")} +
-
+ - ${lang("month")} - - ${lang("year")} - - -   - - + ${lang("month")} + + ${lang("year")} + + +   + +
-
@@ -60,43 +68,41 @@ - - - + + +
-

${lang("start.content.hidden")} | ${lang("month")}: ${data.month} , ${lang("year")}:${data.year}

-
+

${lang("start.content.hidden")} | ${lang("month")}: ${data.month} , ${lang("year")}:${data.year}

+
-

-${lang("content.title")}: ${i.title}
-${lang("content.creator")}: ${i.creator}
-${lang("message.date")}: ${i.webdb_create_formatted}
-
-additional media, type: audio
-additional media, type: video
-additional media, type: other
-additional media, type: image
-

- -

-${lang("content.abstract")}:
-${i.description_parsed}

- -

-${lang("content.content")}:
-${i.content_data_parsed} -

-

 

-
-

 

- +

${i.title}
+ ${lang("content.creator")}: ${i.creator}
+ ${lang("message.date")}: ${i.webdb_create_formatted}
+
+ additional media, type: audio
+ additional media, type: video
+ additional media, type: other
+ additional media, type: image
+

+ +

+ ${lang("content.abstract")}:
+ ${i.description_parsed} +

+ +

+ ${lang("content.content")}:
+ ${i.content_data_parsed} +

+

 

+
+

 

- - -
${lang("no_matches_found")}
${lang("no_matches_found")}
- - - - -
- - ${lang("media.nr_of_media")}
-
-
-   -
- -
-
- - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - ${lang("media.created")}: ${data.webdb_create} / ${lang("media.changed")} ${data.webdb_lastchange}
- ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
- ${lang("media.format")}: ${data.media_descr} / ${data.img_width}x${data.img_height} / ${data.imgformatHashdata[to_img_format]["name"]} / ${data.imglayoutHashdata[to_img_layout]["name"]} / ${data.imgcolorHashdata[to_img_color]["name"]}
- ${lang("media.size")}: ${data.human_readable_size}
- ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
- ${lang("media.type")}: ${data.imgtypeHashdata[to_img_type]["name"]}
-
-
- ${lang("media.mediafolder")}: - -
- ${lang("media.description")}:
- ${lang("media.date")}: -
- ${lang("media.location")}:
- ${lang("media.creator")}: - -
- ${lang("media.keywords")}:
- ${lang("media.comment")}:
- ${lang("media.source")}:
- ${lang("media.is_published")} checked> -
- - ${lang("media.title")}: - - - -
-
-
- ${lang("media.title")}: - - -
- - - - - ${lang("media.is_published")} checked> - - - -
+ + + + + + + + + +
+ ${lang("media.nr_of_media")} :
+
+    +
+ +
- - + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +    + + ${lang("media.created")}: ${data.webdb_create} + / ${lang("media.changed")} ${data.webdb_lastchange}
+ ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
+ ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
+ ${lang("media.size")}: ${data.human_readable_size}
+ ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
+
+ ${lang("media.mediafolder")}: + + +
 
+ ${lang("media.is_published")} : + + checked> +
 
+ ${lang("media.title")}: + + +
+   + +
+
+ ${lang("media.title")}: + + +
+ + + + ${lang("media.is_published")} checked> +    + +
+ +

[<] ${lang("list")}  

+ + + diff --git a/templates/admin/imagelist.template b/templates/admin/imagelist.template index 2ba619b4..7359b0e1 100755 --- a/templates/admin/imagelist.template +++ b/templates/admin/imagelist.template @@ -2,114 +2,98 @@ ${config["Mir.Name"]} | ${lang("imagelist.htmltitle")} + + + + - - - - +
- - - - - - - - - - - - - - - - - -
${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: 
- - - - - - - - -
-
-
+ + + + + + + + + - - - - - - - - - - - class="list1"class="list2" > - - - - - - - - - - - - - + + + class="listrow1"class="listrow2" > + + + + + + + + + + + + + + + + - - +
+ ${lang("media.icon")} + ${lang("media.title")} + ${lang("media.format")} + ${lang("media.size")} + ${lang("media.mediafolder")} + ${lang("media.creator")} +  
- ${lang("media.icon")} - ${lang("media.title")} - ${lang("media.format")} - ${lang("media.size")} - ${lang("media.mediafolder")} - ${lang("media.creator")}
- - - ${entry.title}  -
${entry.description}
${entry.media_descr} ${entry.human_readable_size} ${data.mediafolderHashdata[entry.to_media_folder]["name"]} ${entry.creator}   - ${lang("attach")} - - ${lang("delete")} - | ${lang("edit")} - -
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
+ + + + + + + + ${entry.title}  +
${entry.description}
+
+ ${entry.media_descr}  + + ${entry.human_readable_size}  + + ${data.mediafolderHashdata[entry.to_media_folder]["name"]}  + + ${entry.creator}  +   + + ${lang("attach")} + + ${lang("delete")} + | ${lang("edit")} + +
+ ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} +
+ + ${lang("list.previous")}  + + + ${lang("list.next")} + +
- - zurueck  - - -weiter - -
${lang("no_matches_found")}
${lang("no_matches_found")}
+ diff --git a/templates/admin/infomessage.template b/templates/admin/infomessage.template index a224f1d3..b513a25f 100755 --- a/templates/admin/infomessage.template +++ b/templates/admin/infomessage.template @@ -11,6 +11,12 @@

${lang("infomessage."+message, argument1, argument2)}

+

+
+ [<<<] ${lang("head.start")}    + +

+ diff --git a/templates/admin/language.template b/templates/admin/language.template index 1581f888..50e73bbb 100755 --- a/templates/admin/language.template +++ b/templates/admin/language.template @@ -5,40 +5,29 @@ - + +
- - - - - - - - - - - - + + - + + +
- ${lang("language.name")}: - -
- ${lang("language.code")}: - -
+ + - -
+ +

[<] ${lang("back")}  

diff --git a/templates/admin/languagelist.template b/templates/admin/languagelist.template index 4a4f0ea7..3e61489a 100755 --- a/templates/admin/languagelist.template +++ b/templates/admin/languagelist.template @@ -4,56 +4,33 @@ + + + -

- ${lang("add")} | - ${lang("back")} -

+ configure this template here + + + + + + + + + + + - - - - - - - - - - - - - - - - - - -
${lang("language.name")}${lang("language.code")} 
${entry.name} ${entry.code}  -   - ${lang("delete")} | - ${lang("edit")} - -
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
- -

- - ${lang("list.previous")}  - - - ${lang("list.next")} - - -

${lang("no_matches_found")}

+ + + + +

${lang("no_matches_found")}

- -

- ${lang("add")} | - ${lang("back")} -

- + + diff --git a/templates/admin/linksimcslist.template b/templates/admin/linksimcslist.template index bdde488b..1caa0128 100755 --- a/templates/admin/linksimcslist.template +++ b/templates/admin/linksimcslist.template @@ -1,108 +1,108 @@ - - - ${config["Mir.Name"]} | ${lang("linkimcslist.htmltitle")} - - - - - - - -
- - - - - - - - - - - - - - - - - -
${lang("linkimcslist.search_in")}:${lang("linkimcs.parent")}:${lang("linkimcs.language")}: 
- - - - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - class="list1"class="list2" > - - - - - - - - - - - - -
- ${lang("linkimcs.name")} - ${lang("linkimcs.parent")} - ${lang("linkimcs.url")} - ${lang("linkimcs.sort_by")} - ${lang("linkimcs.language")} -  
${entry.title} ${parent}${entry.url}${entry.sortpriority}${data.language} ${lang("delete")} - | ${lang("edit")} -
- ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} 
-

- - ${lang("list.previous")}  - - -${lang("list.next")} - - - -

${lang("no_matches_found")}

-
- - - \ No newline at end of file + + + ${config["Mir.Name"]} | ${lang("linkimcslist.htmltitle")} + + + + + + + +
+ + + + + + + + + + + + + + + + + +
${lang("linkimcslist.search_in")}:${lang("linkimcs.parent")}:${lang("linkimcs.language")}: 
+ + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + class="list1"class="list2" > + + + + + + + + + + + + +
+ ${lang("linkimcs.name")} + ${lang("linkimcs.parent")} + ${lang("linkimcs.url")} + ${lang("linkimcs.sort_by")} + ${lang("linkimcs.language")} +  
${entry.title} ${parent}${entry.url}${entry.sortpriority}${data.language} ${lang("delete")} + | ${lang("edit")} +
+ ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} 
+

+ + ${lang("list.previous")}  + + +${lang("list.next")} + + + +

${lang("no_matches_found")}

+
+ + + diff --git a/templates/admin/login.template b/templates/admin/login.template index 86f84463..e5aeaa68 100755 --- a/templates/admin/login.template +++ b/templates/admin/login.template @@ -3,7 +3,6 @@ ${config["Mir.Name"]} | ${lang("login.htmltitle")} - - -
+ + + +

- ${lang("login.info", "" + + "\">" + config["Mir.Contact-email.name"] + - "" + "" ) } -

-
+ +
+
+
${lang("login.title")}
+ +
+ +
- - - - - - - - - - - - - - - - - - - - - -
- - ${lang("login.title")} - -
- ${lang("login.name")} - - -
- ${lang("login.password")} - - -
- ${lang("login.language")} - - -
  - -
+ + + + + + + + + + + + + + + + + + + + + +
${lang("login.name")}:
${lang("login.password")}:
${lang("login.language")}: + +
+ +
+
-
+ + +
+
+ + diff --git a/templates/admin/media.template b/templates/admin/media.template index 434bfd52..07e711e8 100755 --- a/templates/admin/media.template +++ b/templates/admin/media.template @@ -11,31 +11,34 @@ function openWin(url) { +
- - - + + + + - - - - + + + +
- - ${lang("media.nr_of_media")}
-
-
-   -
+ ${lang("media.nr_of_media")} :
+
+    +
+ +
- - - + + + + @@ -45,121 +48,99 @@ function openWin(url) { - - + - - - ${lang("media.created")}: ${data.webdb_create} - / ${lang("media.changed")} ${data.webdb_lastchange}
- ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
- ${lang("media.format")}: ${data.mimetype}
- ${lang("media.size")}: ${data.human_readable_size}
- ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
- +    + + + ${lang("media.created")}: ${data.webdb_create} + / ${lang("media.changed")} ${data.webdb_lastchange}
+ ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
+ ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
+ ${lang("media.size")}: ${data.human_readable_size}
+ ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
+
- - ${lang("media.mediafolder")}: - - - + + ${lang("media.mediafolder")}: + + + + - - - - ${lang("media.description")}: - - - - - - ${lang("media.date")}: - - - - - - - ${lang("media.location")}: - - - - - - ${lang("media.creator")}: - - - - - - - ${lang("media.keywords")}: - - - - - - ${lang("media.comment")}: - - - - - - ${lang("media.source")}: - - - + + + + + + + + + +   + - - ${lang("media.is_published")} checked> - + + ${lang("media.is_published")} : + + + checked> + + +   + - - - + + ${lang("media.title")}: - - + + - - - - -
+ + + +   - + +
+ +
- - + + ${lang("media.title")}: - + - + - + ${lang("media.is_published")} checked> - - +    + + +

[<] ${lang("list")}  

+ + diff --git a/templates/admin/mediafolder.template b/templates/admin/mediafolder.template index 6d4060fa..85e5145f 100755 --- a/templates/admin/mediafolder.template +++ b/templates/admin/mediafolder.template @@ -6,47 +6,38 @@ + +
- - - - - - +
${lang("mediafolder.date")}:
+ + + + + - - - - - - - - - - - - - - - - - - - - +
${lang("mediafolder.name")}:
${lang("mediafolder.location")}:
${lang("mediafolder.comment")}:
${lang("mediafolder.keywords")}:
+ - +
+ + +

+ [<] ${lang("list")}   + [<<<] ${lang("head.start")} +

+ diff --git a/templates/admin/mediafolderlist.template b/templates/admin/mediafolderlist.template index b0361c90..371fce8c 100755 --- a/templates/admin/mediafolderlist.template +++ b/templates/admin/mediafolderlist.template @@ -10,27 +10,28 @@ - - - - - + + + + + + - class="list1"class="list2" > + class="listrow1"class="listrow2" > - + | ${lang("list")} - +
${lang("mediafolder.date")}${lang("mediafolder.name")}${lang("mediafolder.location")}${lang("mediafolder.comment")}${lang("mediafolder.keywords")}${lang("mediafolder.date")}${lang("mediafolder.name")}${lang("mediafolder.location")}${lang("mediafolder.comment")}${lang("mediafolder.keywords")} 
${entry.date}  ${entry.name}  ${entry.place}  ${entry.comment}  ${entry.keywords} ${lang("delete")} + ${lang("delete")} | ${lang("edit")} - | ${lang("list")}
${data.count} ${lang("records")} / - ${lang("show_from_to", data.from, data.to)}${data.count} ${lang("records")} / + ${lang("show_from_to", data.from, data.to)}  
@@ -42,8 +43,14 @@ ${lang("list.next")}
-

${lang("no_matches_found")}

+

${lang("no_matches_found")}

+ +

+ [+] ${lang("add")}   + [<<<] ${lang("head.start")} +

+ diff --git a/templates/admin/medialist.template b/templates/admin/medialist.template index c23eb0a9..144e31dc 100755 --- a/templates/admin/medialist.template +++ b/templates/admin/medialist.template @@ -1,113 +1,17 @@ - ${config["Mir.Name"]} | ${lang("other_media.htmltitle")} + ${config["Mir.Name"]} | ${lang("other_medialist.htmltitle")} + + +

 

+ - - - - - - - - - - - - - - - - class="list1"class="list2"> - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: 
- - - - - - - - -
-
-
- ${lang("media.icon")} - ${lang("media.title")} - ${lang("media.format")} - ${lang("media.size")} - ${lang("media.mediafolder")} - ${lang("media.creator")}
- - ${entry.title}  -
${entry.description}
${entry.media_descr} ${entry.human_readable_size} ${data.mediafolderHashdata[entry.to_media_folder]["name"]} ${entry.creator}   - ${lang("attach")} - - ${lang("delete")} - | ${lang("edit")} - -
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
- - zurueck  - - -weiter - -
${lang("no_matches_found")}
diff --git a/templates/admin/message.template b/templates/admin/message.template index d2bd155a..bf99bcd2 100755 --- a/templates/admin/message.template +++ b/templates/admin/message.template @@ -5,54 +5,59 @@ - + + +
- - + + + + + + + - + - - - - - - - - - + + + + + - - - - - + + +
- ${lang("message.date")}: + ${lang("message.date")}: ${data.date}
- ${lang("message.title")}: - -
- ${lang("message.creator")}: - -
- ${lang("message.text")}: ${lang("message.textinfo")} - -
- + + ${lang("message.textinfo")} + + + - - + +
+ + +

+ + [<] ${lang("back")}   + [<<<] ${lang("head.start")} +

+ + diff --git a/templates/admin/messagelist.template b/templates/admin/messagelist.template index 887ed750..53144911 100755 --- a/templates/admin/messagelist.template +++ b/templates/admin/messagelist.template @@ -1,52 +1,68 @@ ${config["Mir.Name"]} | ${lang("messagelist.htmltitle")} - + + +

+ [+] ${lang("add")}   + [<<<] ${lang("head.start")} +

+ - - - - - + +
- ${lang("message.date")} - ${lang("message.title")}
${lang("message.creator")}
- ${lang("message.text")}
+ + + + class="list1"class="list2" > - - - - + + class="listrow1" + class="listrow2" + + > + + + + + - - + + +
+ ${lang("message.date")} + ${lang("message.title")} /
${lang("message.creator")}
+ ${lang("message.text")}
${entry.webdb_create} ${entry.title}
- ${entry.creator}
${entry.description}  ${lang("delete")} - | ${lang("edit")}${entry.webdb_create} ${entry.title}
+ ${lang("by")}: ${entry.creator}
${entry.description}  + [ ${lang("delete")} ]
+ [ ${lang("edit")} ] +
${data.count} ${lang("records")} / - ${lang("show_from_to", data.from, data.to)} ${data.count} ${lang("records")} / + ${lang("show_from_to", data.from, data.to)}

- ${lang("list.previous")}  + [ ${lang("list.previous")} ]  -${lang("list.next")} + [ ${lang("list.next")} ]

${lang("no_matches_found")}

+ diff --git a/templates/admin/producerqueue.template b/templates/admin/producerqueue.template index f9a8637b..fb94a60b 100755 --- a/templates/admin/producerqueue.template +++ b/templates/admin/producerqueue.template @@ -1,77 +1,100 @@ ${config["Mir.Name"]} | ${lang("producerqueue.htmltitle")} - + -${lang("producer.jobqueue.title")} -

- - - - - - - - - - - - - - class="list1"class="list2"> - - - - - ML: needs to be implemented - - - - - - - - - - - +
${lang("producer.job.name")}${lang("producer.job.status")}${lang("producer.job.date")} 
${q.factory}${q.verb}${q.status}${q.lastchange["HH:mm:ss"]}${lang("producer.job.cancel")}
Queue is empty
+ + + + +
+ +

${lang("producer.producerlist.title")}

+ + + + + + + + + + + + + + + + class="listrow2"class="listrow2"> + + + + + + + + + + + + +
${lang("producer.verb.name")}${lang("producer.verb.description")}
${p.name}
${v.name} [!]${v.name}${v.description}${lang("producer.verb.enqueue")} 
-${lang("producer.jobqueue.refresh")}

- -

- -${lang("producer.producerlist.title")} -

- - - - - - - - - - - class="list1"class="list2"> - - - - - class="list1"class="list2"> - - - - - - - - + + + + + + +
 ${lang("producer.verb.name")}${lang("producer.verb.description")} 
${p.name}
${v.name}${v.description}${lang("producer.verb.enqueue")} 
+ +

${lang("producer.jobqueue.title")}

+ + + + + + + + + + + + + + + class="listrow1"class="listrow2"> + + + + + + + + + + + ML: needs to be implemented + + + + + + + + + + + + +
${lang("producer.job.name")}${lang("producer.job.status")}${lang("producer.job.date")} 
${q.factory}(${q.verb})${q.status}${q.status}${q.lastchange["HH:mm:ss"]}${lang("producer.job.cancel")}
${lang("producer.job.empty")}
+
+ ${lang("producer.jobqueue.refresh")} +
+
+ diff --git a/templates/admin/start_admin.template b/templates/admin/start_admin.template index 3f126d31..c5945e66 100755 --- a/templates/admin/start_admin.template +++ b/templates/admin/start_admin.template @@ -2,219 +2,165 @@ ${config["Mir.Name"]} | ${lang("start.htmltitle")} + - - - - - Middle column - - - + + + RIGHT COLUMN - -
- - - - ${lang("start.openpostings.title")} -

- -  ${lang("edit")} - -

- - ${lang("start.comments.title")} -

+ + + + + + + + -
-   - ${lang("start.content.all")}
- -
-   - ${lang("start.content.not_published")}
-   - ${lang("start.content.with_media")}
-   - ${lang("start.content.last_changes")}
-   - ${lang("start.content.with_comments")}
- -
-   - ${lang("start.content.hidden")} -
-
- - ${lang("start.editfiles.title")} - -
- -  ${lang("start.editfiles.include")} - -

- - - - - - ${lang("start.content.search")}: - - - - -
+ +

${lang("start.administer.title")}

+

+ + > ${lang("start.allarticlesoftype", lang("articletypes.openposting"))} +
-  ${lang("edit")} -

- - ${lang("start.breaking.title")} -

-   - ${lang("edit")} -   - ${lang("start.breaking.new")} - - - -
 
- - - ${lang("start.content.title")} - -

-   - ${lang("start.content.new")} -

- ${lang("start.show")}:
- -   - ${lang("start.allarticlesoftype", lang("articletypes."+a.name))}
+ > ${lang("start.content.comments")} + +

+ +

${lang("start.list.title")}

+

+ + > ${lang("start.allarticlesoftype", lang("articletypes."+a.name))}
+
+ > ${lang("start.content.not_published")}
+ > ${lang("start.content.with_media")}
+ > ${lang("start.content.last_changes")}
+ > ${lang("start.content.with_comments")}
+
+ > ${lang("start.content.all")}
+

+ +

${lang("start.extra.title")}

+

+ > ${lang("start.content.hidden")}
+ > ${lang("start.fileedit.title")} +

+
 
- -
 
- - - ${lang("start.producers.title")} -

- ${lang("start.producers.produceAllNew")}
- ${lang("start.producers.advanced")} - - -
 
- - ${lang("start.superusermenu")} - -

  - - - - ${lang("start.images.title")} - - -

- -   ${lang("edit")}
- -   ${lang("add")} - -

- - ${lang("start.audio.title")} - - -

- -   ${lang("edit")} -
- - -   ${lang("add")} - - -

- - ${lang("start.video.title")} - - -

- -   ${lang("edit")} -
- - -   ${lang("add")} - - -

- - ${lang("start.other_media.title")} - - -

- -   ${lang("edit")} -
- - -   ${lang("add")} - - -

- - ${lang("start.mediafolder.title")} - - -

- -   ${lang("edit")} -
- - -   ${lang("add")} - -

  - + +

${lang("start.addandedit.title")}

+
+ > ${lang("start.content.new")} +
+ + > ${lang("start.breaking.title")}  + [+] +
+ + + ${lang("start.open_by_id")} : + + +
+ + +
+ +

${lang("start.media.title")}

+ + + + +

${lang("start.producers.title")}

+

+ > ${lang("start.producers.produceAllNew")}
+ > ${lang("start.producers.advanced")} +

+ +

+ ${lang("start.superusermenu")} +

+ +
  + internal messageboard - - ${lang("start.messageboard.title")} -
${lang("add")} - ${lang("edit")}
- - -

- ${m.title}
- ${m.description}
- - von: ${m.creator} / ${m.webdb_create}
-
- - -

${lang("start.messageboard.no_messages")} - + +

${lang("start.messageboard.title")}

+
+ + [ + ${lang("add")}] + [${lang("edit")}] + + + +

+ ${m.title}
+ ${m.description}
+ + by: ${m.creator} / ${m.webdb_create}
+
+

+
+ +

${lang("start.messageboard.no_messages")} + +

+ + BOTTOM ROW FOR SEARCH +

+

${lang("start.search.title")}

+
+ +
+ + +

+ HELP-Demo:
+ popup small-link:    popup big-link:

+ newwin small-link:    newwin big-link: +

+ + +
 
diff --git a/templates/admin/superusermenu.template b/templates/admin/superusermenu.template index d79d8910..3132f7f6 100755 --- a/templates/admin/superusermenu.template +++ b/templates/admin/superusermenu.template @@ -1,33 +1,34 @@ ${config["Mir.Name"]} | ${lang("superusermenu.htmltitle")} - + - - - ${lang("superusermenu.topics")} - -

- ${lang("superusermenu.articletypes")} - -

- ${lang("superusermenu.comment_statuses")} - -

- ${lang("superusermenu.users")} - -

- ${lang("superusermenu.languages")} - -

- ${lang("superusermenu.abuse")} - -

- ${lang("superusermenu.imcs")} + + + + + + + + + +
+

${lang("superusermenu.manage")}:

+

+ > ${lang("superusermenu.topics")}
+ > ${lang("superusermenu.articletypes")}
+ > ${lang("superusermenu.comment_statuses")}
+ > ${lang("superusermenu.users")}
+ > ${lang("superusermenu.languages")}
+ > ${lang("superusermenu.abuse")}
+ > ${lang("superusermenu.imcs")}
+

+
   
+

[<<<] ${lang("head.start")}

diff --git a/templates/admin/topic.template b/templates/admin/topic.template index 760091c9..4d062065 100755 --- a/templates/admin/topic.template +++ b/templates/admin/topic.template @@ -5,7 +5,9 @@ - + + +
@@ -17,54 +19,23 @@ - - - - - - - - - - - - - - - - - - - - - - -
- - ${lang("topic.title")}: - - - -
- ${lang("topic.description")}: - - -
${lang("topic.filename")}: - -
${lang("topic.main_url")} - - -
${lang("topic.archive_url")}: - -
+ + + + + + + - +
+
+

[<] ${lang("back")}  

diff --git a/templates/admin/topiclist.template b/templates/admin/topiclist.template index 4a0a44e0..97bff9e7 100755 --- a/templates/admin/topiclist.template +++ b/templates/admin/topiclist.template @@ -6,63 +6,36 @@ + + + - ${lang("add")} | - ${lang("back")} - + configure this template here + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - -
${lang("topic.title")}${lang("topic.description")}${lang("topic.main_url")}
${lang("topic.archive_url")}
 
${entry.title} ${entry.description} ${entry.main_url}
${entry.archiv_url}
  - ${lang("delete")} - | ${lang("edit")} -
- ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} -  
-

- -

- - - - - - - - - - - - -
-
-

- -

${lang("no_matches_found")}

+ + + + +

${lang("no_matches_found")}

- - ${lang("add")} | - ${lang("back")} + + + diff --git a/templates/admin/user.template b/templates/admin/user.template index 74e048c9..984c033c 100755 --- a/templates/admin/user.template +++ b/templates/admin/user.template @@ -1,78 +1,52 @@ - - ${config["Mir.Name"]} | ${lang("user.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("user.htmltitle")} + + - + + + + - +
+ + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - ${lang("user.login")}: - - - -
- - ${lang("user.password")}: - - - -
- - ${lang("user.password2")}: - - - -
- - ${lang("user.admin")}: - - - checked> -
- - - - - - - -
-
- - - - + + + + + + + + + + + +
+ ${lang("user.admin")}: + + checked> +
+ + + + + + + +
+ + +

[<] ${lang("back")}  

+ + + + diff --git a/templates/admin/usererror.template b/templates/admin/usererror.template index 594e4dc5..fc61c25c 100755 --- a/templates/admin/usererror.template +++ b/templates/admin/usererror.template @@ -3,7 +3,7 @@ ${lang("usererror.htmltitle")} - + - - +    + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + - + + + + - - + - + - - - - + + - + + - - + - - + -
diff --git a/templates/admin/userlist.template b/templates/admin/userlist.template index 0298fc88..432c0aea 100755 --- a/templates/admin/userlist.template +++ b/templates/admin/userlist.template @@ -5,53 +5,34 @@ - -

- ${lang("add")} | - ${lang("back")} -

+ + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - -
${lang("user.login")}${lang("user.admin")}
${entry.login} ${entry.is_admin}  - ${lang("delete")} - | ${lang("edit")} -
- ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} -  
-

- - - ${lang("list.previous")}  - - - ${lang("list.next")} - -

- -

${lang("no_matches_found")}

+ + + +

${lang("no_matches_found")}

- -

- ${lang("add")} | - ${lang("back")} -

+ diff --git a/templates/admin/video.template b/templates/admin/video.template index d7ff1b27..c63d9206 100755 --- a/templates/admin/video.template +++ b/templates/admin/video.template @@ -10,32 +10,33 @@ function openWin(url) { - +
- - - + + + - - - - + + + +
- - ${lang("media.nr_of_media")}
-
-
-   -
+ ${lang("media.nr_of_media")} :
+
+    +
+ +
- - - + + + + @@ -45,121 +46,99 @@ function openWin(url) {
- + - - ${lang("media.created")}: ${data.webdb_create} - / ${lang("media.changed")} ${data.webdb_lastchange}
- ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
- ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
- ${lang("media.size")}: ${data.human_readable_size}
- ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
-
+ ${lang("media.created")}: ${data.webdb_create} + / ${lang("media.changed")} ${data.webdb_lastchange}
+ ${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}
+ ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}
+ ${lang("media.size")}: ${data.human_readable_size}
+ ${lang("media.rights")}: ${data.rightsHashdata[to_rights]["name"]}
+
- ${lang("media.mediafolder")}: - - + ${lang("media.mediafolder")}: + + +
- ${lang("media.description")}:
- ${lang("media.date")}: -
- ${lang("media.location")}:
- ${lang("media.creator")}: - -
- ${lang("media.keywords")}:
- ${lang("media.comment")}:
- ${lang("media.source")}:
 
- ${lang("media.is_published")} checked> - + ${lang("media.is_published")} : + + checked> +
 
- +
${lang("media.title")}: - +
-
+
+  
+
+
+
${lang("media.title")}: +
+ ${lang("media.is_published")} checked> - - +    +
+ +

[<] ${lang("list")}  

+ + diff --git a/templates/admin/videolist.template b/templates/admin/videolist.template index 0b1a74c1..1577587e 100755 --- a/templates/admin/videolist.template +++ b/templates/admin/videolist.template @@ -7,107 +7,11 @@ + + +

 

+ - - - - - - - - - - - - - - - - class="list1"class="list1" > - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: 
- - - - - - - - -
-
-
- ${lang("media.icon")} - ${lang("media.title")} - ${lang("media.format")} - ${lang("media.size")} - ${lang("media.mediafolder")} - ${lang("media.creator")}
- - ${entry.title}  -
${entry.description}
${entry.media_descr} ${entry.human_readable_size} ${data.mediafolderHashdata[entry.to_media_folder]["name"]} ${entry.creator}   - ${lang("attach")} - - ${lang("delete")} - | ${lang("edit")} - -
${data.count} ${lang("records")} - / ${lang("show_from_to", data.from, data.to)} 
- - zurueck  - - -weiter - -
${lang("no_matches_found")}
diff --git a/templates/error.template b/templates/error.template deleted file mode 100755 index 2a0395d0..00000000 --- a/templates/error.template +++ /dev/null @@ -1,37 +0,0 @@ - - - ${config["Mir.Name"]} | ${lang("error.htmltitle")} - - - - - - - - - - - - - - - - - -
-

${lang("error.title")}

-
-
-

${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])} -

-

-

${data.date} -- ${data.errorstring} -

-

-

- ${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])} -

-

- - - diff --git a/templates/usererror.template b/templates/usererror.template deleted file mode 100755 index fc61c25c..00000000 --- a/templates/usererror.template +++ /dev/null @@ -1,37 +0,0 @@ - - -${lang("usererror.htmltitle")} - - - - - - - - - - - - - - - - -
-

${lang("usererror.title")}

-
-
-

${lang("usererror.text")} -

-

-

${data.errorstring} -

-

-

-

${lang("usererror.what_to_do")} - -

-

- - - diff --git a/web/style/admin.css b/web/style/admin.css index 28fd75a6..4d5506a8 100755 --- a/web/style/admin.css +++ b/web/style/admin.css @@ -1,78 +1,184 @@ body { margin: 6px; - background-color: #ffffff; - url(../img/bgimage.jpg) no-repeat; + background-color: #EEEEEE; } +/* ... basic font-def ... */ + h1, h2, h3, h4, h5, h6, p, li, dt, dd, div, td, blockquote { font-family: arial, helvetica, sans-serif; } h6, p, li, dt, dd, div, td, blockquote { - font-size: small; + font-family: arial, helvetica, sans-serif; + +} + +/* ... boxes ... */ + +.box_head { + background-color:#006600; + padding:2px; + margin:0px; + border:2px solid #006600; + color:#FFFFFF; +} + +.box { + background-color:#FFFFFF; + padding:8px; + margin-top:0px; + margin-bottom:12px; + border:2px solid #006600; + +} + +/* ... for MESSAGEBOX ... */ + +.box_bg { + background-color:#FFFFCC; + padding:8px; + margin-top:0px; + margin-bottom:12px; + border:2px solid #006600; +} + +/* ... creates indent ... */ + +.box_invis { + margin-top:4px; + margin-bottom:4px; + margin-left:12px; + margin-right:12px; + padding:4px; } + +.bg_neutral { + background-color:#DDDDDD; +} + + +/* ... TABLE def ... */ + +.table_head { + color: #FFFFFF; + background-color: #990000; + font-weight: bold; + padding-right:8px; + padding-left:6px; +} + +.table_left { + color: #FFFFFF; + background-color: #006600; + font-size:1em; + font-weight: bold; + padding-top: 4px; + padding-bottom: 4px; + padding-right:8px; + padding-left:6px; +} + +/* ... for unimportent fields ... */ +.table_left_light + { + color: #FFFFFF; + background-color: #999999; + font-size:0.8em; + font-weight: bold; + padding-right:8px; + padding-left:6px; +} + +.table_foot { + color: #006600; + text-align:right; + font-weight: bold; + font-size:0.7em; + padding-right:6px; + padding-left:6px; + border-top:3px solid #990000; -a:link {color: #cc0033;text-decoration:none;} -a:visited {color: #660033;text-decoration:none;} -a:hover {color: #ff3333;text-decoration:none;} - -.dark {background-color: #990000; color: #ffffff; text-decoration:none;} -.middle {background-color: #cc0033; color: #ffffff; text-decoration:none;} -.pink {background-color: #FF9966; color: #ffffff; text-decoration:none;} -.darkgrey {background-color: #999966; color: #000000; text-decoration:none;} -.grey {background-color: #dddddd; color: #000000; text-decoration:none;} -.litegrey {background-color: #eeeeee; color: #990000; text-decoration:none;} -.wite {background-color: #ffffff; color: #990000; text-decoration:none;} -.list1 {background-color: #FFFFCC; color: #000000; text-decoration:none;} -.list2 {background-color: #FFCC99; color: #000000; text-decoration:none;} -.list3 {background-color: #FFFF99; color: #000000; text-decoration:none;} -.list4 {background-color: #CCCC99; color: #000000; text-decoration:none;} - -.pagetitle {font-size: x-large; color: #cc0033; font-weight: bold;} -.litetitel {font-size: large; color: #ffffff; font-weight: bold;} -.darktitel {font-size: large; color: #cc0033; font-weight: bold;} -.spezialtext {font-size: small; color: #CC0000;} -.text {font-size: small;} -.small {font-size: x-small;} -.x-small {font-size: xx-small;} - -.witetext {font-size: large; color: #ffffff; text-decoration:none;} -.witesmall {font-size: small; color: #ffffff; text-decoration:none;} -.witex-small {font-size: x-small; color: #ffffff; text-decoration:none;} +} -.lynx { display:none; } -.editfieldname { - font-size: normal; - color: #000000; - font-weight: bold; - text-decoration:none; - background-color: #CCCCCC; +/* ... for striped Tables ... */ +.listrow1 { + color: #000000; + background-color: #FFFFFF; +} +.listrow2 { + color: #000000; + background-color: #FFFFCC; +} +.listrow3 { + color: #000000; + background-color: #FAFAC8; +} +.listrow4 { + color: #000000; + background-color: #F5F5F5; } -.menucommand { - font-family: arial, helvetica, sans-serif; - font-size: normal; - font-weight: bold; - color: #CC0000; + +/* ... LINKS ... */ +a:link { + color: #990000; + text-decoration:none; } - -.majorcommand { - font-family: arial, helvetica, sans-serif; - font-size: normal; - font-weight: bold; - color: #CC0000; +a:visited { + color: #990000; + text-decoration:none; +} +a:hover { + color: #FFFFFF; + text-decoration:none; + background-color:#990000; +} + +.link_box { + background-color:#DDDDDD; + font-size:0.9em; + padding:2px; + padding-left:8px; + padding-right:8px; + border:1px solid #990000; +} + +.link_help { + background-color:#DDDDDD; + font-size:0.9em; + padding:2px; + padding-left:8px; + padding-right:8px; + border:1px solid #003399; + color: #003399; } - -.minorcommand { - font-family: arial, helvetica, sans-serif; - font-size: normal; - font-weight: bold; - color: #CC0000; -} -.majorbutton { - background-color: #CC0000; - color: #ffffff; - font-weight: bold; +.link_help_small { + background-color:#EEEEEE; + font-size:0.7em; + color: #003399; } + + +/* ... for important text ... */ +.text_alert { + color: #CC0000; + +} + + +.majorcommand { + font-weight: bold; +} + +.listcommand { + font-size: 0.7em; +} + +.small {font-size: 0.8em;} +.x-small {font-size: 0.7em;} + +.lynx { display:none; } +