-bin
.classpath
.project
+.settings
+bin
+build
+dist
--- /dev/null
+2005-09-10 Grok <grok@no-log.org>
+ * doc/diagrams, doc/developpers-guide:
+ writing a developpers guide with diagrams to help
+ document mir
+
+2005-08-07 Grok <grok@no-log.org>
+ * templates/admin/FUNCTIONS.template:
+ adding a form on the edit article pages that allows you
+ to add an image attachment by directly typing in its id
+
+2005-07-26 Grok <grok@no-log.org>
+ * source/mir/media/image/ImageMagickImageProcessor.java:
+ Adding a new ImageMagickImageProcessor class to replace
+ the old JAIImageProcessor class. Removing the non-free JAI,
+ will bring us closer to making mir free. The new class uses
+ ImageMagick commandline programs who's path may be specified
+ in the config.properties configuration file.
-[last changed: $Date: 2006/11/30 18:25:22 $] 2002 mir-coders group
+[last changed: $Date: 2007/04/08 21:46:44 $] 2002 mir-coders group
-------------------------------------------------------------------------------
================================
incrementally when they are produced, uses standard internationalized
template scheme to display results of queries, which can be sorted by real
publication date and include things like image thumbnails
-
-[Bugfixes]
-* more image formats supported with JAI / Java Image I/O
[Build process]
[Maintenance]
-[Notes]
-Mir depends media operations depend on the correct installation of
-JAI / Java Image I/O in the JRE running tomcat.
-
===============================
1.0.0 final released 2002/12/24
===============================
[Bugfixes]
* minor: in source/mir/misc/HTMLTemplateProcessor.java, use Video.Host
config option not the non-existant VideoHost option.
-
+
[Build process]
[Maintenance]
=============================
[New features/Improvements]
-* throw a RuntimeException in MirConfig.getProp(..) if the property is not
+* throw a RuntimeException in MirConfig.getProp(..) if the property is not
found. This should ease upgrading between versions when a new Config property
is added.
[Bugfixes]
* Add a new method to escape characters that are special characters in SQL. It
- does a better job than the old hack in StringUtil.quote(..) which replaced
- single quotes with the HTML representation of a single quote ('
+ does a better job than the old hack in StringUtil.quote(..) which replaced
+ single quotes with the HTML representation of a single quote ('
I believe). The hack papered over a bug in the postgres JDBC driver which
makes it not recognize escaping w/ a backslash (it uses double single quotes
instead).
-
+
[Build process]
[Maintenance]
posting.template that prevented the chossing of a topic in openposting from
working. luckily this bug didn't affect most sites since most installations
customize the template.
-
+
[Build process]
* set a "Cache-control", "Pragma" and "Expires" header to the http response
in the Mir and OpenMir servlets to insure that nothing gets cached by a
client browser.
-* Add a new config parameter: Mir.DefaultHTMLCharset to set the HTML
- content-type charset in one place and re-use it in templates as
+* Add a new config parameter: Mir.DefaultHTMLCharset to set the HTML
+ content-type charset in one place and re-use it in templates as
${config.defEncoding}.
* Allow some HTML tags in the abstract (description field) during an
openposting. strip out the dangerous ones like <head>, <body> and <script> as
* Fix embarrassing bug in the admin interface that caused data to dissappear
when double quotes were in a title form field for example.. (anything
enclosed in a value="...")
-* fix a bug in comment search: if you were at an offset > 0, i.e not on the
+* fix a bug in comment search: if you were at an offset > 0, i.e not on the
first page, the search would be broken.
* fix minor bug in media searching: mediafolder search setting would be reset
each time. make sure it is not so.
[Maintenance]
* comment out a bunch of debug logging in Database.java
* add this file, REPORTING_BUGS, KNOWN_BUGS, CODINGSTYLE and a README file.
-* Add gnu Style ChangeLog using cvs2cl (use "-F MIR_1_0 --utc" options., for
+* Add gnu Style ChangeLog using cvs2cl (use "-F MIR_1_0 --utc" options., for
HEAD, it would be "-F trunk --utc")
[Notes]
[Bugfixes]
* Better and more consistent exception handling: make sure all exceptions make
it to the top.
-* make sure that if some part of a posting fails that the posting however
+* make sure that if some part of a posting fails that the posting however
complete/inconplete it may be is deleted
* many bugfixes all over the place
- form of a war file
- * source-distribution
- Sets up a distributable version of mir as a
- - zipped version of the source tree
+ - gzipped tar version of the source tree
+ - * full-distribution
+ - Sets up a distributable version of mir in the
+ - form of a gzipped tar file with the sources
- * javadoc
- Generates the project's javadoc
-->
<!-- The temporary files made during the build process
will be created here: -->
- <property name="build.home" value="./build"/>
- <property name="build.classes" value="./${build.home}/classes"/>
- <property name="build.jars" value="./${build.home}/jars"/>
- <property name="build.javadoc" value="${build.home}/javadoc"/>
+ <property name="build" value="./build"/>
+ <property name="build.classes" value="./${build}/classes"/>
+ <property name="build.jars" value="./${build}/jars"/>
+ <property name="build.javadoc" value="${build}/javadoc"/>
<!-- retrieve environment variables -->
<property environment="env"/>
-<!--
- <property name="deploy.webinf" value="${deploy.home}/WEB-INF"/>
- <property name="deploy.classes" value="${deploy.webinf}/classes"/>
- <property name="dist.src" value="${app.name}.jar"/>
- <property name="dist.war" value="${app.name}.war"/>
- -->
<property name="tomcat.home" value="${env.TOMCAT_HOME}"/>
<!--
<target name="debug" depends="compile-debug,generate-deployment-tree"
description="Sets up a deployment directory with debug enabled">
-
</target>
<target name="generate-deployment-tree">
</target>
<target name="clean">
- <delete dir="${build.home}"/>
+ <delete dir="${build}"/>
</target>
<!-- Construct the classpath -->
<target name="compile" depends="prepare-compilation" unless="up.to.date"
description="Creates the jars needed for a mir deployment">
- <javac destdir="${build.classes}" deprecation="on">
+ <javac destdir="${build.classes}" debug="true" deprecation="off" source="1.3">
<src path="source"/>
<src path="etc/extrasource"/>
<classpath refid="project.classpath"/>
</javac>
+ <delete file="${build.jars}/mir.jar"/>
+
<jar
jarfile="${build.jars}/mir.jar">
<fileset dir="${build.classes}" includes="**/*.class" />
<mkdir dir="${build.javadoc}"/>
</target>
- <target name="prepare-binary-distribution">
+ <target name="prepare-distribution">
<mkdir dir="${distribution.home}"/>
- <delete dir="${build.home}/binarydist"/>
- <mkdir dir="${build.home}/binarydist"/>
+ <delete dir="${build}/dist"/>
+ <mkdir dir="${build}/dist"/>
</target>
- <target name="binary-distribution" depends="prepare-binary-distribution">
+ <target name="distribution" depends="prepare-distribution">
<antcall target="generate-deployment-tree">
- <param name="destination" value="${build.home}/binarydist"/>
+ <param name="destination" value="${build}/dist"/>
</antcall>
- <zip zipfile="${distribution.home}/binary.zip" >
- <fileset dir="${build.home}/binarydist" includes="**/*" />
- </zip>
+ <tar tarfile="${distribution.home}/mir-${version}.tar.gz" compression="gzip">
+ <tarfileset dir="${build}/dist" includes="**/*" />
+ </tar>
</target>
<target name="prepare-source-distribution">
</target>
<target name="source-distribution" depends="prepare-source-distribution">
- <zip zipfile="${distribution.home}/source.zip" >
+ <!--<zip zipfile="${distribution.home}/mir-source-${version}.zip" >
<fileset dir="."
includes="bundles/**/*,source/**/*,etc/**/*,meta/**/*,web/**/*,templates/**/*,dbscripts/**/*,lib/**/*,doc/**/*,build.xml" />
- </zip>
+ </zip>-->
+ <tar tarfile="${distribution.home}/mir-source-${version}.tar.gz" compression="gzip">
+ <tarfileset dir="."
+ includes="bundles/**/*,source/**/*,etc/**/*,meta/**/*,web/**/*,templates/**/*,dbscripts/**/*,lib/**/*,doc/**/*,build.xml" />
+ </tar>
+
+ </target>
+
+<!--
+
+ <target name="documentation-pdf" description="generates documentation into html form">
+ <xslt in="${temp}/docs/pdf/${document}.xml"
+ out="${temp}/docs/pdf/${document}.fo"
+ style=""/>
+
+ <java classname="org.apache.fop.apps.Fop" fork="yes">
+ <classpath>
+ <fileset dir="lib">
+ <include name="*.jar"/>
+ </fileset>
+ </classpath>
+
+ <arg value="-fo"/>
+ <arg file="${temp}/docs/pdf/${document}.fo"/>
+ <arg file="${build}/pdfdocs/${document}.pdf"/>
+ </java>
+ </target>
+-->
+ <target name="prepare-html">
+ <mkdir dir="${build}/xslt"/>
+
+ <unzip dest="${build}/xslt" src="doc/lib/docbook-xsl-1.70.1.zip"/>
+
+ <copy todir="${build}/xslt">
+ <fileset dir="doc/style">
+ <include name="*"/>
+ </fileset>
+ </copy>
+ </target>
+
+ <target name="documentation-html" description="generates documentation into html form" depends="prepare-html">
+ <mkdir dir="${build}/htmldocs"/>
+
+ <xslt basedir="doc/installation" includes="*.xml"
+ destdir="${build}/htmldocs"
+ style="${build}/xslt/html.xsl"/>
+ </target>
+ <target name="full-distribution" depends="prepare-distribution,deploy,source-distribution">
+ <copy todir="${destination}/WEB-INF">
+ <fileset file="${distribution.home}/mir-source-${version}.tar.gz"/>
+ </copy>
+ <tar tarfile="${distribution.home}/mir-${version}.tar.gz" compression="gzip">
+ <tarfileset dir="bin" includes="**/*" />
+ </tar>
</target>
</project>
########## admin ##########
# language: deutsch / german
-# $Id: admin_de.properties,v 1.31 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_de.properties,v 1.32 2007/04/08 21:46:36 idfx Exp $
languagename=Deutsch
media.nr_of_media=Anzahl der Medien (max 20)
media.nr_of_media.submit=Anzahl festlegen
media.comments=Kommentare
-media.articles=Artike
+media.articles=Artikel
medialist.search_text_in=Search text in
# Article types
-articletypes.OpenPosting=open posting
-articletypes.Newswire=Newswire
-articletypes.Feature=Feature
-articletypes.Spezial\ (Topicpage)=Topic-Special
-articletypes.Spezial\ (Startpage)=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
-# $Id: admin_en.properties,v 1.50 2004/11/06 17:39:45 idfx Exp $
+########## admin ##########
+# language: english
+# $Id: admin_en.properties,v 1.51 2007/04/08 21:46:36 idfx Exp $
languagename=English
media.icon=icon
media.nr_of_media=Number of Media Items (max 20)
media.nr_of_media.submit=define number
-media.comments=Comments
+media.comments=Comments
media.articles=Articles
medialist.search_text_in=Search text in
comment.creator=Author
comment.article=Article
comment.html=HTML
-comment.status=Status
+comment.status=Status
comment.language=Language
comment.allcomments=All comments
comment.comment=Internal Comment
comment.operation.hide=hide
comment.operation.unhide=unhide
+comment.operation.delete=delete
#commentlist
content.operation.hide=hide
content.operation.unhide=unhide
content.operation.newswire=newswire
+content.operation.delete=delete
+
content.preview.default = Preview
+contentsearch.topic = Topic
contentsearch.value = search
contentsearch.field = field
contentsearch.field.title = Title
abuse.commentaction=Action for blocked comment
abuse.showlog=Show the IP log
-abuse.showfilters=Manage filters
+abuse.showfiltergroups=Manage filter groups
+abuse.showfilterconfiguration=Manage filter configuration
abuse.log.time=Time
abuse.log.address=IP number
abuse.log.object=Object
abuse.log.browser=Browser
-abuse.log.filtertype=Filter type
-abuse.log.filterexpression=Expression
+abuse.log.filtertag = Filter tag
abuse.filters = Filters
-abuse.filters.movedown = down
-abuse.filters.moveup = up
-abuse.filters.movebottom = bottom
-abuse.filters.movetop = top
-
-abuse.filter.type = Type
-abuse.filter.expression = Expression
-abuse.filter.articleaction = Article
-abuse.filter.commentaction = Comment
-abuse.filter.comments = Comments (internal usage)
-abuse.filter.lasthit = Last hit
-abuse.filter.htmltitle = Edit filter
-
-abuse.filtertype.ip = IP Number
-abuse.filtertype.regexp = Regular expression
-abuse.filtertype.useragent= User Agent
-abuse.filtertype.throttle = Throttle
-abuse.filtertype.hostname = Host name
-
-abuse.filtererror.title = Error:
-abuse.filtererror.invalidtype = Invalid filter type
-abuse.filtererror.invalidexpression = Invalid expression for this type
-
-abuse.filters.htmltitle = Anti-abuse filter rules
+filters.movedown = down
+filters.moveup = up
+filters.movebottom = bottom
+filters.movetop = top
+
+filter.type = Type
+filter.expression = Expression
+filter.articleaction = Article
+filter.commentaction = Comment
+filter.comment = Comments (internal usage)
+filter.last_hit = Last hit
+filter.htmltitle = Edit filter
+filter.tag = tag
+
+filtertype.ip = IP Number
+filtertype.regexp = Regular expression
+filtertype.useragent= User Agent
+filtertype.throttle = Throttle
+filtertype.hostname = Host name
+filtertype.size= Posting size
+filtertype.urlblacklist = URL Blacklist query
+
+filtererror.title = Error:
+filtererror.invalidtype = Invalid filter type
+filtererror.invalidexpression = Invalid expression for this type
+
+filterlist.htmltitle = Filter rules
+
+filtergroup.name = Name
+filtergroup.moveup = up
+filtergroup.movedown = down
+filtergroup.listfilters = filters
+filtergroup.delete = delete
+filtergrouplist.htmltitle = Filter groups
+
+
+
abuse.log.htmltitle = Anti-abuse open posting log
# head
########## admin ##########
# language: spanish
-# $Id: admin_es.properties,v 1.31 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_es.properties,v 1.32 2007/04/08 21:46:36 idfx Exp $
languagename = Castellano
add = a\u00f1adir
filter = filtrar
attach = adjuntar
-# missing (master value = "remove")
-deattach =
+deattach = quitar
list = mostrar lista
back = atr\u00e1s
cancel = cancelar
commentsearch.field.main_url = URL
commentsearch.field.email = Correo-e
commentsearch.field.description = Descripci\u00f3n
-# missing (master value = "Internal comment")
-commentsearch.field.comment =
+commentsearch.field.comment = Comentario interno
commentsearch.value = Valor
commentsearch.publishedstate = Estado de publicaci\u00f3n
content.operation.unhide = desocultar
content.operation.newswire = newswire
+content.preview.default = Previsualizar
+
contentsearch.value = buscar
contentsearch.field = campo
contentsearch.field.title = T\u00edtulo
contentsearch.field.contents = Contenido
contentsearch.field.creator_email = Correo-e
contentsearch.field.creator_main_url = Direcci\u00f3n web
-# missing (master value = "Internal comment")
-contentsearch.field.comment =
+contentsearch.field.comment = Comentario interno
contentsearch.publishedstate = estado de publicaci\u00f3n
contentsearch.publishedstate.hidden = oculto
superusermenu.languages = idiomas
superusermenu.abuse = aplicar medidas antiabuso
superusermenu.imcs = IMCs (obsoleto)
-# missing (master value = "reload bundles, logging and producers")
-superusermenu.reload =
+superusermenu.reload = Recargar bundles, logs y producers
-# missing (master value = "reload successfull")
-infomessage.reloadSuccessfull =
-# missing (master value = "An error has occurred while reloading: <br>{0}")
-infomessage.reloadFailed =
+infomessage.reloadSuccessfull = Recarga realizada con \u00e9xito
+infomessage.reloadFailed = Ha ocurrido un error al realizar la recarga: <br>{0}
#abuse
abuse.filters = Filtros
abuse.filters.movedown = abajo
abuse.filters.moveup = arriba
-# missing (master value = "bottom")
-abuse.filters.movebottom =
-# missing (master value = "top")
-abuse.filters.movetop =
+abuse.filters.movebottom = hasta abajo
+abuse.filters.movetop = hasta arriba
abuse.filter.type = Tipos
abuse.filter.expression = Expresi\u00f3n
abuse.filtertype.ip = N\u00famero de IP
abuse.filtertype.regexp = Expresi\u00f3n regular
abuse.filtertype.useragent = Navegador
-# missing (master value = "Throttle")
-abuse.filtertype.throttle =
-# missing (master value = "Host name")
-abuse.filtertype.hostname =
+abuse.filtertype.throttle = Extrangulador
+abuse.filtertype.hostname = Nombre host
abuse.filtererror.title = Error:
abuse.filtererror.invalidtype = Tipo de filtro inv\u00e1lido
-########## admin ##########
-# language: euskara / basque
-# $Id: admin_eu.properties,v 1.14 2004/11/06 17:39:45 idfx Exp $
-
-languagename = Euskara
-
-# general
-yes = bai
-no = ez
-dontcare = ez du axola
-all = dena
-month = hilabetea
-year = urtea
-file = fitxategia
-new = berria
-by = nork
-help = laguntza
-
-
-# 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
-administer = administratu
-search = bilatu
-
-
-# special
-fileedit = fitxategia aldatu
-
-
-# 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
-
-system.status = Egoera:
-system.loggedin = Identifikatuta:
-
-# media - used by image, audio, video and other media
-media.urls = URLak
-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 = Gako-hitzak
-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 = Kopurua aldatu
-media.comments = Komentarioak
-media.articles = Artikuluak
-
-medialist.search_text_in = Testua non bilatu
-
-
-# image
-image.htmltitle = Irudia
-imagelist.htmltitle = Irudien zerrenda
-
-
-# audio
-audio.htmltitle = Audioa
-audiolist.htmltitle = Audio zerrenda
-
-
-# video
-video.htmltitle = Bideoa
-videolist.htmltitle = Bideo zerrenda
-
-
-# other
-other_media.htmltitle = Beste baliabide mediatikoa
-other_medialist.htmltitle = Beste baliabide mediatikoen zerrenda
-
-
-# breaking
-breaking.htmltitle = Azken albisteak
-breaking.textinfo = (gehienez 5 lerro / 250 letra)
-breaking.id = id
-breaking.text = testua
-breaking.date = data
-
-breakinglist.htmltitle = Azken albisteen zerrenda
-
-
-# comment
-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 = Artikuluarena
-comment.html = HTML da?
-comment.status = Egoera
-comment.language = Hizkuntza
-comment.allcomments = Komentario guztiak
-comment.comment = Barne-komentarioa
-comment.comment.info = (barne xederako)
-
-comment.operation.hide = ezkutatu
-comment.operation.unhide = agertarazi
-
-
-#commentlist
-commentlist.htmltitle = Komentarioen zerrenda
-commentlist.published = argitaratuta
-commentlist.hidden = ezkutua
-commentlist.allcomments = Artikulu honentzako komentario guztiak
-commentlist.search = bilatu!
-commentlist.activate = aldaketak eragin
-commentlist.order = hurrenkera
-commentlist.order.datedesc = berriena lehenengo
-commentlist.order.dateasc = zaharrena lehenengo
-commentlist.order.articletitle = artikuluaren izenburua
-
-commentsearch.field = Bilatu
-commentsearch.field.title = Izenburua
-commentsearch.field.creator = Egilea
-commentsearch.field.main_url = URL
-commentsearch.field.email = E-posta
-commentsearch.field.description = Deskripzioa
-commentsearch.value = Balorea
-
-commentsearch.publishedstate = Argitaraketa-egoera
-commentsearch.publishedstate.hidden = Ezkutua
-commentsearch.publishedstate.published = Argitaratua
-
-commentsearch.status = Egoera
-
-commentsearch.order = Hurrenkera
-commentsearch.order.datedesc = data (behera)
-commentsearch.order.dateasc = data (gora)
-commentsearch.order.articletitle = artikuluaren izenburua
-
-commentsearch.searchbutton = Bilatu
-
-
-# confirm
-confirm.htmltitle = Ezabaketa baieztatu
-confirm.really_delete = Sarrera hau ezabatu nahi duzu?
-confirm.text = Honek behin betiko ezabatuko du sarrera datu-basetik.
-
-
-# content
-content.htmltitle = Edukia
-content.owner = Jabea
-content.language = Hizkuntza
-content.articletype = Artikulu-mota
-content.topic = Gaia
-content.title = Izenburu luzea
-content.subtitle = Azpi-izenburua
-content.edittitle = 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.keywords = Gako-hitzak
-content.lockedby = {0}-(e)k blokeatua
-content.lock = Blokeatu
-content.unlock = Desblokeatu
-content.forcelock = Blokeoa behartu
-
-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.uploadimage = irudia igo
-content.addaudio = audioa gehitu
-content.uploadaudio = audioa igo
-content.addvideo = bideoa gehitu
-content.uploadvideo = bideoa igo
-content.addother = beste baliabide mediatikoa gehitu
-content.uploadother = beste baliabide mediatikoa igo
-
-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
-
-content.family = Aita eta Semeak
-content.children = Semeak
-content.viewchildren = ikusi
-content.parent = Gurasoa
-content.viewparent = ikusi
-content.clearparent = aukeraketa kendu
-content.selectparent = aukeratu
-
-content.operation.hide = ezkutatu
-content.operation.unhide = agertarazi
-content.operation.newswire = newswirea
-
-contentsearch.value = bilatu
-contentsearch.field = eremua
-contentsearch.field.title = Izenburua
-contentsearch.field.creator = Egilea
-contentsearch.field.contents = Edukiak
-contentsearch.field.creator_email = E-posta
-contentsearch.field.creator_main_url = Web helbidea
-
-contentsearch.publishedstate = argitaraketa-egoera
-contentsearch.publishedstate.hidden = ezkutua
-contentsearch.publishedstate.published = argitaratua
-
-contentsearch.articletype = artikulu-mota
-
-contentsearch.order = hurrenkera
-contentsearch.order.datedesc = Berriena lehenengo
-contentsearch.order.dateasc = Zaharrena lehenengo
-contentsearch.order.title = Izenburua
-contentsearch.order.creator = Egilea
-contentsearch.searchbutton = Bilatu
-
-
-#contentlist
-contentlist.htmltitle = Edukien zerrenda
-contentlist.comments = komentarioak
-contentlist.select = Aukeratu
-
-
-# language
-language.htmltitle = Hizkuntza
-language.id = Id
-language.name = hizkuntza
-language.code = Hizkuntza-kodea
-
-languagelist.htmltitle = Hizkuntzen zerrenda
-
-# login
-login.htmltitle = Sarrera
-login.info = Eremu hau baimendutako taldeentzat bakarrik da. Editore lanetan lagundu nahi baduzu, jar zaitez gurekin kontaktuan <a href="mailto:imc-euskalherria-editorial@lists.indymedia.org">imc-euskalherria-editorial@lists.indymedia.org</a> helbidean mesedez.
-login.title = erabiltzailea
-login.name = Erabiltzailea
-login.password = Pasahitza
-login.language = Hizkuntza
-login.submit = Ados
-
-
-# mediafolder
-mediafolder.htmltitle = Baliabide mediatikoen karpeta
-mediafolder.id = id
-mediafolder.date = data
-mediafolder.name = izena
-mediafolder.location = jatorrizko lekua
-mediafolder.keywords = gako-hitzak
-mediafolder.comment = komentarioa
-
-mediafolderlist.htmltitle = Baliabide mediatikoen karpeten zerrenda
-
-
-# message
-message.htmltitle = Mezuak
-message.id = id
-message.date = data
-message.title = izenburua
-message.creator = Egilea
-message.text = testua
-message.textinfo = (gehienez 5 lerro / 250 letra)
-
-messagelist.htmltitle = Mezuen zerrenda
-
-# admin start page
-start.htmltitle = Administrazioa
-
-start.content.new = artikulu berriak
-start.show = Erakutsi
-start.comment.open_by_id = komentario-ireki zenbakia:
-start.content.open_by_id = artikulu-ireki zenbakia:
-
-start.content.hidden = artikulu 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.allcommentswithstatus = {0}
-
-start.producers.title = Eskuz ekoiztu
-start.producers.produceAllNew = Berri guztia ekoiztu
-start.producers.recipe.allnew = Berri guztia ekoiztu
-
-start.producers.advanced = Aukera arreratuak (kontuz honekin!)
-
-start.administer.title = ADMINISTRATU
-start.administer.comments = komentarioak
-
-start.comments.title = KOMENTARIOAK
-
-start.breaking.title = AZKEN ALBISTEAK
-start.articles.title = ARTIKULUAK
-start.fileedit.includes.title = include fitxategiak aldatu
-start.addandedit.title = GEHITU / ALDATU
-start.extra.title = EXTRA
-start.search.title = BILAKETA
-start.other_media.title = BESTE MEDIOEN FITXATEGIAK
-start.images.title = IRUDIAK
-start.images.open_by_id = irudi-ireki zenbakia:
-start.video.title = BIDEO FITXATEGIAK
-start.audio.title = AUDIO FITXATEGIAK
-start.media.title = MEDIA
-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 = Goi-erabiltzaileentzako funtzioak (kontuz honekin!)
-
-
-# topic
-
-topic.htmltitle = Gaia
-
-topic.id = id
-topic.title = Izena
-topic.description = deskripzioa
-topic.filename = Fitxategiaren izena
-topic.main_url = Informazio nagusiko orria
-topic.archive_url = Fitxategiaren URLa
-
-topiclist.htmltitle = Gaien zerrenda
-
-
-# users
-user.htmltitle = Erabiltzailea
-user.login = erabiltzailea
-user.ownpassword = Zure pasahitza
-user.oldpassword = Pasahitz zaharra
-user.password = Pasahitza
-user.password2 = Pasahitza (berriro)
-user.admin = administratzailea
-user.is_disabled = Ezgaituta?
-user.creationdate = Sorrera-data
-user.lastlogindate = Azken sarketa
-user.email = Posta elektronikoa
-user.comment = Oharra
-user.profile = Profila
-
-
-
-
-userlist.htmltitle = Erabiltzaileen zerrenda
-
-
-#articletype
-articletype.htmltitle = Artikulu-motak
-articletype.id = Id
-articletype.name = Izena
-
-articletypelist.htmltitle = Artikulu-moten zerrenda
-
-# mediatypes
-mediatypelist.htmltitle = Media-motak kudeatu
-mediatype.id = Id
-mediatype.name = Izena
-mediatype.htmltitle = Media-mota
-mediatype.mimetype = MIME-mota
-mediatype.classname = Klase izena
-mediatype.tablename = Taula izena
-
-#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
-fileedit.subdirectory = Azpidirektorioa
-
-fileeditlist.htmltitle = Fitxategien aldaketak
-fileeditlist.filename = Fitxategiaren izena
-fileeditlist.dirname = Azpidirektorioa
-
-
-#producers
-producer.producer = Ekoizlearen izena
-producer.verb.name = Lanaren izena
-producer.verb.description = Lanaren deskripzioa
-producer.verb.enqueue = Eskatu
-
-producer.job.name = Lana
-producer.job.status = Egoera
-producer.job.date = azken aldaketa
-producer.job.empty = Ilada hutsik dago
-producer.job.runningtime = Denbora exekuzioan
-
-producer.jobqueue.canceljobs = Aukeratutako lanak ezeztatu
-producer.jobqueue.cancelalljobs = Egiteke dauden lan guztiak ezeztatu
-producer.jobqueue.title = Oraingo lanak
-producer.jobqueue.refresh = birkargatu
-producer.producerlist.title = Lan berri bat gehitu
-
-producerqueue.htmltitle = Eskuz ekoiztu
-
-
-#superusermenu
-superusermenu.htmltitle = Aukera aurreratuak
-superusermenu.manage = KUDEATU
-superusermenu.topics = Gaien kudeaketa
-superusermenu.articletypes = Artikulu-moten kudeaketa
-superusermenu.mediatypes = Media-motak
-superusermenu.comment_statuses = Komentarioen egoeraren kudeaketa
-superusermenu.users = Erabiltzaileen kudeaketa
-superusermenu.languages = Hizkuntzen kudeaketa
-superusermenu.abuse = gehiegikerien aurkako neurriak eragin
-superusermenu.imcs = MIGen zerrendaren kudeaketa (zaharkitua)
-
-
-#abuse
-abuse.htmltitle = gehiegikerien aurkako neurriak
-
-abuse.setting = Aukera
-abuse.value = Balioa
-
-abuse.disableopenpostings = bidalketa-irekia itxi
-abuse.openpostingpassword = bidalketa-irekientzako pasahitza eskatu
-abuse.logpostings = bidalketa-irekien IPak gorde
-abuse.logsize = Gordetako log-aren tamaina
-abuse.cookies = Blokeatutako erabiltzaileekin cookie-ak erabili
-abuse.articleaction = Blokeatutako artikuluekin egin beharrekoa
-abuse.commentaction = Blokeatutako komentarioekin egin beharrekoa
-
-abuse.showlog = IPen log-a erakutsi
-abuse.showfilters = Iragazkiak kudeatu
-
-abuse.log.time = Ordua
-abuse.log.address = IP zenbakia
-abuse.log.object = Objektua
-abuse.log.browser = Nabigatzaiela
-abuse.log.filtertype = Iragazki-mota
-abuse.log.filterexpression = Espresioa
-
-abuse.filters = Iragazkiak
-abuse.filters.movedown = bera
-abuse.filters.moveup = gora
-
-abuse.filter.type = Motak
-abuse.filter.expression = Espresioa
-abuse.filter.articleaction = Artikulua
-abuse.filter.commentaction = Komentarioa
-abuse.filter.comments = Komentarioak (barne xederako)
-abuse.filter.lasthit = Azken hit-a
-abuse.filter.htmltitle = Iragazkia aldatu
-
-abuse.filtertype.ip = IP Zenbakia
-abuse.filtertype.regexp = Espresio erregularra
-abuse.filtertype.useragent = Nabigatzailea
-
-abuse.filtererror.title = Errakuntza:
-abuse.filtererror.invalidtype = Iragazki-mota okerra
-abuse.filtererror.invalidexpression = Mota honentzako espresio okerra
-
-abuse.filters.htmltitle = Gehiegikerien aurkako iragazki arauak
-abuse.log.htmltitle = Gehiegikerien aurkako bidalketa-irekien log-a
-
-# head
-head.start = hasiera
-head.logout = irten
-head.changepassword = pasahitza
-head.help = laguntza
-head.search = bilatu
-head.logged_in = erregistraturik zaude
-
-# foot
-foot.top = gora
-
-
-########## dynamic values ##########
-
-# (users can add new types, how to translate these)
-# suggestion if not in bundle use value as Text
-
-
-# Article types
-articletypes.openposting = bidalketa-irekia
-articletypes.newswire = newswirea
-articletypes.feature = azalekoa
-articletypes.topicspecial = gaiko berezia
-articletypes.startspecial = azaleko berezia
-
-# Comment status values
-commentstatus.normal = normala
-
-
-
-########## error ##########
-error.htmltitle = Errakuntza
-error.title = Iep! Errakuntza bat gertatu da
-error.text = Ondoren datorren mezuak agian ez dizu askorik lagunduko, baina seguraski <a href="mailto:{0}">{1}</a>koei bai.
-error.text2 = Mesedez, bidali posta elektronikoko mezu bat <a href="mailto:{0}">{1}</a>ra <font color="Red">gorriz agertzen den testuarekin</font> eta egiten ari zinenaren azalpenarekin (fitxategia igotzen, artikulua bidaltzen, komentarioa bidaltzen, bilaketa egiten...). 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
-
-media.error.unsupportedformat = Igo duzun baliabide mediatikoaren formatuarekin ez dugu lan egiten
-user.error.missingpasswords = Pasahitz berria birritan sartu beharra dago
-user.error.passwordmismatch = Pasahitzak ez dira berdinak
-user.error.missingpassword = Pasahitz bat sartu beharra dago
-user.error.incorrectpassword = Pasahitza okerra da
-
-
-########## infomessages ##########
-infomessage.htmltitle = Oharra
-infomessage.recipeAddedToQueue = Zure eskaria ilarara gehitu da
+########## admin ##########\r
+# language: euskara / basque\r
+# $Id: admin_eu.properties,v 1.15 2007/04/08 21:46:36 idfx Exp $\r
+\r
+languagename = Euskara\r
+\r
+# general\r
+yes = bai\r
+no = ez\r
+dontcare = ez du axola\r
+all = dena\r
+month = hilabetea\r
+year = urtea\r
+file = fitxategia\r
+new = berria\r
+by = nork\r
+help = laguntza\r
+\r
+\r
+# actions\r
+insert = sartu\r
+save = gorde\r
+edit = aldatu\r
+delete = ezabatu\r
+add = gehitu\r
+filter = iragazi\r
+attach = atxeki\r
+list = zerrenda erakutsi\r
+back = atzera\r
+cancel = utzi\r
+preview = aurrebista\r
+reset = berrasieratu\r
+administer = administratu\r
+search = bilatu\r
+\r
+\r
+# special\r
+fileedit = fitxategia aldatu\r
+\r
+\r
+# records\r
+records = sarrerak\r
+show_from_to = {0}-(e)tik {1}-(e)ra bitarteko sarrerak erakusten\r
+no_matches_found = Ez da horrelako sarrerarik aurkitu!\r
+list.next = hurrengoa\r
+list.previous = aurrekoa\r
+\r
+system.status = Egoera:\r
+system.loggedin = Identifikatuta:\r
+\r
+# media - used by image, audio, video and other media\r
+media.urls = URLak\r
+media.created = sortua\r
+media.changed = aldatua\r
+media.published = argitaratua\r
+media.format = Formatua\r
+media.rights = Egile eskubideak\r
+media.type = Mota\r
+media.mediafolder = Baliabide mediatikoen karpeta\r
+media.title = Izenburua\r
+media.size = Tamaina\r
+media.description = Deskripzioa\r
+media.date = Data\r
+media.location = Jatorrizko lekua\r
+media.creator = Egilea\r
+media.keywords = Gako-hitzak\r
+media.comment = Komentarioa\r
+media.source = Jatorria\r
+media.is_published = Argitaratzeko prest\r
+media.icon = Ikonoa\r
+media.nr_of_media = Baliabide mediatikoen kopurua\r
+media.nr_of_media.submit = Kopurua aldatu\r
+media.comments = Komentarioak\r
+media.articles = Artikuluak\r
+\r
+medialist.search_text_in = Testua non bilatu\r
+\r
+\r
+# image\r
+image.htmltitle = Irudia\r
+imagelist.htmltitle = Irudien zerrenda\r
+\r
+\r
+# audio\r
+audio.htmltitle = Audioa\r
+audiolist.htmltitle = Audio zerrenda\r
+\r
+\r
+# video\r
+video.htmltitle = Bideoa\r
+videolist.htmltitle = Bideo zerrenda\r
+\r
+\r
+# other\r
+other_media.htmltitle = Beste baliabide mediatikoa\r
+other_medialist.htmltitle = Beste baliabide mediatikoen zerrenda\r
+\r
+\r
+# breaking\r
+breaking.htmltitle = Azken albisteak\r
+breaking.textinfo = (gehienez 5 lerro / 250 letra)\r
+breaking.id = id\r
+breaking.text = testua\r
+breaking.date = data\r
+\r
+breakinglist.htmltitle = Azken albisteen zerrenda\r
+\r
+\r
+# comment\r
+comment.htmltitle = Komentarioa\r
+comment.date = data\r
+comment.title = izenburua\r
+comment.published = argitaratuta\r
+comment.text = komentarioaren testua\r
+comment.address = helbidea\r
+comment.phone = telefonoa\r
+comment.email = posta elektronikoa\r
+comment.url = URL\r
+comment.creator = egilea\r
+comment.article = Artikuluarena\r
+comment.html = HTML da?\r
+comment.status = Egoera\r
+comment.language = Hizkuntza\r
+comment.allcomments = Komentario guztiak\r
+comment.comment = Barne-komentarioa\r
+comment.comment.info = (barne xederako)\r
+\r
+comment.operation.hide = ezkutatu\r
+comment.operation.unhide = agertarazi\r
+\r
+\r
+#commentlist\r
+commentlist.htmltitle = Komentarioen zerrenda\r
+commentlist.published = argitaratuta\r
+commentlist.hidden = ezkutua\r
+commentlist.allcomments = Artikulu honentzako komentario guztiak\r
+commentlist.search = bilatu!\r
+commentlist.activate = aldaketak eragin\r
+commentlist.order = hurrenkera\r
+commentlist.order.datedesc = berriena lehenengo\r
+commentlist.order.dateasc = zaharrena lehenengo\r
+commentlist.order.articletitle = artikuluaren izenburua\r
+\r
+commentsearch.field = Bilatu\r
+commentsearch.field.title = Izenburua\r
+commentsearch.field.creator = Egilea\r
+commentsearch.field.main_url = URL\r
+commentsearch.field.email = E-posta\r
+commentsearch.field.description = Deskripzioa\r
+commentsearch.value = Balorea\r
+\r
+commentsearch.publishedstate = Argitaraketa-egoera\r
+commentsearch.publishedstate.hidden = Ezkutua\r
+commentsearch.publishedstate.published = Argitaratua\r
+\r
+commentsearch.status = Egoera\r
+\r
+commentsearch.order = Hurrenkera\r
+commentsearch.order.datedesc = data (behera)\r
+commentsearch.order.dateasc = data (gora)\r
+commentsearch.order.articletitle = artikuluaren izenburua\r
+\r
+commentsearch.searchbutton = Bilatu\r
+\r
+\r
+# confirm\r
+confirm.htmltitle = Ezabaketa baieztatu\r
+confirm.really_delete = Sarrera hau ezabatu nahi duzu?\r
+confirm.text = Honek behin betiko ezabatuko du sarrera datu-basetik.\r
+\r
+\r
+# content\r
+content.htmltitle = Edukia\r
+content.owner = Jabea\r
+content.language = Hizkuntza\r
+content.articletype = Artikulu-mota\r
+content.topic = Gaia\r
+content.title = Izenburu luzea\r
+content.subtitle = Azpi-izenburua\r
+content.edittitle = Testuinguru izenburua\r
+content.location = Jatorrizko lekua\r
+content.creator = Egilea\r
+content.creator.email = Posta elektronikoa\r
+content.creator.url = Web\r
+content.creator.address = Helbidea\r
+content.creator.telephone = Telefonoa\r
+content.abstract = Deskripzio laburra\r
+content.content = Edukia\r
+content.html = HTML da?\r
+content.comment = Barne komentarioa\r
+content.internal = (barne xederako)\r
+content.keywords = Gako-hitzak\r
+content.lockedby = {0}-(e)k blokeatua\r
+content.lock = Blokeatu\r
+content.unlock = Desblokeatu\r
+content.forcelock = Blokeoa behartu\r
+\r
+content.attachments = Atxekiak\r
+content.images = Irudiak\r
+content.audio = Audioa\r
+content.video = Bideoa\r
+content.other = Beste baliabide mediatikoak\r
+content.media = Baliabide mediatikoak\r
+content.addimage = irudia gehitu\r
+content.uploadimage = irudia igo\r
+content.addaudio = audioa gehitu\r
+content.uploadaudio = audioa igo\r
+content.addvideo = bideoa gehitu\r
+content.uploadvideo = bideoa igo\r
+content.addother = beste baliabide mediatikoa gehitu\r
+content.uploadother = beste baliabide mediatikoa igo\r
+\r
+content.creationdate = data\r
+content.modificationdate = azken aldaketa\r
+content.status = Egoera\r
+content.type = Artikulu-mota\r
+content.import_date = sarreraren data\r
+content.lastchange_date = azken aldaketa\r
+content.create_date = data\r
+content.published = argitaratua\r
+content.comments = Komentarioak\r
+\r
+content.family = Aita eta Semeak\r
+content.children = Semeak\r
+content.viewchildren = ikusi\r
+content.parent = Gurasoa\r
+content.viewparent = ikusi\r
+content.clearparent = aukeraketa kendu\r
+content.selectparent = aukeratu\r
+\r
+content.operation.hide = ezkutatu\r
+content.operation.unhide = agertarazi\r
+content.operation.newswire = newswirea\r
+\r
+contentsearch.value = bilatu\r
+contentsearch.field = eremua\r
+contentsearch.field.title = Izenburua\r
+contentsearch.field.creator = Egilea\r
+contentsearch.field.contents = Edukiak\r
+contentsearch.field.creator_email = E-posta\r
+contentsearch.field.creator_main_url = Web helbidea\r
+\r
+contentsearch.publishedstate = argitaraketa-egoera\r
+contentsearch.publishedstate.hidden = ezkutua\r
+contentsearch.publishedstate.published = argitaratua\r
+\r
+contentsearch.articletype = artikulu-mota\r
+\r
+contentsearch.order = hurrenkera\r
+contentsearch.order.datedesc = Berriena lehenengo\r
+contentsearch.order.dateasc = Zaharrena lehenengo\r
+contentsearch.order.title = Izenburua\r
+contentsearch.order.creator = Egilea\r
+contentsearch.searchbutton = Bilatu\r
+\r
+\r
+#contentlist\r
+contentlist.htmltitle = Edukien zerrenda\r
+contentlist.comments = komentarioak\r
+contentlist.select = Aukeratu\r
+\r
+\r
+# language\r
+language.htmltitle = Hizkuntza\r
+language.id = Id\r
+language.name = hizkuntza\r
+language.code = Hizkuntza-kodea\r
+\r
+languagelist.htmltitle = Hizkuntzen zerrenda\r
+\r
+# login\r
+login.htmltitle = Sarrera\r
+login.info = Eremu hau baimendutako taldeentzat bakarrik da. Editore lanetan lagundu nahi baduzu, jar zaitez gurekin kontaktuan <a href="mailto:imc-euskalherria-editorial@lists.indymedia.org">imc-euskalherria-editorial@lists.indymedia.org</a> helbidean mesedez.\r
+login.title = erabiltzailea\r
+login.name = Erabiltzailea\r
+login.password = Pasahitza\r
+login.language = Hizkuntza\r
+login.submit = Ados\r
+\r
+\r
+# mediafolder\r
+mediafolder.htmltitle = Baliabide mediatikoen karpeta\r
+mediafolder.id = id\r
+mediafolder.date = data\r
+mediafolder.name = izena\r
+mediafolder.location = jatorrizko lekua\r
+mediafolder.keywords = gako-hitzak\r
+mediafolder.comment = komentarioa\r
+\r
+mediafolderlist.htmltitle = Baliabide mediatikoen karpeten zerrenda\r
+\r
+\r
+# message\r
+message.htmltitle = Mezuak\r
+message.id = id\r
+message.date = data\r
+message.title = izenburua\r
+message.creator = Egilea\r
+message.text = testua\r
+message.textinfo = (gehienez 5 lerro / 250 letra)\r
+\r
+messagelist.htmltitle = Mezuen zerrenda\r
+\r
+# admin start page\r
+start.htmltitle = Administrazioa\r
+\r
+start.content.new = artikulu berriak\r
+start.show = Erakutsi\r
+start.comment.open_by_id = komentario-ireki zenbakia:\r
+start.content.open_by_id = artikulu-ireki zenbakia:\r
+\r
+start.content.hidden = artikulu ezkutukoak\r
+start.content.not_published = argitaratzeke dauden artikuluak\r
+start.content.with_media = baliabide mediatikoekin\r
+start.content.last_changes = azken aldaketak\r
+start.content.with_comments = barne xederako komentarioekin\r
+start.content.all = Artikulu guztiak\r
+start.content.search = bilatu\r
+\r
+start.allarticlesoftype = {0}-motatako artikulu guztiak\r
+start.allcommentswithstatus = {0}\r
+\r
+start.producers.title = Eskuz ekoiztu\r
+start.producers.produceAllNew = Berri guztia ekoiztu\r
+start.producers.recipe.allnew = Berri guztia ekoiztu\r
+\r
+start.producers.advanced = Aukera arreratuak (kontuz honekin!)\r
+\r
+start.administer.title = ADMINISTRATU\r
+start.administer.comments = komentarioak\r
+\r
+start.comments.title = KOMENTARIOAK\r
+\r
+start.breaking.title = AZKEN ALBISTEAK\r
+start.articles.title = ARTIKULUAK\r
+start.fileedit.includes.title = include fitxategiak aldatu\r
+start.addandedit.title = GEHITU / ALDATU\r
+start.extra.title = EXTRA\r
+start.search.title = BILAKETA\r
+start.other_media.title = BESTE MEDIOEN FITXATEGIAK\r
+start.images.title = IRUDIAK\r
+start.images.open_by_id = irudi-ireki zenbakia:\r
+start.video.title = BIDEO FITXATEGIAK\r
+start.audio.title = AUDIO FITXATEGIAK\r
+start.media.title = MEDIA\r
+start.mediafolder.title = BALIABIDE MEDIATIKOEN ZERRENDA\r
+start.languages.title = IZENBURUA\r
+start.imcs.title = MIGak\r
+start.messageboard.title = Barneko mezuak\r
+start.messageboard.no_messages = ez dago mezurik\r
+\r
+start.superusermenu = Goi-erabiltzaileentzako funtzioak (kontuz honekin!)\r
+\r
+\r
+# topic\r
+\r
+topic.htmltitle = Gaia\r
+\r
+topic.id = id\r
+topic.title = Izena\r
+topic.description = deskripzioa\r
+topic.filename = Fitxategiaren izena\r
+topic.main_url = Informazio nagusiko orria\r
+topic.archive_url = Fitxategiaren URLa\r
+\r
+topiclist.htmltitle = Gaien zerrenda\r
+\r
+\r
+# users\r
+user.htmltitle = Erabiltzailea\r
+user.login = erabiltzailea\r
+user.ownpassword = Zure pasahitza\r
+user.oldpassword = Pasahitz zaharra\r
+user.password = Pasahitza\r
+user.password2 = Pasahitza (berriro)\r
+user.admin = administratzailea\r
+user.is_disabled = Ezgaituta?\r
+user.creationdate = Sorrera-data\r
+user.lastlogindate = Azken sarketa\r
+user.email = Posta elektronikoa\r
+user.comment = Oharra\r
+user.profile = Profila\r
+\r
+\r
+\r
+\r
+userlist.htmltitle = Erabiltzaileen zerrenda\r
+\r
+\r
+#articletype\r
+articletype.htmltitle = Artikulu-motak\r
+articletype.id = Id\r
+articletype.name = Izena\r
+\r
+articletypelist.htmltitle = Artikulu-moten zerrenda\r
+\r
+# mediatypes\r
+mediatypelist.htmltitle = Media-motak kudeatu\r
+mediatype.id = Id\r
+mediatype.name = Izena\r
+mediatype.htmltitle = Media-mota\r
+mediatype.mimetype = MIME-mota\r
+mediatype.classname = Klase izena\r
+mediatype.tablename = Taula izena\r
+\r
+#commentstatus\r
+commentstatus.htmltitle = Komentarioen egoera\r
+commentstatus.id = Id\r
+commentstatus.name = Izena\r
+\r
+commentstatuslist.htmltitle = Komentarioen egoeraren zerrenda\r
+\r
+\r
+\r
+#file editing\r
+fileedit.htmltitle = Fitxategia aldatu\r
+fileedit.filename = Fitxategiaren izena\r
+fileedit.subdirectory = Azpidirektorioa\r
+\r
+fileeditlist.htmltitle = Fitxategien aldaketak\r
+fileeditlist.filename = Fitxategiaren izena\r
+fileeditlist.dirname = Azpidirektorioa\r
+\r
+\r
+#producers\r
+producer.producer = Ekoizlearen izena\r
+producer.verb.name = Lanaren izena\r
+producer.verb.description = Lanaren deskripzioa\r
+producer.verb.enqueue = Eskatu\r
+\r
+producer.job.name = Lana\r
+producer.job.status = Egoera\r
+producer.job.date = azken aldaketa\r
+producer.job.empty = Ilada hutsik dago\r
+producer.job.runningtime = Denbora exekuzioan\r
+\r
+producer.jobqueue.canceljobs = Aukeratutako lanak ezeztatu\r
+producer.jobqueue.cancelalljobs = Egiteke dauden lan guztiak ezeztatu\r
+producer.jobqueue.title = Oraingo lanak\r
+producer.jobqueue.refresh = birkargatu\r
+producer.producerlist.title = Lan berri bat gehitu\r
+\r
+producerqueue.htmltitle = Eskuz ekoiztu\r
+\r
+\r
+#superusermenu\r
+superusermenu.htmltitle = Aukera aurreratuak\r
+superusermenu.manage = KUDEATU\r
+superusermenu.topics = Gaien kudeaketa\r
+superusermenu.articletypes = Artikulu-moten kudeaketa\r
+superusermenu.mediatypes = Media-motak\r
+superusermenu.comment_statuses = Komentarioen egoeraren kudeaketa\r
+superusermenu.users = Erabiltzaileen kudeaketa\r
+superusermenu.languages = Hizkuntzen kudeaketa\r
+superusermenu.abuse = gehiegikerien aurkako neurriak eragin\r
+superusermenu.imcs = MIGen zerrendaren kudeaketa (zaharkitua)\r
+\r
+\r
+#abuse\r
+abuse.htmltitle = gehiegikerien aurkako neurriak\r
+\r
+abuse.setting = Aukera\r
+abuse.value = Balioa\r
+\r
+abuse.disableopenpostings = bidalketa-irekia itxi\r
+abuse.openpostingpassword = bidalketa-irekientzako pasahitza eskatu\r
+abuse.logpostings = bidalketa-irekien IPak gorde\r
+abuse.logsize = Gordetako log-aren tamaina\r
+abuse.cookies = Blokeatutako erabiltzaileekin cookie-ak erabili\r
+abuse.articleaction = Blokeatutako artikuluekin egin beharrekoa\r
+abuse.commentaction = Blokeatutako komentarioekin egin beharrekoa\r
+\r
+abuse.showlog = IPen log-a erakutsi\r
+abuse.showfilters = Iragazkiak kudeatu\r
+\r
+abuse.log.time = Ordua\r
+abuse.log.address = IP zenbakia\r
+abuse.log.object = Objektua\r
+abuse.log.browser = Nabigatzaiela\r
+abuse.log.filtertype = Iragazki-mota\r
+abuse.log.filterexpression = Espresioa\r
+\r
+abuse.filters = Iragazkiak\r
+abuse.filters.movedown = bera\r
+abuse.filters.moveup = gora\r
+\r
+abuse.filter.type = Motak\r
+abuse.filter.expression = Espresioa\r
+abuse.filter.articleaction = Artikulua\r
+abuse.filter.commentaction = Komentarioa\r
+abuse.filter.comments = Komentarioak (barne xederako)\r
+abuse.filter.lasthit = Azken hit-a\r
+abuse.filter.htmltitle = Iragazkia aldatu\r
+\r
+abuse.filtertype.ip = IP Zenbakia\r
+abuse.filtertype.regexp = Espresio erregularra\r
+abuse.filtertype.useragent = Nabigatzailea\r
+\r
+abuse.filtererror.title = Errakuntza:\r
+abuse.filtererror.invalidtype = Iragazki-mota okerra\r
+abuse.filtererror.invalidexpression = Mota honentzako espresio okerra\r
+\r
+abuse.filters.htmltitle = Gehiegikerien aurkako iragazki arauak\r
+abuse.log.htmltitle = Gehiegikerien aurkako bidalketa-irekien log-a\r
+\r
+# head\r
+head.start = hasiera\r
+head.logout = irten\r
+head.changepassword = pasahitza\r
+head.help = laguntza\r
+head.search = bilatu\r
+head.logged_in = erregistraturik zaude\r
+\r
+# foot\r
+foot.top = gora\r
+\r
+\r
+########## dynamic values ##########\r
+\r
+# (users can add new types, how to translate these)\r
+# suggestion if not in bundle use value as Text\r
+\r
+\r
+# Article types\r
+articletypes.openposting = bidalketa-irekia\r
+articletypes.newswire = newswirea\r
+articletypes.feature = azalekoa\r
+articletypes.topicspecial = gaiko berezia\r
+articletypes.startspecial = azaleko berezia\r
+\r
+# Comment status values\r
+commentstatus.normal = normala\r
+\r
+\r
+\r
+########## error ##########\r
+error.htmltitle = Errakuntza\r
+error.title = Iep! Errakuntza bat gertatu da\r
+error.text = Ondoren datorren mezuak agian ez dizu askorik lagunduko, baina seguraski <a href="mailto:{0}">{1}</a>koei bai.\r
+error.text2 = Mesedez, bidali posta elektronikoko mezu bat <a href="mailto:{0}">{1}</a>ra <font color="Red">gorriz agertzen den testuarekin</font> eta egiten ari zinenaren azalpenarekin (fitxategia igotzen, artikulua bidaltzen, komentarioa bidaltzen, bilaketa egiten...). Eskerrik asko!\r
+\r
+usererror.htmltitle = Errakuntza datuetan\r
+usererror.title = Arranopola! Errakuntza bat gertatu da\r
+usererror.text = Sartu dituzun datuek ondoko errakuntza sortarazi dute:\r
+usererror.what_to_do = Mesedez, sakatu atzera botoia eta saiatu berriz\r
+\r
+media.error.unsupportedformat = Igo duzun baliabide mediatikoaren formatuarekin ez dugu lan egiten\r
+user.error.missingpasswords = Pasahitz berria birritan sartu beharra dago\r
+user.error.passwordmismatch = Pasahitzak ez dira berdinak\r
+user.error.missingpassword = Pasahitz bat sartu beharra dago\r
+user.error.incorrectpassword = Pasahitza okerra da\r
+\r
+\r
+########## infomessages ##########\r
+infomessage.htmltitle = Oharra\r
+infomessage.recipeAddedToQueue = Zure eskaria ilarara gehitu da\r
########## admin ##########
# language: galician
-# $Id: admin_gz.properties,v 1.4 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_gz.properties,v 1.5 2007/04/08 21:46:36 idfx Exp $
languagename = Galego
########## admin #######
# language: italiano
-# $Id: admin_it.properties,v 1.3 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_it.properties,v 1.4 2007/04/08 21:46:36 idfx Exp $
# missing (master value = "English")
languagename = italiano
########## admin ##########
# language: dutch
-# $Id: admin_nl.properties,v 1.10 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_nl.properties,v 1.11 2007/04/08 21:46:36 idfx Exp $
languagename = Nederlands
# ######### admin ##########
# language: portuguese
-# $Id: admin_pt.properties,v 1.7 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_pt.properties,v 1.8 2007/04/08 21:46:36 idfx Exp $
languagename = Portugu\u00eas
########## admin ##########
# language: romanian
-# $Id: admin_ro.properties,v 1.2 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_ro.properties,v 1.3 2007/04/08 21:46:36 idfx Exp $
-languagename=Romana
+languagename = Romana
# general
-yes=da
-no=nu
-dontcare=nuconteaza
-all=tot
-month=luna
-year=an
-file=fisier
-new=nou
-by=de
-help=ajutor
+yes = da
+no = nu
+dontcare = nuconteaza
+all = tot
+month = luna
+year = an
+file = fisier
+new = nou
+by = de
+help = ajutor
# actions
-insert=insert
-save=salveaza
-edit=redacteaza
-delete=sterge
-add=adauga
-filter=filtreaza
-attach=ataseaza
-list=browse
-back=inapoi
-cancel=canceleaza
-preview=preview
-reset=reset
-administer=administreaza
-search=cauta
+insert = insert
+save = salveaza
+edit = redacteaza
+delete = sterge
+add = adauga
+filter = filtreaza
+attach = ataseaza
+# missing (master value = "remove")
+deattach =
+list = browse
+back = inapoi
+cancel = canceleaza
+preview = preview
+reset = reset
+administer = administreaza
+search = cauta
# special
-fileedit=redactareFisier
+fileedit = redactareFisier
# records
-records=entries
-show_from_to=arata de la {0} la {1}
-no_matches_found=No matching entries!
-list.next=urmatorul
-list.previous=precedentul
+records = entries
+show_from_to = arata de la {0} la {1}
+no_matches_found = No matching entries!
+list.next = urmatorul
+list.previous = precedentul
+# missing (master value = "Status:")
+system.status =
+# missing (master value = "Logged in:")
+system.loggedin =
# media - used by image, audio, video and other media
-media.created=creat
-media.changed=ultima modificare
-media.published=publicat
-media.format=format
-media.rights=statut copyright
-media.type=tip
-media.mediafolder=dosar Media
-media.title=titlu
-media.size=marime
-media.description=descriere
-media.date=data
-media.location=loc
-media.creator=autor
-media.keywords=keywords
-media.comment=remarci (pentru us intern)
-media.source=sursa
-media.is_published=publicat
-media.icon=icon
-media.nr_of_media=Number of Media Items (max 20)
-media.nr_of_media.submit=define number
-media.comments=Comentarii
-media.articles=Articole
-
-medialist.search_text_in=Cauta text in
+# missing (master value = "Urls")
+media.urls = Urls
+media.created = creat
+media.changed = ultima modificare
+media.published = publicat
+media.format = format
+media.rights = statut copyright
+media.type = tip
+media.mediafolder = dosar Media
+media.title = titlu
+media.size = marime
+media.description = descriere
+media.date = data
+media.location = loc
+media.creator = autor
+media.keywords = keywords
+media.comment = remarci (pentru uz intern)
+media.source = sursa
+media.is_published = publicat
+media.icon = icoana
+media.nr_of_media = Number of Media Items (max 20)
+media.nr_of_media.submit = define number
+media.comments = Comentarii
+media.articles = Articole
+
+medialist.search_text_in = Cauta text in
# image
-image.htmltitle=Imagine
-imagelist.htmltitle=Images overview
+image.htmltitle = Imagine
+imagelist.htmltitle = Imagini overview
# audio
-audio.htmltitle=Audio
-audiolist.htmltitle=Audio overview
+audio.htmltitle = Audio
+audiolist.htmltitle = Audio overview
# video
-video.htmltitle=Video
-videolist.htmltitle=Video overview
+video.htmltitle = Video
+videolist.htmltitle = Video overview
# other
-other_media.htmltitle=Alta media
-other_medialist.htmltitle=Other media overview
+other_media.htmltitle = Alta media
+other_medialist.htmltitle = Alta media overview
# breaking
-breaking.htmltitle=Ultimile stiri
-breaking.textinfo=(max. 5 linii / 250 caractere)
+breaking.htmltitle = Ultimile stiri
+breaking.textinfo = (max. 5 linii / 250 caractere)
breaking.id = id
-breaking.text=text
-breaking.date=data
+breaking.text = text
+breaking.date = data
-breakinglist.htmltitle=Breaking news overview
+breakinglist.htmltitle = Breaking news overview
# comment
-comment.htmltitle=Comment
-comment.date=Data
-comment.title=Titlu
-comment.published=Publicat
-comment.text=Comenteaza textul
-comment.address=Adresa
-comment.phone=Telefon
-comment.email=Email
-comment.url=Url
-comment.creator=Autor
-comment.article=Articol
-comment.html=HTML
-comment.status=Statut
-comment.language=Limba
-comment.allcomments=Toate comentariile
-
-comment.operation.hide=ascunde
-comment.operation.unhide=neascunde
+comment.htmltitle = Comentariu
+comment.date = Data
+comment.title = Titlu
+comment.published = Publicat
+comment.text = Comenteaza textul
+comment.address = Adresa
+comment.phone = Telefon
+comment.email = Email
+comment.url = Url
+comment.creator = Autor
+comment.article = Articol
+comment.html = HTML
+comment.status = Statut
+comment.language = Limba
+comment.allcomments = Toate comentariile
+# missing (master value = "Internal Comment")
+comment.comment = Comentar intern
+# missing (master value = "(internal)")
+comment.comment.info =
+
+comment.operation.hide = ascunde
+comment.operation.unhide = neascunde
#commentlist
-commentlist.htmltitle=comentarii
-commentlist.published=publicat
-commentlist.hidden=ascuns
-commentlist.allcomments=Toate comentariile despre acest articol
-commentlist.search=go!
+commentlist.htmltitle = comentarii
+commentlist.published = publicat
+commentlist.hidden = ascuns
+commentlist.allcomments = Toate comentariile despre acest articol
+commentlist.search = go!
commentlist.activate = activeaza schimbarile
commentlist.order = ordoneaza
-commentlist.order.datedesc= data (desc.)
-commentlist.order.dateasc= data (asc.)
-commentlist.order.articletitle= titlul articolui
+commentlist.order.datedesc = data (desc.)
+commentlist.order.dateasc = data (asc.)
+commentlist.order.articletitle = titlul articolui
commentsearch.field = Cauta
commentsearch.field.title = Titlu
commentsearch.field.main_url = Url
commentsearch.field.email = Email
commentsearch.field.description = Descriere
+# missing (master value = "Internal comment")
+commentsearch.field.comment = Comentar intern
commentsearch.value = Value
commentsearch.publishedstate = Statut publicat
commentsearch.status = Statut
commentsearch.order = Ordine
-commentsearch.order.datedesc= data (desc.)
-commentsearch.order.dateasc= data (asc.)
-commentsearch.order.articletitle= titlul articolui
+commentsearch.order.datedesc = data (desc.)
+commentsearch.order.dateasc = data (asc.)
+commentsearch.order.articletitle = titlul articolui
commentsearch.searchbutton = Cauta
# confirm
-confirm.htmltitle=confirmare de stergere
-confirm.really_delete=Esti sigur ca vrei sa stergi acest articol?
-confirm.text=Aceasta operatiune este ireversibila.
+confirm.htmltitle = confirmare de stergere
+confirm.really_delete = Esti sigur ca vrei sa stergi acest articol?
+confirm.text = Aceasta operatiune este ireversibila.
# content
-content.htmltitle=Articol
-content.owner=Proprietar
-content.language=Limba
-content.articletype=Tip de articol
-content.topic=Subiect
-content.title=Titlul Lung
-content.subtitle=Titlul scurt
-content.edittitle=Titlul de context
-content.location=Loc
-content.creator=Autor
-content.creator.email=E-mail
-content.creator.url=Web address
-content.creator.address=Adresa
-content.creator.telephone=Telefon
-content.abstract=Abstract
-content.content=Continut
-content.html=HTML
-content.comment=Comentar intern
-content.internal=(intern)
-
-content.attachments=Atasamente
-content.images=Imagini
-content.audio=Audio
-content.video=Video
-content.other=Alta media
-content.media=Media
-content.addimage=adauga imagine
-content.uploadimage=incaraca imagine
-content.addaudio=adauga audio
-content.uploadaudio=incarca audio
-content.addvideo=adauga video
-content.uploadvideo=incarca video
-content.addother=adauga alta media
-content.uploadother=incarca alta media
-
-content.creationdate=data
-content.modificationdate=ultima schimbare
-content.status=Statut
-content.type=Tip de articol
-content.import_date=Data de importare
-content.lastchange_date=Ultima modificare
-content.create_date=Data
-content.published=publicat
-content.comments=comentarii
-
-content.family=Copii si Parinti
-content.children=Copii
-content.viewchildren=view
-content.parent=Parinte
-content.viewparent=view
-content.clearparent=de-selecteaza
-content.selectparent=selecteaza
-
-content.operation.hide=ascunde
-content.operation.unhide=ne-ascunde
-content.operation.newswire=newswire
+content.htmltitle = Articol
+content.owner = Proprietar
+content.language = Limba
+content.articletype = Tip de articol
+content.topic = Subiect
+content.title = Titlul Lung
+content.subtitle = Titlul scurt
+content.edittitle = Titlul de context
+content.location = Loc
+content.creator = Autor
+content.creator.email = E-mail
+content.creator.url = Web address
+content.creator.address = Adresa
+content.creator.telephone = Telefon
+content.abstract = Abstract
+content.content = Continut
+content.html = HTML
+content.comment = Comentar intern
+content.internal = (intern)
+# missing (master value = "Keywords")
+content.keywords = Cuvinteclava
+# missing (master value = "Locked by {0}")
+content.lockedby =
+# missing (master value = "Lock")
+content.lock =
+# missing (master value = "Unlock")
+content.unlock =
+# missing (master value = "Force lock")
+content.forcelock =
+
+content.attachments = Atasamente
+content.images = Imagini
+content.audio = Audio
+content.video = Video
+content.other = Alta media
+content.media = Media
+content.addimage = adauga imagine
+content.uploadimage = incarca imagine
+content.addaudio = adauga audio
+content.uploadaudio = incarca audio
+content.addvideo = adauga video
+content.uploadvideo = incarca video
+content.addother = adauga alta media
+content.uploadother = incarca alta media
+
+content.creationdate = data
+content.modificationdate = ultima schimbare
+content.status = Statut
+content.type = Tip de articol
+content.import_date = Data de importare
+content.lastchange_date = Ultima modificare
+content.create_date = Data
+content.published = publicat
+content.comments = comentarii
+
+content.family = Copii si Parinti
+content.children = Copii
+content.viewchildren = view
+content.parent = Parinte
+content.viewparent = view
+content.clearparent = de-selecteaza
+content.selectparent = selecteaza
+
+content.operation.hide = ascunde
+content.operation.unhide = ne-ascunde
+content.operation.newswire = newswire
+
+# missing (master value = "Preview")
+content.preview.default = Preview
contentsearch.value = cauta
contentsearch.field = field
contentsearch.field.title = Titlu
contentsearch.field.creator = Autor
-contentsearch.field.contents=Continut
+contentsearch.field.contents = Continut
contentsearch.field.creator_email = Email
-contentsearch.field.creator_main_url = Web address
+contentsearch.field.creator_main_url = Adresa web
+# missing (master value = "Internal comment")
+contentsearch.field.comment =
contentsearch.publishedstate = statut de publicare
-contentsearch.publishedstate.hidden=ascuns
-contentsearch.publishedstate.published=publicat
+contentsearch.publishedstate.hidden = ascuns
+contentsearch.publishedstate.published = publicat
contentsearch.articletype = tip de articol
contentsearch.order = in ordine de
-contentsearch.order.datedesc=cel mai nou primul
-contentsearch.order.dateasc=cel mai vechi primul
-contentsearch.order.title=Titlu
-contentsearch.order.creator=Aautor
-contentsearch.searchbutton=Cauta
+contentsearch.order.datedesc = cel mai nou primul
+contentsearch.order.dateasc = cel mai vechi primul
+contentsearch.order.title = Titlu
+contentsearch.order.creator = Autor
+contentsearch.searchbutton = Cauta
#contentlist
-contentlist.htmltitle=Articole
-contentlist.comments=Comentarii
-contentlist.select=Selecteaza
+contentlist.htmltitle = Articole
+contentlist.comments = Comentarii
+contentlist.select = Selecteaza
# language
-language.htmltitle=Llimba
-language.id=Id
-language.name=Limba
-language.code=Limbaj cod
+language.htmltitle = Llimba
+language.id = Id
+language.name = Limba
+language.code = Cod limbaj
-languagelist.htmltitle=Limbi
+languagelist.htmltitle = Limbi
# login
-login.htmltitle=login
-login.info=Aceasta parte este accesibila doar celor care sint autorizati. Daca doresti sa participi in grupul editorial, contacteaza-ne la {0}.
-login.title=login
-login.name=Login
-login.password=Parola
-login.language=Limba
-login.submit= OK
+login.htmltitle = login
+login.info = Aceasta parte este accesibila doar celor care sint autorizati. Daca doresti sa participi in grupul editorial, contacteaza-ne la {0}.
+login.title = login
+login.name = Login
+login.password = Parola
+login.language = Limba
+login.submit = OK
# mediafolder
-mediafolder.htmltitle=dosarmedia
-mediafolder.id=id
-mediafolder.date=data
-mediafolder.name=nume
-mediafolder.location=loc
-mediafolder.keywords=keywords
-mediafolder.comment=comentariu
+mediafolder.htmltitle = dosarmedia
+mediafolder.id = id
+mediafolder.date = data
+mediafolder.name = nume
+mediafolder.location = loc
+mediafolder.keywords = cuvinteclava
+mediafolder.comment = comentariu
-mediafolderlist.htmltitle=media folder list
+mediafolderlist.htmltitle = media folder list
# message
-message.htmltitle=messages
-message.id=id
-message.date=data
-message.title=titlu
-message.creator=autor
-message.text=text
-message.textinfo=(max. 5 linii / 250 caractere)
+message.htmltitle = mesaje
+message.id = id
+message.date = data
+message.title = titlu
+message.creator = autor
+message.text = text
+message.textinfo = (max. 5 linii / 250 caractere)
-messagelist.htmltitle=lista de mesaje
+messagelist.htmltitle = lista de mesaje
# admin start page
-start.htmltitle=admin
-
-start.content.new=articol nou
-start.show=arata
-start.comment.open_by_id=open comment #
-start.content.open_by_id=open article #
-
-start.content.hidden=arata toate articolele ascunse
-start.content.not_published=articole inca nepublicate
-start.content.with_media=cu media
-start.content.last_changes=ultimele schimbari
-start.content.with_comments=cu comentarii interne
-start.content.all=toate articolele
-start.content.search=cauta
-
-start.allarticlesoftype={0}
-start.allcommentswithstatus={0}
-
-start.producers.title=GENEREAZA MANUAL
-start.producers.produceAllNew=genereaza totul nou
-start.producers.recipe.allnew=genereaza totul nou
-
-start.producers.advanced=pagina avansata (utilizati cu grija!)
-
-start.administer.title=ADMINISTREAZA
-start.administer.comments=comentarii
-
-start.comments.title=COMENTARII
-
-start.breaking.title=ultimele stiri
-start.articles.title=ARTICOLE
-start.fileedit.includes.title=edit include files
-start.addandedit.title=ADD / EDIT
-start.extra.title=EXTRA
-start.search.title=SEARCH
-start.other_media.title=alta media
-start.images.title=poze
-start.video.title=video
-start.audio.title=audio
-start.media.title=MEDIA
-start.mediafolder.title=dosarmedia
-start.languages.title=LIMBI
-start.imcs.title=IMCS
-start.messageboard.title=MESSAGEBOARD
-start.messageboard.no_messages=no messages
-
-start.superusermenu=super-user functions (use with care!)
+start.htmltitle = admin
+
+start.content.new = articol nou
+start.show = arata
+start.comment.open_by_id = open comment #
+start.content.open_by_id = open article #
+
+start.content.hidden = arata toate articolele ascunse
+start.content.not_published = articole inca nepublicate
+start.content.with_media = cu media
+start.content.last_changes = ultimele schimbari
+start.content.with_comments = cu comentarii interne
+start.content.all = toate articolele
+start.content.search = cauta
+
+start.allarticlesoftype = {0}
+start.allcommentswithstatus = {0}
+
+start.producers.title = GENEREAZA MANUAL
+start.producers.produceAllNew = genereaza totul nou
+start.producers.recipe.allnew = genereaza totul nou
+
+start.producers.advanced = pagina avansata (utilizati cu grija!)
+
+start.administer.title = ADMINISTREAZA
+start.administer.comments = comentarii
+
+start.comments.title = COMENTARII
+
+start.breaking.title = ultimele stiri
+start.articles.title = ARTICOLE
+start.fileedit.includes.title = redacteaza fisierele include
+start.addandedit.title = ADD / EDIT
+start.extra.title = EXTRA
+start.search.title = SEARCH
+start.other_media.title = alta media
+start.images.title = poze
+# missing (master value = "open image #")
+start.images.open_by_id =
+start.video.title = video
+start.audio.title = audio
+start.media.title = MEDIA
+start.mediafolder.title = dosarmedia
+start.languages.title = LIMBI
+start.imcs.title = IMCS
+start.messageboard.title = MESSAGEBOARD
+start.messageboard.no_messages = no messages
+
+start.superusermenu = super-user functions (use with care!)
# topic
-topic.htmltitle=topic
+topic.htmltitle = topic
-topic.id=id
-topic.title=nume
-topic.description=descriere
-topic.filename=numefisier
-topic.main_url=main infopage
-topic.archive_url=url arhiva
+topic.id = id
+topic.title = nume
+topic.description = descriere
+topic.filename = numefisier
+topic.main_url = main infopage
+topic.archive_url = url arhiva
-topiclist.htmltitle=topiclist
+topiclist.htmltitle = topiclist
# users
-user.htmltitle=User
-user.login=Login
-user.ownpassword=Your own password
-user.oldpassword=Old password
-user.password=Password
-user.password2=Password (confirmation)
-user.admin=Admin
+user.htmltitle = User
+user.login = Login
+user.ownpassword = Parola ta
+user.oldpassword = Parola veche
+user.password = Parola
+user.password2 = Parola (confirmare)
+user.admin = Admin
+# missing (master value = "Disabled ?")
+user.is_disabled =
+# missing (master value = "Creation date")
+user.creationdate =
+# missing (master value = "Last login")
+user.lastlogindate =
+# missing (master value = "Email address")
+user.email =
+# missing (master value = "Comment")
+user.comment =
+# missing (master value = "Profile")
+user.profile =
-userlist.htmltitle=Users
-#articletype
-articletype.htmltitle=Tip de articol
-articletype.id=id
-articletype.name=Name
-articletypelist.htmltitle=Tipuri de articole
+userlist.htmltitle = Users
+#articletype
+articletype.htmltitle = Tip de articol
+articletype.id = id
+articletype.name = Name
+
+articletypelist.htmltitle = Tipuri de articole
+
+# mediatypes
+# missing (master value = "Manage Mediatypes")
+mediatypelist.htmltitle =
+# missing (master value = "id")
+mediatype.id =
+# missing (master value = "Name")
+mediatype.name =
+# missing (master value = "Mediatype")
+mediatype.htmltitle =
+# missing (master value = "MIME-Type")
+mediatype.mimetype =
+# missing (master value = "Classname")
+mediatype.classname =
+# missing (master value = "Tabelname")
+mediatype.tablename =
#commentstatus
-commentstatus.htmltitle=Statut comentar
-commentstatus.id=id
-commentstatus.name=Nume
+commentstatus.htmltitle = Statut comentar
+commentstatus.id = id
+commentstatus.name = Nume
-commentstatuslist.htmltitle=Comment status values
+commentstatuslist.htmltitle = Comment status values
superusermenu.htmltitle = Super-user functions
superusermenu.manage = MANAGE
superusermenu.topics = subiecte
-superusermenu.articletypes = tipuri de articole
-superusermenu.comment_statuses = comment status values
-superusermenu.users = users
-superusermenu.languages =
+superusermenu.articletypes = tipuri de articole
+# missing (master value = "mediatypes")
+superusermenu.mediatypes =
+superusermenu.comment_statuses = comment status values
+superusermenu.users = users
+# missing (master value = "languages")
+superusermenu.languages =
superusermenu.abuse = apply anti-abuse measures
-superusermenu.imcs = IMCS (obsolete)
+superusermenu.imcs = IMCS (obsolete)
+# missing (master value = "reload bundles, logging and producers")
+superusermenu.reload =
+
+# missing (master value = "reload successfull")
+infomessage.reloadSuccessfull =
+# missing (master value = "An error has occurred while reloading: <br>{0}")
+infomessage.reloadFailed =
#abuse
abuse.setting = Setting
abuse.value = Value
-abuse.disableopenpostings=Turn off open posting
-abuse.openpostingpassword=Require a password for open postings
-abuse.logpostings=Log IPs for open postings
-abuse.logsize=Logging buffer size
-abuse.cookies=Use cookies for blocked users
-abuse.articleaction=Action for blocked article
-abuse.commentaction=Action for blocked comment
+abuse.disableopenpostings = Turn off open posting
+abuse.openpostingpassword = Require a password for open postings
+abuse.logpostings = Log IPs for open postings
+abuse.logsize = Logging buffer size
+abuse.cookies = Use cookies for blocked users
+abuse.articleaction = Action for blocked article
+abuse.commentaction = Action for blocked comment
-abuse.showlog=Show the IP log
-abuse.showfilters=Manage filters
+abuse.showlog = Show the IP log
+abuse.showfilters = Manage filters
-abuse.log.time=Time
-abuse.log.address=IP number
-abuse.log.object=Object
-abuse.log.browser=Browser
-abuse.log.filtertype=Filter type
-abuse.log.filterexpression=Expression
+abuse.log.time = Time
+abuse.log.address = IP number
+abuse.log.object = Object
+abuse.log.browser = Browser
+abuse.log.filtertype = Filter type
+abuse.log.filterexpression = Expression
abuse.filters = Filters
abuse.filters.movedown = move down
abuse.filters.moveup = move up
+# missing (master value = "bottom")
+abuse.filters.movebottom =
+# missing (master value = "top")
+abuse.filters.movetop =
abuse.filter.type = Type
abuse.filter.expression = Expression
-abuse.filter.articleaction = Article
-abuse.filter.commentaction = Comment
-abuse.filter.comments = Comments (internal usage)
+abuse.filter.articleaction = Articol
+abuse.filter.commentaction = Comentariu
+abuse.filter.comments = Comentarii (uz intern)
abuse.filter.lasthit = Last hit
abuse.filter.htmltitle = Edit filter
abuse.filtertype.ip = IP Number
abuse.filtertype.regexp = Regular expression
+# missing (master value = "User Agent")
+abuse.filtertype.useragent =
+# missing (master value = "Throttle")
+abuse.filtertype.throttle =
+# missing (master value = "Host name")
+abuse.filtertype.hostname =
abuse.filtererror.title = Error:
abuse.filtererror.invalidtype = Invalid filter type
abuse.log.htmltitle = Anti-abuse open posting log
# head
-head.start=start
-head.logout=logout
-head.changepassword=password
-head.help=help
-head.search=search
-head.logged_in=logged in
+head.start = start
+head.logout = logout
+head.changepassword = password
+head.help = help
+head.search = search
+head.logged_in = logged in
# foot
-foot.top=top
+foot.top = top
########## dynamic values ##########
# 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 = Coloana deschisa
+articletypes.feature = Articol de fond
+articletypes.topicspecial = Subiect-special
+articletypes.startspecial = Primapagina-special
+articletypes.static = Text static
+articletypes.opentrash = Gunoi deschis
+articletypes.closedtrash = Gunoi ascuns
# Comment status values
-commentstatus.normal=normal
+commentstatus.normal = normal
########## 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, <br>it might be helpful to <a href="mailto:{0}">{1}</a>:
-error.text2=So please send an e-mail with the <font color="Red">red text</font> and detailed information regarding the events that led to this error to <a href="mailto:{0}">{1}</a>. Thanks!
+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, <br>it might be helpful to <a href="mailto:{0}">{1}</a>:
+error.text2 = So please send an e-mail with the <font color="Red">red text</font> and detailed information regarding the events that led to this error to <a href="mailto:{0}">{1}</a>. Thanks!
-usererror.htmltitle=Input error
-usererror.title=Input error
-usererror.text=Your input caused the following error:
-usererror.what_to_do=Please press the back button and try it again
+usererror.htmltitle = Input error
+usererror.title = Input 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
-user.error.passwordmismatch=The passwords are not equal
-user.error.missingpassword=A password must be entered
-user.error.incorrectpassword= Incorrect password
+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.incorrectpassword = Incorrect password
########## infomessages ##########
infomessage.htmltitle = Information
infomessage.recipeAddedToQueue = Your request has been added to the queue.
-
########## admin ##########
# language: svenska
-# $Id: admin_sv.properties,v 1.8 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_sv.properties,v 1.9 2007/04/08 21:46:36 idfx Exp $
languagename=Svenska
########## admin ##########
-# $Id: admin_tr.properties,v 1.13 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_tr.properties,v 1.14 2007/04/08 21:46:36 idfx Exp $
languagename = T\u00fcrk\u00e7e
########## admin ##########
# language: english
-# $Id: admin_zh.properties,v 1.3 2004/11/06 17:39:45 idfx Exp $
+# $Id: admin_zh.properties,v 1.4 2007/04/08 21:46:36 idfx Exp $
languagename = Chinese
--
CREATE TABLE "images" (
- "image_data" oid,
- "icon_data" oid,
+ "image_data" bytea,
+ "icon_data" bytea,
"year" character varying(40),
"img_width" smallint,
"img_height" smallint,
"webdb_create" timestamp with time zone NOT NULL
);
+
+--
+-- filter
+--
+
+CREATE SEQUENCE "filter_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "filter" (
+ "id" integer DEFAULT nextval('filter_id_seq'::text) NOT NULL,
+ "priority" integer,
+ "filter_group_id" integer,
+ "type" character varying(255) NOT NULL,
+ "expression" character varying(255) NOT NULL,
+ "tag" character varying(255) NOT NULL,
+ "comment" text,
+ "articleaction" character varying(255) NOT NULL,
+ "commentaction" character varying(255) NOT NULL,
+ "last_hit" timestamp with time zone
+);
+
+--
+-- filter_group
+--
+
+CREATE SEQUENCE "filter_group_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "filter_group" (
+ "id" integer DEFAULT nextval('filter_group_id_seq'::text) NOT NULL,
+ "name" character varying(255),
+ "priority" integer
+);
+
+--
+-- db_patches
+--
+
+CREATE SEQUENCE "db_patches_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "db_patches" (
+ "id" integer DEFAULT nextval('db_patches_id_seq'::text) NOT NULL,
+ "date" date NOT NULL,
+ "description" text
+);
+
+--
+-- model_version
+--
+
+CREATE TABLE "model_version" (
+ "description" character varying(24)
+);
+
echo "grant all on content to $3;" >> ${SCRIPT_FILE}
echo "grant all on comment to $3;" >> ${SCRIPT_FILE}
echo "grant all on media_folder to $3;" >> ${SCRIPT_FILE}
-
+echo "grant all on db_patches to $3;" >> ${SCRIPT_FILE}
+echo "grant all on model_version to $3;" >> ${SCRIPT_FILE}
echo "grant all on media_id_seq to $3;" >> ${SCRIPT_FILE}
echo "grant all on media_folder_id_seq to $3;" >> ${SCRIPT_FILE}
echo "grant all on comment_status_id_seq to $3;" >> ${SCRIPT_FILE}
echo "grant all on article_type_id_seq to $3;" >> ${SCRIPT_FILE}
echo "grant all on language_id_seq to $3;" >> ${SCRIPT_FILE}
-
+echo "grant all on db_patches_id_seq to $3;" >> ${SCRIPT_FILE}
# execute the script
psql -U $2 -f ${SCRIPT_FILE} -d template1
echo "grant all on content to $2;" >> ${SCRIPT_FILE}
echo "grant all on comment to $2;" >> ${SCRIPT_FILE}
echo "grant all on media_folder to $2;" >> ${SCRIPT_FILE}
+echo "grant all on filter to $2;" >> ${SCRIPT_FILE}
+echo "grant all on filter_group to $2;" >> ${SCRIPT_FILE}
echo "grant all on media_id_seq to $2;" >> ${SCRIPT_FILE}
echo "grant all on comment_status_id_seq to $2;" >> ${SCRIPT_FILE}
echo "grant all on article_type_id_seq to $2;" >> ${SCRIPT_FILE}
echo "grant all on language_id_seq to $2;" >> ${SCRIPT_FILE}
+echo "grant all on filter_id_seq to $2;" >> ${SCRIPT_FILE}
+echo "grant all on filter_group_id_seq to $2;" >> ${SCRIPT_FILE}
# execute the script
+++ /dev/null
-alter table role_x_rights drop constraint fk_right_role;
-alter table role_x_rights drop constraint fk_role_right;
-alter table category drop constraint fk_category_categorytype;
-alter table category drop constraint fk_category_parentcategory;
-alter table category drop constraint fk_topic_childcategories;
-alter table media drop constraint fk_media_user;
-alter table media_x_media drop constraint fk_mediaxmedia_sourcemedia;
-alter table media_x_media drop constraint fk_mediaxmedia_relatedmedia;
-alter table media_x_media drop constraint fk_mediaxmedia_mediarelationtype;
-alter table uploaded_media drop constraint fk_uploadedmedia_mediafolder;
-alter table uploaded_media drop constraint fk_uploadedmedia_mediatype;
-alter table uploaded_media drop constraint fk_uploadedmedia_media;
-alter table article drop constraint fk_article_language;
-alter table article drop constraint fk_article_articlestatus;
-alter table article drop constraint fk_article_media;
-alter table article drop constraint fk_article_lockinguser;
-alter table article_x_category drop constraint fk_article_category_2;
-alter table article_x_category drop constraint fk_articlexcategory_category;
-alter table article_x_category drop constraint fk_article_category;
-alter table article_x_category drop constraint fk_category_article;
-alter table article_x_category drop constraint fk_articlexcategory_article_type;
-alter table article_x_category drop constraint fk_articlexcategory;
-alter table users drop constraint fk_user_role;
-alter table users drop constraint fk_role_user;
-drop table role_x_rights;
-drop table category_type;
-drop table media_type;
-drop table rights;
-drop table category;
-drop table media;
-drop table roles;
-drop table article_type;
-drop table media_x_media;
-drop table language;
-drop table uploaded_media;
-drop table article;
-drop table media_relation_type;
-drop table article_x_category;
-drop table breaking_news_items;
-drop table comment_status;
-drop table users;
-drop table media_folder;
-drop table messages;
-drop sequence language_id_seq;
-drop sequence users_id_seq;
-drop sequence media_relation_type_id_seq;
-drop sequence category_type_id_seq;
-drop sequence breaking_id_seq;
-drop sequence media_type_id_seq;
-drop sequence article_type_id_seq;
-drop sequence right_id_seq;
-drop sequence comment_status_id_seq;
-drop sequence media_folder_id_seq;
-drop sequence media_id_seq;
-drop sequence category_id_seq;
-drop sequence role_id_seq;
-create table role_x_rights (
- role_id int4 not null,
- right_id int4 not null,
- primary key (role_id, right_id)
-);
-create table category_type (
- id int4 not null,
- name varchar(40) not null,
- primary key (id)
-);
-create table media_type (
- id int4 not null,
- name varchar(80) not null,
- mime_type varchar(40) not null,
- classname varchar(80) not null,
- tablename varchar(80) not null,
- dcname varchar(20),
- primary key (id)
-);
-create table rights (
- id int4 not null,
- name varchar(80) not null,
- description varchar(255),
- primary key (id)
-);
-create table category (
- id int4 not null,
- title varchar(80) not null,
- description varchar(255),
- filename varchar(20) not null,
- category_type int4,
- parent_id int4,
- primary key (id)
-);
-create table media (
- id int4 not null,
- title varchar(255),
- description text,
- creator varchar(80),
- creator_main_url varchar(255),
- creator_email varchar(80),
- creator_address varchar(80),
- creator_phone varchar(80),
- internal_comment varchar(255),
- is_produced bool not null,
- creation_date timestamp not null,
- last_change timestamp,
- to_publisher int4,
- primary key (id)
-);
-create table roles (
- id int4 not null,
- name varchar(16) not null unique,
- description varchar(255) not null,
- primary key (id)
-);
-create table article_type (
- id int4 not null,
- name varchar(40) not null,
- primary key (id)
-);
-create table media_x_media (
- source_media_id int4 not null,
- media_relation_type_id int4 not null,
- related_media_id int4 not null,
- primary key (source_media_id, related_media_id)
-);
-create table language (
- id int4 not null,
- name varchar(40) not null,
- code varchar(2) not null,
- primary key (id)
-);
-create table uploaded_media (
- media_id int4 not null,
- publish_server varchar(255),
- publish_path varchar(255),
- storage_path varchar(255),
- icon_produced bool not null,
- icon_path varchar(255),
- size int4,
- to_media_folder int4,
- to_media_type int4,
- primary key (media_id)
-);
-create table article (
- media_id int4 not null,
- date varchar(8) not null,
- subtitle varchar(255),
- edittitle varchar(255),
- content text not null,
- is_html bool not null,
- to_article_status int4,
- to_locking_user int4,
- to_language int4,
- primary key (media_id)
-);
-create table media_relation_type (
- id int4 not null,
- name varchar(255),
- primary key (id)
-);
-create table article_x_category (
- article_type_id int4 not null,
- category_id int4 not null,
- article_id int4 not null,
- primary key (category_id, article_id)
-);
-create table breaking_news_items (
- id int4 not null,
- text varchar(255) not null,
- creationDate timestamp not null,
- primary key (id)
-);
-create table comment_status (
- id int4 not null,
- name varchar(40) not null,
- primary key (id)
-);
-create table users (
- id int4 not null,
- login varchar(16) not null unique,
- password varchar(255) not null,
- internal_comment varchar(255),
- is_disabled bool not null,
- email varchar(255) not null,
- profile varchar(255),
- creationDate timestamp not null,
- lastlogin timestamp,
- to_role int4,
- primary key (id)
-);
-create table media_folder (
- id int4 not null,
- name varchar(255) not null,
- date varchar(8) not null,
- place varchar(80),
- keywords varchar(255),
- internal_comment varchar(255),
- creationDate timestamp not null,
- last_change timestamp,
- primary key (id)
-);
-create table messages (
- id int4 not null,
- title varchar(30),
- description varchar(255) not null,
- creator varchar(30) not null,
- creation_date timestamp not null,
- primary key (id)
-);
-alter table role_x_rights add constraint fk_right_role foreign key (right_id) references rights;
-alter table role_x_rights add constraint fk_role_right foreign key (role_id) references roles;
-alter table category add constraint fk_category_categorytype foreign key (category_type) references category_type;
-alter table category add constraint fk_category_parentcategory foreign key (parent_id) references category;
-alter table category add constraint fk_topic_childcategories foreign key (parent_id) references category;
-alter table media add constraint fk_media_user foreign key (to_publisher) references users;
-alter table media_x_media add constraint fk_mediaxmedia_sourcemedia foreign key (source_media_id) references media;
-alter table media_x_media add constraint fk_mediaxmedia_relatedmedia foreign key (related_media_id) references media;
-alter table media_x_media add constraint fk_mediaxmedia_mediarelationtype foreign key (media_relation_type_id) references media_relation_type;
-alter table uploaded_media add constraint fk_uploadedmedia_mediafolder foreign key (to_media_folder) references media_folder;
-alter table uploaded_media add constraint fk_uploadedmedia_mediatype foreign key (to_media_type) references media_type;
-alter table uploaded_media add constraint fk_uploadedmedia_media foreign key (media_id) references media;
-alter table article add constraint fk_article_language foreign key (to_language) references language;
-alter table article add constraint fk_article_articlestatus foreign key (to_article_status) references comment_status;
-alter table article add constraint fk_article_media foreign key (media_id) references media;
-alter table article add constraint fk_article_lockinguser foreign key (to_locking_user) references users;
-alter table article_x_category add constraint fk_article_category_2 foreign key (article_id) references article;
-alter table article_x_category add constraint fk_articlexcategory_category foreign key (category_id) references category;
-alter table article_x_category add constraint fk_article_category foreign key (article_id) references article;
-alter table article_x_category add constraint fk_category_article foreign key (category_id) references category;
-alter table article_x_category add constraint fk_articlexcategory_article_type foreign key (article_type_id) references article_type;
-alter table article_x_category add constraint fk_articlexcategory foreign key (article_type_id, category_id) references article_x_category;
-alter table users add constraint fk_user_role foreign key (to_role) references roles;
-alter table users add constraint fk_role_user foreign key (to_role) references roles;
-create sequence language_id_seq;
-create sequence users_id_seq;
-create sequence media_relation_type_id_seq;
-create sequence category_type_id_seq;
-create sequence breaking_id_seq;
-create sequence media_type_id_seq;
-create sequence article_type_id_seq;
-create sequence right_id_seq;
-create sequence comment_status_id_seq;
-create sequence media_folder_id_seq;
-create sequence media_id_seq;
-create sequence category_id_seq;
-create sequence role_id_seq;
--- /dev/null
+
+INSERT INTO "db_patches" VALUES (1, DATE '2002-12-13', '* introduces sequences and primary keys for comment_status, article_type and
+language\n * adds is_html to comment');
+INSERT INTO "db_patches" VALUES (2, DATE '2003-04-09', '* creates table comment_x_media, to support media in comments\n * adds webdb_lastchange to comment');
+INSERT INTO "db_patches" VALUES (3, DATE '2003-11-22', '* added a bunch of fields to webdb_user: is_disabled, email, profile, creation date, last login date');
+INSERT INTO "db_patches" VALUES (4, DATE '2003-11-24', '* Clean up comments\n * added a comment field for internal comments');
+INSERT INTO "db_patches" VALUES (5, DATE '2003-11-25', '* Removal of media (uploaded_media and content are now independently)\n * Clean up of content\n * Added a field for content-locking\n * Added a keywords field for content');
+INSERT INTO "db_patches" VALUES (6, DATE '2003-12-12', '* makes login unique on webdb_users\n * drops unnecessary index on webdb_users\n * inserts a line for ogg support in media_types\n * drop "- deprecated -" from media_types\n * drop redundant index on id of topic\n * drop redundant index on id of comment\n * recreate indexes on content_x_media');
+INSERT INTO "db_patches" VALUES (7, DATE '2005-01-09', '* adds filter and filtergroups to the database');
+INSERT INTO "db_patches" VALUES (8, DATE '2005-09-13', '* adds "db_patches" and "model_version" tables to the database');
+
INSERT INTO "media_type" VALUES (18,'mp3','audio/mpeg','Mp3','Audio',NULL);
INSERT INTO "media_type" VALUES (19,'png','image/gif','ImagesPng','Images',NULL);
INSERT INTO "media_type" VALUES (20,'avi','video/avi','Video','Video',NULL);
-INSERT INTO "media_type" VALUES (21,'ogg','application/x-ogg','Ogg','Audio',NULL);
+INSERT INTO "media_type" VALUES (21,'ogg','application/ogg','Ogg','Audio',NULL);
--- /dev/null
+
+INSERT INTO "model_version" VALUES ('1.1-1');
+
select setval('comment_status_id_seq',(select max(id) from comment_status));\r
select setval('article_type_id_seq', (select max(id) from article_type));\r
select setval('language_id_seq', (select max(id) from language));\r
+select setval('filter_id_seq', (select max(id) from filter));\r
+select setval('filter_group_id_seq', (select max(id) from filter_group));\r
--- /dev/null
+-- update script 2003-12-12 by rk
+--
+-- * adds filter and filtergroups to the database
+--
+-- This script will terminate with an error the second time it's run,
+-- so running this script when it isn't needed can't do any harm.
+--
+
+BEGIN TRANSACTION;
+
+CREATE SEQUENCE "filter_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "filter" (
+ "id" integer DEFAULT nextval('filter_id_seq'::text) NOT NULL,
+ "priority" integer,
+ "filter_group_id" integer,
+ "type" character varying(255) NOT NULL,
+ "expression" character varying(255) NOT NULL,
+ "tag" character varying(255) NOT NULL,
+ "comment" text,
+ "articleaction" character varying(255) NOT NULL,
+ "commentaction" character varying(255) NOT NULL,
+ "last_hit" timestamp with time zone
+);
+
+--
+-- filter_group
+--
+
+CREATE SEQUENCE "filter_group_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "filter_group" (
+ "id" integer DEFAULT nextval('filter_group_id_seq'::text) NOT NULL,
+ "name" character varying(255),
+ "priority" integer
+);
+
+COMMIT TRANSACTION;
+
--- /dev/null
+-- update script 2005-09-08 by pietro
+--
+-- * adds "db_patches" and "model_version" tables to the database
+--
+-- This script will terminate with an error the second time it's run,
+-- so running this script when it isn't needed can't do any harm.
+--
+
+BEGIN TRANSACTION;
+
+--
+-- db_patches
+--
+
+CREATE SEQUENCE "db_patches_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
+
+CREATE TABLE "db_patches" (
+ "id" integer DEFAULT nextval('db_patches_id_seq'::text) NOT NULL,
+ "date" date NOT NULL,
+ "description" text
+);
+
+INSERT INTO "db_patches" VALUES (1, DATE '2002-12-13', '* introduces sequences and primary keys for comment_status, article_type and
+ language\n * adds is_html to comment');
+INSERT INTO "db_patches" VALUES (2, DATE '2003-04-09', '* creates table comment_x_media, to support media in comments\n * adds webdb_lastchange to comment');
+INSERT INTO "db_patches" VALUES (3, DATE '2003-11-22', '* added a bunch of fields to webdb_user: is_disabled, email, profile, creation date, last login date');
+INSERT INTO "db_patches" VALUES (4, DATE '2003-11-24', '* Clean up comments\n * added a comment field for internal comments');
+INSERT INTO "db_patches" VALUES (5, DATE '2003-11-25', '* Removal of media (uploaded_media and content are now independently)\n * Clean up of content\n * Added a field for content-locking\n * Added a keywords field for content');
+INSERT INTO "db_patches" VALUES (6, DATE '2003-12-12', '* makes login unique on webdb_users\n * drops unnecessary index on webdb_users\n * inserts a line for ogg support in media_types\n * drop "- deprecated -" from media_types\n * drop redundant index on id of topic\n * drop redundant index on id of comment\n * recreate indexes on content_x_media');
+INSERT INTO "db_patches" VALUES (7, DATE '2005-01-09', '* adds filter and filtergroups to the database');
+INSERT INTO "db_patches" VALUES (8, DATE '2005-09-13', '* adds "db_patches" and "model_version" tables to the database for database changes tracking');
+
+--
+-- model_version
+--
+
+CREATE TABLE "model_version" (
+ "description" character varying(24)
+);
+
+INSERT INTO "model_version" VALUES ('1.1-1');
+
+COMMIT TRANSACTION;
+
+++ /dev/null
--------------------------------------------------------------------------------
-
-A short intro to the code-structure of Mir
-
--------------------------------------------------------------------------------
-
-In the java-source tree you will find the following:
-
- - two classes (OpenMir and Mir)
- - two packages (mir and mircoders)
-
-
-Servlets:
--------------------------------------------------------------------------------
-
-Looking from the request of a client browser onto MIR, the http-request is
-passed via Apache/Tomcat to either Mir.class or OpenMir.class. Mir.class
-handles all request that deal with internal administration tasks of MIR.
-OpenMir is the Servlet that deals with all open tasks: adding comments or
-articles/media to the system.
-
-These servlets don't do much but dispatching the tasks to an underlying
-code level, called ServletModules. OpenMir.class is basically a special
-case of Mir.class, no authentication is needed, and only two underlying
-ServletModule are used.
-
-The following explanation is about how requests are passed through, and
-responses to the client-browser are generated. The request has to pass
-through up to four levels of code (and from there asking the database),
-until it collected all the necessary data or performed all necessary
-tasks, to be able to respond.
-
-
-ServletModules:
--------------------------------------------------------------------------------
-
-The ServletModules are called via reflection java-api. The http-request
-parameter "module=XXX" and "do=YYY" are evaluated. A method
-YYY(HttpRequest,HttpResponse) is called in ServletModuleXXX.
-
-A common mistake for those new to Java is to look for usage of a class in
-the code by doing a "grep -r ClassName" or something like that. In this
-case, grep -r ServletModuleImages for example will turn up nothing except
-for ServletModuleImages itself.. that is because of reflection as
-explained above.
-
-The media handlers in mir.media.* work the same way as well.
-
- Database/Entity:
--------------------------------------------------------------------------------
-- db: singeltons, object-representation of db-table, *low-level* access,
-generating entities, does all the dirty JDBC work. There is a Database
-Class for every table in the DB.
-
-If an Entity wants to store itself in the media table, it has to have a
-storage object of type DatabaseMedia....
-
-When you ask a storage object to get something, it hands back an Entity.
-[through Database*.selectByWhereClause(), selectById().]
-
-- entity: representation of row. Contains the contents of "select * from
-dbname where id=rowid" in a HashMap. accessible via
-Entity.getValue("keyname"). One can do Entity.setValue(...,
-Entity.update() which syncs the Hash with the DB row and Entity.insert()
-to insert the HashMap as a new row, etc... basically high level DB access.
-The text component of an article is an entity (EntityContent, a row from
-the content table.) In short this is how we fetch content (whatever that
-may be: actual data, media meta-data, media_types, etc..) from the DB and
-write to the DB. Everything has to be reprented as an Entity.
-
-All Entities must have a StorageObject (theStorage) which is a Database
-object of the appropriate type. it is the connection between the entity
-data and the DB table itself. The only way to get an Entity other than
-asking a storage object to fetch one is to construct one by passing the
-storage object to the Entity Konstruktor.
-
-There is also EntityList, a list of entities..
-
-Modules:
--------------------------------------------------------------------------------
-
-- This one is a little grey... It's pretty much a wrapper around Database
-and Entity combined, so it's a half level higher up or so. It's not always
-necessary to use/have a Module either.. A usage example: you can do
-ModuleName.getByWhereClause() and it returns a list of Entities that match
-the query. Like entities you must have a StorageObject to access the DB.
-but unlike Entity, you can start out without one. Modules use Entity and
-Database objects internally. [Actually it uses Database object internally
-and returns Entitys...]
-
-Also I believe the intention was/is that it should be used in place of
-Entity for any *logic* that would normally have to into an Entity as
-Entity should be free of a case specific logic in theory. But that's not
-always true if you use EntityImages as an example, but that seems to be
-because EntityImages needs low-level DB connections.
-
-Producer
--------------------------------------------------------------------------------
-
-Well, what makes Mir different than other Content Management Systems is
-that it does not generate the content pages dynamically or use simple
-caching methods. Rather it generates static .[s]html files exclusively.
-This makes mir very fast under high viewing loads as it does not use
-servlets for this at all. It also makes it very easy to mirror as the
-mirrors do not have to run any Mir code, they only have to have a static
-webserver. In fact the first site to use Mir, germany.indymedia.org is on
-a whole other machine on another continent than the machine that
-*produces* the static files. Germany.indymedia.org already has 3 mirrors.
-
-The mircoders.producer.* classes are responsible for creating these static
-.html files and the filesystem structure that they reside in. This
-includes files that are article summaries and files that are the whole
-article themselves. Some media types also require Producers.
-
-If the main content *viewing* server is on another host, the FS tree is
-then rsync'ed to the viewing host.
-
-The Producers are called exclusively from the ServletModules in
-mircoders.servlet.*. They are called when a new article/comment is added,
-or when an administrator/moderator makes modifications to the site or when
-a manual update is desired. The method "handle()" is the one that does all
-work it takes parameters that tell it to force update all files even if
-their contents is unchanged, etc.. some Producers take an article ID as an
-argument telling them to create the html page representing the article and
-any summary pages that might be changed due to the addition of the
-article.
-
-Producers of course use Entities, Database, MediaHandler and Module
-objects internally.
-
-A dB field called is_produced is used to determine wether or not an Object
-needs to be produced.
-
-Oh and before I forget, it generates the pages based on a template. It
-uses the Freemarker templating system. Doc on freemarker is available at
-freemarker.sourceforge.net I believe.
-
-TODO: In theory it would be cool if we could abstract the output mechanism
-further to use other types of templates and to generate content other than
-HTML (like WAP for example).
-
-Media Handlers
--------------------------------------------------------------------------------
-They are kind of helper classes to deal with different representations of
-media types. They are called via the java reflection API. The class names
-are resolved through the media_type table. See
-source/mir/media/MirMedia.java for documentation.
-
-Helper classes
--------------------------------------------------------------------------------
-mir.misc.* (source/mir/misc/*) contains a bunch of classes that do Regexp,
-file handling and those sorts of things. Always look here first before
-writing such a thing.
+++ /dev/null
-last changed: $Date: 2002/12/08 07:05:56 $
-------------------------
-
-please us spaces not tabs for indents. all indents should be 2 spaces wide.
-
-If you use the vim editor, below is a good .vimrc entry for java files that
-makes all tabs appear 2 chars. wide and makes indenting using the TAB key create
-2 real spaces. It also sets the shiftwidth to 2 spaces.
-
-in your .vimrc add the following:
-
-autocmd FileType java source /path/to/file/.vimrc.java
-
-create .vimrc.java and add the following:
-
-set tabstop=2
-set shiftwidth=2
-set expandtab
-
-if you can, please try to make your code terminal friendly so a line should
-not be more than 80 characters wide pls. Not all mir code is like this and it
-is not required (well what really is required?)
-
-For java code, class names usually begin with a capital letter. e.g
-StringUtils.java. Names for variables and methods should begin with a lower case
-letter. However, if a variable or method is composed of more than one word
-(glued together of course) the second and following word(s) should begin with
-a capitalized letter. for example in the following code snippet:
-
-String name = "titi";
-Entity contentEntity = getContent();
-contentEntity.setPropertyForValue("name", name);
-
-some java code convention docs:
-
-http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
+++ /dev/null
-Dublin Core (http://purl.org/DC)
-----------------------------------------------------------------
-
-Bei der Dublin Core Metadata Initiative handelt es sich um ein
-Projekt, dass einen "common core of semantics for resource
-description" schafft. Selbstdarstellung unter
-
- http://purl.org/DC/about/index.htm
-
-
-Die Datenbankstruktur von Webdb/NA von der Bennenung soweit moeglich
-an das
-
- "Dublin Core Metadata Element Set, Version 1.1: Reference Description
- Beschreibung unter http://purl.org/DC/documents/rec-dces-19990702.htm"
-
-angelehnt. Dublin Core Metadaten werden entsprechend untenstehendem Matching
-in die Header der produzierten Seiten geschrieben...
-
-
-Matching:
-
-Dublin Core umfasst 15 Attribute. Beschreibung der Attribute siehe oben.
-Angaben in eckigen Klammern beziehen sich auf Funktionalitaeten, die z.Z.
-noch nicht implementiert sind.
-
-Im folgenden, wie die DC-Attribute in den Tabellen repraesentiert sind:
-
-MEDIA/IMAGE Tabelle:
-
-1. DC Element: Title
- MEDIA Element: title
-
-2. DC Element: Creator
- MEDIA Element: creator / to_creator
-
-3. DC Element: Subject
- MEDIA Element: keywords [/ keywords n:m]
-
-4. DC Element: Description
- MEDIA Element: desciption
-
-5. DC Element: Publisher
- MEDIA Element: to_publisher
-
-6. DC Element: Contributor
- MEDIA Element: to_publisher
-
-7. DC Element: Date
- MEDIA Element: publish_date
-
-8. DC Element: Type
- MEDIA Element: to_media_type.dcname
-
-9. DC Element: Format
- MEDIA Element: to_img_format.mimetype
- [fuer video/audio dann analog]
-
-10. Element: Identifier
- MEDIA Element: publish_server + publish_path
-
-11. DC Element: Source
- MEDIA Element: source
-
-12. DC Element: Language
- MEDIA Element to_lang
-
-13. DC Element: Relation
- MEDIA Element: to_media_folder
-
-14. DC Element: Coverage
- MEDIA Element: place [ / to_place]
-
-15. DC Element: Rights
- MEDIA Element: to_rights
-
--------------------------------------------------------------------------
-
-
-CONTENT Tabelle:
-MEDIA/IMAGE Tabelle:
-
-1. DC Element: Title
- MEDIA Element: title
-
-2. DC Element: Creator
- MEDIA Element: creator / to_creator
-
-3. DC Element: Subject
- MEDIA Element: keywords [/ keywords n:m]
-
-4. DC Element: Description
- MEDIA Element: desciption
-
-5. DC Element: Publisher
- MEDIA Element: to_publisher
-
-6. DC Element: Contributor
- MEDIA Element: to_publisher
-
-7. DC Element: Date
- MEDIA Element: publish_date
-
-8. DC Element: Type
- MEDIA Element: to_media_type.dcname
-
-9. DC Element: Format
- MEDIA Element: to_img_format.mimetype
- [fuer video/audio dann analog]
-
-10. Element: Identifier
- MEDIA Element: publish_server + publish_path
-
-11. DC Element: Source
- MEDIA Element: source
-
-12. DC Element: Language
- MEDIA Element to_lang
-
-13. DC Element: Relation
- MEDIA Element: to_media_folder
-
-14. DC Element: Coverage
- MEDIA Element: place [ / to_place]
-
-15. DC Element: Rights
- MEDIA Element: to_rights
-
+++ /dev/null
-MIR INSTALLATION HOWTO
-
-Last updated: $Date: 2004/11/06 17:47:26 $
-----------------------------------------------------------------
-
-Here is a short installation-howto of Mir.
-
-
-prerequisites:
-
-- tomcat 4.0.4+ or 3.3 (4.0.3 and below have some bad bugs)
- tomcat is available from http://jakarta.apache.org/tomcat/
-- apache 1.3.x. with mod_jk.so. As far as I can tell the connector for 2.x is
- still rather undocumented. http://httpd.apache.org
-- postgres 7.1+
-- ant (a java-based make)
-- jaxp-1.1 (a SAX 2.0 compliant XML parser, comes with ant >= 1.4)
-- the JAI image framework (Java Advanced Imaging) version 1.1.2 . Get it from
- java.sun.com. You need both: JAI and JAI Image I/O. Install those two in
- the JRE running tomcat.
-
-- A good reading of Tomcat, Apache and Postgresql documentation if you are not
- familiar with any of them. The documentation is available at:
- http://jakarta.apache.org/tomcat/tomcat-4.0-doc/index.html,
- http://httpd.apache.org/docs/ and http://www.postgresql.org respectively.
-
-1. checkout the cvs
-
-CVS LOGIN:
-
- cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs login
- password: anonymous
-
-CVS CHECKOUT:
-
- cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs co -r MIR_1_1 mir
-
-
-2. customize the config:
-
- cd mir/etc
- cp config.properties-dist config.properties
-
-now customize config.properties for your needs.
-
-
-3. configure the perms.sh file if neccessary -- IMPORTANT! READ THIS!
-We provide a script that sets all files' and direcories' permissions to
-a quite reasonable state. This script gets automagically called by
-ant after compilationl. The most important thing you have to do after
-compiling Mir is to ensure that the log files -- especially
-dbentity.log -- are not readable by users that could compromise
-system security, because all passwords and the like will be logged here.
-
- cp perms.sh-dist perms.sh
-
-Now, change the install directory and group in perms.sh
-
- edit perms.sh
-
-4. There is NO step 4!!
-
-5. compile. For this step, you have to make sure that the TOMCAT_HOME
-environment variable is set to the root of your tomcat installation.
-The build.xml compile target will give up if this is not set.
-
-Do this as root so the permissions script is able to set
-the permissions and owners correctly.
-
- ant
-
-
-6. Link in the webapps directory of tomcat to the install directory (the
-directory is in mir/bin/mir (Here and in the rest of this document,
-we assume you called the link "Mir", but this could be named anything.)
- cd ${TOMCAT_HOME}/webapps
- ln -s /path/to/mir/bin/mir Mir
-
-with tomcat 4.0.x, you could dynamically reload and stop the Mir webapp without
-restarting tomcat by using the "Manager App" with the following url:
-
-http://localhost:8080/manager/stop?path=/Mir
-
-This is practical if you are running several installations of mir on one
-tomcat or other webapps and can't afford to shutdown all of them.
-See the tomcat documentation to learn how to enable and use the manager app.
-
-7. Follow the installation instructions of JAI / JAI Image I/O.
-
-8a. create a new database
-The database name should be the same as in config.properties. Please look at
-the section "Database.*" to look up the names or change them to your needs.
-
-It is wise in terms of system security to use an unprivileged user for this
-task instead of the superuser. This is because if Mir uses the superuser to
-connect to the database and anybody manages to find out the password Mir
-uses to connect, the attacker can take over the complete database. So, in
-the following examples, we assume that the database name is "Mir", the
-database user will be "joe" and the password is "joshua". Please note that
-this particular password is far from being a good one. Watch "Wargames" for
-details. =B)
-
-
-To access the database as the database superuser, you either have to log in
-as postgres on Unix level (which we don't recommend because you will need
-another user to have a login shell and a password which makes system
-penetration more likely) or you have to tell PostgreSQL with each
-application call that you want to connect as a specific user. In the
-following example we'll create the mir database as postgreSQL user
-"pete".
-
- cd mir/dbscripts
- su postgres
- ./createmirdb.sh mir pete joe joshua
-
-8b. Apply neccessary changes to config.properties
-
-Please open config.properties and look for the lines that begin with
-"Database.". The interesting properties are "Username", "Password", "Host"
-and "Name". Change these properties so that they reflect the settings you
-used to create the database and the user.
-
-You should make sure that no copy of config.properties (neither in mir nor
-in Mir/src nor in Mir/WEB-INF/classes nor in the directory tree you compiled
-Mir from) is world-readable. Else you wouldn't have to install a password,
-anyway.
-
-8c. Setup PostgreSQL so that all localhost connections have to pass a
-password
-
-In /etc/postgresql/pg_hba.conf, change the line with 127.0.0.1 as follows:
-
-host all 127.0.0.1 255.0.0.0 password
-
-This means: All connections from 127.0.0.1 to any database will have to
-authenticate themselves with a password. Please refer to the PostgreSQL
-documentation if you want a different authentication setup. Make sure
-however that mir can connect to it's database using password authentication.
-
-9. For now, there's no step 9 either.
-
-10. Tweak mime-type extensions mappings in etc/web.xml file.
-
-*** Note the defaults should be o.k for most installations ***
-
-Add or remove any mime types you wish to support. This is used to figure
-out the mime-type when (broken browsers?) browsers don't send the mime-type
-in the content-type header field when uploading a media file. Note add the
-moment you still have to add these to the media_type SQL table as well which
-maps the mime-types to the correct mediaHandler class. See the comments in
-the MirMedia class in javadoc for more details.
-
-11. restart tomcat
-
-12. configure mod_jk
-
-There are 2 ways to do this. auto-generation of mod_jk.conf or manula JKMount
-lines. (rumour has it that Tomcat 4.0.x doesn't support auto-generation, but
-this is unconfirmed).
-
-In both examples please note that the JkWorkersFile line only needs to appear
-once per Apache config.
-
-Also this assumes that your tomcat installation has it's ajp13 conenctor
-turned on. See tomcat's server.xml file and documentation for this. Chances
-are that it is turned on.
-
-Method a). The automatic mod_jk.conf method:
-
-insert the following patch into /etc/apache/httpd.conf. Edit the directories
-to suit your needs.
-
-<IfModule mod_jk.c>
-JkWorkersFile /path/to/tomcat/conf/workers.properties
-Include /path/to/tomcat/conf/mod_jk.conf-auto
-</IfModule>
-
-Do not put any JkMount lines into your httpd.conf!
-
-If mod_jk.conf-auto doesn't get written or is 0 bytes in size, check your
-system for file ownership/permissions problems.
-
-Method b). Manual JKMount lines
-
-insert the following patch into /etc/apache/httpd.conf. Edit the directories
-to suit your needs.
-
-<IfModule mod_jk.c>
-JkWorkersFile /path/to/tomcat/conf/workers.properties
-JkMount /Mir ajp13
-JkMount /Mir/* ajp13
-</IfModule>
-
-
-13. configure apache for the static site
-
-* Make sure that if you are using a non standard character set enconding that
- Apache doesn't accidentally send the wrong encoding in the HTTP headers.
-edit http.conf:
-* set the document root to the same directory as in the mir config file
-* enable shtml includes:
- - add LoadModule includes_module /usr/lib/apache/1.3/mod_include.so
- - make sure your directory contains "Options Includes"
-* Determine if you need to modify any apache mime-mappings
- - The web-server host must recognize the .m3u, .pls and other file extensions
- and send the proper "audio/x-mpegurl" and "audio/x-scpls" mime-types
- respectively. If the web server is apache, it's easy, just
- add:
-
- audio/x-mpegurl m3u
- audio/x-scpl pls
-
- to the file pointed to by the "TypesConfig" command in your apache config
- file. Or add and equivalent AddType command to your httpd.conf. Of course
- this assumes that the mod_mime is loaded.
-
-that's it :)
-
-now the admin-application is accesable via:
-
- http://host/Mir/servlet/Mir
-
-and the openposting-servlet via
-
- http://host/Mir/servlet/OpenMir
-
-standard login is admin/indymedia. See the webdb_users SQL table to change/add
-users or passwords.
-
-
-SEARCHING
-
-The Mir code offers no internal search facilities, rather, the design
-expects the use of an external program to crawl and index the static
-site. One (recommended) tool for doing this is htdig
-(http://htdig.org), which generates static databases of the site
-content and then accesses those databases through a very fast CGI
-program written in C. In the scripts directory, a perl CGI script
-which wraps calls to htsearch is provided (scripts/search.pl) which
-will allow searching based off of media type. (This is possible
-because the standard templates will include META keywords like
-hasAudio, hasVideo, etc.)
-
-UPGRADING
-
-see the UPGRADING.mir file.
-
-TROUBLESHOOTING
-
-You can give these a try if anything goes wrong:
-
-+ Restart Tomcat. Especially after compiling the sources Tomcat has to be
- restarted.
-
-+ Check file permissions and ownership. Try and run perms.sh.
-
-----------------------------------------------------------------
-
-$Date: 2004/11/06 17:47:26 $ - the Mir coders
+++ /dev/null
-MIR INTERNATIONALIZATION HOWTO
-----------------------------------------------------------------
-
-this short howto explains how to use the internationalization
-features of mir and how you can translate mir to other
-languages. this is actually very easy:
-
-
-* properties files (step 1)
-
-add a new file to the bundles/ directory. it should
-be called exactly like the other files there, except
-for the language code, which is the part after the underscore.
-at the moment these files are called 'admin_XX.properties', so
-
-admin_de.properties contains the strings for the german language
-admin_en.properties is the one for english.
-admin.properties is always used as a fallback and contains imc
-spcific information at the moment (this should probably change)
-
-the correct language code for your language can be found at
-http://www.w3.org/WAI/ER/IG/ert/iso639.htm, for example.
-
-
-* translation (step 2)
-
-the files just contain key and value pairs of the form
-key=value. if a value contains something like {0}, {1}, and so
-on, this means, that these placeholders are replaced when the
-phrase is used. this is for example used for the key
-show_from_to=showing from {0} to {1}. {0} and {1} get replaced
-with the number of the first and the last record shown.
-
-in you new file (say admin_es.properties) you translate every key
-into the appropriate phrase in your language.
-
-
-* adding keys to templates
-
-you can define additional keys just by adding them to the
-properties file and by referncing them in the freemaker template
-with ${lang("keyname")}. you should do that every time you need
-a language specific string!
-
-
-* renaming keys
-
-some keys might not have a perfectly fitting name at the moment.
-if you want to rename a key, please take care that you rename it
-in ALL properties files and ALL templates. take care.
-
-----------------------------------------------------------------
-27.3.2002, br1
+++ /dev/null
-last changed: $Date: 2003/09/03 18:29:00 $ 2002 mir-coders
--------------------------------------------------------------------
-
-In all versions
-===============
-
-* the JAI library used for creating thumnails of images will often make the
- thumbnail for a GIF or PNG image look like it has some television set snow in
- it. The workaround would be to upload Jpeg images if you can. We are looking
- into replacing JAI with another library.
- Zapata: I fixed this (hopefully)
-
-* when deleting an item, be it an article or an uploaded media file, the action
- will remove the data/meta-data from the DB and prevent it from show up in
- lists, but it will not delete the file from the filesystem. hopefully this
- will be fixed before 1.1.0 is released and in 1.0.1. (FIXME: is this still a
- problem in the HEAD branch?)
- Zapata: Deleting objects makes them untraceable and is thus generally a bad
- idea. It can be so configured (using producers.xml) that hidden stuff (articles,
- media) are deleted
-
-* some obscure "under certain conditions" corner cases listed in our bug tracker
- at https://prod.indymedia.nl/mantis
-* some others that I'm forgetting now.
+++ /dev/null
-Version: $Date: 2004/11/06 17:47:26 $
-
-This is the HOWTO of the Localization infrastructure
-which allows easy low-level customization of Mir.
-
-
-1. Mir.Localizer
-
-In the file config.properties-dist
-Mir.Localizer=mircoders.localizer.basic.MirBasicLocalizer
-
-JUST NOTES:
-
--Document how to enable your own CVS tree
--Localizer code must be in etc/extrasource
--build.xml is aware of etc/extrasource
--contents of etc can be stored in extra cvs
--which of etc is known to ant?
--outside of etc nothing should be altered!
--producers can be configured in config.properties
+++ /dev/null
-MIR INSTALLATION HOWTO
-
-Last updated: $Date: 2003/01/18 08:44:09 $
-----------------------------------------------------------------
-
-Here is a short installation-howto of Mir, somewhat more explicit than
-the earlier version. Some Debian-specific instructions are given.
-
-
-prerequisites:
-
-- tomcat 4.0.4 (4.0.3 and below have some bad bugs) or above (3.3 works too as
- of 04.04.2002, but this could change)
- tomcat is available from http://jakarta.apache.org/tomcat/
-- apache 1.3.x. with mod_jk.so. As far as I can tell the connector for 2.x is
- still rather undocumented. http://httpd.apache.org
-- postgres 7.1.x or 7.2.x. http://www.postgresql.org
-- ant (a java-based make)
-- jaxp-1.1 (a SAX 2.0 compliant XML parser, comes with ant >= 1.4)
-- the JAI image framework (Java Advanced Imaging) versin 1.1.1 . get it from
- java.sun.com. ** NOTE: because JAI uses a native acceration library (a .so)
- it must be placed in tomcat's "lib" (i.e $TOMCAT_HOME/common/lib) directory and
- not under the default webapps/Mir/WEB-INF/lib directory **
-- A good reading of Tomcat, Apache and Postgresql documentation if you are not
- familiar with any of them. The documentation is available at:
- http://jakarta.apache.org/tomcat/tomcat-4.0-doc/index.html,
- http://httpd.apache.org/docs/ and http://www.postgresql.org respectively.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-0. To set all this up on Debian:
-
-make sure you have stable, testing, and unstable listings in
-/etc/apt/sources.list. THen do all the following as root or using sudo!
-
-If you already have tomcat, and it's working well with apache, then
-skip directly to (c). If it's not working well, then make sure you
-purge _all_ conf files & so forth ( though it never hurts to back them
-up first). "apt-get remove --purge" may not get rid of everything; try
-
-locate tomcat
-and then delete all the files you find (again, if you're unsure what
-they are, then back them up first).
-
-
-(a) Install Java
-apt-get install j2sdk1.3 j2sdk1.3-doc
-
-JAVA_HOME=/usr/lib/j2sdk1.3; export JAVA_HOME
-PATH=$PATH:$JAVA_HOME/bin; export PATH
-(add these lines to your .bashrc as well)
-
-(b) Installing Tomcat and Apache
-
-As root, do the following:
-apt-get install apache
- configure apache by editing httpd.conf:
-* enable shtml includes:
- - add LoadModule includes_module /usr/lib/apache/1.3/mod_include.so
- - make sure your directory contains "Options Includes"
-* Determine if you need to modify any apache mime-mappings
- - The web-server host must recognize the .m3u, .pls and other file extensions
- and send the proper "audio/x-mpegurl" and "audio/x-scpls" mime-types
- respectively. If the web server is apache, it's easy, just
- add:
-
- audio/x-mpegurl m3u
- audio/x-scpl pls
-
- to the file pointed to by the "TypesConfig" command in your apache config
- file. Or add and equivalent AddType command to your httpd.conf. Of course
- this assumes that the mod_mime is loaded.
-* Make sure that if you are using a non standard character set enconding that
- Apache doesn't accidentally send the wrong encoding in the HTTP headers.
-
-
-
-Now deal with Tomcat:
-apt-get install -t unstable tomcat4 tomcat4-webapps tomcat4-admin
- --> this gets you tomcat4.1. You can work with tomcat 4.0.4
- as well, but a couple of specific configuration elements are
- different. To get 4.0.4, run the following:
- apt-get install -t testing tomcat4 tomcat4-webapps
-apt-get install apachelib-java
-
-Tomcat will be installed in /usr/share/tomcat4, so you should put
-
-CATALINA_HOME=/usr/share/tomcat4; export CATALINA_HOME
-TOMCAT_HOME=$CATALINA_HOME; export TOMCAT_HOME
-
-in your .bashrc; you might as well execute the ocmmand right now as
-well.
-
-I found it somewhat difficult to get Tomcat and Apache working
- together, until I emailed the Debian package maintainer, who told
- me that he had purposely removed the mod_jk.conf-auto function from
- Tomcat4.1! This is because Debian encourages Tomcat users to
- switch to mod_webapp instead. You may want to try this option
- out. I didn't, because I was able to get it working using the
- JkMount option. So in /etc/apache/httpd.conf, look for a section
- like this at the end:
- <IfModule mod_jk.c>
- # The following line is for apacheconfig - DO NOT REMOVE!
- JkWorkersFile /etc/tomcat/jk/workers.properties
- Include /var/lib/tomcat/conf/mod_jk.conf
- </IfModule>
-
- This has been insrted by libapache-java to try to get mod_jk to
- work. unfortunately it doesn't work with Tomcat 4.1, so replace it
- with the following:
-
- <IfModule mod_jk.c>
- # The following line is for apacheconfig - DO NOT REMOVE!
- JkWorkersFile /etc/tomcat/jk/workers.properties
- JkMount /*.jsp ajp13
- JkMount /Mir ajp13
- JkMount /Mir/* ajp13
- JkMount /servlet ajp13
- jkMount /examples/* ajp13
- #Include /var/lib/tomcat/conf/mod_jk.conf
- </IfModule>
-restart tomcat(as root):
-/usr/share/tomcat4/bin/shutdown.sh
-/usr/share/tomcat4/bin/startup.sh
-restart apache(as root):
-apachectl restart
-
-In your browser, check to see if each pogram is working on its own:
-http://localhost should give you the debian apache start page
-http://localhost:8180 should give you the tomcat start page
-
-now check to see if mod_jk is allowing the two programs to connect:
-http://localhost/examples/servlets/index.html should give you the
-Tomcat example servlets.
-
-Once this is working, you should enable the tomcat manager
-application:
-cd /usr/share/tomcat4/conf
-open tomcat-users.xml in a text editor. Add a line like this:
-
-<user username="name" password="password" roles="standard,manager,admin"/>
-
-You should now be able to click on the "Manager" link on the Tomcat
-home page, log in, and use the Manager functions. This is extremely
-convenient when you're eloading Mir multiple times later on!
-
-(c) install postgres:
-apt-get install postgresql postgresql-client postgresql-doc
---> the new postgres package should work fine with Mir. Make sure you
-enable UNICODE, and if asked about JDBC (you shouldn't be) make sure
-to enable it as well. if you would like to try a graphical frontend
-for the database, find one using
-
-apt-cache show postgresql
-
-fmailiarize yourself with the psql interface, and the function of the
-"postgres" user.
-
-(d) install JAI
-go to:
-http://java.sun.com/products/java-media/jai/downloads/download.html
-
-and download the "CLASSPATH for Linux" version of the JAI package
-(1.1.01 works fine, later versions have not been tested by me) to
-/usr/share/tomcat4/common/lib
-
-now:
-
-cd /usr/share/tomcat4/common/lib
-
-gunzip "name_of_file.tar.gz" (don't use the quotes: replace with the
-real name of the file you downloaded!)
-
-tar -xvf "name_of_file.tar"
-
-read the instructions in
-/usr/share/tomcat4/common/lib/jai_whatever_version_you_have/INSTALL-jai.txt
-
-Now add the JAI files to your CLASSPATH and LSD_LIBRARY_PATH:
-JAIHOME=$TOMCAT_HOME/common/lib/jai-1_1_1_01/lib; export JAIHOME
-CLASSPATH=$JAIHOME/jai_core.jar:$JAIHOME/jai_codec.jar:$JAIHOME/mlibwrapper_jai.jar:$CLASSPATH;
-export CLASSPATH
-LD_LIBRARY_PATH=.:$JAIHOME:$CLASSPATH; export LD_LIBRARY_PATH
-
---> make sure to replace "jai-1_1_1_01" in the above with the
-version-number of your copy of JAI
---> as above, it's a good idea to add these lines to your .bashrc
-
----------------------------------------------------------------
-
-
-(1) CONFIGURE MIR!
-
-(a). get the latest version:
-
-cd to the directory where you would like to install the mir package
-
-cd /absolute/path
-
-CVS LOGIN:
-
- cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs login
- password: anonymous
-
-CVS CHECKOUT:
-
- cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs co mir
-
-
-(b) customize the config:
-
- cd mir/etc
- cp config.properties-dist config.properties
-
-now customize config.properties for your needs. config.properties is
-pretty well-documented, but read it carefully. I had to recompile
-several times before I got all the pathnames right.
-
-
-(c) configure the perms.sh file if neccessary -- IMPORTANT! READ THIS!
-We provide a script that sets all files' and direcories' permissions to
-a quite reasonable state. This script gets automagically called by
-ant after compilationl. The most important thing you have to do after
-compiling Mir is to ensure that the log files -- especially
-dbentity.log -- are not readable by users that could compromise
-system security, because all passwords and the like will be logged here.
-
- cp perms.sh-dist perms.sh
-
-Now, change the install directory and group in perms.sh
-
- edit perms.sh
-
-
-(d) Customize the templates
-you need to edit the templates before compiling, or not all of your
-changes will show up in the produced site. If this is too
-intimidating, don't worry -- you can always recompile! It only takes
-about a minute...
-
-(e) check web.xml!
---> tomcat 4.1 has a different method of composing servlet URL's, so
-if you are uasing 4.1, you wil need to make some minor changes to
-mir/etc/web.xml
-
-look for sections like this:
- <servlet-mapping>
- <servlet-name>
- Mir
- </servlet-name>
- <url-pattern>
- /Mir
- </url-pattern>
- </servlet-mapping>
-
-the url-pattern has to change; so replace the above with:
- <servlet-mapping>
- <servlet-name>
- Mir
- </servlet-name>
- <url-pattern>
- /servlet/Mir
- </url-pattern>
- </servlet-mapping>
-make sure to do the same for OpenMir and OutputMir.
-
-
--------------------------------------------------------------
--------------------------------------------------------------
-IMPORTANT! It is a good idea to skip ahead to (2) and create the
-Postgres database at this point. Then cd back to the mir directory,
-and continue.
--------------------------------------------------------------
--------------------------------------------------------------
-
-(f) compile. Make sure all the environment variables are set as
- indicated in section (0), or build.xml will not run properly:
-
-su
-ant
-
- This should take about a minute. If you don't get an error, run
- perms.sh:
- sudo perms.sh
-
-
-Do this as root so the permissions script is able to set
-the permissions and owners correctly.
-
-
-(g) Get Tomcat to recognize Mir.
-Link in the webapps directory of tomcat to the install directory
-(unless you changed the setting in config.properties, the
-directory is called "Mir" and is located in the same directory in which
-you installed the "mir" directory). (Here and in the rest of this document,
-we assume you called the link "Mir", but this could be named anything.)
- cd /path/to/tomcat/webapps (tomcat-4.0.x/webapps)
- ln -s /path/to/Mir Mir
-
-dynamically reload Mir:
-
-http://localhost:8180/manager/stop?path=/Mir
-if you're not using the Debian installation, you need to use:
-http://localhost:8080/manager/stop?path=/Mir
-
-if you're using Tomcat 3.3, you need to restart Tomcat (consult the
-docs for how to do that).
-
-
-(h) Copy any dynamic library files ending with ".so" (so far only the JAI native
-acceleration library found in the JAI package tarball or zip from sun) to your
-$JAVA_HOME/jre/lib/i386 directory (where the other ".so" files live). Or, you
-can skip the whole thing and live without "native" acceleration for image
-manupulation.
-
-(2) CREATE AND CONLFIGURE THE MIR DATABASE!
-
-Review mir/etc/config.properties. Look carefully at the entries you
-put in the DATABASE SETUP section, especially the Username, Password,
-Host, and Name variables. If you don't know anything about Postgres,
-look over the INSTALL.postgresql document, which is very helpful (but
-remember, you don't need to install postgresql from scratch
-anymore if you're on Debian woody!). Please do not use the "postgres"
-user in config.properties -- this is a serious security risk. Choose
-a username,a password, and a database name, then put those values in
-config.properties if you haven't already.
-
-(a) Create the new database
-
-We create and configure the database as posgresql user "postgres":
-
- createdb -U postgres --encoding=unicode Mir
---> here and elsewhere, replace "Mir" with the name you already chose
-for your database
-
-
-(b) create an unprivileged database user for Mir
-First, connect to the database as the database's superuser.
-
- psql -U postgres Mir
-
-Now we create the actual user. Please choose a password that is hard to
-guess instead of "joshua". Good passwords have characters and numerals in
-it, have no link to its owner (like being her birthday, age, name of her
-husband, dog, child, car, favourite beer brand). A good password looks like
-this: "8ncx4un".
-
- CREATE USER Mir WITH PASSWORD 'joshua' NOCREATEDB NOCREATEUSER;
---> again, don't just copy this into the psql command line -- replace
-"Mir" and "joshua" with your username and password from config.properties
-
-now exit:
-\q
-
-
-(c) create base table
-cd back to the mir home directory. now execute the following:
-
- psql -Upostgres -f dbscripts/create_pg.sql Mir
-now quit psql:
- \q
-back in the shell, execute the dbscripts:
- for i in dbscripts/help*.sql ; do psql -Upostgres -f $i Mir ; done
- for i in dbscripts/populate*.sql ; do psql -Upostgres -f $i Mir ; done
-
-(d) Grant the required permissions to the new user
-First, make your new user into the database administrator for the new
-database (instead of postgres):
-psql -U postgres Mir
- select * from pg_database;
- select * from pg_user;
-you'll see a display like this:
- usename | usesysid | usecreatedb | usetrace | usesuper | usecatupd | passwd | valuntil
---------------+----------+-------------+----------+----------+-----------+----------+----------
- postgres | 1 | t | t | t | t | ******** |
- matt | 100 | t | f | t | t | ******** |
- mir | 101 | f | f | f | f | ******** |
-
-followed by
-
- datname | datdba | encoding | datistemplate | datallowconn | datlastsysoid | datvacuumxid | datfrozenxid | datpath
------------+--------+----------+---------------+--------------+---------------+--------------+--------------+---------
-
- template1 | 1 | 5 | t | t | 16554 | 11258 | 3221236731 |
-
- template0 | 1 | 5 | t | f | 16554 | 49 | 49 |
-
- Mir | 1 | 5 | f | t | 16554 | 10805 | 3221236278 |
-
-note the "usesysid" column for your new user, and the datname for your
-new database. now execute the following line, obviousjly using the
-variable you just noted:
-
-update pg_database set datdba=USESYSID_FROM_PG_USER where datname=DATABASENAME
-
-now exit psql:
-\q
-
-save the following lines to a file called set.permissions:
-
-select 'grant all on '||relname||' to Mir;'
-from pg_class
-where relname not like 'pg%'
-order by relname;
-
--->be sure to replace "Mir" with your username!!!
-
-(e) Apply neccessary changes to config.properties
-
---> if you folowed the instructions above, you shouldn't have to do
-this, but doublecheck!
-Please open config.properties and look for the lines that begin with
-"Database.". The interesting properties are "Username", "Password", "Host"
-and "Name". Change these properties so that they reflect the settings you
-used to create the database and the user.
-
-You should make sure that no copy of config.properties (neither in mir nor
-in Mir/src nor in Mir/WEB-INF/classes nor in the directory tree you compiled
-Mir from) is world-readable. Else you wouldn't have to install a password,
-anyway.
-
-(f) Setup PostgreSQL so that all connections have to pass a password
-
-In /etc/postgresql/pg_hba.conf you should make sure that nobody can
-use the database without a password, by inserting these lines:
-
-local all password
-host all 127.0.0.1 255.0.0.0 password
-host all 0.0.0.0 0.0.0.0 reject
-
-make sure you comment out all other permissions lines in this file!
-
-This means: All local connections (i.e. psql without "-h hostname" option)
-have to authenticate themselves with a password. All connections from
-localhost (127.0.0.1) have to supply a password, too. All other connections
-are rejected. This line doen't have to be there if you have a properly
-configured firewall but even if you do have one, it adds to the security in
-case an attacker penetrates the firewall by some hack.
-
-If you can't access PostgreSQL after this for any reason, try and change
-"password" in /etc/postgresql/pg_hba.conf to "trust". This should disable
-any authentication method and make the database accessible again. Please use
-this setting only temporarily because anybody who can access the PostgreSQL
-server could take over the database completely this way. After you fixed
-your password setting, switch the setting back to "password".
-You may want to change your PostgreSQL password from time to time to make
-database takeover harder. Rememer: Security is a process.
-
-----------------------------------------------------------------
-
-AT THIS POINT YOU SHOULD HAVE A WORKING INSTAATION OF MIR! CHECK TO
-MAKE SURE -- DON'T BOTHER WITH THE REST TILL YOIU'VE MADE MIR WORK ONCE!
-
-
-Goodies:
-
-(3) Add the dupe prevention trigger to the database:
- cd mir/dbscripts/dupetrigger
-
- There, read INSTALL and follow the instructions.
-
-
-(4) Tweak mime-type extensions mappings in etc/web.xml file.
-
-*** Note the defaults should be o.k for most installations ***
-
-Add or remove any mime types you wish to support. This is used to figure
-out the mime-type when (broken browsers?) browsers don't send the mime-type
-in the content-type header field when uploading a media file. Note add the
-moment you still have to add these to the media_type SQL table as well which
-maps the mime-types to the correct mediaHandler class. See the comments in
-the MirMedia class in javadoc for more details.
-
-11. restart tomcat
-
-13. configure apache
-
-edit http.conf:
-* set the document root to the same directory as in the mir config file
-* enable shtml includes:
- - add LoadModule includes_module /usr/lib/apache/1.3/mod_include.so
- - make sure your directory contains "Options Includes"
-* Determine if you need to modify any apache mime-mappings
- - The web-server host must recognize the .m3u, .pls and other file extensions
- and send the proper "audio/x-mpegurl" and "audio/x-scpls" mime-types
- respectively. If the web server is apache, it's easy, just
- add:
-
- audio/x-mpegurl m3u
- audio/x-scpl pls
-
- to the file pointed to by the "TypesConfig" command in your apache config
- file. Or add and equivalent AddType command to your httpd.conf. Of course
- this assumes that the mod_mime is loaded.
-
-that's it :)
-
-now the admin-application is accesable via:
-
- http://host/Mir/servlet/Mir
-
-and the openposting-servlet via
-
- http://host/Mir/servlet/OpenMir
-
-standard login is admin/indymedia. See the webdb_users SQL table to change/add
-users or passwords.
-
-
-SEARCHING
-
-The Mir code offers no internal search facilities, rather, the design
-expects the use of an external program to crawl and index the static
-site. One (recommended) tool for doing this is htdig
-(http://htdig.org), which generates static databases of the site
-content and then accesses those databases through a very fast CGI
-program written in C. In the scripts directory, a perl CGI script
-which wraps calls to htsearch is provided (scripts/search.pl) which
-will allow searching based off of media type. (This is possible
-because the standard templates will include META keywords like
-hasAudio, hasVideo, etc.)
-
-UPGRADING
-
-see the UPGRADING.mir file.
-
-TROUBLESHOOTING
-
-You can give these a try if anything goes wrong:
-
-+ Restart Tomcat. Especially after compiling the sources Tomcat has to be
- restarted.
-
-+ Check file permissions and ownership. Try and run perms.sh.
-
-----------------------------------------------------------------
-
-$Date: 2003/01/18 08:44:09 $ - the Mir coders
+++ /dev/null
-last changed $Date: 2004/11/06 17:47:26 $
------------------------------------------
-
-GENERAL INFO
-============
-
-Mir is an Open-Source java servlet based content managment system, designed to
-run an indymedia(type) website. Besides powering several indymedia sites, a
-number of progessive organizations use Mir customized for their own needs. Mir
-aims to provide sophisticated functionality, for example, complete
-multi-lingual content production, editing, administration, and presentation,
-while retaining the ability to be run on less than top of the line hardware
-through extensive static caching.
-
-Mir uses technologies such as Apache Tomcat and the Freemarker template engine.
-
-more info at: http://mir.indymedia.org
-
-development and general questions/discussion happens on the mir-coders mailing
-list: mir-coders at lists.indymedia.org
-
-for archives or to subscribe:
-
-http://lists.indymedia.org/mailman/listinfo/mir-coders
-
-mailing list for cvs commits:
-
-http://lists.indymedia.org/mailman/listinfo/Mir-cvs
-
-LICENSING
-=========
-
-Mir is licensed under the GNU GPL.
-
-FEATURES
-========
-
-* Static publishing: Mir produces static HTML files for easy mirroring and so
- that the site can be viewed without creating a high load on servers. No fancy
- caching mechanisms are necessary. The presentation and production are
- completely independent from each other.
-* Very configurable (see the config.properties file)
-* Written in Java using standard servlet API and popular tools like those from
- the Apache Jakarta project (http://jakarta.apache.org)
-* Uses the Freemarker template engine to allow easy modification of
- site design without programming knowledge.
-* Structured Object oriented 4 layer design. Servlet modules, Entity/Database
- (the persistance layer), Media handlers (an abstraction layer for
- manipulating different media formats) and the Producer layer (for creating
- the static html pages). see doc/CODESTRUCTURE for more details.
-* The persistance layer uses the poolman package for caching Database
- connections.
-* Entity object caching is integrated into the persistance layer.
-* Meta-data/Database schema and classification based on the Dublic Core
- standard. Media folders, topics, features.
-* supports displaying the dynamic part of the site in multiple languages using
- the Java Locale/language bundle standard (.properties files). Bundles exist
- for spanish, english, dutch, quechua, turkish, german and aymara. The
- upcoming 1.1 version (in CVS) supports producing the static site in several
- languages.
-* Media abstraction layer to cleanly and easily handle/add different Media
- formats like mp3, realmedia, video, etc.. uses mime-types to map to the
- correct handler
-* Supports categorization into topics and media folders (eg. different folders
- for different events), features, breaking news, newswire, etc..
-* Production of xml RDF syndication. e.g for the indymedia global newswire.
-* Powerful and rich admin/editor interface with features like the ability to
- change the event date of an article, multiple ways to search.. help and much
- more.
-* Ability to edit some static site files such as CSS, html include files
- through a basic web based text editor.
-* Filtering of uploaded articles to remove unwanted HTML tags.
-* Can output articles into PDF (upcoming 1.1 version has better text wrapping
- support).
-* Search via HTdig index of static files. (upcoming 1.1 CVS version uses
- integrated Jakarta Lucene for indexing the static files.)
-* Automatic thumbnail generation using Java Advanced Imaging (JAI). (1.1 will
- probably use Jmagick)
-
-In the upcoming 1.1 release
-===========================
-
-* completely rewrite of the producer layer. Runs in it's own thread.
- Configurable via an XML file to dynamically choose the structure the site
- should take, what should be archived...
-* Introduction of the Localization infrastructure to allow easy low-level
- customization of Mir.
-
+++ /dev/null
-Last update: $Date: 2002/12/28 03:39:17 $
-
-As of this writing the IBM Jikes compiler up to and including version 1.15 does
-not work with mir. Jikes version 1.18 does work. We have not yet tested Jikes
-V1.16 and V1.17. It is possible that they may work.
+++ /dev/null
-[Updated $Date: 2002/12/23 05:38:50 $]
-
-v 1.1
-
-* producers merged (done, max, mh)
-* bundle cleanup (done, br1)
-* new templates with css (done, thomas - max)
-* seperation of things that should be edited and things that dont change:
- admin templates in templates, producer templates in templates-dist?
- (done, br1)
-* utf8 encoding (mh)
-* media refactoring (mh)
-* index.en.html ,etc..
-* more formats for media uploads --> generic media upload support (mh)
-* drop media_type table (mh)
-* yet another search format what to do about it..
-* merge StringUtil/util *Routines stuff into one
-* see for languages default --> merge it into OpenMir
-* Throwable Vs. Exception
-* merge MirConfig and config stuff in MirGlobal into one..
-* tuneup fileeditor
-* producer queue job stop/start
-* error reporting for Job queue?
-* set config paramater for default timezone.. (for use in templates)
-
-before 2.0
-
-* logging: log4j (max) --> is this not already a 1.1 item?
-* configuration (mh, max)
-* searching (john) --> is this not already a 1.1 item?
-* HTML validation, struts (br1)
-* PDF generation (john)
-* better user interface (br1)
-* split OpenPosting servlet modules or filter mechanism
-
-
-v 2.0
-
-* persistence layer: OJB or Torque (mh, idfx,...)
-* data model
-* struts (br1)
-* users / roles (max)
-* article translation
-
-
-general
-
-* mir website maintainance
-* website design / mir default templates
-* documentation
-
-
---- misc ---
-
-c) Coverage: Alternative start-page for e.g. a event like genua. every article that has
-something to do with this event can be seen on this page. (nn)
-b) P2P-Data-Transfer/Content-Syndication: Implementing RDF/RSS-Support or a own
-indymedia-protocoll.
-drop media_type table
-d) email-article-to-a-friend-servlet
-e) semidynamic create-pdf-from-article-servlet: every requested pdf should be cached (underway, john)
-f) servletapi-2.3: Filters for file upload (also in cos.jar)
-g) servletapi-2.3: use web.xml for simpler/better error handling.
-h) servletapi-2.3: set character encoding properly based on what the template says
-i) servletapi-2.3: servletapi-2.3 requires tomcat-4.x, so require it
-k) better transaction support in the DB/Persistance layer for more efficient
-use of DB.
-m) Editing producer-templates in the mir-servlet. (idfx)
-n) Media infrastructure stuff:
- - make a sort of Factory to get handler perhaps in EntiyMediaType
- - MediaHandler should take care of storage tablename, the entry in SQL is
- redundant. -> get rid of it
- - maybe get rid of the MediaTypeTable entirely and have it in a config file?
- - use FM's TemplateMethodModel to access the MediaHandler method in templates
- instead of the crude way it's done now.
-
-*) move log to WEB-INF!!! (security problem)
-*)
-
---- wishlist ---
-
-* search engine: foto small thumbnails
-* comments: mark last read comments
-* comments: allow some HTML (let user choose)
-* allow HTML in abstracts
-* preview for video
-* protection against spam
- possibility to block submissions in case of spam attacks
- apache: 1-2 postings / IP / minute
- close artice for comments
- image with password
+++ /dev/null
-MIR UPGRADING HOWTO
-----------------------------------------------------------------
-
-For releases after 1.0.0-rc1, always check the NEWS file at the root of the
-tree to check the [Notes] section to see what you might have to adjust.
-
-For non releases or releases before 1.0.0-rc1, aka. the latest sources from
-CVS, it is a good idea to follow the advice below.
-
-Due to weaknesses of the current Mir configuration system, many folks get
-bitten after doing an update of their cvs tree. Suddenly Mir starts throwing
-weird exceptions, etc.. The cause is usually a new config option in the
-source/config.properties-dist that is missing from your
-source/config.properties file (the one that is actually used).
-
-a good way to check for this is to do the following (in the mir/ directory):
-
-cd source
-diff -u config.properties config.properties-dist
-
-for this unfamiliar with the diff(1) program, you'll see a bunch of lines, some
-starting with a "+" or "-". Look for a bunch of consecutive "+" symbols not
-immeadiately followed by a "-". that usually is a new config option that you
-should copy/paste (without the "+"'s of course) over to your existing
-config.properties file and modify if necessary.
-
-----------------------------------------------------------------
-
-last changed: $Date: 2002/12/07 07:00:16 $ - the Mir coders
--- /dev/null
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
+ [
+ <!ENTITY MIR_VERSION "1.1">
+ <!ENTITY introduction SYSTEM "introduction.xml">
+ <!ENTITY producers SYSTEM "producers.xml">
+ <!ENTITY search SYSTEM "search.xml">
+ ]
+>
+<book>
+ <title>Mir CMS 1.1: developer's guide</title>
+ <bookinfo>
+ <revhistory>
+ <revision>
+ <revnumber>0.0.0</revnumber>
+
+ <date>August 2005</date>
+
+ <revremark>First steps</revremark>
+ </revision>
+ </revhistory>
+
+ <authorgroup>
+ <author>
+ <firstname>Grok</firstname>
+ <affiliation>Mir coders
+ <email>grok wants no spam _at_ no-log.org</email>
+ </affiliation>
+ </author>
+ </authorgroup>
+ <keywordset>
+ <keyword>Mir</keyword>
+ <keyword>indymedia</keyword>
+ </keywordset>
+
+ </bookinfo>
+
+ <preface>
+ <abstract>
+ This document is meant for helping mir developers (people that
+ write java code within Mir). It is assumed that
+ you have already installed mir and have some basic knowledge
+ on how to use it. However, reading the introduction chapter might
+ also be worthwhile for sysadmins, webmasters and template designers.
+ </abstract>
+ </preface>
+
+<!-- Chapters -->
+&introduction;
+&producers;
+&search;
+
+</book>
\ No newline at end of file
--- /dev/null
+#!/bin/bash
+
+# converts a single-paged openoffice drawing into pdf,eps and
+# png. This script only works if you have a PDF printer defined in
+# openoffice
+
+# you can also do all this manually by opening openoffice and using
+# the export options...
+
+# usage: ./convert-sxd drawing.sxd
+
+src="$1"
+name=`basename "$src" .sxd`
+
+ooffice -pt PDF "$src"
+mv $HOME/"$src".pdf $name.pdf
+pdf2ps $name.pdf
+ps2eps -f $name.ps
+convert -density 600 $name.eps t.png
+convert t.png -geometry 600x600 $name.png
+
--- /dev/null
+<chapter id="introduction">
+<title>Introduction</title>
+
+<section><title>Architecture overview</title>
+<para>
+ Mir is a fairly large piece of software (over 50.000 lines) written in java.
+It relies on the tomcat servlet framework for administration and open publishing
+tasks. However, unlike many other CMS's that generate html on the fly
+(usually using a cache), Mir writes html pages into a static site.
+Normally, users that visit the mir site, will only see the static site.
+Users that want to publish content (open publishing) will contact
+the dynamic site. Administrators will also contact
+the dynamic site (see figure).
+</para>
+
+<figure><title>mir architecture (single host)</title>
+<mediaobject>
+<imageobject>
+<imagedata fileref="figures/mir-architecture-singlehost.eps" format="EPS"></imagedata></imageobject>
+<imageobject>
+<imagedata fileref="figures/mir-architecture-singlehost.png" format="PNG"></imagedata></imageobject>
+<textobject>
+</textobject>
+</mediaobject>
+</figure>
+
+<para>
+This architecture is interesting because most page requests will be done
+on the static site. Static pages are efficiently handled by the web server.
+It is also interesting because it permits easy mirroring of the static
+site. Mirrors are simple to set up, since only static pages are involved
+(see figure).
+</para>
+
+<figure><title>mir architecture (mirrored)</title>
+<mediaobject>
+<imageobject>
+<imagedata fileref="figures/mir-architecture-mirrored.eps" format="EPS"></imagedata></imageobject>
+<imageobject>
+<imagedata fileref="figures/mir-architecture-mirrored.png" format="PNG"></imagedata></imageobject>
+<textobject>
+</textobject>
+</mediaobject>
+</figure>
+
+</section>
+
+<section><title>Concepts used by Mir</title>
+<para>Here's a list of important terms and concepts used by Mir.
+Many of these concepts will be further detailed later on in this guide.
+</para>
+<glossentry id="producers">
+ <glossterm>producers</glossterm>
+ <glossdef>
+ <para>As mentioned in the architecture overview, mir
+generates a set of static html pages called the static site.
+Generating these pages involves using a template engine to
+replace variables (representing data) in template files. Template files
+are written by web designers.
+In many CMS systems, the available variables (data) are hard-coded into the
+software. In practice, this is often not flexible enough
+for web designers.
+Mir allows designers to request the data they need by using
+the producer framework, configured in the <filename>producers.xml</filename> file.
+</para>
+<para>Originally producers were
+mostly used to generate pages, but they are now used for a lot of
+other tasks. In fact, the <filename>producers.xml</filename> file provides a
+simple, xml-based, programing (scripting) language, so that
+site administrators can script their own custom tasks without
+changing the java code.
+For example, on indymedia.org, producers are used to pull rss
+feeds for the global wire.
+</para>
+<figure><title>An example of article generation with the producers framework</title>
+<mediaobject>
+<imageobject>
+<imagedata fileref="figures/article-generation-example.eps" format="EPS"></imagedata></imageobject>
+<imageobject>
+<imagedata fileref="figures/article-generation-example.png" format="PNG"></imagedata></imageobject>
+<textobject>
+</textobject>
+</mediaobject>
+</figure>
+<para>In the admin web interface, producers appear, for example, on
+the admin->"Generate manually"->"advanced page": (they are called Tasks)</para>
+<para>
+More information on producers is available in <xref linkend="producer_framework" />.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="database">
+ <glossterm>database access</glossterm>
+ <glossdef>
+ <para>
+Mir uses a postgres database to store it's data.
+Currently, the <code>mir.storage</code>, <code>mircoders.storage</code>,
+<code>mir.entity</code>, and <code>mir.entity.adapter</code>
+packages
+are used to access the database in Mir. However, these packages
+are obsolete and will be replaced by the
+<ulink url="http://www.hibernate.org">hibernate</ulink>
+object/relational persistence system.
+</para>
+ </glossdef>
+</glossentry>
+
+
+<glossentry id="localizer">
+ <glossterm>localizer</glossterm>
+ <glossdef>
+ <para>
+Localizers provide a customization framework that allows
+different mir sites to behave differently. Each site can
+write it's own bits of java code that override default behavior.
+This is effectively
+used by various indymedia sites to customize things
+such open posting mechanisms, open
+posting validation, data model enhancements, etc.
+In other words, the localizer framework provides "hooks"
+where admins can plug in
+their custom code.
+</para>
+<para>
+The <classname>MirLocalizer</classname> interface describes
+the centralized localizer, that may be accessed via the global
+<function>MirGlobal.localizer()</function>
+function. The central localizer provides accessors to
+domain specific localizers
+(like <classname>MirBasicOpenPostingLocalizer</classname>).
+</para>
+<para>
+Default behavior is provided by the <classname>MirBasicLocalizer</classname>
+and it's associated classes. These classes can be extended to
+override default behavior.
+</para>
+<para>
+To override default behavior you must implement a new
+<classname>MirLocalizer</classname>
+and give the path to your class in the
+<code>Mir.Localizer</code> property of the
+<filename>config.properties</filename>
+file.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="abuse">
+ <glossterm>abuse filter framework</glossterm>
+ <glossdef>
+ <para>
+Mir can be configured to refuse postings or spam. This is done
+by using a set of filters that will attempt to match posted content.
+If any filter matches, appropriate action (FIXME? what action? ) will be taken.
+Three types of filters are currently implemented: IP filters
+(reject certain ip adresses), regular expression filters
+(try to match parts (FIXME? ip? title? content?) of the posting) and
+throttle filters (avoid repeated postings (FIXME? is this ok?)).
+ </para>
+<para>
+Filters may be organized into groups for easier management.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="generator">
+ <glossterm>generator</glossterm>
+ <glossdef>
+ <para>
+A generator is an abstraction for a template (html template).
+Calling the generator's <function>generate(outputFileWriter,keyValuePairs)</function> method
+will run the template engine on the template file
+and write an output html file.
+Different template engines are
+supported right now:
+<ulink href="http://freemarker.sourceforge.net">freemarker</ulink>
+(used most often), tal (used by some
+sites) and velocity (not used at all but supported anyway).
+</para>
+ </glossdef>
+</glossentry>
+
+
+<glossentry id="logger">
+ <glossterm>logger</glossterm>
+ <glossdef>
+ <para>
+Logging is understood here as "system logs" : information written
+out to files that may be used to track what is going on in Mir,
+especially errors and warnings. Mir uses the <ulink url="http://logging.apache.org/log4j/docs">log4j</ulink> logging system.
+This allows us to split logs into different files, making them
+easier to understand.
+</para>
+ </glossdef>
+</glossentry>
+
+
+<glossentry id="mircoders">
+ <glossterm>mircoders packages</glossterm>
+ <glossdef>
+ <para>
+Originally, the mircoders packages were meant for local developments,
+as opposed to core Mir code. This distinction is now obsolete
+and these packages will probably be reorganized in future releases.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="bundles">
+ <glossterm>bundles</glossterm>
+ <glossdef>
+ <para>
+A Bundle represents a set key/value pairs stored in a ".properties"
+text file. Bundles are used for internationalization (language
+translations) and for <glossterm linkend="configuration">configuration</glossterm> files (config.properties and
+source/default.properties).
+Bundles may be used to create a template for multiple languages.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="search">
+ <glossterm>search framework</glossterm>
+ <glossdef>
+ <para>
+Mir's search framework relies on
+<ulink url="http://lucene.apache.org/java/docs/index.html">apache lucene
+</ulink>.
+Content is inserted into a special index file while it is produced
+(see <glossterm linkend="producers">producers</glossterm> framework).
+This allows for quick retreival during search.
+Indexing is requested in the <filename>producers.xml</filename> file
+by the <code><IndexContent></code> node.
+In other words, when Mir generates a static html page for an article,
+it also creates <classname>SearchTerm</classname>'s and inserts
+them into the index.
+By default, the index file is stored in <filename>bin/mir/WEB-INF/index</filename>.
+</para>
+<para>
+Search queries are managed by <function>ServletModuleContent.search()</function>
+Search results are stored by tomcat in
+the user's session for the purposes of pagination and sorting.
+</para>
+<para>
+The design of the indexing and searching make it completely
+independent of the database once the content is indexed.
+</para>
+<para>
+More information is available in <xref linkend="search_framework" />.
+</para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="servlet">
+ <glossterm>servlet framework</glossterm>
+ <glossdef>
+ <para>
+Mir uses the tomcat servlet framework for the admin interface,
+for open posting and for search queries (FIXME something else?).
+Mir exposes two servlets: the <classname>Mir</classname>
+servlet and the <classname>OpenMir</classname> servlet, whose
+methods are directly called in response to an http request.
+For example, a request for <uri>http://somehost.org/mir/servlet/Mir</uri>
+will call the <function>doGet()</function> method of the
+<classname>Mir</classname> class.
+ </para>
+ <para>
+Once requests are received by the
+<classname>Mir</classname> or <classname>OpenMir</classname>
+classes, they are dispatched to other servlet classes.
+The <code>module</code> argument of the http request
+determines the classes name.
+The <code>do</code> argument determines the method's name.
+So
+<uri>http://somehost.org/mir/servlet/Mir?module=Comment&do=list</uri>
+will call <function>ServletModuleComment.list()</function>.
+ </para>
+ </glossdef>
+</glossentry>
+
+
+<glossentry id="media">
+ <glossterm>media framework</glossterm>
+ <glossdef>
+ <para>
+The media framework is quite old and will be thoroughly changed
+in a future release.
+ </para>
+ </glossdef>
+</glossentry>
+
+<glossentry id="configuration">
+ <glossterm>configuration</glossterm>
+ <glossdef>
+ <para>
+Mir is configured through the
+<filename>etc/config.properties</filename> file, which
+overrides default values in
+the
+<filename>source/default.properties</filename> file.
+The key/value pairs are handled by
+<glossterm linkend="bundles">bundles</glossterm>.
+ </para>
+ </glossdef>
+</glossentry>
+
+
+
+
+</section>
+
+
+
+</chapter>
--- /dev/null
+<chapter id="producer_framework">
+<title>The producer framework</title>
+Please read the presentation of the <glossterm linkend="producers">producers</glossterm> concept
+for an introduction.
+
+<section><title>How to use the <filename>producers.xml</filename> file</title>
+ [FIXME: this should be in the admin's guide, not here]
+
+<para>
+Please check the standard <filename>producers.xml</filename> file
+for two fully commented, real-world examples :
+the <code><nodedefinition name="Language"></code> node
+and the <code><producer name="articles"></code> node.
+</para>
+
+ <section><title>Introduction</title>
+
+ <para>
+ Mir allows admins to fully configure the producer tasks and set up
+ arbitrary producers through the <filename>producers.xml</filename> file.
+ </para>
+
+ <para>
+ Producers consist of "nodes". Every node has a specific function.
+ For example, it is possible to use a node to generate a file out of a template.
+ Or it is possible to use a node to enumerate over a collection of articles.
+ </para>
+
+
+
+ <para>
+ A producer is defined using a Producer tag:
+ <programlisting>
+ <producer name="content"/>
+ </programlisting>
+ This would define a producer named <code>content</code>.
+
+ </para><para>
+ In a producer, <emphasis>verbs</emphasis> must be defined.
+ Verbs are sub-tasks of a producer.
+
+ <programlisting>
+
+ <producer name="content">
+ <verbs>
+ <verb name="new">
+ </verb>
+ <verb name="all">
+ <verb>
+ </verbs>
+ <producer name="content"/>
+ </programlisting>
+
+ This would define a producer with verbs named <code>all</code> and <code>new</code>.
+
+ </para><para>
+ And also the specific nodes and their relationship should be specified:
+
+ <programlisting>
+
+ <producer name="content">
+ <verbs>
+ <verb name="new">
+ </verb>
+ <verb name="all">
+ <verb>
+ </verbs>
+ <body>
+ <Generate
+ generator="/producer/startpage.template"
+ destination="${config.storageRoot}/index.shtml"/>
+ </body>
+ </producer>
+ </programlisting>
+
+ we will later learn that this producer generates a single file.
+
+ </para><para>
+ Producers can be made to do different things for different verbs:
+
+ <programlisting>
+
+ <producer name="content">
+ <verbs>
+ <verb name="new">
+ <Set key="count" value="3"/>
+ </verb>
+ <verb name="all">
+ <Set key="count" value="5"/>
+ <verb>
+ </verbs>
+ <body>
+ <Generate
+ generator="/producer/startpage.template"
+ destination="${config.storageRoot}/index.shtml"/>
+ </body>
+ </producer>
+ </programlisting>
+
+ if a producer is called with a specific verb, first the nodes of that verb
+ are processed, and only thereafter the body: in our case, if the producer
+ <code>content</code> is called with verb <code>new</code>, first the variable <code>count</code>
+
+ is set to <code>3</code>, and after that, a file is generated.
+
+</para>
+ </section>
+<section><title>Node arguments</title>
+ <para>
+ Nodes can have arguments.
+ Arguments that amount to integer values can be direct expressions.
+ Arguments that amount to text values can be enriched with expressions between ${}.
+
+ </para>
+ <para>
+ Some examples:
+ <programlisting>
+ <Log message="This article has the following title: ${content.title}"/>
+
+ </programlisting>
+ <code>Log</code> has 1 mandatory argument, <code>message</code>. This argument should be text,
+ but can be enriched with expressions enclosed by ${ and }. In this example,
+ the title of an article is logged.
+
+ <programlisting>
+ <Set key="age" value="34+22*(3+2)"/>
+ </programlisting>
+ <code>Set</code> has 2 mandatory argument: <code>key</code> and <code>value</code>.
+ The key arugment is a fixed text,
+ the value argument is a direct expression, in this case of arithmetic nature.
+
+ </para>
+
+ </section>
+<section><title>Expressions</title>
+
+
+ <para>
+ Expressions, either direct expressions, or expressions between ${}, can contain the following
+ constructions:
+ </para>
+
+ <para>
+ <table border="1">
+ <title>Expressions</title>
+
+ <tr><td>a string literal</td> <td><code>'hello'</code></td></tr>
+ <tr><td>a numeric literal</td> <td><code>2138</code></td></tr>
+
+ <tr><td>a variable reference</td> <td><code>content.title</code></td></tr>
+ <tr><td>arithmetic operators</td> <td><code> 3 + 4 *(2+5-2)</code></td></tr>
+ <tr><td>string operators</td> <td><code> 'hello' ++ ' ' ++ 'Mir'</code></td></tr>
+
+ <tr><td>boolean operators</td> <td><code>(content.id==3) or (content.id in (5,7,2,8) and (content.title!='hello')</code></td></tr>
+ </table>
+
+ </para>
+ </section>
+<section><title>Node types and statements</title>
+ <para>
+ Here's a list of different node types that can be used inside
+ producer definitions.
+Currently, there exists only one statement (<nodedefinition>), that
+is declared outside producer definitions.
+
+
+ Here an overview:
+
+ </para>
+ <table border="1">
+ <title>Reference for producer node types and statements</title>
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Set</code></td></tr>
+ <tr><td>Purpose</td> <td>Alter a variable's using a free expression</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The variable</td></tr>
+
+ <tr><td>value</td> <td>The expression to set the variable to</td></tr>
+ <tr>
+ <td>Example</td>
+ <td>
+ <code>
+ <Set key="data.result" value="3 + 5 * (5-2)"/>
+
+ </code>
+ </td>
+ </tr>
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Define</code></td></tr>
+ <tr><td>Purpose</td> <td>Alter a variable's using a string</td></tr>
+ <tr><td colspan="2">
+
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The variable</td></tr>
+ <tr><td>value</td> <td>The string to set the variable to</td></tr>
+ <tr>
+ <td>Example</td>
+
+ <td>
+ <code>
+ <Define key="filename" value="/var/www/${content.id}.shtml"/>
+ </code>
+ </td>
+ </tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>If</code></td></tr>
+
+ <tr><td>Purpose</td> <td>Create a conditional part of a producer</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>condition</td> <td>The expression to test</td></tr>
+ <tr><td colspan="2">
+ Sub tags</td></tr>
+
+ <tr><td>then</td> <td>The part to process if the expression evaluates to true</td></tr>
+ <tr><td>else</td> <td>The part to process if the expression evaluates to false</td></tr>
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>nodedefinition</code> (statement)</td></tr>
+
+ <tr><td>Purpose</td> <td>Acts as a "function" (or "macro") that can be "called" elsewhere in a producer.
+More precisely, it is a way to define a new producer node type
+inside the <filename>producers.xml</filename> file.
+(check the <code>Language</code> node in that file for an example).
+</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>name</td> <td>The name of the newly created node ("function")</td></tr>
+ <tr><td colspan="2">
+ Sub tags</td></tr>
+
+ <tr><td>parameters</td> <td>a list describing the arguments the "function" must be given </td></tr>
+ <tr><td>definition</td> <td>the actual body of the function, containing the code that should be executed. Note that this may contain a <code><sub/></code> tag that is replaced by the child nodes of the calling node. </td></tr>
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Log</code></td></tr>
+
+ <tr><td>Purpose</td> <td>Log a message in the producer log</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>message</td> <td>The message to log</td></tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Enumerate</code></td></tr>
+ <tr><td>Purpose</td> <td>Enumerate over the results of a query</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The variable name that receives the enumerated record</td></tr>
+
+ <tr><td>table</td> <td>The table that is used to enumerate over</td></tr>
+ <tr><td>selection (optional)</td> <td>The condition (where clause) of the query.</td></tr>
+ <tr><td>order (optional)</td> <td>The order in which the results of the query are enumerated.</td></tr>
+ <tr><td>skip (optional)</td> <td>The number of records to skip</td></tr>
+
+ <tr><td>limit (optional)</td> <td>The maximum number of records to enumerate</td></tr>
+ <tr><td colspan="2">
+ Sub tags</td></tr>
+ <tr><td colspan="2">
+ This node can have subnodes that will be processed for every enumerated record</td></tr>
+<!--
+ <tr>
+ <td>Remarks</td>
+ <td>
+ </td>
+ </tr>
+ <tr>
+ <td>Example</td>
+ <td>
+ <code>
+ <Generate generator="/producer/content.template" destination="/var/www/${content.date.formatted.yyyy}/${content.date.formatted.MM}/${content.id}.shtml"/>
+ </code>
+ </td>
+ </tr>
+ -->
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>List</code></td></tr>
+
+ <tr><td>Purpose</td> <td>Store the results of a query into a variable</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The variable name that receives the result list</td></tr>
+ <tr><td>table</td> <td>The table that is used to select from</td></tr>
+
+ <tr><td>selection (optional)</td> <td>The condition (where clause) of the query.</td></tr>
+ <tr><td>order (optional)</td> <td>The order in which the results of the query are put into the list.</td></tr>
+ <tr><td>skip (optional)</td> <td>The number of records to skip</td></tr>
+ <tr><td>limit (optional)</td> <td>The maximum size of the list</td></tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Batch</code></td></tr>
+ <tr><td>Purpose</td> <td>Divide the results of a query into batches</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>key</td> <td>The variable name that receives the batch</td></tr>
+ <tr><td>infokey</td> <td>The variable name that receives meta information on the batches</td></tr>
+ <tr><td>table</td> <td>The table that is used to select from</td></tr>
+ <tr><td>batchsize</td> <td>The size of a batch (the first batch however varies in size)</td></tr>
+
+ <tr><td>selection (optional)</td> <td>The condition (where clause) of the query.</td></tr>
+ <tr><td>order (optional)</td> <td>The order in which the results of the query are put into the list.</td></tr>
+ <tr><td>skip (optional)</td> <td>The number of records to skip</td></tr>
+ <tr><td>process (optional)</td> <td>The maximum number of batches to process</td></tr>
+
+ <tr><td>minbatchsize (optional)</td> <td>The minimal size of the first batch</td></tr>
+ <tr><td colspan="2">
+ Sub tags</td></tr>
+ <tr><td>batches</td> <td>The part to process for every batch</td></tr>
+ <tr><td>batchlist</td> <td>The part to process once with the meta info</td></tr>
+
+
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Generate</code></td></tr>
+ <tr><td>Purpose</td> <td>Generate a page using a generator (i.e. an abstraction of a template)</td></tr>
+ <tr><td colspan="2">
+
+ Arguments</td></tr>
+
+ <tr><td>generator</td> <td>the generator to use</td></tr>
+ <tr><td>destination</td> <td>the specification of the destination.</td></tr>
+ <tr><td>parameters</td> <td>Additional configuration info for the generator (for
+ freemarker this now only contains the wanted encoding,
+ empty for the default).</td></tr>
+
+ <tr>
+ <td>Remarks</td>
+ <td>
+ This node is used to have an actual page generated.
+ The generator parameter usually is the name of a template.
+ The destination is the file to be generated.
+ Variable references are possible in all arguments, and, especially for the
+ destination attribute, widely used.
+ </td>
+ </tr>
+ <tr>
+ <td>Example</td>
+
+ <td>
+ <code>
+ <Generate generator="/producer/content.template" destination="/var/www/${content.date.formatted.yyyy}/${content.date.formatted.MM}/${content.id}.shtml"/>
+ </code>
+ </td>
+ </tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>GenerateMedia</code></td></tr>
+ <tr><td>Purpose</td> <td>
+The generateMedia node instructs the media handler associated with the media to
+"reproduce" the media. In practice this can mean generate an icon from an image,
+writing an image from the database to the web root, or create an m3u file or so.
+Media handling is limited at this moment, but a serious
+redesign is planned right after 1.1
+</td></tr>
+ <tr><td colspan="2">
+
+ Arguments</td></tr>
+
+ <tr><td>key</td> <td>FIXME???</td></tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>DeleteFile</code></td></tr>
+ <tr><td>Purpose</td> <td>Delete a file</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+ <tr><td>filename</td> <td>The filename of the file to delete</td></tr>
+
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>SetFileDate</code></td></tr>
+ <tr><td>Purpose</td> <td>Set a file's date</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>filename</td> <td>The filename</td></tr>
+ <tr><td>date</td> <td>The date to use</td></tr>
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Resource</code></td></tr>
+ <tr><td>Purpose</td> <td>Make a message resource bundle available. In other words, this defines a function that can be used in expressions to reference a bundle. </td></tr>
+ <tr><td colspan="2">
+
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The name of the function.</td></tr>
+ <tr><td>bundle</td> <td>The bundle to use</td></tr>
+ <tr><td>language (optional)</td> <td>The specific language to use</td></tr>
+ <tr>
+ <td>Example</td>
+ <td>
+ <code>
+ <Resource bundle="bundles.producer" key="lang" language="en"/>
+ </code>
+ This makes the english language producer bundle available
+ through the "lang()" function. One
+ can then use expressions like ${lang("page.title")} to
+ refer to a that value.
+ </td>
+ </tr>
+
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>Execute</code></td></tr>
+ <tr><td>Purpose</td> <td>Execute a script</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>command</td> <td>The command to execute</td></tr>
+
+
+
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>ModifyContent</code></td></tr>
+ <tr><td>Purpose</td> <td>Modify a field of an article</td></tr>
+ <tr><td colspan="2">
+
+ Arguments</td></tr>
+ <tr><td>key</td> <td>The variable containing the article</td></tr>
+ <tr><td>field</td> <td>The field to modify</td></tr>
+ <tr><td>value</td> <td>The value to set the field to</td></tr>
+
+
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>MarkContent</code></td></tr>
+ <tr><td>Purpose</td> <td>Mark an article as produced</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>key</td> <td>The variable containing the article</td></tr>
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>IndexContent</code></td></tr>
+ <tr><td>Purpose</td> <td>adds/updates content to the search index (search engine)</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>key</td> <td>The variable containing the article (FIXME????)</td></tr>
+ <tr><td>pathToIndex</td> <td>(FIXME????)</td></tr>
+
+ <tr><td>Name</td> <td bgcolor="#eea8a8"><code>UnIndexContent</code></td></tr>
+ <tr><td>Purpose</td> <td>removes content from the search index (search engine)</td></tr>
+ <tr><td colspan="2">
+ Arguments</td></tr>
+
+ <tr><td>key</td> <td>The variable containing the article (FIXME????)</td></tr>
+ <tr><td>pathToIndex</td> <td>(FIXME????)</td></tr>
+
+ </table>
+</section>
+</section>
+
+<section><title>How the producer framework is implemented</title>
+
+<!-- <para>A Producer is a set of tasks, scripted in xml. Producers allow -->
+<!-- mir installations to have their own actions that can be called for -->
+<!-- instance when a new article is posted. Originally producers were -->
+<!-- mostly used to generate pages, but they are used for a lot of -->
+<!-- other tasks such as pulling rss feeds for the global wire on -->
+<!-- indymedia.org. Producers are added and configured through the -->
+<!-- <filename>producers.xml</filename> file.</para> -->
+
+
+<para>The xml nodes contained within a <code><producer></code>
+tag in the <filename>producers.xml</filename> file define
+a small program.
+This program (or script) may contain constructs
+such as <code>if</code> clauses, loops and variables... The program is parsed into a
+tree of <classname>ProducerNode</classname>s (figure). The root of this tree is defined in a
+<classname>NodedProducer</classname> (which is the only class that currently implements
+the <classname>Producer</classname> interface). When the producer is executed, the
+<function>produce()</function> methods of each node are recursively called, effectively
+executing the program as it was scripted. </para>
+
+<figure><title>A producer in the <filename>producer.xml</filename> file is parsed into a tree of <classname>ProducerNodes</classname></title>
+<mediaobject>
+<imageobject>
+<imagedata fileref="figures/producer-node-tree-example.eps" format="EPS"></imagedata></imageobject>
+<imageobject>
+<imagedata fileref="figures/producer-node-tree-example.png" format="PNG"></imagedata></imageobject>
+<textobject>
+</textobject>
+</mediaobject>
+</figure>
+
+<para>
+</para>
+</section>
+</chapter>
--- /dev/null
+<chapter id="search_framework">
+<title>Search Framework</title>
+Please read the short presentation of the <glossterm linkend="search">search framework</glossterm> for an introduction. You can also check the javadoc.
+<section><title>The SearchTerm class</title>
+The SearchTerm class attempts to encapsulate the relationships
+between:
+<itemizedlist>
+<listitem>A fields or property of Content Entities </listitem>
+<listitem>A field of Lucene Documents</listitem>
+<listitem>An HTTP Query Parameter</listitem>
+<listitem>And a bit of HTML on a Search Results Page </listitem>
+</itemizedlist>
+<para>
+The basic idea is that how you index, query, and display a
+particular field in a resource are all intimately related, possibly
+more so than how you index two different fields of the same
+resource.
+</para>
+<para>
+Instances of classes implementing SearchTerm are created when a Mir
+content entity is indexed by the IndexingProducerNode Class. The
+index method of each class is called in turn to add a bit of
+information to the Lucene documents which will be added to the
+index after it is created and all its fields specified. Instances
+of the same classes are created by ServletModuleOpenIndy so that it
+can construct a query to match against the lucene index, here the
+makeTerm methods are called in turn to pick out the parameter they
+want from the request and then construct the appropriate fragment
+of lucene query, which are ultimately concatenated together. These
+classes are also used to return appropriate template models
+representing any hits to be displayed as a result of processing the
+query.
+</para>
+</section>
+<section><title>Available search classes</title>
+<variablelist>
+<varlistentry>
+<term><classname>ContentSearchTerm</classname></term><listitem>tokenizes a string field in an Entity and indexes
+it, but does not store it for retrieval (used for content_data)
+</listitem></varlistentry>
+
+<varlistentry>
+<term><classname>ImagesSearchTerm</classname></term><listitem>indexes whether or not an Entity has associated
+images, and also stores urls of those images for retrieval in the search results
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>KeywordSearchTerm</classname></term><listitem>indexes a field and stores it for retrieval, but
+does not tokenize it. useful for things like strings representing
+dates.
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>MediaSearchTerm</classname></term><listitem>not used
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>AudioSearchTerm</classname></term><listitem>indexes whether an Enity has audio
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>VideoSearchTerm</classname></term><listitem>indexes whether an Enity has video
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>TextSearchTerm</classname></term><listitem>tokenizes a string field in an Entity and indexes
+it, and stores it for retrieval (used for description)
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>TopicSearchTerm</classname></term><listitem>used by indexing and querying documents based on Topic
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>UnIndexedSearchTerm</classname></term><listitem>Stores some metatdata for retrieval with a hit (for example a URL)
+</listitem></varlistentry>
+<varlistentry>
+<term><classname>UnStoredSearchTerm</classname></term><listitem>not currently used
+</listitem></varlistentry>
+</variablelist>
+
+</section>
+<section><title>Lucene field types</title>
+<para>
+The following brief guide to lucene field types is invaluable in
+figuring out what a particular SearchTerm does:
+</para>
+
+ Keyword is stored and indexed, but not tokenized
+ Text is tokenized,stored, indexed
+ Unindexed is not tokenized or indexed, only stored
+ Unstored is tokenized and indexed, but not stored
+
+</section>
+
+</chapter>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
+ [
+ <!ENTITY MIR_VERSION "1.1">
+ ]
+>
+<book>
+ <title>Mir CMS 1.1 Installation manual</title>
+ <bookinfo>
+ <revhistory>
+ <revision>
+ <revnumber>0.0.0</revnumber>
+
+ <date>July 2004</date>
+
+ <revremark>First steps</revremark>
+ </revision>
+ <revision>
+ <revnumber>0.0.1</revnumber>
+
+ <date>October/November 2004</date>
+
+ <revremark>First usable version</revremark>
+ </revision>
+ </revhistory>
+
+ <authorgroup>
+ <author>
+ <firstname>Zapata</firstname>
+ <affiliation>Mir coders</affiliation>
+ </author>
+ </authorgroup>
+ </bookinfo>
+
+ <preface>
+ <abstract>
+ This document helps system administrators install Mir,
+ a Java-based Content Management System distributed under
+ the Gnu Public License.
+ </abstract>
+ </preface>
+
+ <chapter id="introduction">
+
+ <title>Introduction</title>
+
+ <section>
+ <title>Mir</title>
+
+ <para>
+
+ </para>
+
+ </section>
+
+ <section>
+ <title>Version</title>
+
+ <para>
+ This documentation applies to mir version &MIR_VERSION;.
+ </para>
+ </section>
+
+ <section>
+ <title>Overview</title>
+ <para>
+ In order to make use of Mir, one has to install configure
+ several required pieces of third party software.
+
+ </para>
+ </section>
+
+ </chapter>
+
+ <chapter>
+ <title>Overview</title>
+
+ <section>
+ <title></title>
+
+ <para>
+ <itemizedlist>
+ <listitem>
+ Third party software required by mir, such as Postgresql, the Relational
+ Database Management System Mir requires.
+ </listitem>
+ <listitem>
+ The Mir code itself, normally in the form of a binary
+ distribution.
+ </listitem>
+ <listitem>
+ Configuration with details like database access parameters.
+ </listitem>
+ <listitem>
+ A custom mir setup, incorporating the look and feel the mir-driven
+ site should have
+ </listitem>
+ </itemizedlist>
+ </para>
+
+ </section>
+
+ </chapter>
+
+ <chapter>
+ <title>Installing Mir itself</title>
+
+ <section>
+ <title>Introduction</title>
+
+ <para>
+ <itemizedlist>
+ <listitem>
+ Mir versions: x.y.z
+ </listitem>
+ <listitem>
+ Binary distribution, Source distribution,CVS distribution
+ </listitem>
+ <listitem>
+ Mir customization
+ </listitem>
+ </itemizedlist>
+ </para>
+ </section>
+
+ <section>
+ <title>Obtaining a distribution</title>
+
+ <para>
+ </para>
+ </section>
+
+ <section>
+ <title>Configuring mir</title>
+
+ <para>
+ <itemizedlist>
+ </itemizedlist>
+ </para>
+
+ </section>
+
+ <section>
+ <title>Notes for multiple mir installation on a single system</title>
+
+ <para>
+ </para>
+ </section>
+
+ <section>
+ <title>The most commonly used configuration entries</title>
+
+ <para>
+ <variablelist>
+ <varlistentry>
+ <term><literal>Mir.Name</literal></term>
+ <term><literal>Mir.Shortname</literal></term>
+ <term><literal>Mir.Contact-email.address</literal></term>
+ <term><literal>Mir.Contact-email.name</literal></term>
+ <term><literal>Mir.Tech-email.address</literal></term>
+ <term><literal>Mir.Tech-email.name</literal></term>
+ <term><literal>Mir.Public-email.address</literal></term>
+ <term><literal>Mir.Public-email.name</literal></term>
+
+ <listitem>
+ These entries constitute various names and email addresses used in error forms and
+ within mir's admin interface.
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.DefaultTimezone</term>
+ <listitem>
+ The default timezone to be used for showing dates and times.
+ Values like <literal>Europe/Amsterdam</literal> are highly
+ reccommended, since these take daylight savings time into
+ account where applicable.
+
+ For a full list of possible values, see:
+ <ulink url="http://www.fnal.gov/docs/products/crl/misc/Time_Zone_Listing.txt">here</ulink>.
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.DefaultDateTimeFormat</term>
+ <listitem>
+ The format to use for dates and times in admin, e.g. <literal>yyyy-MM-dd HH:mm</literal>.
+
+ For the allowed codes and their meanings, see
+ <ulink url="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html">here</ulink>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Admin.FallbackLanguage</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.DefaultLanguage</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Admin.ShowLoggedinUsers</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Localizer.Admin.ListOperationsFlavor</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>Mir.Login.Languages</term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term></term>
+ <listitem>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </para>
+ </section>
+ </chapter>
+
+ <chapter>
+ <title>Third party software required by Mir</title>
+
+ <section>
+ <title>A Java Virtual Machine (version 1.3 and up)</title>
+
+ <para>
+ Since Mir is a Java application, a Java virtual machine is
+ needed to run it.
+ </para>
+
+ <para>
+ version 1.3+
+
+ For linux systems, both IBM and Sun have such a virtual machine
+ available.
+ </para>
+
+ <para>
+ JRE versus JDK
+ </para>
+
+ <para>
+ Neither the IBM nor the SUN Virtual Machine constitute free
+ software as definied by the <ulink url="http://www.fsf.org">Free Software
+ Foundation</ulink>.
+
+ At this moment
+
+ Given Mir's commitment to Free Software
+
+ Alternatives to propietary JVMs are actively sought by the mir coders,
+ especially regarding gnu's gjc and classpath projects and the
+ sable virtual machine.
+
+ This investigation is ongoing.
+
+ Results will be announced on the mir site as well as the mir coders
+ mailing list.
+
+ Until then, one of the aforementioned proprietary virtual machines
+ is required for Mir.
+ </para>
+ </section>
+
+ <section>
+ <title>RDBMS: Postgresql</title>
+
+ <para>
+ The version of Mir described in this document depends on the
+ Postgresql RDBMS system.
+
+ This section will explain the specific side issues applicable
+ to using it in conjunction with mir.
+
+ For general Postgresql information, see <ulink url="http://www.postgresql.org/">The
+ official Postgresql website</ulink>
+
+ Note that databases to be used by mir can be initialized by
+ a script provided in the mir distribution.
+ </para>
+
+ <section>
+ <title>Installation</title>
+
+ <para>
+ A normal postgresql installation will suffice for Mir (details can
+ be found on the postgresql site).
+
+ It would be wise however to install support for unicode encoded
+ databases, since with Mir, these generally work out the best.
+ </para>
+ </section>
+
+ <section>
+ <title>Configuration</title>
+
+ <para>
+ <programlisting>
+ pg_hba.conf
+ </programlisting>
+ </para>
+ </section>
+
+ <section>
+ <title>Maintenance</title>
+
+ <para>
+ The mircoders advise you to make regular backups of your databases,
+ to prevent accidental loss of data.
+
+ Aside from this, there's one important Postgresql-specific maintenance
+ issue:
+
+ <programlisting>
+ vacuum analyze;
+ </programlisting>
+ </para>
+ </section>
+
+ <section>
+ <title>Practical tips</title>
+
+ <para>
+ A postgresql installation comes with a number of handy tools.
+
+ We'll supply you with a brief overview of them.
+
+ Further information is available in the man pages of the tools
+ in question and on the postgresql website.
+ </para>
+
+ <section>
+ <title><application>psql</application></title>
+
+ <para>
+ <application>psql</application> is postgresql's literal-line
+ interface to perform queries on databases.
+ </para>
+ </section>
+
+ <section>
+ <title><application>pg_dump</application> and <application>pg_restore</application></title>
+
+ <para>
+ </para>
+ </section>
+
+ </section>
+ </section>
+
+ <section>
+ <title>Java servlet container: Tomcat</title>
+
+ <para>
+ The reccommended Java Servlet Container is Tomcat.
+
+ Mir will probably work with Tomcat version 3.3 and up.
+
+ For various practical reasons, Tomcat 4 is recommended.
+
+ The next version of Mir will most likely require at least Tomcat 4.
+ </para>
+
+ <section>
+ <title>Installation</title>
+
+ <para>
+ - distributions
+ </para>
+ </section>
+
+ <section>
+ <title>Configuration</title>
+
+ <para>
+ </para>
+
+ <section>
+ <title>Pointing tomcat to the mir installation</title>
+
+ <para>
+ </para>
+ </section>
+
+ <section>
+ <title>Turning off IP logging</title>
+
+ <para>
+
+ </para>
+ </section>
+
+ <section>
+ <title>Disabling security</title>
+
+ <para>
+ Future versions of this documentation will contain a
+ guide to properly configure tomcat's security manager.
+ </para>
+ </section>
+ </section>
+
+ <section>
+ <title>Practical tips</title>
+
+ <para>
+ manager, tomcat restarts, the user running tomcat
+ </para>
+
+ </section>
+ </section>
+
+ <section>
+ <title>HTTP Server: Apache</title>
+
+ <para>
+ <itemizedlist>
+ <listitem>enabling SSI</listitem>
+ <listitem></listitem>
+ </itemizedlist>
+ </para>
+ </section>
+
+ <section>
+ <title>Servlet connector: mod_jk</title>
+ </section>
+
+ <section>
+ <title>Sun's JAI library</title>
+
+ <para>
+ In addition to a virtual machine, Mir depends at this time on another
+ piece of non-free software, namely the JAI image library from Sun.
+
+ As with the virtual machine dependency, the mir coders will also do
+ its best to move towards a free replacement for JAI.
+ </para>
+
+ <section>
+ <title>Installation</title>
+ </section>
+
+ <section>
+ <title>Setting up</title>
+ </section>
+ </section>
+ </chapter>
+
+
+ <chapter>
+ <title>Setting up Mir on Debian</title>
+
+ <section>
+ <title>Introduction</title>
+
+ <para>
+ For users of the Debian GNU/Linux distribution, this chapter offers
+ easy steps to install mir.
+ </para>
+
+ <para>
+ Most of the third part software needed to run Mir, is available as
+ packages in debian distributions from woody on.
+
+ This chapter assumes the distribution, though most should be applicable
+ to newer distributions as well.
+ </para>
+ </section>
+ <section>
+ <title>Postgresql</title>
+
+ <para>
+ <application>Postgresql</application> is available in debian under the
+ package postgresql.
+
+ <informalexample>
+ <programlisting><literal>apt-get install postgresql</literal></programlisting>
+ </informalexample>
+ </para>
+
+ <para>
+ By default, postgresql in Debian is configured to use
+ <quote>ident</quote> authentication and <quote>sameuser</quote>
+ authorization for local users.
+
+ This means a local user can connect as the postgresql user with the
+ same name.
+
+ For Mir, it's required to have <quote>password</quote> authentication.
+
+ Therefore, in <filename>/etc/postgresql/pg_hba.conf</filename> a
+ change needs to be made:
+
+ The line containing the localhost configuration should be changed to look
+ like:
+ <programlisting>
+host all 127.0.0.1 255.0.0.0 password
+ </programlisting>
+
+ This means that any user from localhost can connect as any postgresql
+ user, as long as she can authenticate herself with the password.
+
+ </para>
+ <para>
+ For convenience reasons, it's also recommended to use password
+ authentication for the local domain.
+
+ For this, first a proper password needs to be selected for the postgres
+
+ super user. As root, do:
+ <informalexample>
+ <programlisting><literal>su postgres</literal>
+<literal>psql template1</literal>
+# alter user postgres with password 'xxxxxxx';
+/q</programlisting>
+ </informalexample>
+
+ Then, the line with local authentication in
+ <filename>/etc/postgresql/pg_hba.conf</filename> should be
+ altered:
+ <programlisting>
+local all password
+ </programlisting>
+ </para>
+ <para>
+ Don't forget to restart the database so that these changes will be taken
+into acount (/etc/init.d/postgresql restart).
+ </para>
+ </section>
+ <section>
+ <title>Tomcat</title>
+ <para>
+ <application>Tomcat 4</application> can be found in Debian-package tomcat4.
+ <informalexample>
+ <programlisting><literal>apt-get install tomcat4</literal></programlisting>
+ </informalexample>
+ </para>
+ <para>
+ The security manager needs to be disabled by editing
+ <filename>/etc/default/tomcat4</filename>
+ and setting the option <option>TOMCAT4_SECURITY</option>
+ to <literal>"no"</literal>
+ <informalexample>
+ <programlisting><option>TOMCAT4_SECURITY</option> = <literal>"no"</literal></programlisting>
+ </informalexample>
+ </para>
+ <para>
+ It is reccommended to disable ip logging.
+
+ This can be done by editing
+ <filename>/usr/share/tomcat4/conf/server.xml</filename>
+ and deleting or commenting out the <quote>acces log valve</quote>:
+ <informalexample>
+ <programlisting>
+<!--
+<Valve className="org.apache.catalina.valves.AccessLogValve"
+ directory="logs" prefix="localhost_access_log." suffix=".txt"
+ pattern="common" />
+
+ -->
+ </programlisting>
+ </informalexample>
+ </para>
+ </section>
+ </chapter>
+</book>
+
+
+
+
+
+
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\r<html>\r<head>\r <title></title>\r</head>\r<body>\r<h1>mir developer mission statement </h1>\r<br>\rbuild creative free software that allows people to share and access content\rin an accesible way that promotes participation and is insensitive to repression,\rfocussing to the needs of progressive grassroots organization.<br>\r<br>\r<h2>mir key features:</h2>\r<ul>\r <li>cms(content management system) implemented in the java programming\rlanguage with an emphasis on design and structure.</li>\r <li>simplicity of mirroring content.</li>\r <li>production system of the cms is independent of publication system\rlocation and type</li>\r <li>support for multiple languages, media types and publication means</li>\r <li>implements a wide range of content submission, approval and publication\rmodels without the need to alter the underlying code, from complete open\rposting to total editorial control</li>\r</ul>\r</body>\r</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+ <head>
+ <title>Mir mission statement</title>
+ </head>
+
+ <body>
+ <h1>mir developer mission statement </h1>
+
+ <p>
+ build creative free software that allows people to
+ share and access content in an accesible way that
+ promotes participation and is insensitive to
+ repression, focussing to the needs of progressive
+ grassroots organization.
+ </p>
+
+ <h2>mir key features:</h2>
+ <ul>
+ <li>cms(content management system) implemented in the
+ java programming language with an emphasis on design
+ and structure.</li>
+
+ <li>simplicity of mirroring content.</li>
+
+ <li>production system of the cms is independent
+ of publication system location and type</li>
+
+ <li>support for multiple languages, media types and
+ publication means</li>
+
+ <li>implements a wide range of content submission,
+ approval and publication models without the need to
+ alter the underlying code, from complete open posting
+ to total editorial control</li>
+ </ul>
+ </body>
+</html>
\ No newline at end of file
--- /dev/null
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'>
+ <xsl:import href="docbook-xsl-1.70.1/html/docbook.xsl"/>
+ <xsl:param name="html.stylesheet">mirdoc.css</xsl:param>
+ <xsl:param name="navig.showtitles">1</xsl:param>
+ <xsl:param name="section.autolabel" select="1"/>
+ <xsl:param name="section.label.includes.component.label" select="1"/>
+</xsl:stylesheet>
# by Matthias <mjordan@code-fu.de> 2001-09-12
# reorganized by <init@nadir.org> 2003-02-12
#
+# The options shown here are the more frequently used options. A full
+# list of all default options is available in the
+# source/default.properties file. If you need to change any of those,
+# just override the values in *this* file (don't change the
+# source/default.properties file
+#
# The Mir software realizes a semi-dynamic web service:
# The web server that is accessed by readers has pure static
# pages. These pages are generated by the Mir software that
# http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html
Mir.DefaultDateTimeFormat = yyyy-MM-dd HH:mm
-# where to put the lucene index
-# for the build in searchengine
-# (must be creatable and writable by the tomcat user)
-IndexPath=index
-
-# temp-dir used for media-uploads
-TempDir=/tmp
-
-# Logging
-#
-Log.LogClass = mir.log.log4j.LoggerImpl
-Log.log4j.ConfigurationFile = etc/log4j.properties
-Log.Home = log
-
-# Mir.Localizer
-# for your additional site-specific java-code
-#
-Mir.Localizer=mircoders.localizer.basic.MirBasicLocalizer
-
-# The location of the producer specifiations
-#
-Mir.Localizer.ProducerConfigFile=etc/producer/producers.xml
-
# For missing values, the FallbackLanguage is used as default
#
Mir.Admin.FallbackLanguage=en
-# the templates
+# warning: advanced feature. Don't change unless you know
+# Localizers provide a customization framework that allows different
+# mir sites to behave differently. Each site can write it's own bits
+# of java code that override default behavior. The localizer
+# framework provides "hooks" where admins can plug in their custom
+# code.
#
-Mir.Localizer.Producer.GeneratorLibrary= default=freemarker(etc/producer/)
-Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/)
-Mir.Localizer.OpenPosting.GeneratorLibrary= default=freemarker(etc/open/)
+# example setup:
+# Mir.Localizer=org.indymedia.de.DeLocalizer
#################################
#
Mir.Admin.ShowLoggedinUsers=1
-# How should the custom operations (hide etc) in article and comment lists
-# be presented?
-# 0 = links, 1 = checkboxes, 2 = a listbox
-#
-Mir.Localizer.Admin.ListOperationsFlavor=1
-
-# How should the topics be presented on the article edit page?
-# 0 = in a multiselect list box, 1 = checkboxes
-#
-Mir.Localizer.Admin.TopicListFlavor=1
-
-# For the checkboxes flavour, how many columns should there be?
-#
-Mir.Localizer.Admin.TopicListColumns=3
-
-# In which order should the topic appear?
-#
-Mir.Localizer.Admin.TopicListOrder=title
-
# enable deletion of comments/articles?
#
Mir.Localizer.Admin.AllowDeleteComment=1
Mir.Localizer.Admin.AllowDeleteArticle=1
-# Article Preview Link URL (Link to produced articles from within admin)
-#
-Article.PublicUrl=http://mir.code-foo.org/en/${to_content.date.formatted.yyyy}/${to_content.date.formatted.MM}/${to_content.id}.shtml
-Comment.PublicUrl=http://mir.code-foo.org/en/${date.formatted.yyyy}/${date.formatted.MM}/${id}.shtml
-
-
#######################
# automated producers #
#######################
ServletModule.FileEdit.Configuration= \
includes:/var/www/project/site/includes:.*\\.inc:1
-
-
-
################################################
########### B) STATIC SITE CONFIG #############
################################################
#
ServletModule.OpenIndy.DefaultMediaUploadItems=1
+# path to ImageMagick executables. Default is "" (nothing), which
+# means executables will be searched using the default system PATH
+# example:Producer.Image.ImageMagickPath=/usr/local/ImageMagick/bin
+#
+Producer.Image.ImageMagickPath=
+
######################
# PDF configurations #
# specify your database
#
-Database.Name=Mir
-Database.Username=postgres
-Database.Password=
+Database.Name=mir
+Database.Username=mir
+Database.Password=indymedia
Database.Host=localhost
Database.Port=5432
log4j.appender.GlobalA.layout.ConversionPattern=%d [%p] %c %x %m%n
log4j.appender.UtilityA=org.apache.log4j.RollingFileAppender
-log4j.appender.UtilityA.File=${log.home}/global.log
+log4j.appender.UtilityA.File=${log.home}/utility.log
log4j.appender.UtilityA.layout=org.apache.log4j.PatternLayout
log4j.appender.UtilityA.layout.ConversionPattern=%d [%p] %c %x %m%n
+++ /dev/null
-StoreContainer.EntityDefaultSize 45
-StoreContainer.EntityListDefaultSize 15
-StorableObjectEntity.Entity.DefaultSize 300
-StorableObjectEntity.EntityList.DefaultSize 100
-EntityTopics.Entity.DefaultSize 200
-EntityTopics.EntityList.DefaultSize 20
+++ /dev/null
-<html>
-<head>
- <title>${lang("comment.htmltitle")}</title>
- <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
-</head>
-<body bgcolor="white" text="black" link="#006600" vlink="#009900" alink="red">
-
-<form action="${config["Producer.OpenAction"]}" method=post>
-<input type="hidden" name="do" value="inscomment">
-
-<table width="100%" border="0" cellspacing="0" cellpadding="4" bgcolor="silver">
- <tr>
- <td bgcolor="#663399" colspan="3">
- <font color="White"><b>${lang("comment.header")}</b></font>
- </td>
- </tr>
- <tr>
- <td bgcolor="#003300" colspan="3">
- <p>
- <font color="white"">
- ${lang("comment.note")}
-<if data.passwd>
- <br>
- ${data.passwd}
-</if>
- </font>
- </p>
-
- </td>
- </tr>
- <tr>
- <td bgcolor="#663399" colspan="3">
- <font face="Helvetica, Arial" color="white" size=+2><b>${lang("comment.formtitle")}</b></font>
- </td>
- </tr>
-<if data.passwd>
- <tr>
- <td><td>${lang("comment.password")}:</td>
- <td><input type="text" name="passwd" size="10"></td>
- </tr>
-</if>
- <tr>
- <td>
- <b>${lang("comment.title")}:</b>
- </td>
- <td colspan="2">
- <input type="text" name="title" size="45" maxlength="45"> <font size="-1" color="#663399">(${lang("required")})</font>
- </td>
- </tr>
- <tr>
- <td>
- <b>${lang("comment.name")}:</b>
- </td>
- <td colspan="2">
- <input type="text" name="creator" size="20" maxlength="45"> <font size="-1" color="#663399">(${lang("required")})</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("comment.email")}:
- </td>
- <td colspan="2">
- <input type="text" name="email" size="30" maxlength="80"> <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("comment.url")}:
- </td>
- <td colspan="2">
- <input type="text" name="main_url" size="40" maxlength="160" value="http://"> <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("comment.phone")}:
- </td>
- <td colspan="2">
- <input type="text" name="phone" size="30" maxlength="80"> <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("comment.address")}:
- </td>
- <td colspan="2">
- <input type="text" name="address" size="40" maxlength="160"><font size="-1"> <i>(${lang("optional")})</i></font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("comment.language")}:
- </td>
- <td colspan="2">
- <select name="to_language">
- <list extra.languagePopUpData as l>
- <option value="${l.key}">${l.value}</option>
- </list>
- </select>
- <font size="-1"><i>(${lang("optional")})</i></font>
- </td>
- </tr>
- <tr>
- <td valign="top">
- <b>${lang("comment.text")}:</b>
- </td>
- <td bgcolor="#003300" colspan="2">
- <textarea name="description" rows="20" cols="60" wrap=virtual></textarea>
- <br><br>
- </td>
- </tr>
- <tr>
- <td>
- </td>
- <td bgcolor="#663399" valign="top" align="center">
- <br>
- <input type="submit" value="${lang("comment.submit")}"><br>
-
- </td>
- <td bgcolor="#003300" valign="top" align="center">
- <br>
- <input type="reset" value="${lang("comment.reset")}"><br>
- <input type="hidden" name="to_media" value="${data.aid}">
- <br>
- </td>
- </tr>
-</table>
-
-</form>
-
-</body>
-</html>
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
- <title>${lang("commentdone.htmltitle")}</title>
-</head>
-
-<body bgcolor="White" text="Black" link="#006600" vlink="#009900" alink="Red">
-
-<table width="100%" border="0" cellspacing="0" cellpadding="10">
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <font color="White"><b>${lang("commentdone.thanks")}</b></font
- </td>
- </tr>
- <tr>
- <td bgcolor="#cccccc" align="center">
-
- <br>
- ${lang("commentdone.wait")}
- <br>
- ${lang("commentdone.criteria")}
- <br>
- <em>${lang("commentdone.stay_calm")}</em><br>
- <br>
-
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> ${lang("commentdone.back")}</b></font></a>
- </td>
- </tr>
-</table>
-
-</body>
-</html>
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
- <title>${lang("commentdupe.htmltitle")}</title>
-</head>
-
-<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
-
-<table width="100%" border="0" cellspacing="0" cellpadding="10">
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <font color="White"><b>
- ${lang("commentdupe.title")}
- </b></font
- </td>
- </tr>
- <tr>
- <td bgcolor="003300" width=70%>
- <font color="White">
- <br>
- ${lang("commentdupe.explanation")}
- <br>
- <center><em>${lang("commentdupe.no_panic")}</em></center><br>
- <br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> ${lang("commentdupe.back")}</b></font></a>
- </td>
- </tr>
-</table>
-
-</body>
-</html>
</if>
<form enctype="multipart/form-data" action="${actionURL}&do=opensession&sessiontype=comment" method="post">
-<input type="hidden" name="to_media" value="${to_media}">
+<input type="hidden" name="to_media" value="${utility.encodeHTML(to_media)}">
<h2>
${lang("posting.step01")}
<tr>
<td>
<p>
- <p align="center"><font color="red">${errorstring}</font>
+ <p align="center"><font color="red">${utility.encodeHTML(data.errorstring)}</font>
<p>
</td>
</tr>
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//DE">
-<html>
-<head>
- <title>${lang("posting.htmltitle")}</title>
- <meta name="description" content="${lang("posting.meta.description")}">
- <meta name="author" content="${lang("posting.meta.author")}">
- <meta name="keywords" content="${lang("posting.meta.keywords")}">
- <!--<meta name="date" content="### Date ###Time">-->
- <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
- <meta name="robots" content="index">
- <meta name="robots" content="follow">
-
- <link rel=stylesheet type="text/css" href="${config["Producer.ProductionHost"]}/style/formate.css">
-</head>
-
-<body bgcolor="White" text="Black" link="#006600" vlink="#006600" alink="Red">
-
-
-<table width="99%" border="0" cellspacing="0" cellpadding="8" bgcolor="silver">
- <tr>
- <td align="left" bgcolor="#663399" colspan="3">
- <a href="#form"><font face="Verdana, Arial, Helvetica, sans-serif" size="-2" color="white"><b>>> ${lang("posting.jump_to_form")}</b></font></a>
- <br>
- </td>
- </tr>
- <tr>
- <td align="center" colspan="3">
- <font size="+1" face="Verdana, Arial, Helvetica, sans-serif"><b>${lang("posting.title")}</b></font><br>
- </td>
- </tr>
- <tr>
- <td colspan="3" bgcolor="white">
-
-<include "open/disclaimer.inc.de">
-<if data.passwd>
-
-<br>${data.passwd}
-</if>
-<br><br>
-<a name="form"></a>
- </td>
- </tr>
-<form action="${config["Producer.OpenAction"]}?do=addposting" method="post">
- <tr>
- <td><b>${lang("posting.nr_of_media")}</b> <br>
- ${lang("posting.nr_of_media.info")}</td>
- <td colspan="2"><input type="text" name="medianum" value="${data.medianum}"> <input type="submit" value="${lang("posting.nr_of_media.submit")}">
- </tr>
-</form>
-
-
-<form enctype="multipart/form-data" action="${config["Producer.OpenAction"]}?do=insposting" method="post">
- <tr>
- <td bgcolor="#663399" colspan="3">
- <center><font size="+2" face="Helvetica, Arial,sans-serif" color="white"><b>${lang("posting.form.title")}</b></font></center>
- </td>
- </tr>
-<if data.passwd>
- <tr>
- <td>${lang("posting.password")}</td>
- <td><input type="text" name="passwd" size="10"></td>
- </tr>
-</if>
- <tr>
- <td valign="top">
- ${lang("posting.title")}:<br>
- <font size="-2">${lang("posting.title.info")}</font>
- </td>
- <td colspan="2" bgcolor="#003300">
- <input type="text" name="title" size="45" maxlength="45" value=""> <font size="-1" color="white"><br>(${lang("required")})</font>
- </td>
- </tr>
- <tr>
- <td valign="top">
- ${lang("posting.topic")}:<br>
- <font size="-2">${lang("posting.topic.info")}</font>
- </td>
- <td colspan="2">
- <select name="to_topic" size="3" multiple>
- <list extra.themenPopupData as t>
- <option value="${t.key}" <list data.to_topic as to><if (t.key == to)>selected</if></list>>${t.value}</option>
- </list>
- </select>
- <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td valign="top">
- ${lang("posting.author")}:
- </td>
- <td colspan="2" bgcolor="#003300">
- <input type="text" name="creator" size="45" maxlength="45"> <font size="-1" color="white"><br>${lang("required")}</font>
- </td>
- </tr>
- <tr>
- <td valign="top">
- ${lang("posting.abstract")}:</b> <br>
- <font size="-2">${lang("posting.abstract.info")}</font>
- </td>
- <td colspan="2" bgcolor="#003300">
- <textarea name="description" rows="6" cols="55" wrap=virtual></textarea>
- <font size="-1" color="white"><br>${lang("posting.abstract.constraint")}</font>
- </td>
- </tr>
- <tr>
- <td colspan="3" bgcolor="#FFFFFF">
- <font face="Helvetica, Arial, sans-serif" size=-1 color="#222222">
- ${lang("posting.contact.info")}
- </font>
- </td>
- </tr>
-
- <tr>
- <td>
- ${lang("posting.email")}:
- </td>
- <td colspan="2">
- <input type="text" name="creator_email" size="55" maxlength="80" value=""><br>
- <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("posting.url")}:
- </td>
- <td colspan="2">
- <input type="text" name="creator_main_url" size="55" maxlength="160" value="http://"><br>
- <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("posting.address")}:
- </td>
- <td colspan="2">
- <input type="text" name="creator_address" size="55" maxlength="160" value=""><br>
- <font size="-1"> <i>(${lang("optional")})</i></font>
- </td>
- </tr>
- <tr>
- <td>
- ${lang("posting.phone")}:
- </td>
- <td colspan="2">
- <input type="text" name="creator_phone" size="20" maxlength="20" value=""><br>
- <font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
-
- <tr>
- <td colspan="3" bgcolor="#FFFFFF"> </td>
- </tr>
-
- <tr>
- <td>
- ${lang("posting.language")}:
- </td>
- <td colspan="2">
- <select name="to_language">
- <list extra.languagePopUpData as l>
- <option value="${l.key}">${l.value}</option>
- </list>
- </select>
- <font size="-1"><i>(${lang("optional")})</i></font>
- </td>
- </tr>
- <tr>
- <td valign="top">
- ${lang("posting.text")}:<br>
- <font size="-2">${lang("posting.text.info")}</font>
- </td>
- <td bgcolor="#003300" colspan="2">
- <textarea name="content_data" rows="20" cols="55" wrap="soft"></textarea>
- <br><br>
- </td>
- </tr>
-
- <tr>
- <td>
- <b>${lang("posting.media")}:</b>
- </td>
- <td colspan="2">
- ${lang("posting.media.info")}<br>
- <font size="-2">${lang("posting.media.howto")}</font>
- </td>
- </tr>
-<list data.mediafields as m>
- <tr>
- <td>
- ${lang("posting.media.title")} ${m}:
- </td>
- <td colspan="2">
- <input type="text" name="media_title${m}" size="40" maxlength="80" value=""><br>
- </td>
- </tr>
- <tr>
- <td>${lang("posting.media.media")} ${m}</td>
- <td colspan="2">
- <INPUT TYPE="file" NAME="media${m}">
- <br><font size="-1">(<i>${lang("optional")}</i>)</font>
- </td>
- </tr>
-</list>
-
- <tr>
- <td colspan="3" bgcolor="#FFFFFF"> </td>
- </tr>
-
- <tr>
- <td align="left" valign="center">
-
- <!-- text -->
- ${lang("posting.submit.info")}
-
- <br>
- ${lang("posting.criteria")}<br>
-
- </td>
- <td bgcolor="#663399" valign="center" align="center">
- <input type="submit" value="${lang("posting.submit")}">
-
- </td>
- <td bgcolor="#003300" valign="center" align="center">
- <input type="reset" value="${lang("posting.reset")}">
- </td>
- </tr>
-</form>
-
-</table>
-
-
-
-</body>
-</html>
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
- <title>${lang("postingdone.htmltitle")}</title>
-</head>
-
-<body bgcolor="White" text="Black" link="#006600" vlink="#666666" alink="Red">
-
-<table width="100%" border="0" cellspacing="0" cellpadding="4" bgcolor="#cccccc">
- <tr>
- <td align="center" bgcolor="#666666">
- <font color="White">${lang("postingdone.title")}</font></td>
- </tr>
- <tr>
- <td bgcolor="#eeeeee"><font color="#000000">
-
-
-<br>
-${lang("postingdone.info")}
-<br><br>
-<center><EM>${lang("postingdone.stay_calm")}</EM></center><br><br>
-
- </font>
- </td>
-</tr>
-
-<tr>
- <td valign="top" align="center" bgcolor="#666666">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> ${lang("postingdone.back")}</b></font></a>
- </td>
- </tr>
-</table>
-</body>
-</html>
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
- <title>${lang("postingdupe.htmltitle")}</title>
-</head>
-
-<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
-
-<table width="100%" border="0" cellspacing="0" cellpadding="10">
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <font color="White"><b>
- ${lang("postingdupe.title")}
- </b></font
- </td>
- </tr>
- <tr>
- <td bgcolor="003300" width=70%>
- <font color="White">
- <br>
- ${lang("postingdupe.explanation")}
- <br>
- <center><em>${lang("postingdupe.no_panic")}</em></center><br>
- <br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#663399">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> ${lang("postingdupe.back")}</b></font></a>
- </td>
- </tr>
-</table>
-
-</body>
-</html>
<tr>
<td>
<p>
- <p align="center"><font size="5" color="Red"><b> ${data.errorstring}</b></font>
+ <p align="center"><font size="5" color="Red"><b> ${utility.encodeHTML(data.errorstring)}</b></font>
<p>
<p>
</td>
xmlns="http://purl.org/rss/1.0/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
- xmlns:content="http://purl.org/rss/1.0/modules/content/"\r
+ xmlns:content="http://purl.org/rss/1.0/modules/content/"
>
<channel rdf:about="${utility.encodeHTML(channelidentifier)}">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
- <title>${config["Mir.Name"]} | ${article.title}</title>
+ <title>${config["Mir.Name"]} | ${utility.encodeHTML(article.title)}</title>
<meta name="keywords" content="indymedia,imc">
<meta name="description" content="indymedia,imc">
<meta http-equiv="expires" content="599">
<table cellpadding="30" cellspacing="0" border="0" width="80%"><tr><td>
<table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td bgcolor="#669999">
<!--#include virtual="/languagebar/${article.to_original.date.formatted.yyyy}/${article.to_original.date.formatted.MM}/${article.to_original.id}.shtml"-->
- </td></tr></table>
+ </td></tr></table>
<br>
<table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td bgcolor="#669999">
<a href="${config.openAction}?do=opensession&sessiontype=translation&to_content=${article.to_original.id}"><font color="#dddddd">${lang("general.addtranslation")} >></font></a>
</td></tr></table>
<br>
- <h2>${article.title}</h2>
+ <h2>${utility.encodeHTML(article.title)}</h2>
- <p><i><font size="-1">${article.to_original.creator} <if article.to_original.id!=article.id>(${lang("general.translatedby", article.creator)})</if><if article.creator || article.to_original.creator>, </if>${article.to_original.creationdate.formatted["dd.MM.yyyy HH:mm"]}</font></i></p>
+ <p><i><font size="-1">${utility.encodeHTML(article.to_original.creator)} <if article.to_original.id!=article.id>(${lang("general.translatedby", utility.encodrHTML(article.creator))})</if><if article.creator || article.to_original.creator>, </if>${article.to_original.creationdate.formatted["dd.MM.yyyy HH:mm"]}</font></i></p>
<br>
<p>${article.description_parsed}</p>
<!-- media -->
<list article.to_original.to_media_audio as media>
<p>
- <img src="../../../img/${media["big_icon"]}" border="0" alt="">
- <a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}
+ <img src="../../../img/${media.big_icon}" border="0" alt="">
+ <a href="${media.publish_server}${media.publish_path}">
+ ${media.title} - ${media.info.description} ${media.human_readable_size}
</a>
</p>
</list>
<list article.to_original.to_media_video as media>
<p>
<img src="../../../img/${media["big_icon"]}" border="0" alt="">
- <a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+ <a href="${media.publish_server}${media.publish_path}">
+ ${media.title} - ${media.info.description} ${media.human_readable_size}</a>
</p>
</list>
<list article.to_original.to_media_other as media>
<p>
- <img src="../../../img/${media["big_icon"]}" border="0" alt="">
- <a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+ <img src="../../../img/${media.big_icon}" border="0" alt="">
+ <a href="${media["publish_server"]}${media.publish_path}">
+ ${media.title} - ${media.info.description} ${media.human_readable_size}</a>
</p>
</list>
<list article.to_original.to_media_images as image>
<p>
<img src="${image["publish_server"]}${image["publish_path"]}"
- border="0" width="${image["img_width"]}"
- height="${image["img_height"]}" alt="${image["title"]}">
- <br><i>${image["title"]}</i>
+ border="0" width="${image.img_width}"
+ height="${image.img_height}" alt="${image.title}">
+ <br><i>${image.title}</i>
</p>
</list>
</if>
<p>
<font size="-1">
<if article.creator_email>
- <img src="../../../img/mail_small.gif" width="12" height="10" border="0" alt="-"> ${lang("article.email.prefix")}: <a href="mailto:${article.creator_email}">${article.creator_email}</a><br>
+ <img src="../../../img/mail_small.gif" width="12" height="10" border="0" alt="-"> ${lang("article.email.prefix")}: <a href="mailto:${utility.encodeHTML(article.creator_email)}">${utility.encodeHTML(article.creator_email)}</a><br>
</if>
<if article.creator_main_url>
- <img src="../../../img/link_small.gif" width="12" height="10" border="0" alt=""> ${lang("article.homepage.prefix")}: <a href="${article.creator_main_url}" target="extern">${article.creator_main_url}</a><br>
+ <img src="../../../img/link_small.gif" width="12" height="10" border="0" alt=""> ${lang("article.homepage.prefix")}: <a href="${utility.encodeHTML(article.creator_main_url)}" target="extern">${utility.encodeHTML(article.creator_main_url)}</a><br>
</if>
</font>
</p>
<list c.to_media_audio as media>
<a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}
+ ${utility.encodeHTML(media["title"])} - ${media["media_descr"]} ${media["human_readable_size"]}
</a>
</list>
<list c.to_media_video as media>
<img src="../../../img/${media["big_icon"]}" border="0" alt="">
<a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+ ${utility.encodeHTML(media["title"])} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
</list>
<list c.to_media_other as media>
<img src="../../../img/${media["big_icon"]}" border="0" alt="">
<a href="${media["publish_server"]}${media["publish_path"]}">
- ${media["title"]} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
+ ${utility.encodeHTML(media["title"])} - ${media["media_descr"]} ${media["human_readable_size"]}</a>
</list>
<list c.to_media_images as image>
<img src="${image["publish_server"]}${image["publish_path"]}"
border="0" width="${image["img_width"]}"
- height="${image["img_height"]}" alt="${image["title"]}">
- <br><i>${image["title"]}</i>
+ height="${image["img_height"]}" alt="${utility.encodeHTML(image["title"])}">
+ <br><i>${utility.encodeHTML(image["title"])}</i>
</list>
<input type="hidden" name="language" value="${language.code}">
<input type="text" name="search_content" size="10" id="searchfield"><br>
- <input type="checkbox" name="search_hasImages"> ${lang("navigation.search.images")} <br>
- <input type="checkbox" name="search_hasAudio"> ${lang("navigation.search.audio")} <br>
- <input type="checkbox" name="search_hasVideo"> ${lang("navigation.search.video")} <br>
+ <input type="checkbox" name="search_hasImages" value="y"> ${lang("navigation.search.images")} <br>
+ <input type="checkbox" name="search_hasAudio" value="y"> ${lang("navigation.search.audio")} <br>
+ <input type="checkbox" name="search_hasVideo" value="y"> ${lang("navigation.search.video")} <br>
<input type="submit" value="${lang("navigation.search.button")}" name="search_submit" size="16">
</td></tr></table>
- a feature archive
- articles
- media
+
+ please check the mir user's guide and developer's guide
+ for documentation on the syntax of this file
-->
<producers>
+ <!-- This first section contains nodedefinitions. -->
+ <!-- A nodedefinition is a sort of "function" that can be "called" later -->
+ <!-- in a producer. -->
+
+ <!-- The Language node enumerates over all the available languages -->
+ <!-- and calls the subnode for each language. This way the subnode -->
+ <!-- is succesivelly called with its pathprefix set to "en", "de", -->
+ <!-- "fr", etc. -->
<nodedefinition name="Language">
<parameters>
+ <!-- by default, use all valid languages -->
+ <!-- 'ot' = "Other": used for translations. -->
<string name="languagecondition" defaultvalue="code != 'ot'"/>
+ <!-- prefix of bundles that contain language translations -->
+ <!-- this will be: etc/bundles/producer_xx.properties -->
<string name="bundle" defaultvalue="bundles.producer" />
+ <!-- "sub": reference to subnode of the calling node -->
<node name="sub"/>
</parameters>
<definition>
<List key="languages" table="language" selection="${languagecondition}" order="code"/>
<Enumerate key="language" table="language" selection="${languagecondition}" order="code">
+ <!-- The Resource node defines a function that can be used -->
+ <!-- in expressions. The name of the function is given by the -->
+ <!-- "key" parameter. So in this case, it's lang. One -->
+ <!-- can henceforth use expressions like ${lang("page.title")} to -->
+ <!-- refer to a bundle value. -->
<Resource bundle="${bundle}" key="lang" language="${language.code}"/>
<Define key="pathprefix" value="${language.code}" />
<Define key="languagepreference" value="${language.code}" />
+ <!-- This <sub/> tag is replaced by the node arguments of this -->
+ <!-- "function". In other words, if this function (nodedef) was -->
+ <!-- called this way: <Language> <Generate ... > </Language> then -->
+ <!-- the <sub/> tag is replaced by the <Generate ... > node. -->
<sub/>
+ <!-- This condition is meant for sites where the startpage for, -->
+ <!-- say, english prefer english translations over non-english -->
+ <!-- originals. For those sites, an "original" startpage is also -->
+ <!-- generated, which always has articles in their original -->
+ <!-- language. A concrete example: -->
+ <!-- -->
+ <!-- * say the site has languages english and german. -->
+ <!-- * say article 1 was written in german -->
+ <!-- * say article 2 was written in english, with a german -->
+ <!-- translation -->
+ <!-- -->
+ <!-- Then the english startpage might have article 1 in german -->
+ <!-- and article 2 in english -->
+ <!-- -->
+ <!-- The german startpage might have article 1 in german and -->
+ <!-- the german translation of article 2 -->
+ <!-- -->
+ <!-- The Original startpage might have article 1 in german -->
+ <!-- and article 2 in english -->
<If condition="language.code=='en'">
<then>
<Define key="pathprefix" value="or" />
<definition>
<!-- newswire -->
<RSSChannel
- articleSelection="(c.to_article_type in (${articletype.newswire})) and ${selection}"
+ articleSelection="(c.to_article_type in (${articletype.newswire}) or (c.to_article_type=${articletype.translation} and c.to_original.to_articletype in (${articletype.newswire}))) and ${selection}"
channelfilename="${basefilename}-newswire.rss"
channeltitle="${config['Mir.Name']} ${basefilename} newswire"
limit="20"
extratables="${extratables}"
/>
<RSSChannel
- articleSelection="(c.to_article_type in (${articletype.newswire})) and ${selection}"
+ articleSelection="(c.to_article_type in (${articletype.newswire}) or (c.to_article_type=${articletype.translation} and c.to_original.to_articletype in (${articletype.newsire}))) and ${selection}"
channelfilename="${basefilename}-newswire-content.rss"
channeltitle="${config['Mir.Name']} ${basefilename} newswire"
limit="20"
/>
<!-- features -->
<RSSChannel
- articleSelection="(c.to_article_type in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial})) and ${selection}"
+ articleSelection="(c.to_article_type in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial}) or (c.to_article_type=${articletype.translation} and c.to_original.to_articletype in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial}))) and ${selection}"
channelfilename="${basefilename}-features.rss"
channeltitle="${config['Mir.Name']} ${basefilename} features"
limit="20"
extratables="${extratables}"
/>
<RSSChannel
- articleSelection="(c.to_article_type in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial})) and ${selection}"
+ articleSelection="(c.to_article_type in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial}) or (c.to_article_type=${articletype.translation} and c.to_original.to_articletype in (${articletype.feature},${articletype.startspecial},${articletype.topicspecial}))) and ${selection}"
channelfilename="${basefilename}-features-content.rss"
channeltitle="${config['Mir.Name']} ${basefilename} features"
limit="20"
</nodedefinition>
+ <!-- This second section contains actual producers that will appear -->
+ <!-- on the admin->"Generate manually"->"advanced page". -->
+
+ <!-- This producer generates html pages, as well as media and video -->
+ <!-- files for articles stored in the database. -->
+
+ <!-- It's a good example of the use of the "verb" concept. The
+ "articles" producer (the producer responsible for generating
+ article pages), can be called in 3 modes:
+
+ * changed, to regenerate articles with changes (new ones,
+ recently edited ones, or ones with added/removed/changed
+ comments/media). Note that in this case it will regenerate at
+ most 10 changes articles.
+
+ * all, to regenerate all articles
+
+ * sample to regenerate the 10 latest articles -->
<producer name="articles">
+ <!-- verbs define the different actions that may be done by -->
+ <!-- this producer -->
<verbs>
+ <!-- only generate articles that have changed (including new article) -->
<verb name="changed" default="1">
<Define key="verbcondition" value="(not is_produced)"/>
<Set key="limit" value="10"/>
</verb>
+ <!-- generate all articles in the db (under certain condiftions...) -->
<verb name="all">
<Define key="verbcondition" value=""/>
<Set key="limit" value="-1"/>
</verb>
+ <!-- only generate the last 10 articles in the db -->
<verb name="sample">
<Define key="verbcondition" value=""/>
<Set key="limit" value="10"/>
</verb>
</verbs>
<body>
+ <!-- loop on all articles requested by the "verb" -->
<Enumerate key="article" table="content" selection="${verbcondition}"
limit="limit" order="webdb_create desc">
+ <!-- For each article, generate it's corresponding image files -->
+ <!-- The following sql statements select images that are -->
+ <!-- associated with the article (either directly or -->
+ <!-- through comments). -->
<Enumerate
key="media" table="image"
selection="exists (select * from content_x_media where media_id=images.id and content_id=${article.id})
or exists (select * from comment_x_media, comment
where comment_id = comment.id and media_id=images.id and comment.to_media=${article.id})"
order="id desc">
-
+ <!-- The generateMedia node instructs the media handler
+ associated with the media to "reproduce" the media. In
+ practice this can mean generate an icon from an image,
+ writing an image from the database to the web root, or
+ create an m3u file or so. Media handling is limited at
+ this moment, but a serious redesign is planned -->
<GenerateMedia key="media" />
</Enumerate>
+ <!-- for each article, generate it's corresponding video files -->
<Enumerate
key="media" table="video"
selection="exists (select * from content_x_media where media_id=video.id and content_id=${article.id})
order="id desc">
<GenerateMedia key="media" />
</Enumerate>
+ <!-- for each article, generate it's corresponding audio files -->
<Enumerate
key="media" table="audio"
selection="exists (select * from content_x_media where media_id=audio.id and content_id=${article.id})
<GenerateMedia key="media" />
</Enumerate>
+ <!-- for each article, generate it's corresponding other media files
+ (like pdf's) -->
<Enumerate
key="media" table="otherMedia"
selection="exists (select * from content_x_media where media_id=other_media.id and content_id=${article.id})
</Enumerate>
<If condition="article.is_published == '1'">
+ <!-- only generate published articles -->
<then>
+ <!-- loop on all available languages -->
<Language>
+ <!-- actually generate the article -->
<Generate
generator="/article.template"
destination="${config.storageRoot}/${pathprefix}/${article.date.formatted.yyyy}/${article.date.formatted.MM}/${article.id}.shtml"/>
- </Language>
- <Generate
- generator="/languagebar.template"
- destination="${config.storageRoot}/languagebar/${article.to_original.date.formatted.yyyy}/${article.to_original.date.formatted.MM}/${article.to_original.id}.shtml"/>
+ </Language>
+ <!-- generate the article's languagebar -->
+ <Generate
+ generator="/languagebar.template"
+ destination="${config.storageRoot}/languagebar/${article.to_original.date.formatted.yyyy}/${article.to_original.date.formatted.MM}/${article.to_original.id}.shtml"/>
+ <!-- add article to the "search engine" index (lucene) -->
<IndexContent key="article" pathToIndex="${config['IndexPath']}"/>
</then>
+ <!-- if article is not published, remove it from the search index -->
<else>
<UnIndexContent key="article" pathToIndex="${config['IndexPath']}"/>
</else>
</If>
+ <!-- mark (tag) the article as produced -->
<MarkContent key="article"/>
</Enumerate>
</body>
</producer>
+ <!-- generates the left column -->
<producer name="navigation">
<verbs>
<verb name="generate" default="1" description="generates the left column"/>
</body>
</producer>
+ <!-- generates the main html page (startpage) of an indymedia site -->
<producer name="startpage">
<verbs>
<verb name="generate" default="1" description="Generates the startpage"/>
</body>
</producer>
+ <!-- Use rsync to copy static site to mirrors (only if requested -->
+ <!-- in config file) -->
<producer name="synchronization">
<verbs>
<verb name="run" default="1" description="Synchronizes the publication site with the production site"/>
</verbs>
<body>
+ <ReportChanges format="${config.now.formatted['HH:mm:ss']} ${change.type} ${config['Producer.ProductionHost']}${change.path}"
+ file="${config['Producer.StorageRoot']}/changes/changes${config.now.formatted['yyyyMMdd']}.txt"
+ basepath="${config['Producer.StorageRoot']}" />
+
+
+
+
<If condition="config['Rsync'] in ('1', 'y', 'yes', 'Y')">
<then>
<Execute command="${config['Rsync.Script.Path']}"/>
</producer>
+ <producer name="radicalendar">
+ <verbs>
+ <verb name="pull" />
+ </verbs>
+ <body>
+ <!-- groupname you will see as the value of "group" in the url for your radicalendar page, -->
+ <!-- gmtoffset is in minutes -->
+ <Radicalendar key="calendar" groupname="_imc" gmtoffset="60" />
+ <Generate
+ generator="/radicalendar.template"
+ destination="${config.storageRoot}/calendarinclude.shtml"/>
+ </body>
+ </producer>
+
</producers>
--- /dev/null
+<ul class="radicalendar">
+ <list calendar as c>
+ <li>${c.eventdate} <a href="http://www.radicalendar.org/group/${c.shortname}/all/display/${c.objectid}/index.php?fulldate=${c.eventdate}">${c.title}</a> ${c.eventtime} <br /> ${c.description}
+ </list>
+</ul>
-<comment>\r
- This file contains several routines to be used in the templates\r
-</comment>\r
-\r
-<function showArticleUrl(aPrefix, anArticle, aText, aCSSClass)>\r
- <a class="${aCSSClass}" href="/${aPrefix}/${anArticle.date.formatted.yyyy}/${anArticle.date.formatted.MM}/${anArticle.id}.shtml">${aText}</a>\r
-</function>\r
-\r
-<function showSafeText(aText)>\r
- ${utility.encodeHTML(aText)}\r
-</function>\r
-\r
-<function showSafeTextOrDefault(aField, aDefault)>\r
- <if aField>\r
- <call showSafeText(aField)>\r
- <else>\r
- ${aDefault}\r
- </if>\r
-</function>\r
+<comment>
+ This file contains several routines to be used in the templates
+</comment>
+
+<function showArticleUrl(aPrefix, anArticle, aText, aCSSClass)>
+ <a class="${aCSSClass}" href="/${aPrefix}/${anArticle.date.formatted.yyyy}/${anArticle.date.formatted.MM}/${anArticle.id}.shtml">${aText}</a>
+</function>
+
+<function showSafeText(aText)>
+ ${utility.encodeHTML(aText)}
+</function>
+
+<function showSafeTextOrDefault(aField, aDefault)>
+ <if aField>
+ <call showSafeText(aField)>
+ <else>
+ ${aDefault}
+ </if>
+</function>
<function showAddCommentLink(anArticle, aText, aLanguage)>
<a href="${config["Producer.OpenAction"]}?do=addcomment&aid=${anArticle.id}&language=${aLanguage.code}">${aText}</a>
</function>
- \r
-<function showArticleMedia(anArticle)>\r
- <!-- media -->\r
- <list anArticle.to_media_audio as audio>\r
- <br>\r
- <br>\r
- <a href="${audio["publish_server"]}${audio["publish_path"]}">\r
- <img src="/images/${video["big_icon"]}" border="0" alt="">\r
- <call showSafeText(audio.title)> - <call showSafeText(audio.descr)>\r
- </a>\r
- </list>\r
-\r
- <list anArticle.to_media_video as video>\r
- <br>\r
- <br>\r
- <a href="${video["publish_server"]}${video["publish_path"]}">\r
- <img src="/images/${video["big_icon"]}" border="0" alt="">\r
- <call showSafeText(video.title)> - <call showSafeText(video.descr)>\r
- </a>\r
- </list>\r
-\r
- <list anArticle.to_media_other as other>\r
- <br>\r
- <br>\r
- <a href="${other["publish_server"]}${other["publish_path"]}">\r
- <img src="/images/${other["big_icon"]}" border="0" alt="">\r
- <call showSafeText(other.title)> - <call showSafeText(other.descr)>\r
- </a>\r
- </list>\r
-\r
- <list anArticle.to_media_images as image>\r
- <br>\r
- <br>\r
- <img src="${image["publish_server"]}${image["publish_path"]}"\r
- border="0" width="${image["img_width"]}"\r
- height="${image["img_height"]}" alt="${image["title"]}"><br>\r
- <i><call showSafeText(image.title)></i>\r
- </list>\r
- <!-- media -->\r
-</function>\r
-\r
-<function showArticleMediaIcons(anArticle)>\r
+
+<function showArticleMedia(anArticle)>
+ <!-- media -->
+ <list anArticle.to_media_audio as audio>
+ <br>
+ <br>
+ <a href="${audio["publish_server"]}${audio["publish_path"]}">
+ <img src="/images/${video["big_icon"]}" border="0" alt="">
+ <call showSafeText(audio.title)> - <call showSafeText(audio.descr)>
+ </a>
+ </list>
+
+ <list anArticle.to_media_video as video>
+ <br>
+ <br>
+ <a href="${video["publish_server"]}${video["publish_path"]}">
+ <img src="/images/${video["big_icon"]}" border="0" alt="">
+ <call showSafeText(video.title)> - <call showSafeText(video.descr)>
+ </a>
+ </list>
+
+ <list anArticle.to_media_other as other>
+ <br>
+ <br>
+ <a href="${other["publish_server"]}${other["publish_path"]}">
+ <img src="/images/${other["big_icon"]}" border="0" alt="">
+ <call showSafeText(other.title)> - <call showSafeText(other.descr)>
+ </a>
+ </list>
+
+ <list anArticle.to_media_images as image>
+ <br>
+ <br>
+ <img src="${image["publish_server"]}${image["publish_path"]}"
+ border="0" width="${image["img_width"]}"
+ height="${image["img_height"]}" alt="${image["title"]}"><br>
+ <i><call showSafeText(image.title)></i>
+ </list>
+ <!-- media -->
+</function>
+
+<function showArticleMediaIcons(anArticle)>
<if anArticle.to_media_audio >
<img src="/img/${anArticle.to_media_audio[0]["big_icon"]}">
</if>
- \r
+
<if anArticle.to_media_video >
<img src="/img/${anArticle.to_media_video[0]["big_icon"]}">
</if>
- \r
+
<if anArticle.to_media_other >
<img src="/img/${anArticle.to_media_other[0]["big_icon"]}">
</if>
- \r
+
<if anArticle.to_media_images >
<img src="${anArticle.to_media_images[0]["icon_path"]}"
width="${anArticle.to_media_images[0]["icon_width"]}"
height="${anArticle.to_media_images[0]["icon_height"]}"
border=0 alt="${anArticle.to_media_images[0]["title"]}">
</if>
-</function>\r
-\r
-<function showArticleAsFeature(anArticle)>\r
+</function>
+
+<function showArticleAsFeature(anArticle)>
<h3><call showSafeText(anArticle.title)></h3>
<h4><i><call showSafeText(anArticle.creator)>, ${anArticle.creationdate.formatted["dd.MM.yyyy HH:mm"]}</i></h4>
<p>
<call showArticleMediaIcons(anArticle)>
- ${anArticle.description_parsed} \r
+ ${anArticle.description_parsed}
</p>
-\r
+
<p align="right">
[<call showArticleUrl(pathprefix, anArticle, lang("general.readarticle"), "featurelink")>]
</p>
-</function>\r
-\r
-\r
-<function showArticleAsNewswire(anArticle)>\r
+</function>
+
+
+<function showArticleAsNewswire(anArticle)>
<img alt=${anArticle.to_media_icon["icon_alt"]} border="0" height="10"
- src="${anArticle.to_media_icon["tiny_icon"]}" width="12"> \r
- \r
+ src="${anArticle.to_media_icon["tiny_icon"]}" width="12">
+
<call showArticleUrl(pathprefix, anArticle, anArticle.title, "")><br />
<font size="-2">${n.creationdate.formatted["dd-MM-yyyy HH:mm"]}</font><br>
-</function>\r
-\r
+</function>
+
- virtually no CSS functions
- all paths relative to /
- no complicated freemarker code
-</comment>
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+</comment><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
<table width="100%" border="0" cellspacing="0" cellpadding="10" bgcolor="#eeeeee"><tr><td>
<p><font size="+2">
- <a href="${config["Producer.DocRoot"]}/${language.code}/${s.date.formatted["yyyy'/'MM"]}/${s.id}.shtml"><b>${s.title}</b></a>
+ <a href="${config["Producer.DocRoot"]}/${language.code}/${s.date.formatted["yyyy'/'MM"]}/${s.id}.shtml"><b>${utility.encodeHTML(s.title)}</b></a>
</font><br>
<font size="-2">${sorig.creator} <if sorig.id!=s.id>(${lang("general.translatedby", s.creator)})</if><if s.creator || sorig.creator>, </if> ${sorig.creationdate.formatted["dd.MM.yyyy - HH:mm"]}</font></p>
<p><font size="-1">
</if>
<p><font size="+1">
- <a href="${config["Producer.DocRoot"]}/${language.code}/${i.date.formatted["yyyy'/'MM"]}/${i.id}.shtml"><b>${i.title}</b></a>
+ <a href="${config["Producer.DocRoot"]}/${language.code}/${i.date.formatted["yyyy'/'MM"]}/${i.id}.shtml"><b>${utility.encodeHTML(i.title)}</b></a>
</font><br>
<font size="-2">${forig.creator} <if forig.id!=i.id>(${lang("general.translatedby", i.creator)})</if><if i.creator || forig.creator>, </if> ${forig.creationdate.formatted["dd.MM.yyyy - HH:mm"]}</font></p>
<p><font size="-1">
<img src="${norig.to_media_icon.tiny_icon}" alt="${norig.to_media_icon.icon_alt}" height="10" width="12">
- <a href="${config["Producer.DocRoot"]}/${language.code}/${n.date.formatted.yyyy}/${n.date.formatted.MM}/${n.id}.shtml">${n.title}</a>
+ <a href="${config["Producer.DocRoot"]}/${language.code}/${n.date.formatted.yyyy}/${n.date.formatted.MM}/${n.id}.shtml">${utility.encodeHTML(n.title)}</a>
<br>
<font size="-2">${n.creationdate.formatted["dd-MM-yyyy HH:mm"]}</font><br>
<br>
enforcements, and several lightweight
convenience implementations of the
generic components.
-todo : update to 4.1.4
+todo : update to 4.2 (not developed anymore)
url : http://xml.apache.org/batik/
description: batik is for images in the Scalable Vector
Graphics (SVG)
-todo : check if necessary / update to version 1.1.1
+todo : check if necessary / update to version 1.5.1
MIR compiles without it. Is it (still)
necessary?
description: Commons-BeanUtils provides
easy-to-use wrappers around the Java
reflection and introspection APIs.
-
+
commons-collections
------------------------------------------------
description: needed for parsing the configuration
properties file and provides more useful collections
like a LRUCache
+todo : update to 3.1
+
+
+commons-dbcp
+-----------------------------------------------
+version : 1.1
+url : http://jakarta.apache.org/commons/
+description: database connection pooling library
+todo : upgrade to 1.2.1
+
+commons-fileupload
+-----------------------------------------------
+version : 1.0
+url : http://jakarta.apache.org/commons/
+description: jakarta version of fileupload
+
+
+commons-httpclient
+-----------------------------------------------
+version : 2.0
+url : http://jakarta.apache.org/commons/
+description: httpclient simulation
+todo : upgrade to 3.0
commons-logging
description: Commons-Logging is a wrapper around
a variety of logging API
implementations.
+todo : upgrade to 1.0.4
commons-net
version : 1.0
url : http://jakarta.apache.org/commons/
description: needed for the mail feature
+todo : upgrade to 1.3.0
+
+
+commons-pool
+------------------------------------------------
+version : 1.1
+url : http://jakarta.apache.org/commons-pool
+description: generic object pooling framework
+todo : upgrade to 1.2
+
fop
version : 1.6.2 (probably)
url : http://fm-classic.sourceforge.net
description: template engine
-todo : update to version 1.7.5
+todo : update to version 1.8.x
template changes involved on update
version : 1.1.4
url : http://www.cacas.org/java/gnu/regexp/
description: GNU regular expression library
-todo : check if to be replaced with jakarta
- commons regexp
+todo : check if to be replaced with jakarta
+ commons regexp 1.3
iText
version : ??
url : http://www.lowagie.com/iText/
description: PDF
-todo : check if necessary
+todo : upgrade to version 1.2.x
jimi
url : http://jakarta.apache.org/log4j/
description: Jakarta Log4J standard library for
the logging layer of MIR.
-
+todo : upgrade to 1.2.9
logkit
------------------------------------------------
version : 1.0
-url : http://apache.serveftp.org/apache-site/dist/avalon/logkit/latest/
+url : http://www.axint.net/apache/avalon/logkit/v1.2/
description: LogKit is an easy to use logging
toolkit.
depends on : avalon
-todo : update to version 1.2 ??
+todo : update to version 1.2
lucene
description: Jakarta Lucene is a high-performance,
full-featured text search engine written
entirely in Java.
-
+todo : upgrade to 1.4.3
multex
------------------------------------------------
version : 3
url : http://www.tfh-berlin.de/~knabe/java/multex
description: nested exceptions
-todo : rename to multex-3.jar
+todo : upgrade to multex 6
postgresql
------------------------------------------------
-version : 7.4 (jdbc2-version)
+version : 7.4 (jdbc2-version) build 215
url : http://jdbc.postgresql.org
description: JDBC driver for postgresql database
+
+tidy
+------------------------------------------------
+version : ??
+url : http://jtidy.sourceforge.net/ (probably)
+description: html cleanup jar
+
+
velocity
------------------------------------------------
version : 1.3.1
url : http://jakarta.apache.org/velocity
description: template engine
+todo : upgrade to 1.4
+
-commons-pool-1.1
+xmlrpc
------------------------------------------------
-version : 1.1
-url : http://jakarta.apache.org/commons-pool
-description: generic object pooling framework
+version : 1.2-b1
+url : http://ws.apache.org/xmlrpc/
+description: Java implementation of XML-RPC, a popular
+ protocol that uses XML over HTTP to
+ implement remote procedure calls
+
-commons-dbcp-1.1
------------------------------------------------
-version : 1.1
-url : http://jakarta.apache.org/commons-dbcp
-description: database connection pooling library
-$Id: README,v 1.1 2005/06/13 22:23:43 zak Exp $
+$Id: README,v 1.2 2007/04/08 21:46:44 idfx Exp $
The mir-setup script was developed initially on pulp (the
UK development server) and then on traven. It hasn't been
-# $Id: config,v 1.1 2005/06/13 22:23:43 zak Exp $
+# $Id: config,v 1.2 2007/04/08 21:46:43 idfx Exp $
# System configuration file for mir-setup script
-# $Id: config-examplesite,v 1.2 2005/09/25 11:59:24 zak Exp $
+# $Id: config-examplesite,v 1.3 2007/04/08 21:46:43 idfx Exp $
# Example site configuration file for mir-setup script
-# $Id: config.properties-default,v 1.1 2005/06/13 22:23:43 zak Exp $
+# $Id: config.properties-default,v 1.2 2007/04/08 21:46:43 idfx Exp $
# Based on mir/etc/config.properties-dist 1.31.2.5
#
# Sample config for Mir
-# $Id: tomcat-manager.conf,v 1.1 2005/06/13 22:29:03 zak Exp $
+# $Id: tomcat-manager.conf,v 1.2 2007/04/08 21:46:43 idfx Exp $
# Configuration for Tomcat manager access
#!/bin/bash
-# $Id: mir-setup,v 1.2 2005/09/25 11:59:24 zak Exp $
+# $Id: mir-setup,v 1.3 2007/04/08 21:46:44 idfx Exp $
# Script to install a new Mir site
#!/usr/bin/perl -w
-# $Id: munge_config_file.pl,v 1.1 2005/06/13 22:23:43 zak Exp $
+# $Id: munge_config_file.pl,v 1.2 2007/04/08 21:46:44 idfx Exp $
use strict;
--- /dev/null
+#!/bin/sh
+
+# This script will run tests with the update script to ensure
+# that all is good :)
+
+SCRIPT=/home/mish/active/indymedia/mirror-scripts/update.pl
+
+TESTDIR=/tmp/test_updatemirror
+CHANGEDIR=$TESTDIR/changes
+STATEDIR=$TESTDIR/state
+
+LASTUPDATEFILE=$STATEDIR/lastupdate.txt
+OUTPUTFILE=$TESTDIR/out.txt
+CORRECTFILE=$TESTDIR/correct.txt
+
+# set up - set up the directories and files required
+setup ()
+{
+ # first remove anything left
+ rm -rf $TESTDIR
+
+ # create the directory and copy the files we need to it
+ mkdir -p $CHANGEDIR
+ mkdir -p $STATEDIR
+ cp change*.txt $TESTDIR/
+ return
+}
+
+# teardown - remove all stuff so that next time is clean
+teardown ()
+{
+ # do we want to wait before tear down
+ if [ "$INTERACTIVE" == "i" ]; then
+ echo "Press any key to continue to next test"
+ read -n1
+ fi
+
+ rm -rf $TESTDIR
+ return
+}
+
+# setlastupdate - set the last update date/time
+# pass the date/time as YYYY MM DD hh mm ss
+setlastupdate ()
+{
+ # set the format as for `date -s %Y/%m/%d %H:%M:%S`
+ # or use that if no argument is set
+ if [ "$#" -eq "0" ]; then
+ date +"%Y:%m:%dT%H:%M:%S" > $LASTUPDATEFILE
+ else
+ echo "$1:$2:$3T$4:$5:$6" > $LASTUPDATEFILE
+ fi
+ return
+}
+
+# get the list of change files - one day only
+testChangeFileListOneDay ()
+{
+ setup
+ setlastupdate 2006 06 22 16 13 11
+ $SCRIPT --test \
+ --workingdir=$TESTDIR \
+ --list-change-files \
+ --now="2006:06:22T16:31:11.01" \
+ --output=$OUTPUTFILE
+ # check output file
+ echo "/changes/changes20060622.txt" > $CORRECTFILE
+ diff $OUTPUTFILE $CORRECTFILE
+ if [ "$?" -ne "0" ]; then
+ echo "*** FAILED testChangeFileListOneDay ***"
+ else
+ echo "Passed testChangeFileListOneDay"
+ fi
+
+ teardown
+}
+
+
+# generic test
+testGeneric ()
+{
+ setup
+ teardown
+}
+
+# do we want to do tests interactively
+if [ $# -eq 0 ]; then
+ INTERACTIVE=0
+else
+ INTERACTIVE=$1
+fi
+
+
+# do the tests
+testGeneric
+testChangeFileListOneDay
--- /dev/null
+#!/usr/bin/perl -w
+
+# This script is to get the changes needed to update the
+# files on a mir mirror.
+#
+# Full details (among other stuff) at
+# http://lists.indymedia.org/pipermail/imc-uk-tech/2006-May/0531-ib.html
+#
+# An extract is
+#
+# Mir will simply publish a list of file changes. It will produce one
+# file per day. The file will be publicly viewable on the web at
+#
+# /changes/changesYYYYMMDD.txt
+#
+# So on May 28th, 2006, the file name would be
+#
+# /changes/changes20060528.txt
+#
+# The format of the file will also be simple. There will be three
+# columns. First will be the time, then (add/change/delete) depending
+# whether the file is new, has been updated or deleted, and then the full
+# relative path of the file. So an example line would be
+#
+# 2006:01:24T09:08:17 add /en/2006/05/341547.html
+#
+# This will have to be done for HTML files, media files and the include
+# files.
+
+use strict;
+
+use Date::Calc::Object; # For date/time math
+use File::Copy; # For moving files
+use File::stat; # For getting mtimes
+use Getopt::Long; # For parsing command-line options
+use HTTP::Status; # For HTTP status codes
+use LWP::UserAgent; # For HTTP client functionality
+use HTTP::Date; # For HTTP-compatible str2time and time2str
+
+
+##################
+# Global variables
+##################
+
+# Verbose? (Debugging messages)
+my $verbose = 0;
+
+# by default, this is the working directory
+my $workingdir = ".";
+
+# get the time and date - using UTC
+my $timenow = time();
+
+# if this is 1, we only list the change files that are needed and stop
+# otherwise we do our normal processing
+my $listchangefiles = 0;
+
+# The root URL to fetch files from
+my $remoteroot;
+
+# The time we believe we were last up to date
+my $timeoflastupdate;
+
+# The most recent update we've just processed, for updating the above.
+# We use this rather than $timenow, in case of clock discrepancies
+# between the local and remote systems.
+my $mostrecentupdateprocessed;
+
+################################
+# process command line arguments
+################################
+
+sub usage() {
+ print STDERR <<EOF
+Usage: update.pl [options]
+
+ --remoteroot=url Set the remote root URL to mirror from (mandatory)
+ --workingdir=path Set the root of the local mirror (default ".")
+ --now=timestring Pretend it's currently the specified time
+ --lastupdate=timestring Pretend we were last up-to-date at the specified time
+ --list-change-files Just list the change files we would fetch
+ --verbose Run in verbose mode
+ --help Output this help
+
+EOF
+ ;
+ exit 1;
+}
+
+GetOptions( "verbose!" => \$verbose,
+ "workingdir=s" => \$workingdir,
+ "now=s" => sub($$) { $timenow = str2time($_[1]) or die "Can't parse argument to --".join('=',@_); },
+ "lastupdate=s" => sub($$) { $timeoflastupdate = str2time($_[1]) or die "Can't parse argument to --".join('=',@_); },
+ "remoteroot=s" => \$remoteroot,
+ "list-change-files!" => \$listchangefiles,
+ "help" => sub() { usage(); } );
+
+usage() if not defined $remoteroot;
+
+# the directory where all files with state are kept
+my $statedir = "$workingdir/state";
+if (! -e $statedir) {
+ mkdir $statedir or die "Can't create $statedir";
+}
+
+# the directory where changes files are kept
+my $changesdir = "$workingdir/changes";
+
+# the file we want with the last time in it is
+my $lastupdatefile = "$statedir/lastupdate.txt";
+
+# where we get changes files from
+my $changesroot = "$remoteroot/changes";
+
+# LWP user agent for fetching files
+# keep_alive is important, to avoid the overhead of
+# establishing a new connection for each file we fetch
+my $ua = new LWP::UserAgent( agent => "MirMirror/0.1",
+ keep_alive => 1 );
+
+
+###############
+# SUBROUTINES #
+###############
+
+# find the last update time
+# if the file with the update time has disappeared, alert the admin
+# and use the datestamp on the startpage file ( /en/index.html )
+sub findLastUpdateTime() {
+ open (UPDATETIME, "<", $lastupdatefile) or return Date::Calc->today()->date2time();
+ my $lastupdatetimestr = <UPDATETIME>;
+ close (UPDATETIME);
+
+ chomp ($lastupdatetimestr);
+ my $lastupdatetime = str2time ($lastupdatetimestr);
+ die "Can't parse last update time" if not $lastupdatetime;
+ return str2time ($lastupdatetimestr);
+}
+
+# write the given time into the last update file
+sub saveLastUpdateTime($) {
+ my $time = $_[0];
+ $time = $timeoflastupdate if !defined $time;
+
+ print STDERR "Updating timestamp to ".time2str($time)."\n" if $verbose;
+ open (UPDATETIME, ">", $lastupdatefile) or die "Can't open $lastupdatefile for writing ($!)";
+ print UPDATETIME time2str($time);
+ close (UPDATETIME);
+}
+
+# return an array of filename
+sub getChangesFileList($$)
+{
+ my ($fromtime, $totime) = @_;
+ my @files;
+ my $time = Date::Calc->time2date($fromtime);
+ my $maxtime = Date::Calc->time2date($totime);
+ for (; $time <= $maxtime; ++$time) {
+ my ($y,$m,$d) = $time->date;
+ push @files, sprintf("changes%04d%02d%02d.txt",$y,$m,$d);
+ }
+ return @files;
+}
+
+# get the directory part of a filename
+sub dirPart($) {
+ my $dir = $_[0];
+ $dir =~ s{/+[^/]*$}{};
+ return $dir;
+}
+
+# ensure the given directory exists (like mkdir -p)
+sub ensureDir($) {
+ my $dir = $_[0];
+ if (! -e $dir) {
+ my $parent = dirPart($dir);
+ &ensureDir($parent) if ($parent);
+ mkdir $dir or die "Can't create directory $dir ($!)";
+ }
+}
+
+# get the mtime of a file
+sub getmtime($) {
+ my $file = $_[0];
+ my $stat = stat($file);
+ die "Can't stat $file ($!)" if !$stat;
+ return $stat->mtime;
+}
+
+# get a file, optionally saving it locally.
+# if a local filename is given, return:
+# undef if not found on the server
+# 1 if found but not updated since local version
+# 2 if found and more recent than local version
+#
+# if no local filename is given, return the content of the
+# file, or undef if it was not found on the server
+#
+# on all other errors, die
+sub fetchFile($;$) {
+ my ($remotefile, $localfile) = @_;
+
+ if ($verbose) {
+ print STDERR "fetching $remotefile";
+ print STDERR " as $localfile" if $localfile;
+ }
+
+ my $req = new HTTP::Request(GET => "$remotefile");
+
+ if ($localfile) {
+ if (-e $localfile) {
+ # Don't fetch unless more recent than local copy
+ $req->header("If-Modified-Since" => time2str(getmtime($localfile)));
+ }
+ else {
+ ensureDir(dirPart($localfile));
+ }
+ }
+ my $resp = $ua->request($req, $localfile.".part");
+ if ($resp->is_success) { # 2xx codes
+ my $mtime = str2time($resp->header("Last-Modified"));
+ if ($verbose) {
+ print STDERR " -> success";
+ print STDERR "; mtime ".time2str($mtime) if $mtime;
+ print STDERR "\n";
+ }
+
+ if ($localfile) {
+ if ($mtime) {
+ utime $mtime, $mtime, $localfile.".part";
+ }
+ move($localfile.".part", $localfile) or die "Can't move $localfile into place";
+ }
+ return $localfile ? 2 : $resp->content;
+ }
+ elsif ($resp->is_redirect) { # 3xx codes
+ if ($resp->code == RC_NOT_MODIFIED) { # 304
+ print STDERR " -> not modified\n" if $verbose;
+ die "Got 304 with no local file" if not $localfile;
+ return 1;
+ }
+ print STDERR " -> redirect (".$resp->code.")\n" if $verbose;
+ die "Can't fetch $remotefile (got redirect, not yet handled)";
+ }
+ else {
+ if ($resp->code == RC_NOT_FOUND) { # 404
+ print STDERR " -> not found\n" if $verbose;
+ return undef;
+ }
+
+ print STDERR " -> failed (".$resp->code.")\n" if $verbose;
+ die "Can't fetch $remotefile (".$resp->status_line.")";
+ }
+}
+
+# get a changes file
+sub getChangesFile($) {
+ return fetchFile($changesroot."/".$_[0], $changesdir."/".$_[0]);
+}
+
+
+# update the timestamp if the new one is more recent
+sub updatestamp(\$$) {
+ my ($stampref, $newtime) = @_;
+ $$stampref = $newtime if (!defined $$stampref or $newtime > $$stampref);
+}
+
+
+##################
+# the program flow
+##################
+
+# first work out when the last time we were up to date is, if
+# it wasn't overridden on the command line
+$timeoflastupdate = findLastUpdateTime() if !defined $timeoflastupdate;
+
+if ($verbose) {
+ print STDERR "timenow is ".time2str($timenow)." \n";
+ print STDERR "timeoflastupdate is ".time2str($timeoflastupdate)." \n\n";
+}
+
+# Now we know which days' changes we need to get from the server
+my @changesfiles = getChangesFileList($timeoflastupdate, $timenow);
+if ($verbose) {
+ foreach my $file (@changesfiles) { print STDERR "using changes file $file\n"; }
+}
+
+if ($listchangefiles) {
+ foreach my $file (@changesfiles) { print "$file\n"; }
+ exit 0;
+}
+
+# fetch each changes file in turn, building up a list of files
+# to fetch/delete
+my %files;
+foreach my $changesfile (@changesfiles)
+{
+ my $rv = getChangesFile($changesfile);
+
+ # If the file isn't there, ignore it
+ if (! -e "$changesdir/$changesfile") {
+ print STDERR "Skipping changes file $changesfile; not present\n" if $verbose;
+ next;
+ }
+
+ my $date = $changesfile;
+ $date =~ s{^(?:.*/)?changes([0-9]+)\.txt$}{$1} or die "Can't extract date from changes filename $changesfile";
+
+ # The file exists, set most recent update to at lease "YYYY-MM-DD 00:00:00"
+ updatestamp($mostrecentupdateprocessed, str2time("$date 00:00:00"));
+
+ # If the file has not changed (response code 304) then ignore it
+ # Also check mtime against "last update" time so that we won't ignore
+ # it if previous runs have been failing
+ if ((!$rv or $rv < 2) and getmtime("$changesdir/$changesfile") < $timeoflastupdate) {
+ print STDERR "Skipping changes file $changesfile; not changed since last run\n" if $verbose;
+ next;
+ }
+
+ print STDERR "Processing changes file $changesfile\n" if $verbose;
+
+ open (CHANGES, "<", "$changesdir/$changesfile") or die "Can't open $changesfile";
+ while (my $change = <CHANGES>) {
+ my ($time, $op, $path) = split ' ', $change;
+
+ # Ignore malformed lines, especially wacky paths that could be malicious
+ if ($time =~ /[^0-9:]/) {
+ die "Invalid time $time in $changesfile";
+ }
+
+ if ($path =~ m{(?:^|/)\.\.(?:/|$)}) {
+ die "Invalid path $path (contains ..) in $changesfile";
+ }
+
+ # Strip scheme and host from absolute URLs
+ $path =~ s{^[a-z]+://[a-z0-9\-\.]+/}{/};
+
+ # Combine time with date and parse
+ $time = str2time("$date $time");
+ if (not defined $time) {
+ die "Failed to parse datetime '$date $time'";
+ }
+
+ # Ignore changes prior to $timeoflastupdate
+ next if $time < $timeoflastupdate;
+
+ # Update timestamp
+ updatestamp($mostrecentupdateprocessed, $time);
+
+ $files{$path} = $op;
+ print STDERR "Marked $path as '$op'\n" if $verbose;
+ }
+}
+
+# Fetch all files whose last operation was "add" or "change"
+# Delete all files whose last operation was "delete"
+while (my ($file, $op) = each %files) {
+ if ($op eq "delete") {
+ if (-e "$workingdir/$file") {
+ # delete: if the file exists, remove it
+ print STDERR "deleting $workingdir/$file\n" if $verbose;
+ unlink "$workingdir/$file" or die "Can't delete $workingdir/$file ($!)";
+ }
+ else {
+ print STDERR "not deleting $workingdir/$file beacuse it doesn't exist\n" if $verbose;
+ }
+ }
+ elsif ($op eq "add" or $op eq "change" or $op eq "Modification") {
+ # add/change: re-fetch the file
+ fetchFile("$remoteroot/$file","$workingdir/$file") or die "File $remoteroot/$file not found";
+ }
+ else {
+ die "Unknown operation '$op'";
+ }
+}
+
+
+# update the last "up-to-date" time
+saveLastUpdateTime($mostrecentupdateprocessed);
+
+# finish
+exit 0;
+
+
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
import mir.bundle.Bundle;
import mir.config.MirPropertiesConfiguration;
-import mir.servlet.*;
-import mir.util.ExceptionFunctions;
+import mir.servlet.AbstractServlet;
+import mir.servlet.AdminServletModule;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.ExceptionRoutines;
import mir.util.StringRoutines;
-import mir.log.LoggerWrapper;
import mircoders.entity.EntityUsers;
import mircoders.global.MirGlobal;
import mircoders.module.ModuleUsers;
import mircoders.servlet.ServletHelper;
+import multex.Failure;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
-import javax.servlet.http.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
import java.io.IOException;
import java.io.PrintWriter;
-import java.lang.reflect.Method;
-import java.util.*;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
-/**
- * Mir.java - main servlet, that dispatches to servletmodules
- *
- * @author $Author: idfx $
- *
- */
public class Mir extends AbstractServlet {
private static ModuleUsers usersModule = null;
- private final static Map servletModuleInstanceHash = new HashMap();
private static Locale fallbackLocale = null;
private static List loginLanguages = null;
- protected List getLoginLanguages() throws ServletException {
+ private List getLoginLanguages() throws Failure {
synchronized (Mir.class) {
try {
if (loginLanguages == null) {
return loginLanguages;
}
catch (Throwable t) {
- throw new ServletException(t.getMessage());
+ throw new Failure("Error while retrieving the available login languages", t);
}
}
}
return user;
}
catch (Throwable t) {
- t.printStackTrace();
-
- throw new ServletException(t.toString());
+ throw new ServletException(t.getMessage());
}
}
moduleName="Admin";
}
-
if (moduleName.equals("login")) {
String target = (String) session.getAttribute("login.target");
}
else {
try {
- ServletModule servletModule = getServletModuleForName(moduleName);
- ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);
+ AdminServletModule servletModule = getServletModuleForName(moduleName);
+ servletModule.handleRequest(aRequest, aResponse);
sessionConnectTime = System.currentTimeMillis() - startTime;
logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
}
catch (Throwable e) {
- Throwable cause = ExceptionFunctions.traceCauseException(e);
+ Throwable cause = ExceptionRoutines.traceCauseException(e);
if (cause instanceof ServletModuleUserExc)
handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);
}
}
catch (Throwable t) {
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
throw new ServletException(t.toString());
}
}
/**
* caching routine to get a module for a module name
*
- * @param moduleName the module name
+ * @param aModuleName the module name
* @return the requested module
* @throws ServletModuleExc
*/
-
- 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 static AdminServletModule getServletModuleForName(String aModuleName) throws ServletModuleExc {
+ return ServletHelper.getServletModule(aModuleName);
}
private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});
responseData.put("errorstring", anException.toString());
+ StringWriter writer = new StringWriter();
+ anException.printStackTrace(new PrintWriter(writer));
+ responseData.put("stacktrace", writer.toString());
responseData.put("date", new GregorianCalendar().getTime());
ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));
logger.error("Error handling error: " + e.toString());
try {
- Throwable rootException = ExceptionFunctions.traceCauseException(anException);
+ Throwable rootException = ExceptionRoutines.traceCauseException(anException);
PrintWriter writer = aResponse.getWriter();
writer.println("<html><head><title>FATAL Error</title><body>");
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
* If you do not wish to do so, delete this exception statement from your version.
*/
-import java.io.IOException;
-import java.io.PrintWriter;
+import mir.servlet.AbstractServlet;
+import mir.servlet.ServletModuleUserExc;
+import mir.util.ExceptionRoutines;
+import mircoders.servlet.ServletModuleOpenIndy;
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.servlet.ServletModuleOpenIndy;
+import java.io.IOException;
+import java.io.PrintWriter;
/**
* 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.39 2007/04/08 21:46:44 idfx Exp $
*
*/
public class OpenMir extends AbstractServlet {
- public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
- throws ServletException, IOException {
- if ((configuration.getString("RootUri") == null) ||
- configuration.getString("RootUri").equals("")) {
+ private ServletModuleOpenIndy servletModule;
+
+ private synchronized ServletModuleOpenIndy getServletModule() {
+ if (servletModule == null) {
+ servletModule = new ServletModuleOpenIndy();
+ }
+
+ return servletModule;
+ }
+
+ public void process(HttpServletRequest aRequest,
+ HttpServletResponse aResponse) throws ServletException, IOException {
+ if ("".equals(configuration.getString("RootUri", ""))) {
configuration.setProperty("RootUri", aRequest.getContextPath());
}
long startTime = System.currentTimeMillis();
- long sessionConnectTime=0;
HttpSession session = aRequest.getSession();
aResponse.setContentType("text/html; charset="+configuration.getString("Mir.DefaultHTMLCharset"));
try {
- ServletModuleDispatch.dispatch(ServletModuleOpenIndy.getInstance(), aRequest, aResponse);
+ // call appropriate ServletModuleOpenIndy method
+ // as specified in http request
+ // example: OpenMir?do=opensession calls the opensession method
+
+ getServletModule().handleRequest(aRequest, aResponse);
}
catch (Throwable e) {
- Throwable cause = ExceptionFunctions.traceCauseException(e);
+ logger.warn("Error in open publishing", e);
- if (cause instanceof ServletModuleUserExc)
+ Throwable cause = ExceptionRoutines.traceCauseException(e);
+
+ if (cause instanceof ServletModuleUserExc) {
handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
- else
+ }
+ else {
handleError(aRequest, aResponse, aResponse.getWriter(), cause);
+ }
}
- sessionConnectTime = System.currentTimeMillis() - startTime;
+ long sessionConnectTime = System.currentTimeMillis() - startTime;
+
logger.debug("EXECTIME (ServletModuleOpenIndy): " + sessionConnectTime + " ms");
}
private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
- PrintWriter out, ServletModuleUserExc anException) {
- ((ServletModuleOpenIndy) ServletModuleOpenIndy.getInstance()).handleUserError(aRequest, aResponse, out, anException);
+ PrintWriter anOutputWriter, ServletModuleUserExc anException) {
+ getServletModule().handleUserError(aRequest, aResponse, anOutputWriter, anException);
}
private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
- ((ServletModuleOpenIndy) ServletModuleOpenIndy.getInstance()).handleError(aRequest, aResponse, out, anException);
+ getServletModule().handleError(aRequest, aResponse, out, anException);
}
public String getServletInfo(){
#
# GENERAL SETUP
#
+# This is a full list of defaults options. To configure your site
+# do NOT change this file. You can override all of these values in
+# your etc/config.properties
+#
### mir/imc information
Mir.Name=mir.indymedia.org
Mir.Public-email.name=mir-coders mailinglist
Mir.Version=1.1.0rc0
-DirectOpenposting=yes
# The name of the abuse config file (relative to the WEB-INF dir)
Abuse.Config=abuse.properties
Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/),preview=freemarker(etc/producer)
Mir.Localizer.OpenPosting.GeneratorLibrary= default=freemarker(etc/open/)
+# Should an XSS preventing interceptor be used by the producer subsystem?
+Mir.Producer.UseInterceptor=1
+
# How should the custom operations (hide etc) in article and comment lists
# be presented?
# 0 = links, 1 = checkboxes, 2 = a listbox
-Mir.Localizer.Admin.ListOperationsFlavor=1
-
+Mir.Localizer.Admin.ListOperationsFlavor=2
+
# Article previews, a comma seperated list of name = generator
Mir.Localizer.Admin.ArticlePreview = \
default = preview::article.template
# will be linked to.
Producer.ImageRoot=/img
+# path to ImageMagick executables. Default is "" (nothing), which
+# means executables will be searched using the default system PATH
+# example:Producer.Image.ImageMagickPath=/usr/local/ImageMagick/bin
+#
+Producer.Image.ImageMagickPath=
# the url of the video-server
Producer.Video.Host=http://indy.code-fu.de/video
# absolute directory, where the images are saved
Producer.Image.Path=/pub/Dokumente/Indymedia/de-tech/Mir/produced/images/
+# absolute directory where image originals are saved if image resizing is enabled
+# this can be ignored if image scaling is not being used
+#
+Producer.ImagesOriginalDir.Path=/pub/Dokumente/Indymedia/de-tech/Mir/produced/images/raw
+
+# relative path from the site root where the templates can find raw (unresized) images:
+# this can be ignored if image scaling is not being used
+Producer.ImagesOriginalDir.RelPath=/images/raw
+
# images will be scaled down so that the size (both widht and height) are below:
Producer.Image.MaxSize = 640
PDF.Title.LineHeight=28
PDF.Title.FontFamily=courier
-# footer is about two lines of small text which will appear at the bottom of every page
+# Source will be expanded to come to a URL to the article
+PDF.Source=${config["Producer.PublicationHost"]}${config['Mir.Login.DefaultLanguage']}/${article.date.formatted['yyyy/MM']}/${article.id}.shtml
+# footer is about two lines of small text which will appear at the bottom of every page
PDF.Footer.String=Indymedia does blah. Content is good, and free to use for non-commercial purposes under the Open Content license. if you have questions, email someone.
PDF.Footer.Height=54
PDF.Footer.FontSize=12
Localizer.OpenSession.PersistentUploadedFiles = 0
# Should support for ftp-like uploads (uploads done
-# outside of mir, but included into postings) be
+# outside of mir, but included into postings) be
# supported at all?
Localizer.OpenSession.AllowFTPUploads = 0
Localizer.OpenSession.comment.DefaultMediaFolder=openposting
Localizer.OpenSession.ErrorTemplate = sessionerror.template
+Localizer.OpenSession.translation.EditTemplate=edittranslation.template
+Localizer.OpenSession.translation.DupeTemplate=dupearticle.template
+Localizer.OpenSession.translation.UnsupportedMediaTemplate=unsupportedmediatype.template
+Localizer.OpenSession.translation.DoneTemplate=donetranslation.template
+
+
Localizer.OpenSession.email.PrepareTemplate = preparemail.template
Localizer.OpenSession.email.MailTemplate = email_article.template
Localizer.OpenSession.email.DoneTemplate =/sent_mail.template
+Localizer.HTML.Whitelist=a;img;h1;h2;h3;h4;h5;h6;br;form;input;hr;strong;font;b;i;em;p;table;tr;td;th;ul;ol;li
+
+Localizer.HTML.BadAttributeValuePrefixes=javascript;vbscript;about;wysiwyg;data;view-source;ms-its;mhtml;shell;lynxexec;lynxcgi;hcp;ms-help;help;disk;vnd.ms.radio;opera;res;resource;chrome;mocha;livescript
+Localizer.HTML.BadAttributes=onabort;onblur;onchange;onclick;ondblclick;onerror;onfocus;onkeydown;onKeypress;onkeyup;onload;onmousedown;onmousemove;onmouseout;onmouseover;onmouseup;onreset;onselect;onsubmit;onunload;onload;onclick;onfocus;onblur;FSCommand;onAbort;onActivate;onAfterPrint;onAfterUpdate;onBeforeActivate;onBeforeCopy;onBeforeCut;onBeforeDeactivate;onBeforeEditFocus;onBeforePaste;onBeforePrint;onBeforeUnload;onBegin;onBlur;onBounce;onCellChange;onChange;onClick;onContextMenu;onControlSelect;onCopy;onCut;onDataAvailible;onDataSetChanged;onDataSetComplete;onDblClick;onDeactivate;onDrag;onDragEnd;onDragLeave;onDragEnter;onDragOver;onDragDrop;onDrop;onEnd;onError;onErrorUpdate;onExit;onFilterChange;onFinish;onFocus;onFocusIn;onFocusOut;onHelp;onKeyDown;onKeyPress;onKeyUp;onLayoutComplete;onLoad;onLoseCapture;onMediaComplete;onMediaError;onMouseDown;onMouseEnter;onMouseLeave;onMouseMove;onMouseOut;onMouseOver;onMouseUp;onMouseWheel;onMove;onMoveEnd;onMoveStart;onOutOfSync;onPaste;onPause;onProgress;onPropertyChange;onReadyStateChange;onRepeat;onReset;onResize;onResizeEnd;onResizeStart;onResume;onReverse;onRowEnter;onRowExit;onRowDelete;onRowInserted;onScroll;onSeek;onSelect;onSelectionChange;onSelectStart;onStart;onStop;onSynchRestored;onSubmit;onTimeError;onTrackChange;onUnload;onURLFlip;seekSegmentTime;style;height;width
#
# config used for OpenIndy
ServletModule.MediaType.EditTemplate=mediatype.template
ServletModule.MediaType.ListTemplate=mediatypelist.template
+
#
# Object store configuration
#
StoreContainer.EntityListDefaultSize= 15
StorableObjectEntity.Entity.DefaultSize= 300
StorableObjectEntity.EntityList.DefaultSize= 100
-EntityTopics.Entity.DefaultSize= 200
-EntityTopics.EntityList.DefaultSize= 20
+EntityTopics.Entity.DefaultSize=200
+EntityTopics.EntityList.DefaultSize=20
#
# config for abuse
-ServletModule.Abuse.EditFilter.Template = abuse.filter.template
-ServletModule.Abuse.ListFilters.Template = abuse.filters.template
+ServletModule.Abuse.EditFilter.Template = filter.template
+ServletModule.Abuse.ListFilters.Template = filterlist.template
+ServletModule.Abuse.EditFilterGroup.Template = filtergroup.template
+ServletModule.Abuse.ListFilterGroups.Template = filtergrouplist.template
ServletModule.Abuse.ViewLog.Template = abuse.log.template
ServletModule.Abuse.Main.Template = abuse.template
+++ /dev/null
-<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
-
-<hibernate-configuration>
- <session-factory>
- <!--
- <property name="hibernate.connection.url">
- jdbc:postgresql://localhost/mir
- </property>
- <property name="hibernate.connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password"></property>
- <property name="dialect">
- net.sf.hibernate.dialect.MySQLDialect
- </property>
- //-->
- <property name="hibernate.connection.url">
- jdbc:postgresql://127.0.0.1:5432/mir3
- </property>
- <property name="hibernate.connection.driver_class">
- org.postgresql.Driver
- </property>
- <property name="hibernate.connection.username">mir</property>
- <property name="hibernate.connection.password"></property>
- <property name="dialect">
- net.sf.hibernate.dialect.PostgreSQLDialect
- </property>
- <property name="hibernate.show_sql">true</property>
- <property name="hibernate.use_outer_join">false</property>
- <!--
- <property name="hibernate.connection.url">
- jdbc:mysql://localhost/mir2
- </property>
- <property name="hibernate.connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password" />
- <property name="dialect">
- net.sf.hibernate.dialect.MySQLDialect
- </property>
- //
- //
- //-->
- <!--
- <property name="hibernate.transaction.factory_class">
- net.sf.hibernate.transaction.JTATransactionFactory
- </property>
- <property name="jta.UserTransaction">
- java:comp/UserTransaction
- </property>
- //
- //
- //-->
- <!-- connection pool -->
- <property name="dbcp.initialSize">0</property>
- <property name="dbcp.maxActive">8</property>
- <property name="dbcp.maxIdle">8</property>
- <property name="dbcp.minIdle">0</property>
- <property name="dbcp.maxWait">-1</property>
- <!-- end connection pool -->
- <mapping resource="org/codecoop/mir/core/model/Media.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/UploadedMedia.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Article.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/ArticleStatus.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/ArticleType.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Message.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/MediaType.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/MediaFolder.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/MediaRelationType.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Language.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/BreakingNewsItem.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Role.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/User.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Right.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/Category.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/CategoryType.hbm.xml" />
- <mapping resource="org/codecoop/mir/core/model/TypedCategory.hbm.xml" />
- </session-factory>
-</hibernate-configuration>
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.util.List;
+/**
+ * A Bundle represents a set key/value pairs, for instane stored in a
+ * ".properties" text file. Bundles are used for internationalization
+ * (language translations).
+ */
public interface Bundle {
+ /**
+ * Returns a bundle value. The argument list is used for formating the
+ * returned value: braced expressions like {0}, {1} are replaced with
+ * appropriate parameter
+ */
public String getValue(String aKey, List anArguments);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.util.List;
public class CascadingBundleFactory implements BundleFactory {
- private BundleFactory masterFactory;
+ BundleFactory masterFactory;
/** {@inheritDoc} */
public CascadingBundleFactory(BundleFactory aMasterFactory) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.bundle;
-import java.util.Properties;
-import java.util.List;
import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
import mir.util.StringParseRoutines;
if (result==null || result.trim().length()==0)
return null;
- else
- return formatValue(result, anArguments);
+ return formatValue(result, anArguments);
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.bundle;
import java.io.File;
-import java.io.IOException;
import java.io.FileInputStream;
+import java.io.IOException;
import java.util.Properties;
/**
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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.changetracker;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Calendar;
+
+/**
+ * Change tracker, tracks changes to a path based repository.
+ * All methods are thread-safe
+ */
+
+public class ChangeTracker {
+ private final List changes = new ArrayList();
+ private Calendar calendar = Calendar.getInstance();
+
+ // to prevent memory issues with the number of recorded changes,
+ // we'll adhere to this maximum
+ private static final int MAX_CHANGES = 10000;
+
+ /**
+ * Add a single change. A change is represented by the full path
+ * of the file involved.
+ */
+ public void addChange(String aPath, ChangeType aChangeType) {
+ synchronized (changes) {
+ changes.add(new Change(aPath, aChangeType, calendar.getTime()));
+ }
+ }
+
+ /**
+ * Add an array of changes. Each change is represented by the full path
+ * of the file involved.
+ */
+ public void addChanges(String[] aPaths, ChangeType aChangeType) {
+ addChanges(Arrays.asList(aPaths), aChangeType);
+ }
+
+ /**
+ * Adds a <code>Collection</code> of changes. Each change is represented by the
+ * full path of the file involved.
+ */
+ public void addChanges(Collection aChanges, ChangeType aChangeType) {
+ synchronized (changes) {
+ Iterator i = aChanges.iterator();
+ while (i.hasNext()) {
+ addChange((String) i.next(), aChangeType);
+ }
+ }
+ }
+
+ public class Change {
+ private ChangeType type;
+ private String path;
+ private Date date;
+
+ Change(String anAbsolutePath, ChangeType aType, Date aDate) {
+ type = aType;
+ path = anAbsolutePath;
+ date = aDate;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public ChangeType getType() {
+ return type;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ }
+
+ /**
+ * Returns a <code>Collection</code> of {@link Change}s within a base
+ * path, and removes them from the tracker.
+ */
+ public Collection flushChanges(String aBasePath) {
+ return flushChanges(aBasePath, Collections.EMPTY_LIST);
+ }
+
+ /**
+ * Returns a <code>Collection</code> of {@link Change}s within a base
+ * path, exluding a list of excluded paths, and removes them from
+ * the tracker.
+ */
+ public Collection flushChanges(String aBasePath, Collection anExcludedPaths) {
+ synchronized (changes) {
+ Collection result = getChanges(aBasePath, anExcludedPaths);
+
+ removeChanges(result);
+
+ return result;
+ }
+ }
+
+ /**
+ * Remove specific changes from the change tracker.
+ *
+ * @param someChanges a <code>Collection</code> of changes represented by
+ * their full path in the form of a <code>String</code>
+ */
+ void removeChanges(Collection someChanges) {
+ synchronized (changes) {
+ changes.removeAll(someChanges);
+ }
+ }
+
+ /**
+ * Returns all changes within a base path
+ */
+ List getChanges(String aBasePath) {
+ synchronized (changes) {
+ List result = new ArrayList();
+
+ Iterator i = changes.iterator();
+ while (i.hasNext()) {
+ Change change = (Change) i.next();
+ if (change.getPath().startsWith(aBasePath)) {
+ result.add(change);
+ }
+ }
+
+ return result;
+ }
+ }
+
+ /**
+ * Gets all changes within a base path, but excluding some other paths
+ *
+ * @param aBasePath
+ * @param anExcludedPaths a collection of paths to exclude. may be <code>null</code>
+ * to not exclude anything
+ */
+ Collection getChanges(String aBasePath, Collection anExcludedPaths) {
+ synchronized (changes) {
+ List result = getChanges(aBasePath);
+
+ if (anExcludedPaths != null) {
+ Iterator i = anExcludedPaths.iterator();
+ while (i.hasNext()) {
+ String excludedPath = (String) i.next();
+ List remove = new ArrayList();
+ Iterator j = result.iterator();
+ while (j.hasNext()) {
+ Change change = (Change) j.next();
+ if (change.getPath().startsWith(excludedPath)) {
+ remove.add(change);
+ }
+ }
+ result.removeAll(remove);
+ }
+ }
+
+ if (changes.size()>MAX_CHANGES) {
+ changes.clear();
+ }
+
+ return result;
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+package mir.changetracker;\r
+\r
+/**\r
+ * Class that is used to indicate the kind of change\r
+ */\r
+public final class ChangeType {\r
+ private String name;\r
+\r
+ ChangeType(String aName) {\r
+ name = aName;\r
+ }\r
+\r
+ public String getName() {\r
+ return name;\r
+ }\r
+\r
+ /**\r
+ * <code>ChangeType</code> indicating the file(s) in question have been added.\r
+ */\r
+ public static final ChangeType ADDITION = new ChangeType("Addition");\r
+\r
+ /**\r
+ * <code>ChangeType</code> indicating the file(s) in question have been modified.\r
+ */\r
+ public static final ChangeType MODIFICATION = new ChangeType("Modification");\r
+\r
+ /**\r
+ * The file(s) in question have been deleted.\r
+ */\r
+ public static final ChangeType DELETION = new ChangeType("Deletion");\r
+\r
+\r
+}\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.config;
+import multex.Exc;
+import multex.Failure;
+import org.apache.commons.collections.ExtendedProperties;
+
+import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import javax.servlet.ServletContext;
-
-import multex.Exc;
-import multex.Failure;
-import org.apache.commons.collections.ExtendedProperties;
/**
* @author idefix
if (result.isAbsolute()) {
return result;
}
- else {
- return new File(home, path);
- }
+ return new File(home, path);
}
/**
/**
* @return the value of this property as String
- * @param key the key of the property
- * @param defaultValue the default value of this property if it is null
+ * @param aKey the key of the property
+ * @param aDefaultValue the default value of this property if it is null
* @see org.apache.commons.collections.ExtendedProperties#getString(java.lang.String, java.lang.String)
*/
- public String getString(String key, String defaultValue) {
- Object object = getProperty(key);
- if(object == null){
- if (defaultValue == null) {
- return new String();
- }
- return defaultValue;
+ public String getString(String aKey, String aDefaultValue) {
+ if (aDefaultValue == null) {
+ aDefaultValue = "";
}
- if (object instanceof String) {
- return (String)object;
+ Object result = getProperty(aKey);
+
+ if (result == null){
+ return aDefaultValue;
+ }
+
+ if (result instanceof String) {
+ return (String) result;
}
- return object.toString();
+
+ return result.toString();
}
public boolean getBoolean(String aKey, boolean aDefaultValue) {
String value = getString(aKey).trim();
return "1".equals(value) || "y".equalsIgnoreCase(value) ||
- "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value);
+ "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value);
}
/**
*/
public Object getProperty(String key) {
if (super.getProperty(key) == null) {
- return new String();
+ return "";
}
return super.getProperty(key);
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.util.Map;
import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseExc;
+import mir.storage.DatabaseFailure;
+import mir.storage.Database;
/**
* Base class the entities are derived from. Provides base functionality of
* an entity.
*
- * @version $Id: AbstractEntity.java,v 1.9 2004/11/06 19:18:12 idfx Exp $
+ * @version $Id: AbstractEntity.java,v 1.10 2007/04/08 21:46:44 idfx Exp $
*/
public class AbstractEntity implements Entity {
protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
protected Map values;
- protected StorageObject storageObject;
- protected LoggerWrapper logger;
+ protected Database database;
public AbstractEntity() {
- logger = new LoggerWrapper("Entity");
-
values = new HashMap();
}
- /**
- * Constructor
- * @param StorageObject The StorageObject of the Entity.
- */
- public AbstractEntity(StorageObject StorageObject) {
- this();
-
- setStorage(StorageObject);
- }
-
- public void setStorage(StorageObject storage) {
- this.storageObject = storage;
+ public void setStorage(Database aDatabase) {
+ database = aDatabase;
}
/** {@inheritDoc} */
/** {@inheritDoc} */
public String getId() {
- return getFieldValue(storageObject.getIdName());
+ return getFieldValue(database.getIdFieldName());
}
/** {@inheritDoc} */
public void setId(String id) {
- setFieldValue(storageObject.getIdName(), id);
+ setFieldValue(database.getIdFieldName(), id);
}
/** {@inheritDoc} */
- public String insert() throws StorageObjectExc {
- logger.debug("Entity: trying to insert ...");
+ public String insert() throws DatabaseExc {
+ getLogger().debug("Entity: trying to insert ...");
- if (storageObject != null) {
- return storageObject.insert(this);
+ if (database != null) {
+ return database.insert(this);
}
- else
- throw new StorageObjectExc("storageObject == null!");
+
+ throw new DatabaseExc("database == null!");
}
/** {@inheritDoc} */
- public void update() throws StorageObjectFailure {
- storageObject.update(this);
+ public void update() throws DatabaseFailure {
+ database.update(this);
}
/** {@inheritDoc} */
* 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 StorageObjectFailure
+ * @exception DatabaseFailure
*/
- public void setFieldValue(String theProp, String theValue) throws StorageObjectFailure {
+ public void setFieldValue(String theProp, String theValue) throws DatabaseFailure {
if (hasField(theProp))
values.put(theProp, theValue);
else {
- logger.warn("Entity.setFieldValue: Property not found: " + theProp + " (" + theValue + ")");
+ getLogger().warn("Entity.setFieldValue: Property not found: " + theProp + " (" + theValue + ")");
}
}
/**
* Returns the field names of the Entity
*/
- public List getFieldNames() throws StorageObjectFailure {
- return storageObject.getFields();
+ public List getFieldNames() throws DatabaseFailure {
+ return database.getFieldNames();
}
/** 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 StorageObjectFailure
+ * @exception DatabaseFailure
*/
- public boolean hasField(String fieldName) throws StorageObjectFailure {
+ public boolean hasField(String fieldName) throws DatabaseFailure {
return getFieldNames().contains(fieldName);
}
+
+ protected LoggerWrapper getLogger() {
+ return new LoggerWrapper("Entity");
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
import java.util.Map;
+import java.util.List;
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseExc;
+import mir.storage.DatabaseFailure;
/**
* An <code>Entity</code> represents a persistent data object, typically
* stored in a database.<p>
*
- * @version $Id: Entity.java,v 1.23 2004/11/06 19:18:12 idfx Exp $
+ * @version $Id: Entity.java,v 1.24 2007/04/08 21:46:44 idfx Exp $
*/
-public interface Entity
-{
- public void setStorage(StorageObject storage);
-
+public interface Entity {
/**
* Sets the values of the Entity. (Only to be called by the Storage Object)
*
public String getId();
/**
- * Defines the primary key of the Entity (only to be set by the StorageObject)
+ * Defines the primary key of the Entity (only to be set by the Database)
* @param id
*/
public void setId(String id);
/**
- * Insers Entity into the database via StorageObject
+ * Inserts Entity into the database via Database
* @return Primary Key of the Entity
- * @exception StorageObjectExc
+ * @exception DatabaseExc
*/
- public String insert() throws StorageObjectExc;
+ public String insert() throws DatabaseExc;
/**
* Saves changes of this Entity to the database
- * @exception StorageObjectFailure
+ * @exception DatabaseFailure
*/
- public void update() throws StorageObjectFailure;
+ public void update() throws DatabaseFailure;
/**
* 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 StorageObjectFailure
+ * @param aFieldName The field name whose value has to be set
+ * @param aValue The new value of the field
+ * @exception DatabaseFailure
*/
- public void setFieldValue(String theProp, String theValue);
+ public void setFieldValue(String aFieldName, String aValue);
/**
* Returns the field names of the Entity
*/
- public List getFieldNames() throws StorageObjectFailure;
+ public List getFieldNames() throws DatabaseFailure;
/**
* Returns the value of a field by field name.
- * @param field The name of the field
+ * @param aFieldName The name of the field
* @return value of the field
*/
- public String getFieldValue(String field);
+ public String getFieldValue(String aFieldName);
- public boolean hasFieldValue(String field);
+ public boolean hasFieldValue(String aFieldName);
/** Returns whether fieldName is a valid field name of this Entity.
*/
- public boolean hasField(String aFieldName) throws StorageObjectFailure;
+ public boolean hasField(String aFieldName) throws DatabaseFailure;
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity;
import java.util.List;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.Database;
+import mir.storage.DatabaseFailure;
+import mir.storage.DatabaseExc;
import mir.util.RewindableIterator;
+import multex.Failure;
public class EntityBrowser implements RewindableIterator {
- private StorageObject storage;
+ private Database database;
private String mainTablePrefix;
private List extraTables;
private String whereClause;
private int batchPosition;
private int positionInBatch;
- public EntityBrowser(StorageObject aStorage, String aMainTablePrefix, List someExtraTables,
+ public EntityBrowser(Database aDatabase, String aMainTablePrefix, List someExtraTables,
String aWhereClause, String anOrderByClause,
- int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure {
+ int aBatchSize, int aLimit, int aSkip) throws DatabaseFailure {
- storage=aStorage;
+ database=aDatabase;
mainTablePrefix=aMainTablePrefix;
extraTables=someExtraTables;
whereClause=aWhereClause;
rewind();
}
- public EntityBrowser(StorageObject aStorage, String aWhereClause, String anOrderByClause,
- int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure {
- this(aStorage, "", null, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip);
+ public EntityBrowser(Database aDatabase, String aWhereClause, String anOrderByClause,
+ int aBatchSize, int aLimit, int aSkip) throws DatabaseFailure {
+ this(aDatabase, "", null, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip);
}
- public EntityBrowser(StorageObject aStorage,
+ public EntityBrowser(Database aDatabase,
String aWhereClause, String anOrderByClause,
- int aBatchSize) throws StorageObjectFailure {
- this(aStorage, aWhereClause, anOrderByClause, aBatchSize, -1, 0);
+ int aBatchSize) throws DatabaseFailure {
+ this(aDatabase, aWhereClause, anOrderByClause, aBatchSize, -1, 0);
}
- public void readCurrentBatch(int aSkip) throws StorageObjectFailure {
- currentBatch = storage.selectByWhereClause(mainTablePrefix, extraTables, whereClause, orderByClause, aSkip, batchSize);
+ public void readCurrentBatch(int aSkip) throws DatabaseExc, DatabaseFailure {
+ currentBatch = database.selectByWhereClause(mainTablePrefix, extraTables,
+ whereClause, orderByClause, aSkip, batchSize);
batchPosition = aSkip;
positionInBatch = 0;
}
readCurrentBatch(skip);
}
catch (Throwable t) {
- throw new RuntimeException(t.getMessage());
+ throw new Failure("Error while rewinding", t);
}
}
return result;
}
- else {
- return null;
- }
+ return null;
}
catch (Throwable t) {
throw new RuntimeException(t.getMessage());
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity;
-import java.util.ArrayList;
-import java.util.Set;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
+import mir.storage.Database;
import mir.storage.store.StorableObject;
import mir.storage.store.StoreContainerType;
import mir.storage.store.StoreIdentifier;
import mir.storage.store.StoreUtil;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
/**
*
* Container class for lists of Entities.
- * Now implements @see mir.storage.store.StorableObject.
+ * Now implements @see mir.database.store.StorableObject.
*
- * @author <RK>
+ * @author rk
* first version 27.6.1999
*
* @version 1.1 (cleaned up)
*/
public class EntityList implements StorableObject {
- protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
protected LoggerWrapper logger;
- private ArrayList theEntityArrayList = new ArrayList();
+ private List entities = new ArrayList();
private String whereClause, orderClause;
- private StorageObject theStorage;
- private int count, offset, limit;
- private int offsetnext = -1, offsetprev = -1;
+ private Database storage;
+ private int offset, limit;
+ private int nextOffset = -1;
public EntityList(){
logger = new LoggerWrapper("Entity.List");
}
-/* get/set EntityClass of Objects stored in EntityList */
- public void setStorage(StorageObject storage) { this.theStorage=storage; }
- public StorageObject getStorage() { return theStorage; }
+ public void setStorage(Database aStorage) {
+ storage=aStorage;
+ }
+
+ public Database getStorage() {
+ return storage;
+ }
- public void setLimit(int limit) { this.limit = limit; }
+ public void setLimit(int aLimit) {
+ limit = aLimit;
+ }
/**
* Sets the WHERE clause that fetched the Entities of this EntityList from the database.
+ *
* @param wc The string that contains the WHERE clause
*/
public void setWhere(String wc) {
}
/**
- * Returns the WHERE clause that returned this EntityList from the database
- * @return whereClause The WHERE clause
- */
- public String getWhere() {
- return whereClause;
- }
-
- /**
* Sets the sorting criterium of this EntityList
+ *
* @param oc
*/
public void setOrder(String oc) {
}
/**
- * Returns the sorting criterium.
- * @return orderClause The sort order
- */
- public String getOrder() {
- return orderClause;
- }
-
- /**
- * Sets the number of rows that match the WHERE clause
- * @param i The number of rows that match the WHERE clause
- */
- public void setCount(int i) {
- this.count = i;
- }
-
- /**
- * Returns the number of rows that match the WHERE clause
- * @return The number of rows ...
- */
- public int getCount() {
- return count;
- }
-
- /**
* Sets the offset
+ *
* @param i The offset
*/
public void setOffset(int i) {
/**
* Returns the offset
+ *
* @return offset
*/
public int getOffset() {
/**
* Sets the offset of the next batch of Entities.
+ *
* @param i The next offset
*/
public void setNextBatch(int i) {
- offsetnext = i;
+ nextOffset = i;
}
/**
* Returns the offset of the next batch of Entities.
+ *
* @return offset of the next batch
*/
public int getNextBatch() {
- return offsetnext;
+ return nextOffset;
}
/**
* Returns whether there is a next batch within the WHERE clause
+ *
* @return true if yes, false if no.
*/
public boolean hasNextBatch() {
- return (offsetnext >= 0);
- }
-
- /**
- * Sets the offset of the previous batch.
- * @param i the previous offset
- */
- public void setPrevBatch(int i) {
- offsetprev = i;
- }
-
- /**
- * Returns the offset of the previous batch.
- * @return offset of the previous batch
- */
- public int getPrevBatch() {
- return offsetprev;
- }
-
- /**
- * Returns whether there is a previous batch.
- * @return true if yes, false if no
- */
- public boolean hasPrevBatch() {
- return (offsetprev >= 0);
- }
-
- /**
- * Returns the start index of the batch.
- * @return
- */
- public int getFrom() {
- return offset+1;
- }
-
- /**
- * Returns the end index of the batch.
- * @return
- */
- public int getTo() {
- if (hasNextBatch())
- return offsetnext;
- else
- return count;
+ return (nextOffset >= 0);
}
/**
* Inserts an Entity into the EntityList.
+ *
* @param anEntity The entity to be inserted.
*/
public void add (Entity anEntity) {
if (anEntity!=null)
- theEntityArrayList.add(anEntity);
+ entities.add(anEntity);
else
logger.warn("EntityList: add called with empty Entity");
}
*/
public int size() {
- return theEntityArrayList.size();
+ return entities.size();
}
*/
public Entity elementAt(int i) {
- /** todo check if i is in list.size() */
- return (Entity) theEntityArrayList.get(i);
+ return (Entity) entities.get(i);
}
public Set getNotifyOnReleaseSet() { return null; }
public StoreIdentifier getStoreIdentifier() {
- if ( theStorage!=null ) {
+ if ( storage!=null ) {
return
- new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST,
- StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(),
- whereClause, orderClause, offset, limit ));
+ new StoreIdentifier(
+ this, StoreContainerType.STOC_TYPE_ENTITYLIST,
+ StoreUtil.getEntityListUniqueIdentifierFor( storage.getTableName(),
+ whereClause, orderClause, offset, limit ));
}
- logger.warn("EntityList could not return StoreIdentifier");
- return null;
+ logger.warn("EntityList could not return StoreIdentifier");
+
+ return null;
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity;
-/**
- * Title: StorableObjectEntity
- * Description: Basic Container that can be handled by ObjectStore
- * Copyright: Copyright (c) 2002
- * Company: indy
- * @author rk
- * @version 1.0
- */
-
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;
*/
public StoreIdentifier getStoreIdentifier() {
String id = getId();
- if ( id!=null && storageObject!= null )
- return new StoreIdentifier(this, id+"@"+storageObject.getTableName());
+ if ( id!=null && database!= null )
+ return new StoreIdentifier(this, id+"@"+database.getTableName());
return null;
}
Class theEntityClass, String theTable, String id) {
if (id == null) {
return null;
- } else {
- return new StoreIdentifier(theEntityClass, id + "@" + theTable);
}
+ return new StoreIdentifier(theEntityClass, id + "@" + theTable);
}
public static final StoreIdentifier getStoreIdentifier(Database theStorage,
Class theEntityClass, ResultSet rs) throws SQLException {
- String idcol = theStorage.getIdName();
+ String idcol = theStorage.getIdFieldName();
String idval = rs.getObject(idcol).toString();
if (idval != null) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity.adapter;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
import mir.entity.Entity;
import mir.util.CachingRewindableIterator;
-
-public class EntityAdapter implements Map {
+import mir.util.RewindableIterator;
+
+import java.util.*;
+
+/** An EntityAdapter is a wrapper around an Entity meant to add
+ * missing functionality. It provides "calculated fields"
+ * which mir installations can extend reasonably easilly.
+ * "calculated fields" compute values that are not directly present
+ * in the db table. For example:
+ * a field to have the number of comments associated with an article;
+ * a field to get the list of hidden comments associated with an article;
+ * etc.
+ * <p>This whole framework is meant to be replaced by hibernate</p>
+ */
+public class EntityAdapter {
private Entity entity;
private EntityAdapterDefinition definition;
private Map calculatedFieldsCache;
model = aModel;
}
- public boolean containsKey(Object aKey) {
- try {
- if (aKey instanceof String)
- return entity.hasField((String) aKey)
- || definition.hasCalculatedField((String) aKey);
- }
- catch (Throwable t) {
- }
-
- return false;
- }
-
public boolean equals(Object anObject) {
return anObject instanceof EntityAdapter
&& ((EntityAdapter) anObject).entity.equals(entity);
}
public int hashCode() {
- return entity.hashCode();
+ if (entity!=null) {
+ return entity.hashCode();
+ }
+ else {
+ return 0;
+ }
}
public Entity getEntity() {
return model;
}
- public Object get(Object aKey) {
+ public Object get(String aKey) {
Object result;
if (calculatedFieldsCache.containsKey(aKey)) {
return calculatedFieldsCache.get(aKey);
}
- else if (aKey instanceof String && definition.hasCalculatedField((String) aKey)) {
- result = definition.getCalculatedField((String) aKey).getValue(this);
+ else if (definition.hasCalculatedField(aKey)) {
+ result = definition.getCalculatedField(aKey).getValue(this);
calculatedFieldsCache.put(aKey, result);
return result;
}
- else if (aKey instanceof String) {
- return entity.getFieldValue((String) aKey);
- }
else {
- return null;
+ return entity.getFieldValue(aKey);
}
}
- public boolean isEmpty() {
- return false;
- }
-
- public Set keySet() {
- throw new UnsupportedOperationException("EntityAdapter.keySet()");
- }
+ public Iterator getIterator(String aKey) {
+ Object result = get(aKey);
- public Object put(Object aKey, Object value) {
- throw new UnsupportedOperationException("EntityAdapter.put()");
- }
-
- public void putAll(Map t) {
- throw new UnsupportedOperationException("EntityAdapter.putAll()");
- }
-
- public Object remove(Object aKey) {
- throw new UnsupportedOperationException("EntityAdapter.remove()");
- }
-
- public int size() {
- throw new UnsupportedOperationException("EntityAdapter.size()");
- }
-
- public Collection values() {
- throw new UnsupportedOperationException("EntityAdapter.values()");
- }
-
- public void clear() {
- throw new UnsupportedOperationException("EntityAdapter.clear()");
- }
-
- public boolean containsValue(Object value) {
- throw new UnsupportedOperationException("EntityAdapter.containsValue()");
- }
-
- public Set entrySet() {
- throw new UnsupportedOperationException("EntityAdapter.entrySet()");
+ if (result instanceof RewindableIterator) {
+ ((RewindableIterator) result).rewind();
+ return (RewindableIterator) result;
+ }
+ else if (result instanceof Iterator) {
+ return (Iterator) result;
+ }
+ else if (result instanceof Collection) {
+ return ((Collection) result).iterator();
+ }
+ else if (result!=null) {
+ return Collections.singletonList(result).iterator();
+ }
+ else {
+ return null;
+ }
}
public Object getComplexRelation(String aMainTablePrefix, List someExtraTables,
}
- public Object getRelation(String aWhereClause, String anOrderByClause, String aDefinition) {
+ public List getRelation(String aWhereClause, String anOrderByClause, String aDefinition) {
try {
- return
- new CachingRewindableIterator(
- new EntityIteratorAdapter(
- aWhereClause, anOrderByClause, -1, getModel(), aDefinition));
+ return EntityAdapterEngine.retrieveAdapterList(model, aDefinition, aWhereClause, anOrderByClause, -1, 0);
}
catch (Throwable t) {
throw new RuntimeException(t.getMessage());
if (i.hasNext())
return (EntityAdapter) i.next();
- else
- return null;
+ return null;
}
catch (Throwable t) {
throw new RuntimeException(t.getMessage());
if (i.hasNext())
return (EntityAdapter) i.next();
- else
- return null;
+ return null;
}
catch (Throwable t) {
throw new RuntimeException(t.getMessage());
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.
*/
/**
*
* @param aFieldName
- * @return
+ * @return boolean true if aFieldName is a calculated Field
*/
public boolean hasCalculatedField(String aFieldName) {
return calculatedFields.containsKey(aFieldName);
}
public Object getValue(EntityAdapter anEntityAdapter) {
-
Object result = null;
String textValue = anEntityAdapter.getEntity().getFieldValue(fieldName);
Calendar calendar = GregorianCalendar.getInstance();
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity.adapter;
-import java.util.List;
-
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import java.util.List;
public class EntityAdapterEngine {
private EntityAdapterEngine() {
}
- /**
- *
- * @param aStorage
- * @param aDefinition
- * @param aQualifier
- * @param anOrder
- * @param aLimit
- * @param anOffset
- * @return
- */
- static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) {
+ public static List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition,
+ String aQualifier, String anOrder, int aLimit, int anOffset) {
+ return retrieveAdapterList(aModel, aDefinition, "", null, aQualifier, anOrder, aLimit, anOffset);
+ }
+
+ public static List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aMainTablePrefix, List someExtraTables,
+ String aQualifier, String anOrder, int aLimit, int anOffset) {
try {
- EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset);
+ EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getDatabase(),
+ aMainTablePrefix, someExtraTables, aQualifier, anOrder, 30, aLimit, anOffset);
return new EntityListAdapter(aModel, aDefinition, browser, aLimit);
}
catch (Throwable t) {
- throw new StorageObjectFailure(t);
+ throw new DatabaseFailure(t);
}
}
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.entity.adapter;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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 multex.Failure;
public class EntityAdapterFailure extends Failure {
- public EntityAdapterFailure(String msg,Throwable cause) {
- super(msg,cause);
+ public EntityAdapterFailure(String msg, Throwable cause) {
+ super(msg, cause);
}
public EntityAdapterFailure(Throwable aCause) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.util.Map;
import mir.entity.Entity;
-import mir.storage.StorageObject;
+import mir.storage.Database;
public class EntityAdapterModel {
private Map entityAdapterMappings;
entityAdapterMappings = new HashMap();
}
- public EntityAdapter makeEntityAdapter( String aName, Entity anEntity ) throws EntityAdapterExc {
+ public EntityAdapter makeEntityAdapter( String aName, Entity anEntity ) {
Mapping mapping = getMappingForName( aName );
return mapping.getDefinition().makeEntityAdapter( anEntity, this );
public EntityAdapter createNewEntity( String aName ) throws EntityAdapterExc {
try {
Mapping mapping = getMappingForName(aName);
- StorageObject storage = mapping.storage;
- Entity entity = (Entity) storage.getEntityClass().newInstance();
- entity.setStorage(storage);
+ Entity entity = mapping.database.createNewEntity();
return mapping.getDefinition().makeEntityAdapter(entity, this);
}
}
}
- public void addMapping( String aName, StorageObject aStorage, EntityAdapterDefinition aDefinition ) {
- entityAdapterMappings.put( aName, new Mapping( aStorage, aDefinition ) );
+ public void addMapping(String aName, Database aDatabase, EntityAdapterDefinition aDefinition ) {
+ entityAdapterMappings.put(aName, new Mapping(aDatabase, aDefinition));
}
- public Mapping getMappingForName( String aName ) throws EntityAdapterExc {
+ public Mapping getMappingForName( String aName ) {
if (!entityAdapterMappings.containsKey(aName))
- throw new EntityAdapterExc( "'" + aName + "' not present in model" );
+ throw new EntityAdapterFailure("'" + aName + "' not present in model", null);
return (Mapping) entityAdapterMappings.get( aName );
}
public class Mapping {
- private StorageObject storage;
+ private Database database;
private EntityAdapterDefinition definition;
- public Mapping( StorageObject aStorage, EntityAdapterDefinition aDefinition ) {
- storage = aStorage;
+ public Mapping(Database aDatabase, EntityAdapterDefinition aDefinition ) {
+ database = aDatabase;
definition = aDefinition;
}
- public StorageObject getStorage() {
- return storage;
+ public Database getDatabase() {
+ return database;
}
public EntityAdapterDefinition getDefinition() {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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 mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mir.util.RewindableIterator;
public class EntityIteratorAdapter implements RewindableIterator {
public EntityIteratorAdapter(String aWhereClause, String anOrderByClause,
int aBatchSize, EntityAdapterModel aModel, String aDefinitionName )
- throws StorageObjectFailure, EntityAdapterExc {
- this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getStorage(), aWhereClause, anOrderByClause, aBatchSize), aModel, aDefinitionName);
+ throws DatabaseFailure {
+ this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aWhereClause, anOrderByClause, aBatchSize), aModel, aDefinitionName);
}
public EntityIteratorAdapter(String aWhereClause, String anOrderByClause,
int aBatchSize, EntityAdapterModel aModel, String aDefinitionName,
- int aLimit, int aSkip) throws StorageObjectFailure, EntityAdapterExc {
- this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getStorage(), aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName);
+ int aLimit, int aSkip) throws DatabaseFailure {
+ this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName);
}
public EntityIteratorAdapter(String aMainTablePrefix, List someExtraTables,
String aWhereClause, String anOrderByClause,
int aBatchSize, EntityAdapterModel aModel, String aDefinitionName,
- int aLimit, int aSkip) throws StorageObjectFailure, EntityAdapterExc {
- this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getStorage(), aMainTablePrefix, someExtraTables, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName);
+ int aLimit, int aSkip) throws DatabaseFailure {
+ this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aMainTablePrefix, someExtraTables, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName);
}
}
public Object next() {
- try {
- return model.makeEntityAdapter(definitionName, (Entity) iterator.next());
- }
- catch (EntityAdapterExc e) {
- return null;
- }
+ return model.makeEntityAdapter(definitionName, (Entity) iterator.next());
}
public void remove() {
public void rewind() {
iterator.rewind();
- };
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.
*/
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.entity.adapter;\r
+\r
+public class ToManyRelationField implements EntityAdapterDefinition.CalculatedField{\r
+ private String fromField;\r
+ private String toField;\r
+ private String toEntity;\r
+ private String orderByField;\r
+\r
+ public ToManyRelationField(String aFromField, String aToEntity, String aToField, String anOrderByField) {\r
+ fromField = aFromField;\r
+ toField = aToField;\r
+ toEntity = aToEntity;\r
+ orderByField = anOrderByField;\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return anEntityAdapter.getRelation(\r
+ toField + "=" + anEntityAdapter.get(fromField),\r
+ orderByField,\r
+ toEntity);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.entity.adapter;\r
+\r
+public class ToOneRelationField implements EntityAdapterDefinition.CalculatedField{\r
+ private String fromField;\r
+ private String toField;\r
+ private String toEntity;\r
+\r
+ public ToOneRelationField(String aFromField, String aToEntity, String aToField) {\r
+ fromField = aFromField;\r
+ toField = aToField;\r
+ toEntity = aToEntity;\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ if (anEntityAdapter.get(fromField)==null) {\r
+ return null;\r
+ }\r
+ \r
+ return anEntityAdapter.getToOneRelation(\r
+ toField + "=" + anEntityAdapter.get(fromField),\r
+ toField,\r
+ toEntity);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+}\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
generatorLibraries.put(aQualifier, aLibrary);
}
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
+ public Generator makeGenerator(String anIdentifier, Generator.Interceptor anInterceptor) throws GeneratorExc, GeneratorFailure {
String qualifier;
String libraryName;
int position;
if (library==null)
throw new GeneratorExc("CompositeGeneratorLibrary: library '"+libraryName+"' not found");
- return library.makeGenerator(qualifier);
+ return library.makeGenerator(qualifier, anInterceptor);
}
- else {
- if (defaultLibrary!=null)
- return defaultLibrary.makeGenerator(anIdentifier);
- else
- throw new GeneratorExc("CompositeGeneratorLibrary: no default library speficied");
- }
- };
+ if (defaultLibrary!=null)
+ return defaultLibrary.makeGenerator(anIdentifier, anInterceptor);
+ throw new GeneratorExc("CompositeGeneratorLibrary: no default library speficied");
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
-import java.io.PrintWriter;
import java.io.File;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Collection;
+
+import mir.log.LoggerWrapper;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.RewindableIterator;
+
+import org.apache.commons.beanutils.MethodUtils;
+import org.apache.commons.beanutils.PropertyUtils;
import freemarker.template.FileTemplateCache;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateModelRoot;
import freemarker.template.TemplateScalarModel;
-import mir.log.LoggerWrapper;
-import mir.util.GeneratorFormatAdapters;
-import mir.util.RewindableIterator;
-import org.apache.commons.beanutils.MethodUtils;
-import org.apache.commons.beanutils.PropertyUtils;
public class FreemarkerGenerator implements Generator {
private Template template;
+ private Interceptor interceptor;
- public FreemarkerGenerator(Template aTemplate) {
+ public FreemarkerGenerator(Template aTemplate, Interceptor anInterceptor) {
template = aTemplate;
+ interceptor = anInterceptor;
}
public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {
- if (!(anOutputWriter instanceof PrintWriter))
+ if (!(anOutputWriter instanceof PrintWriter)) {
throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");
+ }
try {
template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);
}
catch (Throwable t) {
- t.printStackTrace();
- aLogger.error("Exception occurred: "+t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- throw new GeneratorFailure( t );
+ aLogger.error("Exception occurred: "+t.getMessage(), t);
+
+ throw new GeneratorFailure(t);
}
}
return new SimpleScalar(aString);
}
- private static TemplateHashModel makeMapAdapter(Map aMap) {
+ private TemplateHashModel makeMapAdapter(Map aMap) {
return new MapAdapter(aMap);
}
- private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {
+ private TemplateListModel makeIteratorAdapter(Iterator anIterator) {
return new IteratorAdapter(anIterator);
}
- private static TemplateMethodModel makeFunctionAdapter(Generator.Function aFunction) {
+ private TemplateMethodModel makeFunctionAdapter(Generator.Function aFunction) {
return new FunctionAdapter(aFunction);
}
- private static TemplateHashModel makeBeanAdapter(Object anObject) {
+ private TemplateHashModel makeBeanAdapter(Object anObject) {
return new BeanAdapter(anObject);
}
- public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {
- if (anObject == null)
- return null;
+ public TemplateModel makeAdapter(Object anObject) throws TemplateModelException {
+ Object object = anObject;
+ if (interceptor != null) {
+ object = interceptor.intercept(object);
+ }
- if (anObject instanceof TemplateModel)
- return (TemplateModel) anObject;
- else if (anObject instanceof Generator.Function)
- return makeFunctionAdapter((Generator.Function) anObject);
- else if (anObject instanceof Integer)
- return makeStringAdapter(anObject.toString());
- else if (anObject instanceof Boolean) {
- if (((Boolean) anObject).booleanValue())
+ if (object == null) {
+ return null;
+ }
+ if (object instanceof TemplateModel) {
+ return (TemplateModel) object;
+ }
+ else if (object instanceof Generator.Function) {
+ return makeFunctionAdapter((Generator.Function) object);
+ }
+ else if (object instanceof Integer) {
+ return makeStringAdapter(object.toString());
+ }
+ else if (object instanceof Boolean) {
+ if (((Boolean) object).booleanValue()) {
return makeStringAdapter("1");
- else
+ }
+ else {
return makeStringAdapter("0");
+ }
+ }
+ else if (object instanceof String) {
+ return makeStringAdapter((String) object);
+ }
+ else if (object instanceof Map) {
+ return makeMapAdapter((Map) object);
+ }
+ else if (object instanceof Iterator) {
+ return makeIteratorAdapter((Iterator) object);
+ }
+ else if (object instanceof Collection) {
+ return makeIteratorAdapter(((Collection) object).iterator());
+ }
+ else if (object instanceof Number) {
+ return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) object));
+ }
+ else if (object instanceof Date) {
+ return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) object));
+ }
+ else {
+ return makeBeanAdapter(object);
}
- else if (anObject instanceof String)
- return makeStringAdapter((String) anObject);
- else if (anObject instanceof Map)
- return makeMapAdapter((Map) anObject);
- else if (anObject instanceof Iterator)
- return makeIteratorAdapter((Iterator) anObject);
- else if (anObject instanceof List)
- return makeIteratorAdapter(((List) anObject).iterator());
- else if (anObject instanceof Number)
- return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject));
- else if (anObject instanceof Date)
- return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) anObject));
- else
- return makeBeanAdapter(anObject);
}
- private static class MapAdapter implements TemplateModelRoot {
+ private class MapAdapter implements TemplateModelRoot {
private Map map;
private Map valuesCache;
}
}
- private static class IteratorAdapter implements TemplateListModel {
+ private class IteratorAdapter implements TemplateListModel {
private Iterator iterator;
private List valuesCache;
private int position;
{
valuesCache.add(makeAdapter(iterator.next()));
}
- };
+ }
public TemplateModel get(int anIndex) throws TemplateModelException {
- TemplateModel result;
-
getUntil(anIndex);
- if (anIndex<valuesCache.size())
- {
- result = (TemplateModel) valuesCache.get(anIndex);
-
- return result;
+ if (anIndex<valuesCache.size()) {
+ return (TemplateModel) valuesCache.get(anIndex);
}
- else
- throw new TemplateModelException( "Iterator out of bounds" );
+ throw new TemplateModelException( "Iterator out of bounds" );
}
public boolean hasNext() {
}
}
- private static class ListAdapter implements TemplateListModel {
- List list;
- List valuesCache;
- int position;
-
- private ListAdapter(List aList) {
- list = aList;
- valuesCache = new ArrayList();
- position=0;
- }
-
- public boolean isEmpty() {
- return list.isEmpty();
- }
-
- public TemplateModel get(int i) throws TemplateModelException {
-
- if (i>=valuesCache.size() && i<list.size()) {
- for(int j=valuesCache.size(); j<=i; j++) {
- valuesCache.add(makeAdapter(list.get(j)));
- }
- }
-
- if (i<valuesCache.size())
- return (TemplateModel) valuesCache.get(i);
- else
- throw new TemplateModelException( "Iterator out of bounds" );
- }
-
- public boolean hasNext() {
- return position<list.size();
- }
-
- public boolean isRewound() {
- return position==0;
- }
-
- public TemplateModel next() throws TemplateModelException {
- TemplateModel result;
-
- if (hasNext()) {
- result = get(position);
- position++;
- }
- else {
- throw new TemplateModelException( "Iterator out of bounds" );
- }
-
- return result;
- }
-
- public void rewind() {
- position = 0;
- }
- }
-
- private static class FunctionAdapter implements TemplateMethodModel {
+ private class FunctionAdapter implements TemplateMethodModel {
private Generator.Function function;
- public FunctionAdapter(Generator.Function aFunction) {
+ FunctionAdapter(Generator.Function aFunction) {
function = aFunction;
}
}
- private static class BeanAdapter implements TemplateHashModel {
+ private class BeanAdapter implements TemplateHashModel {
private Object object;
public BeanAdapter(Object anObject) {
public TemplateModel get(String aKey) throws TemplateModelException {
try {
- if (PropertyUtils.isReadable(object, aKey))
+ if (PropertyUtils.isReadable(object, aKey)) {
return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));
- else
- return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));
+ }
+ return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));
}
catch (Throwable t) {
throw new TemplateModelException(t.getMessage());
templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);
}
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
+ public Generator makeGenerator(String anIdentifier, Interceptor anInterceptor) throws GeneratorExc, GeneratorFailure {
Template template = (Template) templateCache.getItem(anIdentifier, "template");
if (template==null) {
- throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+"/"+anIdentifier);
+ throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template " +
+ templateCache.getDirectory() + File.separatorChar + anIdentifier);
}
- return new FreemarkerGenerator(template);
+ return new FreemarkerGenerator(template, anInterceptor);
}
+
}
public static class FreemarkerGeneratorLibraryFactory implements LibraryFactory {
public Library makeLibrary(String anInitializationString) {
// todo: the initialization string should be parsed
return new FreemarkerGeneratorLibrary(new File(basePath, anInitializationString));
- };
+ }
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
-import java.io.PrintWriter;
-import java.io.Reader;
+import mir.log.LoggerWrapper;
+
import java.util.List;
import java.util.Map;
-import mir.log.LoggerWrapper;
-
/**
- * Interface representing a "generator", typically a template engine/
+ * A "generator" is an abstraction for a template
+ * If you need a generator, use MirGeneratorLocalizer
*/
public interface Generator {
- public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure;
+ /** This is the method that actually runs the template engine on this template
+ * @param anOutputWriter a writer to the file we want to generate, use the
+ * MirGeneratorLocalizer to create a writer.
+ * @param aValues the key/value pairs which the template engine will use as variables
+ */
+ void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure;
+
+ interface Library {
+ Generator makeGenerator(String anIdentifier, Interceptor anInterceptor) throws GeneratorExc, GeneratorFailure;
+ }
- public static interface Library {
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure;
+ interface LibraryFactory {
+ Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure ;
}
- public static interface LibraryFactory {
- public Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure ;
+ interface Interceptor {
+ Object intercept(Object anObject);
}
/** interface for a generator implementation independent function */
- public static interface Function {
+ interface Function {
/** performs the function with the given parameters */
- public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure;
- }
-
- public static interface Transformer {
- public void perform(Reader aSource, PrintWriter anOutput) throws GeneratorExc, GeneratorFailure;
+ Object perform(List aParameters) throws GeneratorExc, GeneratorFailure;
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.List;
-
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.util.CachingRewindableIterator;
import mir.bundle.Bundle;
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.entity.adapter.EntityAdapterModel;
import mir.util.generator.BundleGeneratorFunction;
import mircoders.global.MirGlobal;
+import java.util.*;
+
public class GeneratorHelper {
* Method to initialize the basic generation values for templates. Does nothing which assumes a servlet context.
*/
- public static Map makeBasicGenerationData(Locale[] aLocales, String aBundle, String aDefaultBundle) throws GeneratorExc{
+ public static Map makeBasicGenerationData(Locale[] aLocales, String aBundle, String aDefaultBundle) throws GeneratorExc {
try {
Map result = new HashMap();
MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result);
- Object languages = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "language"));
+ EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
+
+ List languages = EntityAdapterEngine.retrieveAdapterList(model, "language", "", "id", -1, 0);
- Object topics = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+ List topics = EntityAdapterEngine.retrieveAdapterList(model, "topic", "", "id", -1, 0);
- Object articleTypes = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "articleType"));
+ List articleTypes = EntityAdapterEngine.retrieveAdapterList(model, "articleType", "", "id", -1, 0);
- Object commentStatuses = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"));
+ List commentStatuses = EntityAdapterEngine.retrieveAdapterList(model, "commentStatus", "", "id", -1, 0);
result.put("commentstatuses", commentStatuses);
result.put("articletypes", articleTypes);
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
import java.util.HashMap;
import java.util.Map;
+import java.util.Arrays;
import mir.log.LoggerWrapper;
import mir.util.SimpleParser;
parser.skip(SPACE);
if (!parser.isAtEnd()) {
- parser.parse(SEMICOLON, "; expected");
+ parser.parse(SEMICOLON, "';' expected");
}
}
}
catch (Exception e) {
- throw new GeneratorFailure("Failed to construct generator library: " + e.getMessage(), e);
+ logger.error("Failed to parse generator library expression " +
+ Arrays.asList(aSpecification).toString(), e);
+
+ throw new GeneratorFailure("Failed to parse generator library expression " +
+ Arrays.asList(aSpecification).toString(), e);
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
-import java.io.PrintWriter;
import java.io.File;
+import java.io.PrintWriter;
import java.util.Map;
import mir.generator.tal.MirExpressionParser;
-import mir.generator.tal.template.Template;
import mir.generator.tal.TALTemplateEngine;
import mir.generator.tal.interfaces.TALLogger;
+import mir.generator.tal.template.Template;
import mir.log.LoggerWrapper;
public class TALGenerator implements Generator {
private String templateIdentifier;
private TALGeneratorLibrary library;
+ private Interceptor interceptor;
- public TALGenerator(String aTemplate, TALGeneratorLibrary aLibrary) {
+ public TALGenerator(String aTemplate, TALGeneratorLibrary aLibrary, Interceptor anInterceptor) {
templateIdentifier = aTemplate;
library = aLibrary;
+ interceptor = anInterceptor;
}
public void generate(Object anOutputWriter, Map aValues, final LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {
engine = new TALTemplateEngine(new MirExpressionParser(), aTemplateRoot);
}
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
- return new TALGenerator(anIdentifier, this);
+ public Generator makeGenerator(String anIdentifier, Interceptor anInterceptor) throws GeneratorExc, GeneratorFailure {
+ return new TALGenerator(anIdentifier, this, anInterceptor);
}
}
public Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure {
return new TALGeneratorLibrary(new File(basePath, anInitializationString));
- };
+ }
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
+import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
-import java.io.File;
import java.util.AbstractList;
+import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
+
+import mir.log.LoggerWrapper;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.RewindableIterator;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.LogSystem;
-import mir.log.LoggerWrapper;
-import mir.util.GeneratorFormatAdapters;
-import mir.util.RewindableIterator;
public class VelocityGenerator implements Generator {
private String templateIdentifier;
private VelocityGeneratorLibrary library;
private static LoggerWrapper logger = new LoggerWrapper("Generator.velocity");
+ private Interceptor interceptor;
/**
*
* @param aLibrary
*/
- public VelocityGenerator(String aTemplate, VelocityGeneratorLibrary aLibrary) {
+ public VelocityGenerator(String aTemplate, VelocityGeneratorLibrary aLibrary, Interceptor anInterceptor) {
templateIdentifier = aTemplate;
library = aLibrary;
+ interceptor = anInterceptor;
}
/**
if (anObject instanceof VelocityAdapter) {
return ((VelocityAdapter) anObject).getOriginal();
}
- else
- return anObject;
+ return anObject;
}
/**
}
public Object call(Object aParameters[]) throws GeneratorExc {
- List parameters = new Vector();
+ List parameters = new ArrayList();
for (int i = 0; i<aParameters.length; i++) {
parameters.add(unmakeAdapter(aParameters[i]));
}
public Object call() throws GeneratorExc {
- return makeAdapter(function.perform(new Vector()));
+ return makeAdapter(function.perform(new ArrayList()));
}
public Object call(Object anObject) throws GeneratorExc {
private IteratorAdapter(Iterator anIterator) {
iterator = anIterator;
- valuesCache = new Vector();
+ valuesCache = new ArrayList();
if (iterator instanceof RewindableIterator) {
((RewindableIterator) iterator).rewind();
{
valuesCache.add(makeAdapter(iterator.next()));
}
- };
+ }
public Object getOriginal() {
return iterator;
return result;
}
- else
- throw new RuntimeException( "Iterator out of bounds" );
+ throw new RuntimeException( "Iterator out of bounds" );
}
public int size() {
private ListAdapter(List aList) {
list = aList;
- valuesCache = new Vector();
+ valuesCache = new ArrayList();
}
private void getUntil(int anIndex) {
{
valuesCache.add(makeAdapter(list.get(valuesCache.size())));
}
- };
+ }
public Object getOriginal() {
return list;
return result;
}
- else
- throw new RuntimeException( "Iterator out of bounds" );
+ throw new RuntimeException( "Iterator out of bounds" );
}
public int size() {
* @version 1.0
*/
private static class VelocityLoggerWrapper implements LogSystem {
- private LoggerWrapper logger;
-
+
public VelocityLoggerWrapper(LoggerWrapper aLogger) {
logger = aLogger;
}
engine.init();
}
catch (Throwable t) {
- t.printStackTrace(logger.asPrintWriter(logger.ERROR_MESSAGE));
-
logger.error("Failed to set up a VelocityGeneratorLibrary: " + t.toString());
throw new GeneratorFailure(t);
}
}
- public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
- return new VelocityGenerator(anIdentifier, this);
+ public Generator makeGenerator(String anIdentifier, Interceptor anInterceptor) throws GeneratorExc, GeneratorFailure {
+ return new VelocityGenerator(anIdentifier, this, anInterceptor);
}
}
public Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure {
return new VelocityGeneratorLibrary(new File(basePath, anInitializationString));
- };
+ }
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator;
/**
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2002</p>
- * <p>Company: </p>
- * @author unascribed
- * @version 1.0
+ * <p>A WriterEngine creates a java PrinterWriter object for writing
+ * formated output to a file. The openWriter method creates a Writer
+ * given a filename and an encoding. The closeWriter method closes
+ * the writer.</p>
+ *
+ * <p> This interface allows customization via the
+ * MirGeneratorLocalizer.makeWriterEngine() method. The created writer is
+ * used for
+ * specifying where the output of a Generator should go.</p>
*/
-
public interface WriterEngine {
public Object openWriter(String anIdentifier, String aParameter) throws GeneratorExc, GeneratorFailure;
public void closeWriter(Object aWriter) throws GeneratorExc, GeneratorFailure;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal;
import java.io.BufferedInputStream;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal;
import java.util.Iterator;
import java.util.Map;
import mir.generator.tal.interfaces.TALExpressionParser;
+import mir.generator.Generator;
import mir.util.ParameterExpander;
import mir.util.RewindableIterator;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal;
-import java.util.Map;
import java.util.HashMap;
+import java.util.Map;
-import mir.generator.tal.template.TemplateNodeLibraryRegistry;
import mir.generator.tal.template.TemplateNodeLibrary;
+import mir.generator.tal.template.TemplateNodeLibraryRegistry;
public class SimpleTemplateNodeLibraryRegistry implements TemplateNodeLibraryRegistry {
private Map urlToLibrary;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
-import java.util.Map;
import java.util.List;
+import java.util.Map;
import mir.generator.tal.interfaces.TALExpressionParser;
-import mir.generator.tal.template.*;
+import mir.generator.tal.template.CoreTemplateNodeLibrary;
+import mir.generator.tal.template.MacroTemplateNodeLibrary;
+import mir.generator.tal.template.Template;
+import mir.generator.tal.template.TemplateLibrary;
+import mir.generator.tal.template.TemplateNode;
+import mir.generator.tal.template.TemplateNodeLibrary;
+import mir.generator.tal.template.TemplateProcessingException;
import mir.util.StringRoutines;
public class TALTemplateEngine implements TemplateLibrary {
return new Template(expressionParser, (TemplateNode) definitions.get(parts.get(1)), baseTemplate.getContext());
}
- else {
- return baseTemplate;
- }
-
-
-
-// public Template(TALExpressionParser aParser, TemplateNode aRootNode, Map aTemplateContext) {
+ return baseTemplate;
}
public Template lookupTemplate(String aName) throws TemplateProcessingException {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import java.util.HashMap;
import mir.generator.tal.interfaces.TALExpressionParser;
import mir.generator.tal.template.CompositeTemplateNode;
import mir.generator.tal.template.PlainTextTemplateNode;
import mir.generator.tal.template.Template;
-import mir.generator.tal.template.TemplateNodeLibrary;
import mir.generator.tal.template.TemplateNode;
+import mir.generator.tal.template.TemplateNodeLibrary;
import mir.generator.tal.template.TemplateNodeLibraryRegistry;
import mir.util.HTMLRoutines;
import mir.util.xml.SectionHandler;
}
return new TALHandler(parser, templateContext);
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (library == null) {
tag = null;
attributes = null;
}
- };
+ }
protected void appendSubNode(TemplateNode aNode) {
flushData();
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal;
-import java.io.PrintWriter;
import java.io.File;
+import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import mir.generator.tal.interfaces.TALLogger;
+import mir.generator.tal.template.CoreTemplateNodeLibrary;
+import mir.generator.tal.template.MacroTemplateNodeLibrary;
import mir.generator.tal.template.Template;
import mir.generator.tal.template.TemplateLibrary;
import mir.generator.tal.template.TemplateProcessingException;
-import mir.generator.tal.template.CoreTemplateNodeLibrary;
-import mir.generator.tal.template.MacroTemplateNodeLibrary;
public class TALTest {
public static void main(String args[]) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal.interfaces;
import java.util.Iterator;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal.interfaces;
public interface TALLogger {
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2005 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
* exception to your version of the file, but you are not obligated to do so.\r
* If you do not wish to do so, delete this exception statement from your version.\r
*/\r
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mir.generator.tal.template;\r
-\r
-import java.util.*;\r
-\r
-import mir.generator.tal.interfaces.TALExpressionParser;\r
-import mir.generator.tal.interfaces.TALLogger;\r
-import mir.util.HTMLRoutines;\r
-import mir.util.StringRoutines;\r
-import mir.util.xml.XMLName;\r
-import mir.util.xml.XMLParserExc;\r
-import mir.util.xml.XMLReaderTool;\r
-\r
-public class CoreTemplateNodeLibrary implements TemplateNodeLibrary {\r
- private String prefix;\r
- private String uri;\r
-\r
- private boolean isOurTag(XMLName aName) {\r
- return prefix.equals(aName.getPrefix()) || uri.equals(aName.getNamespaceURI());\r
- }\r
-\r
- public CoreTemplateNodeLibrary(String aPrefix, String aUri) {\r
- prefix = aPrefix;\r
- uri = aUri;\r
- }\r
-\r
- private static final String CONDITION_ATTRIBUTE = "condition";\r
- private static final String REPEAT_ATTRIBUTE = "repeat";\r
- private static final String CONTENT_ATTRIBUTE = "content";\r
- private static final String ERROR_ATTRIBUTE = "on-error";\r
- private static final String REPLACE_ATTRIBUTE = "replace";\r
- private static final String DEFINITION_ATTRIBUTE = "define";\r
- private static final String OMITTAG_ATTRIBUTE = "omit-tag";\r
- private static final String ATTRIBUTE_ATTRIBUTE = "attributes";\r
-\r
- public TemplateNode constructTemplateNode(TALExpressionParser aParser, XMLName aTag, Map anAttributes,\r
- TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc {\r
- TALBasicTemplateNode result = new TALBasicTemplateNode(XMLReaderTool.normalizeXMLName(aTag));\r
- result.setBody(aChildTemplateNode);\r
-\r
- if (isOurTag(aTag))\r
- result.setOmitTag(aParser.preparseTRUE());\r
-\r
- Iterator i = anAttributes.entrySet().iterator();\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
- XMLName name = (XMLName) entry.getKey();\r
-\r
- if (!isOurTag(name)) {\r
- result.addFixedAttribute(XMLReaderTool.normalizeXMLName(name), (String) entry.getValue());\r
- }\r
- else {\r
- if (name.getLocalName().equalsIgnoreCase(DEFINITION_ATTRIBUTE)) {\r
- List definitions = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\');\r
-\r
- Iterator j = definitions.iterator();\r
- while (j.hasNext())\r
- {\r
- List parts = StringRoutines.separateString((String) j.next(), " ");\r
-\r
- if (parts.size()==2) {\r
- result.addDefinition(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1)));\r
- }\r
- }\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(CONDITION_ATTRIBUTE)) {\r
- result.setCondition(aParser.preparseBooleanExpression((String) entry.getValue()));\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(CONTENT_ATTRIBUTE)) {\r
- result.setContent(aParser.preparseStringExpression((String) entry.getValue()));\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(ERROR_ATTRIBUTE)) {\r
- result.setError(aParser.preparseStringExpression((String) entry.getValue()));\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(OMITTAG_ATTRIBUTE)) {\r
- if (((String) entry.getValue()).trim().length()==0)\r
- result.setOmitTag(aParser.preparseTRUE());\r
- else\r
- result.setOmitTag(aParser.preparseBooleanExpression((String) entry.getValue()));\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(REPLACE_ATTRIBUTE)) {\r
- result.setOmitTag(aParser.preparseTRUE());\r
- result.setContent(aParser.preparseStringExpression((String) entry.getValue()));\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(REPEAT_ATTRIBUTE)) {\r
- List parts = StringRoutines.separateString((String) entry.getValue(), " ");\r
-\r
- if (parts.size()==2) {\r
- result.setRepeat(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1)));\r
- }\r
- }\r
- else if (name.getLocalName().equalsIgnoreCase(ATTRIBUTE_ATTRIBUTE)) {\r
- List attributes = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\');\r
-\r
- Iterator j = attributes.iterator();\r
- while (j.hasNext()) {\r
- String value = (String) j.next();\r
- List parts = StringRoutines.separateString(value.trim(), " ");\r
-\r
- if (parts.size()==2) {\r
- result.addModifiedAttribute((String) parts.get(0), aParser.preparseExpression((String) parts.get(1)));\r
- }\r
- else {\r
- throw new XMLParserExc(ATTRIBUTE_ATTRIBUTE + " tag should have exactly 2 parts ("+value+")");\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- return result;\r
- }\r
-\r
- public static class TALBasicTemplateNode implements TemplateNode {\r
- private String tag;\r
- private Map fixedAttributes;\r
- private Map attributeModifiers;\r
-\r
- private List definitions;\r
- private Object condition;\r
-\r
- private Object repeatVariable;\r
- private Object repeatExpression;\r
- private Object contentExpression;\r
- private Object omitTagExpression;\r
- private Object errorExpression;\r
-\r
- private TemplateNode body;\r
-\r
- public TALBasicTemplateNode(String aTag) {\r
- tag = aTag;\r
-\r
- fixedAttributes = new HashMap();\r
- attributeModifiers = new HashMap();\r
-\r
- definitions = new ArrayList();\r
- condition = null;\r
-\r
- repeatVariable = null;\r
- repeatExpression = null;\r
- contentExpression = null;\r
- omitTagExpression = null;\r
-\r
- body = null;\r
- }\r
-\r
- public void setBody(TemplateNode aBody) {\r
- body = aBody;\r
- }\r
-\r
- public void addFixedAttribute(String aKey, String aValue) {\r
- fixedAttributes.put(aKey, aValue);\r
- }\r
-\r
- public void addModifiedAttribute(String aKey, Object aValue) {\r
- attributeModifiers.put(aKey, aValue);\r
- }\r
-\r
- public void addDefinition(Object aKey, Object aValue) {\r
- definitions.add(new Definition(aKey, aValue));\r
- }\r
-\r
- public void setCondition(Object aCondition) {\r
- condition = aCondition;\r
- }\r
-\r
- public void setRepeat(Object aRepeatVariable, Object aRepeatExpression) {\r
- repeatVariable = aRepeatVariable;\r
- repeatExpression = aRepeatExpression;\r
- }\r
-\r
- public void setContent(Object aContentExpression) {\r
- contentExpression = aContentExpression;\r
- }\r
-\r
- public void setOmitTag(Object anOmitTagExpression) {\r
- omitTagExpression = anOmitTagExpression;\r
- }\r
-\r
- public void setError(Object anErrorExpression) {\r
- errorExpression = anErrorExpression;\r
- }\r
-\r
- public static class Definition {\r
- private Object variable;\r
- private Object expression;\r
-\r
- public Definition(Object aVariable, Object anExpression) {\r
- variable = aVariable;\r
- expression = anExpression;\r
- }\r
-\r
- public Object getVariable() {\r
- return variable;\r
- }\r
-\r
- public Object getExpression() {\r
- return expression;\r
- }\r
- }\r
-\r
- public void process(TALExpressionParser aParser, Object aContext,\r
- StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext,\r
- TemplateLibrary aLibrary) throws TemplateProcessingException {\r
- if (errorExpression != null) {\r
- StringBuffer destination = new StringBuffer();\r
-\r
- try {\r
- outerProcess(aParser, aContext, destination, aLogger, aTemplateContext, aLibrary);\r
- }\r
- catch (Throwable t) {\r
- try {\r
-// destination.delete(0, destination.length());\r
- aParser.processPseudoAssignment(aContext, "exception", t);\r
- destination.insert(0, aParser.evaluateStringExpression(aContext, errorExpression));\r
- destination.append(" >>>ERROR POSITION<<< ");\r
- }\r
- catch (Throwable s) {\r
- throw new TemplateProcessingException(s);\r
- }\r
- }\r
- finally {\r
- aDestination.append(destination);\r
- }\r
- }\r
- else {\r
- outerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);\r
- }\r
- }\r
-\r
- public String getPlainText() {\r
- return body.getPlainText();\r
- }\r
-\r
- public void outerProcess(TALExpressionParser aParser, Object aContext,\r
- StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext,\r
- TemplateLibrary aLibrary) throws TemplateProcessingException {\r
-\r
- Object oldAttributes = aParser.evaluatePseudoVariable(aContext, "tagattributes");\r
- aParser.processPseudoAssignment(aContext, "tagattributes", Collections.unmodifiableMap(fixedAttributes));\r
-\r
- Object oldContent = aParser.evaluatePseudoVariable(aContext, "tagcontent");\r
- aParser.processPseudoAssignment(aContext, "tagcontent", body.getPlainText());\r
-\r
- try {\r
- Iterator i;\r
-\r
- i = definitions.iterator();\r
- while (i.hasNext()) {\r
- Definition d = (Definition) i.next();\r
- aParser.processAssignment(aContext, d.getVariable(), d.getExpression());\r
- }\r
-\r
- if (condition == null || aParser.evaluateBooleanExpression(aContext, condition)) {\r
- if (repeatExpression != null) {\r
- i = aParser.evaluateListExpression(aContext, repeatExpression);\r
-\r
- while (i.hasNext()) {\r
- aParser.processDirectAssignment(aContext, repeatVariable, i.next());\r
- innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);\r
- }\r
- }\r
- else {\r
- innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);\r
- }\r
- }\r
- }\r
- finally {\r
- try {\r
- aParser.processPseudoAssignment(aContext, "tagattributes", oldAttributes);\r
- aParser.processPseudoAssignment(aContext, "tagcontent", oldContent);\r
- }\r
- catch (Throwable t) {\r
- }\r
- }\r
- };\r
-\r
- private void innerProcess(TALExpressionParser aParser, Object aContext,\r
- StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext, TemplateLibrary aLibrary)\r
- throws TemplateProcessingException {\r
-\r
- boolean omitTag = false;\r
- StringBuffer content = aDestination;\r
-\r
- if (omitTagExpression != null)\r
- omitTag = aParser.evaluateBooleanExpression(aContext, omitTagExpression);\r
-\r
- if (!omitTag) {\r
- content = new StringBuffer();\r
- Map generatedAttributes = new HashMap(fixedAttributes);\r
-\r
- Iterator i = attributeModifiers.entrySet().iterator();\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
-\r
- generatedAttributes.put(entry.getKey(), aParser.evaluateStringExpression(aContext, entry.getValue()));\r
- }\r
-\r
- aDestination.append("<");\r
- aDestination.append(tag);\r
-\r
- i = generatedAttributes.entrySet().iterator();\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
- aDestination.append(" ");\r
- aDestination.append(entry.getKey());\r
- aDestination.append("=");\r
- aDestination.append("\"");\r
- aDestination.append(HTMLRoutines.encodeHTML( (String) entry.getValue()));\r
- aDestination.append("\"");\r
- }\r
- }\r
-\r
- try{\r
- if (contentExpression != null) {\r
- content.append(aParser.evaluateStringExpression(aContext, contentExpression));\r
- }\r
- else {\r
- if (body != null) {\r
- body.process(aParser, aContext, content, aLogger, aTemplateContext, aLibrary);\r
- }\r
- }\r
- if (!omitTag) {\r
- if (content.length()==0) {\r
- aDestination.append(" />");\r
- }\r
- else {\r
- aDestination.append(">");\r
- aDestination.append(content);\r
- aDestination.append("</");\r
- aDestination.append(tag);\r
- aDestination.append(">");\r
- }\r
- }\r
- }\r
- catch (Throwable t) {\r
- if (!omitTag) {\r
- aDestination.append(content);\r
- }\r
-\r
- if (t instanceof TemplateProcessingException) {\r
- throw (TemplateProcessingException) t;\r
- }\r
- else if (t instanceof RuntimeException) {\r
- throw (RuntimeException) t;\r
- }\r
- else throw new TemplateProcessingException(t.toString());\r
- }\r
- }\r
- }\r
-}\r
+/*
+ * Copyright (C) 2005 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 any library licensed under the Apache Software License.
+ * 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.generator.tal.template;
+
+import mir.generator.tal.interfaces.TALExpressionParser;
+import mir.generator.tal.interfaces.TALLogger;
+import mir.util.HTMLRoutines;
+import mir.util.StringRoutines;
+import mir.util.xml.XMLName;
+import mir.util.xml.XMLParserExc;
+import mir.util.xml.XMLReaderTool;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class CoreTemplateNodeLibrary implements TemplateNodeLibrary {
+ private String prefix;
+ private String uri;
+
+ private boolean isOurTag(XMLName aName) {
+ return prefix.equals(aName.getPrefix()) || uri.equals(aName.getNamespaceURI());
+ }
+
+ public CoreTemplateNodeLibrary(String aPrefix, String aUri) {
+ prefix = aPrefix;
+ uri = aUri;
+ }
+
+ private static final String CONDITION_ATTRIBUTE = "condition";
+ private static final String REPEAT_ATTRIBUTE = "repeat";
+ private static final String CONTENT_ATTRIBUTE = "content";
+ private static final String ERROR_ATTRIBUTE = "on-error";
+ private static final String REPLACE_ATTRIBUTE = "replace";
+ private static final String DEFINITION_ATTRIBUTE = "define";
+ private static final String OMITTAG_ATTRIBUTE = "omit-tag";
+ private static final String ATTRIBUTE_ATTRIBUTE = "attributes";
+
+ public TemplateNode constructTemplateNode(TALExpressionParser aParser, XMLName aTag, Map anAttributes,
+ TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc {
+ TALBasicTemplateNode result = new TALBasicTemplateNode(XMLReaderTool.normalizeXMLName(aTag));
+ result.setBody(aChildTemplateNode);
+
+ if (isOurTag(aTag))
+ result.setOmitTag(aParser.preparseTRUE());
+
+ Iterator i = anAttributes.entrySet().iterator();
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry) i.next();
+ XMLName name = (XMLName) entry.getKey();
+
+ if (!isOurTag(name)) {
+ result.addFixedAttribute(XMLReaderTool.normalizeXMLName(name), (String) entry.getValue());
+ }
+ else {
+ if (name.getLocalName().equalsIgnoreCase(DEFINITION_ATTRIBUTE)) {
+ List definitions = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\');
+
+ Iterator j = definitions.iterator();
+ while (j.hasNext())
+ {
+ List parts = StringRoutines.separateString((String) j.next(), " ");
+
+ if (parts.size()==2) {
+ result.addDefinition(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1)));
+ }
+ }
+ }
+ else if (name.getLocalName().equalsIgnoreCase(CONDITION_ATTRIBUTE)) {
+ result.setCondition(aParser.preparseBooleanExpression((String) entry.getValue()));
+ }
+ else if (name.getLocalName().equalsIgnoreCase(CONTENT_ATTRIBUTE)) {
+ result.setContent(aParser.preparseStringExpression((String) entry.getValue()));
+ }
+ else if (name.getLocalName().equalsIgnoreCase(ERROR_ATTRIBUTE)) {
+ result.setError(aParser.preparseStringExpression((String) entry.getValue()));
+ }
+ else if (name.getLocalName().equalsIgnoreCase(OMITTAG_ATTRIBUTE)) {
+ if (((String) entry.getValue()).trim().length()==0)
+ result.setOmitTag(aParser.preparseTRUE());
+ else
+ result.setOmitTag(aParser.preparseBooleanExpression((String) entry.getValue()));
+ }
+ else if (name.getLocalName().equalsIgnoreCase(REPLACE_ATTRIBUTE)) {
+ result.setOmitTag(aParser.preparseTRUE());
+ result.setContent(aParser.preparseStringExpression((String) entry.getValue()));
+ }
+ else if (name.getLocalName().equalsIgnoreCase(REPEAT_ATTRIBUTE)) {
+ List parts = StringRoutines.separateString((String) entry.getValue(), " ");
+
+ if (parts.size()==2) {
+ result.setRepeat(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1)));
+ }
+ }
+ else if (name.getLocalName().equalsIgnoreCase(ATTRIBUTE_ATTRIBUTE)) {
+ List attributes = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\');
+
+ Iterator j = attributes.iterator();
+ while (j.hasNext()) {
+ String value = (String) j.next();
+ List parts = StringRoutines.separateString(value.trim(), " ");
+
+ if (parts.size()==2) {
+ result.addModifiedAttribute((String) parts.get(0), aParser.preparseExpression((String) parts.get(1)));
+ }
+ else {
+ throw new XMLParserExc(ATTRIBUTE_ATTRIBUTE + " tag should have exactly 2 parts ("+value+")");
+ }
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static class TALBasicTemplateNode implements TemplateNode {
+ private String tag;
+ private Map fixedAttributes;
+ private Map attributeModifiers;
+
+ private List definitions;
+ private Object condition;
+
+ private Object repeatVariable;
+ private Object repeatExpression;
+ private Object contentExpression;
+ private Object omitTagExpression;
+ private Object errorExpression;
+
+ private TemplateNode body;
+
+ public TALBasicTemplateNode(String aTag) {
+ tag = aTag;
+
+ fixedAttributes = new HashMap();
+ attributeModifiers = new HashMap();
+
+ definitions = new ArrayList();
+ condition = null;
+
+ repeatVariable = null;
+ repeatExpression = null;
+ contentExpression = null;
+ omitTagExpression = null;
+
+ body = null;
+ }
+
+ public void setBody(TemplateNode aBody) {
+ body = aBody;
+ }
+
+ public void addFixedAttribute(String aKey, String aValue) {
+ fixedAttributes.put(aKey, aValue);
+ }
+
+ public void addModifiedAttribute(String aKey, Object aValue) {
+ attributeModifiers.put(aKey, aValue);
+ }
+
+ public void addDefinition(Object aKey, Object aValue) {
+ definitions.add(new Definition(aKey, aValue));
+ }
+
+ public void setCondition(Object aCondition) {
+ condition = aCondition;
+ }
+
+ public void setRepeat(Object aRepeatVariable, Object aRepeatExpression) {
+ repeatVariable = aRepeatVariable;
+ repeatExpression = aRepeatExpression;
+ }
+
+ public void setContent(Object aContentExpression) {
+ contentExpression = aContentExpression;
+ }
+
+ public void setOmitTag(Object anOmitTagExpression) {
+ omitTagExpression = anOmitTagExpression;
+ }
+
+ public void setError(Object anErrorExpression) {
+ errorExpression = anErrorExpression;
+ }
+
+ public static class Definition {
+ private Object variable;
+ private Object expression;
+
+ public Definition(Object aVariable, Object anExpression) {
+ variable = aVariable;
+ expression = anExpression;
+ }
+
+ public Object getVariable() {
+ return variable;
+ }
+
+ public Object getExpression() {
+ return expression;
+ }
+ }
+
+ public void process(TALExpressionParser aParser, Object aContext,
+ StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext,
+ TemplateLibrary aLibrary) throws TemplateProcessingException {
+ if (errorExpression != null) {
+ StringBuffer destination = new StringBuffer();
+
+ try {
+ outerProcess(aParser, aContext, destination, aLogger, aTemplateContext, aLibrary);
+ }
+ catch (Throwable t) {
+ try {
+// destination.delete(0, destination.length());
+ aParser.processPseudoAssignment(aContext, "exception", t);
+ destination.insert(0, aParser.evaluateStringExpression(aContext, errorExpression));
+ destination.append(" >>>ERROR POSITION<<< ");
+ }
+ catch (Throwable s) {
+ throw new TemplateProcessingException(s);
+ }
+ }
+ finally {
+ aDestination.append(destination);
+ }
+ }
+ else {
+ outerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);
+ }
+ }
+
+ public String getPlainText() {
+ return body.getPlainText();
+ }
+
+ public void outerProcess(TALExpressionParser aParser, Object aContext,
+ StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext,
+ TemplateLibrary aLibrary) throws TemplateProcessingException {
+
+ Object oldAttributes = aParser.evaluatePseudoVariable(aContext, "tagattributes");
+ aParser.processPseudoAssignment(aContext, "tagattributes", Collections.unmodifiableMap(fixedAttributes));
+
+ Object oldContent = aParser.evaluatePseudoVariable(aContext, "tagcontent");
+ aParser.processPseudoAssignment(aContext, "tagcontent", body.getPlainText());
+
+ try {
+ Iterator i;
+
+ i = definitions.iterator();
+ while (i.hasNext()) {
+ Definition d = (Definition) i.next();
+ aParser.processAssignment(aContext, d.getVariable(), d.getExpression());
+ }
+
+ if (condition == null || aParser.evaluateBooleanExpression(aContext, condition)) {
+ if (repeatExpression != null) {
+ i = aParser.evaluateListExpression(aContext, repeatExpression);
+
+ while (i.hasNext()) {
+ aParser.processDirectAssignment(aContext, repeatVariable, i.next());
+ innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);
+ }
+ }
+ else {
+ innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary);
+ }
+ }
+ }
+ finally {
+ try {
+ aParser.processPseudoAssignment(aContext, "tagattributes", oldAttributes);
+ aParser.processPseudoAssignment(aContext, "tagcontent", oldContent);
+ }
+ catch (Throwable t) {
+ }
+ }
+ }
+
+ private void innerProcess(TALExpressionParser aParser, Object aContext,
+ StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext, TemplateLibrary aLibrary)
+ throws TemplateProcessingException {
+
+ boolean omitTag = false;
+ StringBuffer content = aDestination;
+
+ if (omitTagExpression != null)
+ omitTag = aParser.evaluateBooleanExpression(aContext, omitTagExpression);
+
+ if (!omitTag) {
+ content = new StringBuffer();
+ Map generatedAttributes = new TreeMap(fixedAttributes);
+
+ Iterator i = attributeModifiers.entrySet().iterator();
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry) i.next();
+
+ generatedAttributes.put(entry.getKey(), aParser.evaluateStringExpression(aContext, entry.getValue()));
+ }
+
+ aDestination.append("<");
+ aDestination.append(tag);
+
+ i = generatedAttributes.entrySet().iterator();
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry) i.next();
+ aDestination.append(" ");
+ aDestination.append(entry.getKey());
+ aDestination.append("=");
+ aDestination.append("\"");
+ aDestination.append(HTMLRoutines.encodeHTML( (String) entry.getValue()));
+ aDestination.append("\"");
+ }
+ }
+
+ try{
+ if (contentExpression != null) {
+ content.append(aParser.evaluateStringExpression(aContext, contentExpression));
+ }
+ else {
+ if (body != null) {
+ body.process(aParser, aContext, content, aLogger, aTemplateContext, aLibrary);
+ }
+ }
+ if (!omitTag) {
+ if (content.length()==0) {
+ aDestination.append(" />");
+ }
+ else {
+ aDestination.append(">");
+ aDestination.append(content);
+ aDestination.append("</");
+ aDestination.append(tag);
+ aDestination.append(">");
+ }
+ }
+ }
+ catch (Throwable t) {
+ if (!omitTag) {
+ aDestination.append(content);
+ }
+
+ if (t instanceof TemplateProcessingException) {
+ throw (TemplateProcessingException) t;
+ }
+ else if (t instanceof RuntimeException) {
+ throw (RuntimeException) t;
+ }
+ else throw new TemplateProcessingException(t.toString());
+ }
+ }
+ }
+}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.generator.tal.template;
-import java.util.Map;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import java.util.HashMap;
+import java.util.Map;
import mir.generator.tal.interfaces.TALExpressionParser;
import mir.generator.tal.interfaces.TALLogger;
+import mir.util.HTMLRoutines;
+import mir.util.StringRoutines;
import mir.util.xml.XMLName;
import mir.util.xml.XMLParserExc;
import mir.util.xml.XMLReaderTool;
-import mir.util.StringRoutines;
-import mir.util.HTMLRoutines;
public class MacroTemplateNodeLibrary implements TemplateNodeLibrary {
/** {@inheritDoc} */
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2005 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
* exception to your version of the file, but you are not obligated to do so.\r
* If you do not wish to do so, delete this exception statement from your version.\r
*/\r
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2005 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
* exception to your version of the file, but you are not obligated to do so.\r
* If you do not wish to do so, delete this exception statement from your version.\r
*/\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.
*/
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2005 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
* exception to your version of the file, but you are not obligated to do so.\r
* If you do not wish to do so, delete this exception statement from your version.\r
*/\r
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mir.generator.tal.template;\r
-\r
-import java.util.Map;\r
-\r
-import mir.util.xml.XMLName;\r
-import mir.util.xml.XMLParserExc;\r
-import mir.generator.tal.interfaces.TALExpressionParser;\r
-\r
-public interface TemplateNodeLibrary {\r
- /**\r
- * Construct a {@link TemplateNode} based on the tag and attributes given.\r
- *\r
- * @param anExpressionParser\r
- * @param aTag\r
- * @param anAttributes\r
- * @param aChildTemplateNode\r
- */\r
- public TemplateNode constructTemplateNode(TALExpressionParser anExpressionParser,\r
- XMLName aTag, Map anAttributes, TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc;\r
-}\r
+/*
+ * Copyright (C) 2005 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 any library licensed under the Apache Software License.
+ * 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.generator.tal.template;
+
+import java.util.Map;
+
+import mir.generator.tal.interfaces.TALExpressionParser;
+import mir.util.xml.XMLName;
+import mir.util.xml.XMLParserExc;
+
+public interface TemplateNodeLibrary {
+ /**
+ * Construct a {@link TemplateNode} based on the tag and attributes given.
+ *
+ * @param anExpressionParser
+ * @param aTag
+ * @param anAttributes
+ * @param aChildTemplateNode
+ */
+ public TemplateNode constructTemplateNode(TALExpressionParser anExpressionParser,
+ XMLName aTag, Map anAttributes, TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc;
+}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.
*/
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2005 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
* exception to your version of the file, but you are not obligated to do so.\r
* If you do not wish to do so, delete this exception statement from your version.\r
*/\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.log;
-
public interface Logger {
- public void debug( Object o, String s);
- public void info( Object o, String s);
- public void warn( Object o, String s);
- public void error( Object o, String s);
- public void fatal( Object o, String s);
+ public void debug(Object o, String s);
+ public void info(Object o, String s);
+ public void warn(Object o, String s);
+ public void warn(Object o, String s, Throwable anException);
+ public void error(Object o, String s);
+ public void error(Object o, String s, Throwable anException);
+ public void fatal(Object o, String s);
public void reload() throws LoggerExc, LoggerFailure;
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.log;
import mir.config.MirPropertiesConfiguration;
loggerInstance.warn(o, s);
}
+ public static void warn(Object o, String s, Throwable anException) {
+ loggerInstance.warn(o, s, anException);
+ }
+
public static void error(Object o, String s) {
loggerInstance.error(o, s);
}
+ public static void error(Object o, String s, Throwable anException) {
+ loggerInstance.error(o, s, anException);
+ }
+
public static void fatal(Object o, String s) {
loggerInstance.fatal(o, s);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.log;
import java.io.Writer;
}
lineBuffer.delete(0, from);
- };
+ }
public void write(char[] aBuffer, int anOffset, int aLength) {
lineBuffer.append(aBuffer, anOffset, aLength);
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.log;
import java.io.PrintWriter;
public void debug( String aMessage ) {
LoggerEngine.debug(object, aMessage);
- };
+ }
public void info( String aMessage ) {
LoggerEngine.info(object, aMessage);
- };
+ }
public void warn( String aMessage ) {
LoggerEngine.warn(object, aMessage);
- };
+ }
+
+ public void warn(String aMessage, Throwable anException) {
+ LoggerEngine.warn(object, aMessage, anException);
+ }
public void error( String aMessage ) {
LoggerEngine.error(object, aMessage);
- };
+ }
+
+ public void error(String aMessage, Throwable anException) {
+ LoggerEngine.error(object, aMessage, anException);
+ }
public void fatal( String aMessage ) {
LoggerEngine.fatal(object, aMessage);
- };
+ }
public void message( int aType, String aMessage) {
switch(aType) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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 mir.config.MirPropertiesConfiguration;
import mir.log.LoggerExc;
import mir.log.LoggerFailure;
+
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LoggerImpl implements mir.log.Logger {
- private static Map loggers = new HashMap();
+ private static final Map loggers = new HashMap();
public LoggerImpl() throws LoggerExc {
reload();
}
/** {@inheritDoc} */
+ public void warn(Object o, String s, Throwable anException) {
+ this.getLogger(o).warn(s, anException);
+ }
+
+ /** {@inheritDoc} */
public void error(Object o, String s) {
this.getLogger(o).error(s);
}
/** {@inheritDoc} */
+ public void error(Object o, String s, Throwable anException) {
+ this.getLogger(o).error(s, anException);
+ }
+
+ /** {@inheritDoc} */
public void fatal(Object o, String s) {
this.getLogger(o).fatal(s);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.media;
import multex.Exc;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.media;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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.media;
-import java.io.InputStream;
-import java.io.File;
-import java.util.List;
-
import mir.entity.Entity;
import mir.session.UploadedFile;
+import java.io.InputStream;
+
/**
* Interface for Media handling in Mir. All media handlers
* must implement this interface. Each specific media type,
* content-type map for this....).
* <p>
* The "mime_type" field is the most important as it does maps the type to Java
- * classes (the storage and media_handler name). We call those classes using
+ * classes (the database and media_handler name). We call those classes using
* reflection. This way, once a Handler for a specific media type is implemented
* and entered into the media_type table, no other Mir code needs to be modified.
* <p>
* The "classname" field is the name of the media handler (e.g MediaHandlerAudio)
* we use it to call the MediaHandler methods via reflection.
* <p>
- * The "tablename" is the name of the database storage classes (e.g DatabaseImages
- * and EntityImages). We use this to fetch/storage the media (meta)data in the db.
+ * The "tablename" is the name of the database database classes (e.g DatabaseImages
+ * and EntityImages). We use this to fetch/database the media (meta)data in the db.
* <p?
* The "dcname" field is as of yet unused. Do search for "Dublin Core" on google
* to learn more.
* ) and just override the things that need to be specific. see MediaHandlerAudio
*
* @author <mh@nadir.org>, the Mir-coders group
+ * @version $Id: MediaHandler.java,v 1.3 2007/04/08 21:46:43 idfx Exp $
*/
public interface MediaHandler {
public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure;
/**
- * Store the media content from a file.
- */
- public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure;
-
- /**
* Perform production related tasks for this media.
*/
public void produce(Entity aMedia, Entity aMediaType ) throws MediaExc, MediaFailure;
/**
- * Get's the media data from storage and returns it as an InputStream
- * Not very useful for most media types as they are stored in a file,
- * but very usefull for ones stored in the DB as it is necessary to get
- * it first before making a file out of it (in Producer*).
+ * Returns the associated media as an input stream
*/
public InputStream getMedia (Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure;
/**
- * Pretty much like get() above. But get's the specific Icon
- * representation. useful for media stored in the DB.
+ * Returns a thumbnail of the associated media as an input stream
*/
public InputStream getThumbnail(Entity aMedia) throws MediaExc, MediaFailure;
-
/**
* Returns the mime-type of the media's thumbnail
*/
public String getThumbnailMimeType(Entity aMediaEntity, Entity aMediaType) throws MediaExc, MediaFailure;
/**
- * gets the final content representation for the media
- * in the form of a URL (String) that allows someone to
- * download, look at or listen to the media. (HREF, img src
- * streaming link, etc..)
- * It should use the helper functions in the StringUtil class to
- * build URL's safely, eliminating any *illegal* user input.
- */
- public List getURL (Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure;
-
- /**
* Returns the absolute filesystem path to where the media
* content should be stored. This path is usually defined
* in the configuration wich is accessible through the MirConfig
* class.
*/
- public String getStoragePath () throws MediaExc, MediaFailure;
+ public String getBaseStoragePath () throws MediaExc, MediaFailure;
- /**
+ /**
* Returns the *relative* filesystem path to where the media
* icon content should be stored. It is relative to the path
- * returned by getStoragePath()
+ * returned by getBaseStoragePath()
* This path is usually defined
* in the configuration wich is accessible through the MirConfig
* class.
*/
- public String getIconStoragePath () throws MediaExc, MediaFailure;
+ public String getBaseIconStoragePath () throws MediaExc, MediaFailure;
- /**
+ /**
* Returns the base URL to that the media is accessible from
* to the end user. This could be a URL to another host.
* This is used in the Metadata stored in the DB and later on
*/
public String getPublishHost () throws MediaExc, MediaFailure;
- /**
+ /**
* Returns the file name of the Icon representing the media type.
* It is used in the summary view.
* It is usually defined
*/
public String getBigIconName ();
- /**
+ /**
* Returns the file name of the small Icon representing
* the media type.
* It is used in the right hand newswire list of the startpage.
--- /dev/null
+/*
+ * Copyright (C) 2005 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 any library licensed under the Apache Software License.
+ * 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.media.image;
+
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.util.StreamCopier;
+import mir.util.ShellRoutines;
+import mir.config.MirPropertiesConfiguration;
+
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.StringTokenizer;
+
+
+/**
+ * Image processing by calling the ImageMagick command line progrmas
+ * "convert" and "identify". The main task of this class is to scale
+ * images. The path to ImageMagick commandline programs can be
+ * specified in the coonfiguration file.
+ *
+ * @author <grok@no-log.org>, the Mir-coders group
+ */
+public class ImageMagickImageProcessor implements ImageProcessor {
+ protected static MirPropertiesConfiguration configuration =
+ MirPropertiesConfiguration.instance();
+ static final LoggerWrapper logger =
+ new LoggerWrapper("media.image.imagemagick");
+
+ private ImageFile sourceImage;
+ private ImageFile scaledImage;
+
+ /**
+ * ImageFile is a thin wrapper around a file that contains an
+ * image. It uses ImageMagick to retreive information about the
+ * image. It can also scale images using ImageMagick. Intended for
+ * use in the ImageMagickImageProcessor class.
+ */
+ static class ImageFile {
+ /**
+ * path to the file represented by this class
+ */
+ File file;
+ /**
+ * whether the file must be deleted on cleanup
+ */
+ boolean fileIsTemp = false;
+ /**
+ * image information is stored here to avoid multiple costly calls to
+ * "identify"
+ */
+ int width;
+ int height;
+ int fileSize;
+
+ /**
+ * Image type as returned by identify %m : "PNG", "GIF", ...
+ */
+ String type;
+ /**
+ * number of scenes in image >1 (typically animated gif)
+ */
+ boolean isAnimation;
+
+ /**
+ * Empty constructor automatically creates a temporary file
+ * that will later hold an image
+ */
+ ImageFile() throws IOException {
+ file = File.createTempFile("mirimage", "");
+ fileIsTemp = true;
+ }
+
+ /**
+ * if the file doesn't already have an image in it
+ * we don't want to read its information
+ */
+ ImageFile(File file, boolean doReadInfo) throws IOException {
+ this.file = file;
+ if (doReadInfo) {
+ readInfo();
+ }
+ }
+
+ ImageFile(File file) throws IOException {
+ this(file, true);
+ }
+
+ /**
+ * delete temporary files
+ */
+ public void cleanup() {
+ logger.debug("ImageFile.cleanup()");
+ if (fileIsTemp) {
+ logger.debug("deleting:" + file);
+ file.delete();
+ file = null;
+ fileIsTemp = false;
+ }
+ }
+
+ void debugOutput() {
+ logger.debug(" filename:" + file +
+ " Info:" +
+ " width:" + width +
+ " height:" + height +
+ " type:" + type +
+ " isAnimation:" + isAnimation);
+ }
+
+ private void checkFile() throws IOException {
+ if (file == null || !file.exists()) {
+ String message = "ImageFile.checkFile file \"" + file +
+ "\" does not exist";
+ logger.error(message);
+ throw new IOException(message);
+ }
+ }
+
+ /**
+ * Uses the imagemagick "identify" command to retreive image information
+ */
+ public void readInfo() throws IOException {
+ checkFile();
+ String infoString = ShellRoutines.execIntoString
+ (getImageMagickPath() +
+ "identify " + "-format \"%w %h %m %n %b \" " +
+ file.getAbsolutePath()); // extra space, for multiframe (animations)
+ StringTokenizer st = new StringTokenizer(infoString);
+ width = Integer.parseInt(st.nextToken());
+ height = Integer.parseInt(st.nextToken());
+ type = st.nextToken();
+ isAnimation = Integer.parseInt(st.nextToken()) > 1;
+ // yoss: different versions of ImageMagick produce different formatted output file sizes
+ // for example, Version: ImageMagick 6.2.4 (Ubuntu Dapper 6.06) produces a byte value, i.e. 67013
+ // Version: ImageMagick 6.0.6 (Debian Sarge) produces output like 67kb or 500mb.
+ // Trying to do an int.parse in Sarge fails for obvious reasons.
+ /*String sFileSize = st.nextToken();
+ if (sFileSize.endsWith("kb") || sFileSize.endsWith("Kb") || sFileSize.endsWith("KB") || sFileSize.endsWith("kB")){
+ sFileSize = sFileSize.substring(0, sFileSize.length() - 2);
+ fileSize = 1024 * Integer.parseInt(sFileSize);
+ } else if (sFileSize.endsWith("mb") || sFileSize.endsWith("Mb") || sFileSize.endsWith("MB") || sFileSize.endsWith("mB")){
+ sFileSize = sFileSize.substring(0, sFileSize.length() - 2);
+ fileSize = 1048576 * Integer.parseInt(sFileSize);
+ } else {
+ fileSize = Integer.parseInt(sFileSize);
+ }*/
+ fileSize = (int)file.length();
+ }
+
+ public ImageFile scale(float aScalingFactor) throws IOException {
+ logger.debug("ImageFile.scale");
+ checkFile();
+ ImageFile result = new ImageFile();
+ String command = getImageMagickPath() + "convert " +
+ file.getAbsolutePath() + " " +
+ "-scale " +
+ Float.toString(aScalingFactor * 100) + "% " +
+ result.file.getAbsolutePath();
+ logger.debug("ImageFile.scale:command:" + command);
+ ShellRoutines.simpleExec(command);
+ result.readInfo();
+ return result;
+ }
+ }
+
+ public ImageMagickImageProcessor(InputStream inputImageStream)
+ throws IOException {
+ logger.debug("ImageMagickImageProcessor(stream)");
+ sourceImage = new ImageFile();
+ // copy stream into temporary file
+
+ FileOutputStream outputStream = new FileOutputStream(sourceImage.file);
+ try {
+ StreamCopier.copy(inputImageStream, outputStream);
+ }
+ finally {
+ outputStream.close();
+ }
+ sourceImage.readInfo();
+ sourceImage.debugOutput();
+ }
+
+
+ public ImageMagickImageProcessor(File aFile) throws IOException {
+ logger.debug("ImageMagickImageProcessor(file)");
+ sourceImage = new ImageFile(aFile);
+ sourceImage.debugOutput();
+ }
+
+ /**
+ * Deletes temporary files
+ */
+ public void cleanup() {
+ logger.debug("ImageMagickImageProcessor.cleanup()");
+ sourceImage.cleanup();
+ scaledImage.cleanup();
+ }
+
+ /**
+ * Path to ImageMagick commandline programs
+ */
+ private static String getImageMagickPath() {
+ String result = configuration.getString("Producer.Image.ImageMagickPath");
+ // we want the path to finish by "/", so add it if it's missing
+ if (result.length() != 0 && !result.endsWith("/")) {
+ result = result.concat("/");
+ }
+ logger.debug("getImageMagickPath:" + result);
+ return result;
+ }
+
+ public void descaleImage(int aMaxSize) throws MediaExc {
+ descaleImage(aMaxSize, 0);
+ }
+
+ public void descaleImage(int aMaxSize, float aMinDescale) throws MediaExc {
+ descaleImage(aMaxSize, aMaxSize, aMinDescale, 0);
+ }
+
+ public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc {
+ descaleImage(aMaxSize, aMaxSize, 0, aMinResize);
+ }
+
+ public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize)
+ throws MediaExc {
+ descaleImage(aMaxSize, aMaxSize, aMinDescale, aMinResize);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void descaleImage(int aMaxWidth, int aMaxHeight,
+ float aMinDescale, int aMinResize) throws MediaExc {
+ float scale;
+ logger.debug("descaleImage:" +
+ " aMaxWidth:" + aMaxWidth +
+ ", aMaxHeight:" + aMaxHeight +
+ ", aMinDescale:" + aMinDescale +
+ ", aMinResize:" + aMinResize);
+ if ((aMaxWidth > 0 && getWidth() > aMaxWidth + aMinResize - 1) ||
+ (aMaxHeight > 0 && getHeight() > aMaxHeight + aMinResize - 1)) {
+ logger.debug("descaleImage: image needs scaling");
+
+ scale = 1;
+
+ if (aMaxWidth > 0 && getWidth() > aMaxWidth) {
+ scale = Math.min(scale, (float) aMaxWidth / (float) getWidth());
+ }
+ if (aMaxHeight > 0 && getHeight() > aMaxHeight) {
+ scale = Math.min(scale, (float) aMaxHeight / (float) getHeight());
+ }
+
+ if (1 - scale > aMinDescale) {
+ scaleImage(scale);
+ }
+ } else {
+ logger.debug("descaleImage: image size is ok, not scaling image");
+ try {
+ scaledImage = new ImageFile(sourceImage.file);
+ }
+ catch (IOException e) {
+ throw new MediaExc(e.toString());
+ }
+ }
+ }
+
+
+ /**
+ * Scales image by a factor using the convert ImageMagick command
+ */
+ public void scaleImage(float aScalingFactor)
+ throws MediaExc {
+ logger.debug("scaleImage:" + aScalingFactor);
+ try {
+ // first cleanup previous temp scaledimage file if necesary
+ if (scaledImage != null) {
+ scaledImage.cleanup();
+ }
+ // now create temp file and execute convert
+ scaledImage = sourceImage.scale(aScalingFactor);
+ }
+ catch (Exception e) {
+ throw new MediaExc(e.toString());
+ }
+ logger.debug(" scaledImage:");
+ scaledImage.debugOutput();
+ }
+
+ public int getWidth() {
+ return sourceImage.width;
+ }
+
+ public int getHeight() {
+ return sourceImage.height;
+ }
+
+ public int getSourceFileSize() {
+ return sourceImage.fileSize;
+ }
+
+ public int getScaledFileSize() {
+ return scaledImage.fileSize;
+ }
+
+ public int getScaledWidth() {
+ return scaledImage.width;
+ }
+
+ public int getScaledHeight() {
+ return scaledImage.height;
+ }
+
+ public void writeScaledData(OutputStream aStream, String anImageType)
+ throws MediaExc {
+ // we can't asume that requested "anImageType" is the same as the
+ // scaled image type, so we have to convert
+ try {
+ // if image is an animation and target type doesn't support
+ // animations, then just use first frame
+ String frame = "";
+ scaledImage.debugOutput();
+ if (scaledImage.isAnimation && !anImageType.equals("GIF")) {
+ frame = "[0]";
+ }
+ // ImageMagick "convert" into temp file
+ File temp = File.createTempFile("mirimage", "");
+ String command = getImageMagickPath() + "convert " +
+ scaledImage.file.getAbsolutePath() + frame + " " +
+ anImageType + ":" + temp.getAbsolutePath();
+ logger.debug("writeScaledData command:" + command);
+ ShellRoutines.simpleExec(command);
+ // copy temp file into stream
+ StreamCopier.copy(new FileInputStream(temp), aStream);
+ temp.delete();
+ }
+ catch (Exception e) {
+ throw new MediaExc(e.toString());
+ }
+ }
+
+ public byte[] getScaledData(String anImageType) throws MediaExc {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ writeScaledData(outputStream, anImageType);
+ return outputStream.toByteArray();
+ }
+
+ public void writeScaledData(File aFile, String anImageType) throws MediaExc {
+ try {
+ OutputStream stream = new BufferedOutputStream(new FileOutputStream(aFile), 8192);
+
+ try {
+ writeScaledData(stream, anImageType);
+ }
+ finally {
+ try {
+ stream.close();
+ }
+ catch (Throwable t) {
+ logger.debug("Unable to close stream when writing scaled data.");
+ }
+ }
+ }
+ catch (FileNotFoundException f) {
+ throw new MediaFailure(f);
+ }
+ catch (Exception e) {
+ logger.debug("Exception caught while trying to write scaled data: " + e.toString());
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2005 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 any library licensed under the Apache Software License.
+ * 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.media.image;
+
+import mir.media.MediaExc;
+
+import java.io.File;
+import java.io.OutputStream;
+
+public interface ImageProcessor {
+ public void descaleImage(int aMaxSize) throws MediaExc;
+
+ public void descaleImage(int aMaxSize, float aMinDescale) throws MediaExc;
+
+ public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc;
+
+ public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize) throws MediaExc;
+
+ /**
+ * Resizes an image to fit inside <code>aMaxWidth</code> and <code>aMaxHeight</code>, provided
+ * this requires at least <code>aMinResize</code> pixels will be removed from either the width or
+ * the height
+ */
+ public void descaleImage(int aMaxWidth, int aMaxHeight, float aMinDescale, int aMinResize) throws MediaExc;
+
+ public void scaleImage(float aScalingFactor) throws MediaExc;
+
+ public int getWidth();
+ public int getHeight();
+ public int getSourceFileSize();
+ public int getScaledFileSize();
+ public int getScaledWidth();
+ public int getScaledHeight();
+ public void writeScaledData(OutputStream aStream, String anImageType)
+ throws MediaExc;
+ public byte[] getScaledData(String anImageType) throws MediaExc;
+ public void writeScaledData(File aFile, String anImageType) throws MediaExc;
+
+ /**
+ * call this when you're over using this object (removes temp files)
+ */
+ public void cleanup();
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+++ /dev/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 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;
-
-
-
-/**
- * Reports the location of the error in the File.
- * Based and inspired by a source from the Ant distribution
- * (Copyright (c) 1999-2001 The Apache Software Foundation.)
- *
- * @version $Id: ConfigException.java,v 1.4 2003/04/21 12:42:52 idfx Exp $
- *
- * @author The Mir-coders group
- */
-
-public class ConfigException extends RuntimeException {
-
- /** Exception that might have caused this one. */
- private Throwable cause;
-
- /** Location in the build file where the exception occured */
- private Location location = Location.UNKNOWN_LOCATION;
-
- /**
- * Constructs a build exception with no descriptive information.
- */
- public ConfigException() {
- super();
- }
-
- /**
- * Constructs an exception with the given descriptive message.
- * @param msg Description of or information about the exception.
- */
- public ConfigException(String msg) {
- super(msg);
- }
-
- /**
- * Constructs an exception with the given message and exception as
- * a root cause.
- * @param msg Description of or information about the exception.
- * @param cause Throwable that might have cause this one.
- */
- public ConfigException(String msg, Throwable cause) {
- super(msg);
- this.cause = cause;
- }
-
- /**
- * Constructs an exception with the given message and exception as
- * a root cause and a location in a file.
- * @param msg Description of or information about the exception.
- * @param cause Exception that might have cause this one.
- * @param location Location in the project file where the error occured.
- */
- public ConfigException(String msg, Throwable cause, Location location) {
- this(msg, cause);
- this.location = location;
- }
-
- /**
- * Constructs an exception with the given exception as a root cause.
- * @param cause Exception that might have caused this one.
- */
- public ConfigException(Throwable cause) {
- super(cause.toString());
- this.cause = cause;
- }
-
- /**
- * Constructs an exception with the given descriptive message and a location
- * in a file.
- * @param msg Description of or information about the exception.
- * @param location Location in the project file where the error occured.
- */
- public ConfigException(String msg, Location location) {
- super(msg);
- this.location = location;
- }
-
- /**
- * Constructs an exception with the given exception as
- * a root cause and a location in a file.
- * @param cause Exception that might have cause this one.
- * @param location Location in the project file where the error occured.
- */
- public ConfigException(Throwable cause, Location location) {
- this(cause);
- this.location = location;
- }
-
- /**
- * Returns the nested exception.
- */
- public Throwable getException() {
- return cause;
- }
-
- /**
- * Returns the location of the error and the error message.
- */
- public String toString() {
- return location.toString() + getMessage();
- }
-
- /**
- * Sets the file location where the error occured.
- */
- public void setLocation(Location location) {
- this.location = location;
- }
-
- /**
- * Returns the file location where the error occured.
- */
- public Location getLocation() {
- return location;
- }
-
- // Override stack trace methods to show original cause:
- public void printStackTrace() {
- printStackTrace(System.err);
- }
-
-}
+++ /dev/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 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;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-/**
- * Hilfsklasse zum Mergen von Template und Daten
- */
-public final class FileUtil {
- /**
- * Privater Construktor to avoid accidental instantiation
- */
- private FileUtil() {
- }
-
- public static File getFile(String filename) throws IOException {
-
- try {
- File f = null;
- f = new File(filename);
- File dir = new File(f.getParent());
- dir.mkdirs();
-
- return f;
- }
- catch (Exception e) {
- throw new IOException(e.toString());
- }
-
- }
-
- public static long write(File f, InputStream in) throws IOException {
-
- long size = 0;
-
- if (in != null) {
- try {
- BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f),8192);
-
- // TODO get size with in.available()
- int read;
- byte[] buf = new byte[8 * 1024];
- while ( (read = in.read(buf)) != -1) {
- out.write(buf, 0, read);
- size += read;
- }
-
- in.close();
- out.close();
- }
- catch (IOException e) {
- throw new IOException(e.toString());
- }
- }
- return size;
- }
-
- public static long write(String filename, InputStream in) throws IOException {
-
- long size = 0;
-
- if (in != null) {
- try {
- File f = getFile(filename);
- size = write(f, in);
- }
- catch (IOException e) {
- throw new IOException(e.toString());
- }
- }
- return size;
- }
-
- public static long write(String filename, Reader in, String encoding) throws IOException {
-
- long size = 0;
-
- if (in != null) {
- try {
- File f = getFile(filename);
- FileOutputStream fOut = new FileOutputStream(f);
- BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fOut, encoding),8192);
- int read;
- char[] cbuf = new char[8 * 1024];
- while ( (read = in.read(cbuf)) != -1) {
- out.write(cbuf, 0, read);
- size += read;
- }
-
- out.close();
- in.close();
- }
- catch (IOException e) {
- throw new IOException(e.toString());
- }
- }
- return size;
- }
-
- public static boolean read(String filename, byte out[]) throws IOException {
-
- File f = null;
- f = new File(filename);
-
- if (f.exists()) {
- try {
- if (out.length != f.length())
- return false;
- BufferedInputStream inStream;
- inStream = new BufferedInputStream(new FileInputStream(f),8192);
- inStream.read(out);
- inStream.close();
- }
- catch (IOException e) {
- throw new IOException(e.toString());
- }
- }
- else {
- return false;
- }
- return true;
- }
-
- public static long getSize(String filename) {
- File f = null;
- f = new File(filename);
- long l = 0;
-
- if (f.exists()) {
- return f.length();
- }
- else {
- return -1;
- }
- }
-
-}
+++ /dev/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 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;
-
-/**
- * Stores the file name and line number in a file.
- *
- * @version $Id: Location.java,v 1.3 2003/04/21 12:42:52 idfx Exp $
- *
- */
-public class Location {
- private String fileName;
- private int lineNumber;
- private int columnNumber;
-
- public static final Location UNKNOWN_LOCATION = new Location();
-
- /**
- * Creates an "unknown" location.
- */
- private Location() {
- this(null, 0, 0);
- }
-
- /**
- * Creates a location consisting of a file name but no line number.
- */
- public Location(String fileName) {
- this(fileName, 0, 0);
- }
-
- /**
- * Creates a location consisting of a file name and line number.
- */
- public Location(String fileName, int lineNumber, int columnNumber) {
- this.fileName = fileName;
- this.lineNumber = lineNumber;
- this.columnNumber = columnNumber;
- }
-
- /**
- * Returns the file name, line number and a trailing space. An error
- * message can be appended easily. For unknown locations, returns
- * an empty string.
- */
- public String toString() {
- StringBuffer buf = new StringBuffer();
-
- if (fileName != null) {
- buf.append(fileName);
-
- if (lineNumber != 0) {
- buf.append(":");
- buf.append(lineNumber);
- }
-
- buf.append(": ");
- }
-
- return buf.toString();
- }
-}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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;
/**
* Help methods for number handling.
*
- * @version $Id: NumberUtils.java,v 1.5 2003/04/21 12:42:52 idfx Exp $
+ * @version $Id: NumberUtils.java,v 1.6 2007/04/08 21:46:44 idfx Exp $
* @author mh, Mir-coders group
*
*/
public final class NumberUtils {
+ private NumberUtils() {
+ }
/*
* Uses a suffix indicating multiples of 1024 (K),
* @return A text representation of the number of bytes,
* abbreviated for larger quantities.
*/
- public static String humanReadableSize(double bytes)
- {
+ public static String humanReadableSize(double aBytes) {
+ double bytes = aBytes;
String suffix;
-
- if( bytes >= 1024 * 1024 * 1024 )
- {
- bytes /= (1024 * 1024 * 1024);
+
+ if ( bytes >= (double) (1024 * 1024 * 1024) ) {
+ bytes /= (double) (1024 * 1024 * 1024);
suffix = "G";
}
- else if( bytes >= 1024 * 1024 )
- {
- bytes /= (1024 * 1024);
+ else if( bytes >= (double) (1024 * 1024) ) {
+ bytes /= (double) (1024 * 1024);
suffix = "M";
}
- else if( bytes >= 1024 )
- {
- bytes /= 1024;
+ else if( bytes >= 1024.0 ) {
+ bytes /= 1024.0;
suffix = "K";
}
- else
- {
+ else {
suffix = "";
}
- int frac = (bytes >= 10 || bytes == 0) ? 0 : 1;
+ int frac = bytes > 9.5 || bytes < 0.05 ? 0 : 1;
+
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(frac);
nf.setMaximumFractionDigits(frac);
nf.setGroupingUsed(false);
+
return nf.format(bytes) + suffix;
}
-
}
+++ /dev/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 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;
-
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.fop.apps.Driver;
-import org.apache.fop.apps.InputHandler;
-import org.apache.fop.apps.XSLTInputHandler;
-import org.apache.log.Hierarchy;
-import org.apache.log.Logger;
-import org.apache.log.Priority;
-import org.xml.sax.XMLReader;
-
-public class PDFUtil {
-
- public static void makePDF(String foFilePath,Object pdfDestination,String stylesheetPath) throws Exception
- {
- try{
- Driver driver = new Driver();
-
- //stupid logging that fop wants to use, needs to be changed
- Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
- Logger fopLog=null;
- fopLog = hierarchy.getLoggerFor("fop");
- fopLog.setPriority(Priority.WARN);
- driver.setLogger(fopLog);
-
- driver.setRenderer(Driver.RENDER_PDF);
-
- File foFile=new File(foFilePath);
-
- String html2foStyleSheetPath;
- html2foStyleSheetPath=stylesheetPath;
-
- File html2foStyleSheet=new File(html2foStyleSheetPath);
- InputHandler inputHandler =
- new XSLTInputHandler(foFile, html2foStyleSheet);
- XMLReader parser = inputHandler.getParser();
-
- if (pdfDestination instanceof String) {
- String filePath = (String) pdfDestination;
- driver.setOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));
- driver.render(parser, inputHandler.getInputSource());
- }
- else if (pdfDestination instanceof HttpServletResponse){
- HttpServletResponse res = (HttpServletResponse) pdfDestination;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- driver.setOutputStream(out);
- res.setContentType("application/pdf");
-
- driver.render(parser, inputHandler.getInputSource());
-
- byte[] content = out.toByteArray();
- res.setContentLength(content.length);
- res.getOutputStream().write(content);
- res.getOutputStream().flush();
- }
- else {
- throw new Exception("I'm sorry but I don't know how to output a pdf to an object of type" + pdfDestination.getClass().getName());
- }
- }
-
- catch (Exception ex){
- throw(ex);
- }
- }
-}
-
-
-
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2005 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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
+ * the code of this program with any library licensed under the Apache Software License.
+ * 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;
-import gnu.regexp.RE;
-import gnu.regexp.REException;
+import org.apache.oro.text.regex.Pattern;
+import org.apache.oro.text.regex.Perl5Matcher;
+import org.apache.oro.text.regex.Perl5Substitution;
+import org.apache.oro.text.regex.Util;
+import org.apache.oro.text.regex.Perl5Compiler;
+import org.apache.oro.text.regex.MalformedPatternException;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
+import mir.util.UtilFailure;
+
/**
- * Statische Hilfsmethoden zur Stringbehandlung
- *
- * @version $Id: StringUtil.java,v 1.35 2004/11/06 19:27:33 idfx Exp $
- * @author mir-coders group
- *
*/
public final class StringUtil {
- private static RE re_newline2br, re_brbr2p, re_mail, re_url, re_tags,
- re_tables, re_forbiddenTags;
+ private static TimeZone UTC = TimeZone.getTimeZone("UTC");
private StringUtil() { } // this avoids contruction
- static {
- try {
- //precompile regex
- re_newline2br = new RE("(\r?\n){1}");
- re_brbr2p = new RE("(<br>\r?\n<br>){1,}");
- re_mail = new RE("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b");
- re_url = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
- re_tags = new RE("<[^>]*>",RE.REG_ICASE);
- re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE);
- re_forbiddenTags = new RE("<[ \t\r\n/]*(html|meta|body|head|script)[ \t\r\n]*>",RE.REG_ICASE);
- }
- catch (REException e){
- System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
- }
- }
-
/**
* Formats a number with the specified minimum and maximum number of digits.
**/
public static synchronized String zeroPaddingNumber(long value, int minDigits,
- int maxDigits)
+ int maxDigits)
{
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumIntegerDigits(minDigits);
* @return 8-ziffriger String (yyyymmdd)
*/
- public static final String date2webdbDate (GregorianCalendar theDate) {
+ public static String date2webdbDate (GregorianCalendar theDate) {
StringBuffer webdbDate = new StringBuffer();
webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
webdbDate.append(pad2(theDate.get(Calendar.DATE)));
- return webdbDate.toString();
- }
-
- /**
- * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
- * @param theDate
- * @return 12-ziffriger String (yyyymmdd)
- */
- public static final String date2webdbDateTime (GregorianCalendar theDate) {
- StringBuffer webdbDate = new StringBuffer();
- webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
- webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
- webdbDate.append(pad2(theDate.get(Calendar.DATE)));
- webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
- webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
return webdbDate.toString();
}
* @return w3approved datetime
*/
- public static final String date2w3DateTime (GregorianCalendar theDate) {
+ public static String date2w3DateTime (GregorianCalendar theDate) {
StringBuffer webdbDate = new StringBuffer();
webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
webdbDate.append("-");
}
/**
- * deleteForbiddenTags
- * this method deletes all <script>, <body> and <head>-tags
- */
- public static final String deleteForbiddenTags(String haystack) {
- return re_forbiddenTags.substituteAll(haystack,"");
- }
-
- /**
- * deleteHTMLTableTags
- * this method deletes all <table>, <tr> and <td>-tags
- */
- public static final String deleteHTMLTableTags(String haystack) {
- return re_tables.substituteAll(haystack,"");
- }
-
- /**
* wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
* getrennt ist.
*
* @param webdbDate
* @return String mit <code>/yyyy/mm/dd</code>
*/
- public static final String webdbDate2path (String webdbDate) {
+ public static String webdbDate2path (String webdbDate) {
StringBuffer path = new StringBuffer();
path.append("/").append(webdbDate.substring(0, 4));
path.append("/").append(webdbDate.substring(4, 6));
}
/**
- * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
- * @param s
- * @param pattern
- * @param substitute
- * @return String mit den Ersetzungen
- */
- public static String regexpReplace(String haystack, String pattern, String substitute) {
- try {
- RE regex = new RE(pattern);
- return regex.substituteAll(haystack,substitute);
- } catch(REException ex){
- return null;
- }
- }
-
- /**
* L?scht <code>/</code> am Ende des Strings, falls vorhanden
* @param path
* @return String ohne <code>/</code> am Ende
*/
- public static final String removeSlash (String path) {
+ public static String removeSlash (String path) {
return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
- 1) : path;
}
/**
- * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
- * in den html-tag <p>
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String convertNewline2P(String haystack) {
- return re_brbr2p.substituteAll(haystack,"\n</p><p>");
- }
-
- /**
- * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
- * in den html-tag <br>
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String convertNewline2Break(String haystack) {
- return re_newline2br.substituteAll(haystack,"$0<br />");
- }
-
- /**
- * createMailLinks wandelt text im email-adressenformat
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createMailLinks(String haystack) {
- return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
- }
-
-
- /**
- * createMailLinks wandelt text im email-adressenformat
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
- return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
- }
-
-
- /**
- * createURLLinks wandelt text im url-format
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createURLLinks(String haystack) {
- return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
- }
-
- /**
- * this routine takes text in url format and makes
- * a clickaeble "<href>" link removing any "illegal" html tags
- * @param haystack, the url
- * @param title, the href link text
- * @param imagRoot, the place to find icons
- * @param extImage, the url of the icon to show next to the link
- * @return a String containing the url
- */
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
- if (title == null) {
- return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
- } else {
- title = removeHTMLTags(title);
- return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">"+title+"</a>");
- }
- }
-
- /**
- * this routine takes text in url format and makes
- * a clickaeble "<href>" link removing any "illegal" html tags
- * @param haystack, the url
- * @param imageRoot, the place to find icons
- * @param extImage, the url of the icon to show next to the link
- * @param intImage, unused
- * @return a String containing the url
- */
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
- return createURLLinks(haystack, title, imageRoot, extImage);
- }
-
- /**
- * this method deletes all html tags
- */
- public static final String removeHTMLTags(String haystack){
- return re_tags.substituteAll(haystack,"");
- }
-
- /**
- * this method deletes all but the approved tags html tags
- * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
- */
- public static String approveHTMLTags(String haystack){
- try {
- String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
- String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
- String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
-
- // kill all the bad tags that have attributes
- String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
- RE regex = new RE(s,RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the bad tags that are attributeless
- regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which have a javascript attribute like onLoad
- regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which include a url to an unacceptable protocol
- regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- return haystack;
- } catch(REException ex){
- ex.printStackTrace();
- return null;
- }
- }
-
-
- /**
- * createHTML ruft alle regex-methoden zum unwandeln eines nicht
- * htmlcodierten string auf und returnt einen htmlcodierten String
- */
- public static String createHTML(String content){
- content=convertNewline2Break(content);
- content=convertNewline2P(content);
- content=createMailLinks(content);
- content=createURLLinks(content);
- return content;
- }
-
-
- /**
- * createHTML ruft alle regex-methoden zum unwandeln eines nicht
- * htmlcodierten string auf und returnt einen htmlcodierten String
- */
- public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
- content=convertNewline2Break(content);
- content=convertNewline2P(content);
- content=createMailLinks(content,producerDocRoot,mailImage);
- content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
- return content;
- }
-
- /**
* Converts mir's horrible internal date format (yyyy-MM-dd HH:mm:ss+zz) into a java Date
*
* @param anInternalDate
- * @return
*/
public static Date convertMirInternalDateToDate(String anInternalDate) {
Calendar calendar = new GregorianCalendar();
seconds = Integer.parseInt(anInternalDate.substring(17,19));
timezoneOffset = Integer.parseInt(anInternalDate.substring(20,22));
- if (anInternalDate.charAt(19) == '-')
+ if (anInternalDate.charAt(19) == '-') {
timezoneOffset = -timezoneOffset;
+ }
- calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
+ calendar.setTimeZone(UTC);
calendar.set(year, month-1, day, hours, minutes, seconds);
calendar.add(Calendar.HOUR, -timezoneOffset);
return calendar.getTime();
}
-}
+ public static String regexpReplace(String anInput, String anExpression, String aReplacement) throws UtilFailure {
+ Perl5Matcher matcher = new Perl5Matcher();
+ try {
+ return Util.substitute(
+ matcher, new Perl5Compiler().compile(anExpression),
+ new Perl5Substitution(aReplacement), anInput,
+ Util.SUBSTITUTE_ALL);
+ }
+ catch (MalformedPatternException e) {
+ throw new UtilFailure(e);
+
+ }
+ }
+}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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.module;
-import java.util.Map;
-import java.sql.SQLException;
+package mir.module;
import mir.entity.Entity;
import mir.entity.EntityList;
-import mir.storage.StorageObject;
+import mir.storage.Database;
+import mir.storage.DatabaseExc;
+import java.util.Map;
/**
* This class provides the base functionality for the derived Module-Classes.
*/
public class AbstractModule {
- protected StorageObject storage;
+ protected Database database;
- public AbstractModule(StorageObject aStorageObject) {
- storage = aStorageObject;
+ public AbstractModule(Database aDatabase) {
+ database = aDatabase;
}
/**
- * Returns the storage object associated with this module
+ * Returns the database object associated with this module
*/
- public StorageObject getStorageObject () {
- return storage;
+ public Database getStorageObject () {
+ return database;
}
- public Entity getById (String id) throws ModuleExc, ModuleFailure {
- try {
- if (storage == null)
- throw new ModuleExc("AbstractModule.getById: No StorageObject set!");
- Entity entity = storage.selectById(id);
-
- if (entity == null)
- throw new ModuleExc("AbstractModule.getById: No object for id = " + id);
- else
- return entity;
- }
- catch (Throwable e) {
- throw new ModuleFailure(e);
- }
- }
+ public Entity getById (String anId) throws ModuleFailure, EntityNotFoundExc {
+ if (database == null) {
+ throw new ModuleFailure("AbstractModule.getById: No Database set!");
+ }
- public EntityList getByWhereClause (String whereClause, int offset) throws ModuleExc, ModuleFailure {
- try {
- if (storage == null)
- throw new ModuleExc("AbstractModule.getByWhereClause: No StorageObject set!");
+ try {
+ Entity result = database.selectById(anId);
- return storage.selectByWhereClause(whereClause, offset);
- }
- catch (Throwable e) {
- throw new ModuleFailure(e);
- }
+ if (result == null) {
+ throw new EntityNotFoundExc("AbstractModule.getById: No object for id = " + anId);
+ }
+
+ return result;
+ }
+ catch (DatabaseExc e) {
+ throw new ModuleFailure("Database exception while retrieving entity with id " + anId);
+ }
}
- /**
- * * Standardfunktion, um einen Datensatz via StorageObject einzuf?gen
- * @param theValues Hash mit Spalte/Wert-Paaren
- * @return Id des eingef?gten Objekts
- * @exception ModuleExc
- * @exception ModuleFailure
- */
- public String add (Map theValues) throws ModuleExc, ModuleFailure {
+ public EntityList getByWhereClause (String whereClause, int offset) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = (Entity)storage.getEntityClass().newInstance();
- theEntity.setStorage(storage);
- theEntity.setFieldValues(theValues);
- return theEntity.insert();
+ if (database == null)
+ throw new ModuleExc("AbstractModule.getByWhereClause: No Database set!");
+
+ return database.selectByWhereClause(whereClause, offset);
}
catch (Throwable e) {
throw new ModuleFailure(e);
}
}
- /**
- * This function creates an Entity without yet storing it in the database
- */
- public Entity createNew() throws ModuleExc, ModuleFailure {
+ public String add(Map theValues) throws ModuleExc, ModuleFailure {
try {
- Entity result = (Entity)storage.getEntityClass().newInstance();
- result.setStorage(storage);
+ Entity entity = database.createNewEntity();
+ entity.setFieldValues(theValues);
- return result;
+ return entity.insert();
}
catch (Throwable e) {
throw new ModuleFailure(e);
}
}
- /**
- * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren
- * @param theValues Hash mit Spalte/Wert-Paaren
- * @return Id des eingef?gten Objekts
- * @exception ModuleExc
- * @exception ModuleFailure
- */
public String set (Map theValues) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = storage.selectById((String)theValues.get("id"));
+ Entity theEntity = database.selectById((String) theValues.get("id"));
if (theEntity == null)
throw new ModuleExc("No object found with id " + theValues.get("id"));
theEntity.setFieldValues(theValues);
*/
public void deleteById (String idParam) throws ModuleExc, ModuleFailure {
try {
- storage.delete(idParam);
+ database.delete(idParam);
}
catch (Throwable e) {
throw new ModuleFailure(e);
}
}
-
- /**
- * returns the number of rows
- */
- public int getSize(String where) throws ModuleExc, ModuleFailure {
- try {
- return storage.getSize(where);
- }
- catch (SQLException e) {
- throw new ModuleFailure("Can't retrieve number of entities: " + e.toString(), e);
- }
- }
-
}
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.module;\r
+\r
+/**\r
+ * Exception thrown when an entity did not exist (but what expected to)\r
+ */\r
+public class EntityNotFoundExc extends ModuleExc {\r
+ public EntityNotFoundExc(String aMessage) {\r
+ super(aMessage);\r
+ }\r
+}\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.module;
import multex.Exc;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.module;
import multex.Failure;
public class ModuleFailure extends Failure {
+ public ModuleFailure(String aMessage) {
+ super(aMessage, null);
+ }
- public ModuleFailure(String msg,Throwable cause) {
- super(msg,cause);
+ public ModuleFailure(String aMessage,Throwable aCause) {
+ super(aMessage,aCause);
}
public ModuleFailure(Throwable aCause) {
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.producer;\r
+\r
+import mir.log.LoggerWrapper;\r
+\r
+import java.util.Map;\r
+\r
+public abstract class AbstractProducerNode implements ProducerNode {\r
+ /**\r
+ * Compatibility construction \r
+ */\r
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure {\r
+ }\r
+\r
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure {\r
+ produce(aProductionContext.getValueSet(), aProductionContext.getVerb(), aProductionContext.getLogger());\r
+ }\r
+}\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
+import java.util.Map;
+
public class AssignmentProducerNode extends ProducerNodeDecorator {
private String key;
- private String bundleIdentifier;
private Object value;
public AssignmentProducerNode(String aKey, Object aValue, ProducerNode aSubNode) {
}
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ }
+
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure {
try {
- ParameterExpander.setValueForKey(aValueMap, key, value);
+ ParameterExpander.setValueForKey(aProductionContext.getValueSet(), key, value);
- super.produce(aValueMap, aVerb, aLogger);
+ super.produce(aProductionContext);
}
catch (Throwable t) {
throw new ProducerFailure(t.getMessage(), t);
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/**
* This producer node loads a bundle
*/
-public class BundleProducerNode implements ProducerNode {
+public class BundleProducerNode extends AbstractProducerNode {
private String key;
private String bundleExpression;
private String languageExpression;
key = aKey;
}
- /** {@inheritDoc} */
+ /** {@inheritDoc} */
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
try {
String bundle = ParameterExpander.expandExpression( aValueMap, bundleExpression );
String[] languages = new String[0];
- if (languageExpression!=null)
- languages = new String[] { ParameterExpander.expandExpression( aValueMap, languageExpression ) };
+ if (languageExpression != null) {
+ languages = new String[]{ParameterExpander.expandExpression(aValueMap, languageExpression)};
+ }
- if (MirGlobal.config().getString("Producer.BundleCompatibility", "0").equals("1") &&
+ if ("1".equals(MirGlobal.config().getString("Producer.BundleCompatibility", "0")) &&
bundle.startsWith("bundles.")) {
bundle = "etc/bundles/" + bundle.substring("bundles.".length());
}
aLogger.error("Failed to load bundle " + bundleExpression + " for language " +
languageExpression + " into key " + key + ": " + t.getMessage());
}
- };
-
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
+/**
+ * A <code>ProducerNode</code> that simply executes a
+ * list of <code>ProducerNode</code>s sequentially
+ */
public class CompositeProducerNode implements ProducerNode {
private List subNodes;
public CompositeProducerNode(ProducerNode[] aSubNodes) {
this();
- int i;
-
- for (i=0; i<aSubNodes.length; i++) {
+ for (int i = 0; i<aSubNodes.length; i++) {
addSubNode(aSubNodes[i]);
}
}
}
public void addSubNode(ProducerNode aSubNode) {
- if (aSubNode!=null)
+ if (aSubNode != null) {
subNodes.add(aSubNode);
+ }
}
public void clear() {
subNodes.clear();
}
- protected boolean isAborted(Map aValueMap) {
- Object producerValue = aValueMap.get(NodedProducer.PRODUCER_KEY);
- return (
- (producerValue instanceof NodedProducer) &&
- ((NodedProducer) producerValue).getIsAborted());
+ protected boolean isAborted(ProductionContext aProductionContext) {
+ return aProductionContext.getProducer() instanceof NodedProducer &&
+ ((NodedProducer) aProductionContext.getProducer()).getIsAborted();
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure {
Iterator i = subNodes.iterator();
- while (i.hasNext() && !isAborted(aValueMap)) {
+ while (i.hasNext() && !isAborted(aProductionContext)) {
ProducerNode node = (ProducerNode) i.next();
- node.produce(aValueMap, aVerb, aLogger);
+ node.produce(aProductionContext);
}
}
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
+/**
+ * <code>ProducerNode</code> for conditional constructs.
+ *
+ * <p>
+ * Based on an expression that will be evaluated as a boolean,
+ * one of 2 subnodes will be called.
+ */
public class ConditionalProducerNode implements ProducerNode {
private String condition;
private ProducerNode trueNode;
falseNode = aFalseNode;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ /**
+ * {@inheritDoc}
+ */
+ public void produce(ProductionContext aProducerContext) throws ProducerExc, ProducerFailure {
try {
- if (ParameterExpander.evaluateBooleanExpression(aValueMap, condition)) {
+ if (ParameterExpander.evaluateBooleanExpression(aProducerContext.getValueSet(), condition)) {
if (trueNode!=null)
- trueNode.produce(aValueMap, aVerb, aLogger);
+ trueNode.produce(aProducerContext);
}
else {
if (falseNode!=null)
- falseNode.produce(aValueMap, aVerb, aLogger);
+ falseNode.produce(aProducerContext);
}
}
catch (Exception e) {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
+import mir.changetracker.ChangeTracker;
+import mir.changetracker.ChangeType;
+import mir.log.LoggerWrapper;
+import mir.util.FileRoutines;
+import mir.util.ParameterExpander;
+import mircoders.global.MirGlobal;
+
import java.io.File;
import java.util.Map;
-import mir.log.LoggerWrapper;
-import mir.util.FileFunctions;
-import mir.util.ParameterExpander;
+/**
+ *
+ */
+public class DirCopyingProducerNode extends AbstractProducerNode {
+
+ private String sourceExpression;
+ private String destinationExpression;
+ private File sourceBasePath;
+ private File destinationBasePath;
-public class DirCopyingProducerNode implements ProducerNode {
- private String sourceExpression;
- private String destinationExpression;
- private File sourceBasePath;
- private File destinationBasePath;
+ public DirCopyingProducerNode(File aSourceBasePath, File aDestinationBasePath, String aSource, String aDestination) {
+ sourceBasePath = aSourceBasePath;
+ destinationBasePath = aDestinationBasePath;
+ sourceExpression = aSource;
+ destinationExpression = aDestination;
+ }
- public DirCopyingProducerNode(File aSourceBasePath, File aDestinationBasePath, String aSource, String aDestination) {
- sourceBasePath = aSourceBasePath;
- destinationBasePath = aDestinationBasePath;
- sourceExpression = aSource;
- destinationExpression = aDestination;
- }
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ String source = "";
+ String destination = "";
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
- String source = "";
- String destination = "";
+ try {
+ source = ParameterExpander.expandExpression( aValueMap, sourceExpression );
+ destination = ParameterExpander.expandExpression( aValueMap, destinationExpression );
+ FileRoutines.copy(
+ new File(sourceBasePath, source),
+ new File(destinationBasePath, destination));
+ aLogger.info(source + " copied into " + destination);
+ // YOSS TODO: changed this puppy, is it the correct path?
+ reportChange(destinationBasePath + destination);
+ }
+ catch (Throwable e) {
+ aLogger.error("Copying " + source + " into " + destination + " failed: " + e.getMessage());
+ }
+ }
- try {
- source = ParameterExpander.expandExpression( aValueMap, sourceExpression );
- destination = ParameterExpander.expandExpression( aValueMap, destinationExpression );
- FileFunctions.copy(
- new File(sourceBasePath, source),
- new File(destinationBasePath, destination));
- aLogger.info(source + " copied into " + destination);
- }
- catch (Throwable e) {
- aLogger.error("Copying " + source + " into " + destination + " failed: " + e.getMessage());
- }
- }
+ private void reportChange(String destination) {
+ ChangeTracker changeTracker = MirGlobal.getChangeEngine().getTracker();
+ changeTracker.addChange(destination, ChangeType.MODIFICATION);
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.ArrayList;
-
import mir.entity.adapter.EntityAdapterModel;
import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
import mir.util.StringRoutines;
+import java.util.*;
+
/**
- * <p>Title: EntityBatchingProducerNode</p>
- * <p>Description:
- * This producer makes it possible to show articles in batches, like on archive
- * pages.
- *
- * <emph> The order by clause should lead to a result set in <b>reverse order<b>:
- * the first row will be the last entity in the last batch
- * </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * This producer makes it possible to show articles in batches, like on archive pages.
+ * <emph> The order by clause should lead to a result set in <b>reverse order</b>:
+ * the first row will be the last entity in the last batch </emph>
*/
public class EntityBatchingProducerNode implements ProducerNode {
((NodedProducer) producerValue).getIsAborted());
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ public void produce(ProductionContext aProducerContext) throws ProducerExc, ProducerFailure {
int nrEntities;
int nrBatchesAfterFirst;
int nrEntitiesInFirstBatch;
int minNrEntitiesInFirstBatch;
try {
- nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, nrBatchesToProcessExpression, -1 );
+ nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault(aProducerContext.getValueSet(), nrBatchesToProcessExpression, -1);
- expandedWhereClause = ParameterExpander.expandExpression( aValueMap, whereClause );
- expandedOrderByClause = ParameterExpander.expandExpression( aValueMap, orderByClause );
+ expandedWhereClause = ParameterExpander.expandExpression( aProducerContext.getValueSet(), whereClause );
+ expandedOrderByClause = ParameterExpander.expandExpression( aProducerContext.getValueSet(), orderByClause );
- nrEntitiesToSkip = ParameterExpander.evaluateIntegerExpression( aValueMap, nrEntitiesToSkipExpression);
- nrEntitiesPerBatch = ParameterExpander.evaluateIntegerExpression( aValueMap, nrEntitiesPerBatchExpression);
- minNrEntitiesInFirstBatch = ParameterExpander.evaluateIntegerExpression( aValueMap, minNrEntitiesInFirstBatchExpression);
- List extraTableList = StringRoutines.splitString(ParameterExpander.expandExpression( aValueMap, extraTables).trim(), ",");
+ nrEntitiesToSkip = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), nrEntitiesToSkipExpression);
+ nrEntitiesPerBatch = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), nrEntitiesPerBatchExpression);
+ minNrEntitiesInFirstBatch = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), minNrEntitiesInFirstBatchExpression);
+ List extraTableList = StringRoutines.splitString(ParameterExpander.expandExpression( aProducerContext.getValueSet(), extraTables).trim(), ",");
batchesData = new ArrayList();
batchLocations = new ArrayList();
- nrEntities = model.getMappingForName(definition).getStorage().getSize(
+ nrEntities = model.getMappingForName(definition).getDatabase().getSize(
mainTablePrefix, extraTableList, expandedWhereClause)-nrEntitiesToSkip;
nrEntitiesInFirstBatch = nrEntities % nrEntitiesPerBatch;
while (nrEntitiesInFirstBatch<minNrEntitiesInFirstBatch && nrEntities-nrEntitiesInFirstBatch>=nrEntitiesPerBatch)
}
batchData = new HashMap();
- ParameterExpander.setValueForKey(aValueMap, batchInfoKey, batchData);
+ ParameterExpander.setValueForKey(aProducerContext.getValueSet(), batchInfoKey, batchData);
batchData.put("all", batchesData);
batchData.put("first", batchesData.get(0));
batchData.put("last", batchesData.get(batchesData.size()-1));
batchData.put("count", new Integer(batchesData.size()));
- if (batchListSubNode!=null && (!isAborted(aValueMap))) {
- batchListSubNode.produce(aValueMap, aVerb, aLogger);
+ if (batchListSubNode!=null && (!isAborted(aProducerContext.getValueSet()))) {
+ batchListSubNode.produce(aProducerContext);
}
if (nrBatchesToProcess<0 || nrBatchesToProcess>nrBatchesAfterFirst+1) {
}
if (batchSubNode!=null) {
- for (i=0; i<nrBatchesToProcess && !isAborted(aValueMap); i++) {
+ for (i=0; i<nrBatchesToProcess && !isAborted(aProducerContext.getValueSet()); i++) {
location = (BatchLocation) batchLocations.get(i);
batchData.put("current", batchesData.get(i));
while (j.hasNext())
entities.add(0, j.next());
- ParameterExpander.setValueForKey(aValueMap, batchDataKey, entities );
+ ParameterExpander.setValueForKey(aProducerContext.getValueSet(), batchDataKey, entities );
- batchSubNode.produce(aValueMap, aVerb, aLogger);
+ batchSubNode.produce(aProducerContext);
}
}
}
catch (Throwable t) {
- aLogger.error("EntityBatchingProducerNode caused an exception: " + t.getMessage());
+ aProducerContext.getLogger().warn("EntityBatchingProducerNode caused an exception: " + t.getMessage());
}
- };
+ }
private class BatchLocation {
int nrEntities;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Map;
-
import mir.entity.adapter.EntityAdapterModel;
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
-public class EntityDeletingProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class EntityDeletingProducerNode extends AbstractProducerNode {
private String whereClause;
private EntityAdapterModel model;
private String definition;
try {
EntityAdapterModel.Mapping mapping = model.getMappingForName(definition);
- mapping.getStorage().deleteByWhereClause(ParameterExpander.expandExpression( aValueMap, whereClause ));
+ mapping.getDatabase().deleteByWhereClause(ParameterExpander.expandExpression( aValueMap, whereClause ));
}
catch (Throwable t) {
aLogger.error("Error while deleting entities: " + t.toString());
}
- };
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Iterator;
-import java.util.Map;
-
import mir.entity.adapter.EntityAdapterModel;
import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
import mir.util.StringRoutines;
+import java.util.Iterator;
+
public class EntityEnumeratingProducerNode extends ProducerNodeDecorator {
private String key;
private EntityAdapterModel model;
skip = aSkip;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure {
Iterator browser;
try {
browser = new EntityIteratorAdapter(
mainTablePrefix,
- StringRoutines.splitString(ParameterExpander.expandExpression( aValueMap, extraTables).trim(), ","),
- ParameterExpander.expandExpression( aValueMap, whereClause ),
- ParameterExpander.expandExpression( aValueMap, orderByClause ),
+ StringRoutines.splitString(ParameterExpander.expandExpression(aProductionContext.getValueSet(),
+ extraTables).trim(), ","),
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(), whereClause),
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(), orderByClause),
100,
model,
definition,
- ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, limit, -1),
- ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, skip, 0));
+ ParameterExpander.evaluateIntegerExpressionWithDefault(aProductionContext.getValueSet(), limit, -1),
+ ParameterExpander.evaluateIntegerExpressionWithDefault(aProductionContext.getValueSet(), skip, 0));
+
+ while (browser.hasNext() && !isAborted(aProductionContext)) {
+ ParameterExpander.setValueForKey(aProductionContext.getValueSet(), key, browser.next());
- while (browser.hasNext() && !isAborted(aValueMap)) {
- ParameterExpander.setValueForKey( aValueMap, key, browser.next());
- super.produce(aValueMap, aVerb, aLogger);
+ super.produce(aProductionContext);
}
}
catch (Throwable t) {
- aLogger.error("Exception occurred inside an EntityEnumeratingProducerNode: " + t.getMessage());
+ aProductionContext.getLogger().warn("Exception occurred inside an EntityEnumeratingProducerNode: " +
+ t.getMessage());
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Collections;
-import java.util.Map;
-
import mir.entity.adapter.EntityAdapterModel;
import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
import mir.util.CachingRewindableIterator;
import mir.util.ParameterExpander;
import mir.util.StringRoutines;
+import java.util.Collections;
+
public class EntityListProducerNode extends ProducerNodeDecorator {
private String keyExpression;
private String whereClause;
skipExpression = aSkipExpression;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc {
try {
- int limit = ParameterExpander.evaluateIntegerExpressionWithDefault(aValueMap, limitExpression, -1);
- int skip = ParameterExpander.evaluateIntegerExpressionWithDefault(aValueMap, skipExpression, 0);
+ int limit = ParameterExpander.evaluateIntegerExpressionWithDefault(aProductionContext.getValueSet(), limitExpression, -1);
+ int skip = ParameterExpander.evaluateIntegerExpressionWithDefault(aProductionContext.getValueSet(), skipExpression, 0);
if (skipExpression != null && !skipExpression.trim().equals(""))
- skip = ParameterExpander.evaluateIntegerExpression(aValueMap, skipExpression);
- String key = ParameterExpander.expandExpression(aValueMap, keyExpression);
+ skip = ParameterExpander.evaluateIntegerExpression(aProductionContext.getValueSet(), skipExpression);
+ String key = ParameterExpander.expandExpression(aProductionContext.getValueSet(), keyExpression);
try {
ParameterExpander.setValueForKey(
- aValueMap,
+ aProductionContext.getValueSet(),
key,
new CachingRewindableIterator(
new EntityIteratorAdapter( mainTablePrefix,
- StringRoutines.splitString(ParameterExpander.expandExpression( aValueMap, extraTables).trim(), ","),
- ParameterExpander.expandExpression( aValueMap, whereClause ),
- ParameterExpander.expandExpression( aValueMap, orderByClause ),
+ StringRoutines.splitString(ParameterExpander.expandExpression(aProductionContext.getValueSet(), extraTables).trim(), ","),
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(), whereClause ),
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(), orderByClause ),
Math.min(50, limit),
model,
definition,
);
}
catch (Throwable t) {
- aLogger.error("cannot retrieve list into keyExpression " + key + ": " + t.getMessage());
+ aProductionContext.getLogger().warn("cannot retrieve list into keyExpression " + key, t);
+
try {
ParameterExpander.setValueForKey(
- aValueMap,
+ aProductionContext.getValueSet(),
key,
new CachingRewindableIterator(Collections.EMPTY_LIST.iterator())
);
}
}
catch (Throwable t) {
- aLogger.error("cannot process entity list producer node: : " + t.getMessage());
+ aProductionContext.getLogger().error("cannot process entity list producer node: : ", t);
}
- super.produce(aValueMap, aVerb, aLogger);
+ super.produce(aProductionContext);
}
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.entity.adapter.EntityAdapterModel;
import mir.util.JDBCStringRoutines;
import mir.util.ParameterExpander;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
-public class EntityModifyingProducerNode implements ProducerNode {
+public class EntityModifyingProducerNode extends AbstractProducerNode {
private String entityExpression;
private String definition;
private Map fields;
throw new ProducerExc( entityExpression + " does not evaluate to an entity");
}
catch (Throwable t) {
- aLogger.error("Error while performing entity modification operation: " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ aLogger.error("Error while performing entity modification operation: " + t.getMessage(), t);
throw new ProducerFailure(t.getMessage(), t);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
-public class EvaluatedAssignmentProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class EvaluatedAssignmentProducerNode extends AbstractProducerNode {
private String key;
- private String bundleIdentifier;
private String value;
public EvaluatedAssignmentProducerNode(String aKey, String aValue) {
catch (Throwable t) {
aLogger.error("key " + key + " could not be set to " + value + ": " + t.getMessage());
}
- };
+ }
}
\ No newline at end of file
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mir.producer;\r
-\r
-import java.util.Map;\r
-\r
-import mir.log.LoggerWrapper;\r
-import mir.util.ParameterExpander;\r
-\r
-public class ExecuteProgramProducerNode implements ProducerNode {\r
- private String scriptExpression;\r
- private String maxDurationExpression;\r
- private String outputVariableExpression;\r
- private String returnValueVariableExpression;\r
-\r
- public ExecuteProgramProducerNode(String aScriptExpression, String aMaxDurationExpression, String anOutputVariableExpression,\r
- String aReturnValueVariableExpression) {\r
- scriptExpression = aScriptExpression;\r
- maxDurationExpression = aMaxDurationExpression;\r
- outputVariableExpression = anOutputVariableExpression;\r
- returnValueVariableExpression = aReturnValueVariableExpression;\r
- }\r
-\r
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {\r
- String script;\r
- long maxDuration;\r
-\r
- try {\r
- script = ParameterExpander.expandExpression(aValueMap, scriptExpression);\r
- maxDuration = ParameterExpander.evaluateIntegerExpressionWithDefault(aValueMap, maxDurationExpression, 0);\r
-\r
- ProcessRunner runner = new ProcessRunner(aLogger, script);\r
- runner.start();\r
-\r
- synchronized (runner) {\r
- runner.wait(maxDuration);\r
- }\r
- runner.interrupt();\r
-\r
- if (runner.getFinished()) {\r
- aLogger.info(script + " terminated successfully, return value = " + runner.getReturnValue() + ".");\r
-\r
- if (returnValueVariableExpression != null) {\r
- ParameterExpander.setValueForKey(aValueMap,\r
- ParameterExpander.expandExpression(aValueMap, returnValueVariableExpression),\r
- new Integer(runner.getReturnValue()));\r
- }\r
-\r
- }\r
- else {\r
- aLogger.info(script + " interrupted prematurely after " + maxDuration + "ms.");\r
- }\r
- }\r
- catch (Throwable e) {\r
- aLogger.error("Error while executing " + scriptExpression + " : " + e.toString());\r
- }\r
- }\r
-\r
- private static class ProcessRunner extends Thread {\r
- private String script;\r
- private boolean finished = false;\r
- private int returnValue = 0;\r
- private LoggerWrapper logger;\r
-\r
- public ProcessRunner(LoggerWrapper aLogger, String aScript) {\r
- script = aScript;\r
- logger = aLogger;\r
- }\r
-\r
- public boolean getFinished() {\r
- return finished;\r
- }\r
-\r
- public int getReturnValue() {\r
- return returnValue;\r
- }\r
-\r
- public void run() {\r
- Process process = null;\r
- try {\r
- process = Runtime.getRuntime().exec(script);\r
- returnValue = process.waitFor();\r
-\r
- finished = true;\r
-\r
- synchronized (this) {\r
- this.notify();\r
- }\r
- }\r
- catch (InterruptedException e) {\r
- if (process!=null) {\r
- process.destroy();\r
- }\r
- }\r
- catch (Exception e) {\r
- logger.error(script + " failed to execute: " + e.getMessage());\r
- }\r
- }\r
- }\r
-\r
-}\r
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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;
+
+import mir.log.LoggerWrapper;
+import mir.util.ParameterExpander;
+
+import java.util.Map;
+
+public class ExecuteProgramProducerNode extends AbstractProducerNode {
+ private String scriptExpression;
+ private String maxDurationExpression;
+ private String outputVariableExpression;
+ private String returnValueVariableExpression;
+
+ public ExecuteProgramProducerNode(String aScriptExpression, String aMaxDurationExpression, String anOutputVariableExpression,
+ String aReturnValueVariableExpression) {
+ scriptExpression = aScriptExpression;
+ maxDurationExpression = aMaxDurationExpression;
+ outputVariableExpression = anOutputVariableExpression;
+ returnValueVariableExpression = aReturnValueVariableExpression;
+ }
+
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ String script;
+ long maxDuration;
+
+ try {
+ script = ParameterExpander.expandExpression(aValueMap, scriptExpression);
+ maxDuration = ParameterExpander.evaluateIntegerExpressionWithDefault(aValueMap, maxDurationExpression, 0);
+
+ ProcessRunner runner = new ProcessRunner(aLogger, script);
+ runner.start();
+
+ synchronized (runner) {
+ runner.wait(maxDuration);
+ }
+ runner.interrupt();
+
+ if (runner.getFinished()) {
+ aLogger.info(script + " terminated successfully, return value = " + runner.getReturnValue() + ".");
+
+ if (returnValueVariableExpression != null) {
+ ParameterExpander.setValueForKey(aValueMap,
+ ParameterExpander.expandExpression(aValueMap, returnValueVariableExpression),
+ new Integer(runner.getReturnValue()));
+ }
+
+ }
+ else {
+ aLogger.info(script + " interrupted prematurely after " + maxDuration + "ms.");
+ }
+ }
+ catch (Throwable e) {
+ aLogger.error("Error while executing " + scriptExpression + " : " + e.toString());
+ }
+ }
+
+ private static class ProcessRunner extends Thread {
+ private String script;
+ private boolean finished = false;
+ private int returnValue = 0;
+ private LoggerWrapper logger;
+
+ public ProcessRunner(LoggerWrapper aLogger, String aScript) {
+ script = aScript;
+ logger = aLogger;
+ }
+
+ public boolean getFinished() {
+ return finished;
+ }
+
+ public int getReturnValue() {
+ return returnValue;
+ }
+
+ public void run() {
+ Process process = null;
+ try {
+ process = Runtime.getRuntime().exec(script);
+ returnValue = process.waitFor();
+
+ finished = true;
+
+ synchronized (this) {
+ this.notify();
+ }
+ }
+ catch (InterruptedException e) {
+ if (process!=null) {
+ process.destroy();
+ }
+ }
+ catch (Exception e) {
+ logger.error(script + " failed to execute: " + e.getMessage());
+ }
+ }
+ }
+
+}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
-public class ExpandedAssignmentProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class ExpandedAssignmentProducerNode extends AbstractProducerNode {
private String key;
- private String bundleIdentifier;
private String value;
public ExpandedAssignmentProducerNode(String aKey, String aValue) {
catch (Throwable t) {
aLogger.error("key " + key + " could not be set to " + value + ": " + t.getMessage());
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
+import mir.util.ParameterExpander;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
-import java.sql.*;
-
-
-import mir.log.LoggerWrapper;
-import mir.util.ExceptionFunctions;
-import mir.util.ParameterExpander;
public class ExternalDbProducerNode extends ProducerNodeDecorator {
private String key;
private String database;
private String username;
private String password;
- private String query;
-
+ private String query;
- public ExternalDbProducerNode(String aKey, String aDriver, String aHost, String aPort, String aDatabase, String aUsername, String aPassword,String aQuery,ProducerNode aSubNode) {
+ public ExternalDbProducerNode(String aKey, String aDriver, String aHost, String aPort, String aDatabase, String aUsername, String aPassword, String aQuery, ProducerNode aSubNode) {
super(aSubNode);
+
key = aKey;
driver = aDriver;
host = aHost;
database = aDatabase;
username = aUsername;
password = aPassword;
- query =aQuery;
-
+ query = aQuery;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure {
try {
- String expandedKey = ParameterExpander.expandExpression( aValueMap, key );
- String expandedDriver = ParameterExpander.expandExpression( aValueMap, driver);
- String expandedHost = ParameterExpander.expandExpression( aValueMap, host);
- String expandedPort = ParameterExpander.expandExpression( aValueMap, port);
- String expandedDatabase = ParameterExpander.expandExpression( aValueMap, database);
- String expandedUsername = ParameterExpander.expandExpression( aValueMap, username);
- String expandedPassword = ParameterExpander.expandExpression( aValueMap, password);
- String expandedQuery = ParameterExpander.expandExpression( aValueMap, query);
+ String expandedKey = ParameterExpander.expandExpression(aProductionContext.getValueSet(), key);
+ String expandedDriver = ParameterExpander.expandExpression(aProductionContext.getValueSet(), driver);
+ String expandedHost = ParameterExpander.expandExpression(aProductionContext.getValueSet(), host);
+ String expandedPort = ParameterExpander.expandExpression(aProductionContext.getValueSet(), port);
+ String expandedDatabase = ParameterExpander.expandExpression(aProductionContext.getValueSet(), database);
+ String expandedUsername = ParameterExpander.expandExpression(aProductionContext.getValueSet(), username);
+ String expandedPassword = ParameterExpander.expandExpression(aProductionContext.getValueSet(), password);
+ String expandedQuery = ParameterExpander.expandExpression(aProductionContext.getValueSet(), query);
- if (expandedDriver.equals("postgresql")){
- Class.forName("org.postgresql.Driver");
+ if ("postgresql".equals(expandedDriver)) {
+ Class.forName("org.postgresql.Driver");
}
- if (expandedDriver.equals("mysql")){
- Class.forName("com.mysql.jdbc.Driver");
+ if ("mysql".equals(expandedDriver)) {
+ Class.forName("com.mysql.jdbc.Driver");
}
else {
- throw new Exception("Unsupported DB Driver:"+expandedDriver);
+ throw new Exception("Unsupported DB Driver:" + expandedDriver);
}
-
- Connection db = DriverManager.getConnection("jdbc:"+expandedDriver+"://"+expandedHost
- +":"+expandedPort+"/"+expandedDatabase
- , expandedUsername, expandedPassword);
-
+
+ Connection db = DriverManager.getConnection("jdbc:" + expandedDriver + "://" + expandedHost
+ + ":" + expandedPort + "/" + expandedDatabase
+ , expandedUsername, expandedPassword);
+
Statement st = db.createStatement();
ResultSet rs = st.executeQuery(expandedQuery);
ResultSetMetaData rsmd = rs.getMetaData();
- int numberOfColumns= rsmd.getColumnCount();
- ArrayList fieldNames = new ArrayList(numberOfColumns);
- for (int i=0;i<numberOfColumns;i++){
- fieldNames.add(rsmd.getColumnName(i+1));
+ int numberOfColumns = rsmd.getColumnCount();
+ List fieldNames = new ArrayList(numberOfColumns);
+ for (int i = 0; i < numberOfColumns; i++) {
+ fieldNames.add(rsmd.getColumnName(i + 1));
}
- while(rs.next() && !isAborted(aValueMap)) {
- HashMap result=new HashMap();
- Iterator fields = fieldNames.iterator();
- while (fields.hasNext()) {
- String field=(String) fields.next();
- result.put(field,rs.getString(field));
- }
- ParameterExpander.setValueForKey(aValueMap,expandedKey,result);
- super.produce(aValueMap, aVerb, aLogger);
+ while (rs.next() && !isAborted(aProductionContext)) {
+ Map result = new HashMap();
+ Iterator fields = fieldNames.iterator();
+ while (fields.hasNext()) {
+ String field = (String) fields.next();
+ result.put(field, rs.getString(field));
+ }
+ ParameterExpander.setValueForKey(aProductionContext.getValueSet(), expandedKey, result);
+ super.produce(aProductionContext);
}
rs.close();
st.close();
db.close();
}
catch (Throwable t) {
- Throwable s = ExceptionFunctions.traceCauseException(t);
- aLogger.error("Error while accessing external database: " + s.getClass().getName()+","+ s.getMessage());
+ aProductionContext.getLogger().warn("Error while accessing external database", t);
}
- };
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
import java.util.Date;
import java.util.Map;
+import mir.changetracker.ChangeTracker;
+import mir.changetracker.ChangeType;
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
+import mircoders.global.MirGlobal;
public class FileDateSettingProducerNode extends FileOperationProducerNode {
String dateExpression;
if (!aFile.setLastModified(((Date) date).getTime())) {
aLogger.error("Can't set date for " + aFile.getName());
}
+ else
+ {
+ ChangeTracker tracker = MirGlobal.getChangeEngine().getTracker();
+ tracker.addChange(aFile.getAbsolutePath(), ChangeType.MODIFICATION);
+ }
}
catch (Throwable t) {
aLogger.error( "File " + aFile.getName() + " could not be set to date " + dateExpression + ": " + t.getMessage());
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
+import mir.changetracker.ChangeTracker;
+import mir.changetracker.ChangeType;
+import mir.log.LoggerWrapper;
+import mircoders.global.MirGlobal;
+
import java.io.File;
import java.util.Map;
-import mir.log.LoggerWrapper;
-
public class FileDeletingProducerNode extends FileOperationProducerNode {
public FileDeletingProducerNode(String aFileIdentifier) {
}
protected void perform(File aFile, Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
- if (!aFile.delete()) {
- aLogger.error("Can't delete file " + aFile.getName());
+ try {
+ if (!aFile.delete()) {
+ throw new Exception("Unable to delete file " + aFile);
+ }
+
+ // Notify the change tracker that the file was deleted
+ ChangeTracker tracker = MirGlobal.getChangeEngine().getTracker();
+ tracker.addChange(aFile.getAbsolutePath(), ChangeType.DELETION);
+
+ aLogger.debug("File " + aFile.getName() + " deleted");
}
- else {
- aLogger.info("File " + aFile.getName() + " deleted");
+ catch (Throwable t) {
+ aLogger.warn("Can't delete file " + aFile.getAbsolutePath());
}
}
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.io.File;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
-public abstract class FileOperationProducerNode implements ProducerNode {
- String fileName;
+import java.io.File;
+import java.util.Map;
+
+public abstract class FileOperationProducerNode extends AbstractProducerNode {
+ private String fileName;
public FileOperationProducerNode(String aFileName) {
fileName = aFileName;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.util.ParameterExpander;
-public class FreeQueryProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class FreeQueryProducerNode extends AbstractProducerNode {
public static final int QUERY_TYPE_SET = 1;
public static final int QUERY_TYPE_ROW = 2;
public static final int QUERY_TYPE_VALUE = 3;
catch (Throwable t) {
aLogger.error("Error while setting key " + key + ": " + t.toString());
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
import java.util.HashMap;
import java.util.Map;
+import mir.changetracker.ChangeTracker;
+import mir.changetracker.ChangeType;
import mir.generator.Generator;
import mir.generator.WriterEngine;
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
+import mircoders.global.MirGlobal;
-public class GeneratingProducerNode implements ProducerNode {
+public class GeneratingProducerNode extends AbstractProducerNode {
private String generatorExpression;
private String destinationExpression;
private String parametersExpression;
private Generator.Library generatorLibrary;
private WriterEngine writerEngine;
+ private Generator.Interceptor interceptor;
- public GeneratingProducerNode(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination, String aParameters) {
+ public GeneratingProducerNode(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine, Generator.Interceptor anInterceptor, String aGenerator, String aDestination, String aParameters) {
generatorExpression=aGenerator;
destinationExpression=aDestination;
parametersExpression=aParameters;
generatorLibrary = aGeneratorLibrary;
writerEngine = aWriterEngine;
+ interceptor = anInterceptor;
}
- public GeneratingProducerNode(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine, String aGenerator, String aDestination) {
- this(aGeneratorLibrary, aWriterEngine, aGenerator, aDestination, "");
+ public GeneratingProducerNode(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine, Generator.Interceptor anInterceptor, String aGenerator, String aDestination) {
+ this(aGeneratorLibrary, aWriterEngine, anInterceptor, aGenerator, aDestination, "");
}
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
destinationIdentifier = ParameterExpander.expandExpression(aValueMap, destinationExpression);
generatorIdentifier = ParameterExpander.expandExpression(aValueMap, generatorExpression);
parameters = ParameterExpander.expandExpression(aValueMap, parametersExpression);
-
+ //String relPathExpression = "/${article.date.formatted.yyyy}/${article.date.formatted.MM}/${article.id}.shtml";
+ //String relativePath = ParameterExpander.expandExpression(aValueMap, relPathExpression);
mirMap.put("generator", generatorIdentifier);
mirMap.put("destination", destinationIdentifier);
mirMap.put("parameters", parameters);
writer = writerEngine.openWriter(destinationIdentifier, parameters);
- generator = generatorLibrary.makeGenerator(generatorIdentifier);
+ generator = generatorLibrary.makeGenerator(generatorIdentifier, interceptor);
generator.generate(writer, aValueMap, aLogger);
writerEngine.closeWriter(writer);
endTime = System.currentTimeMillis();
- aLogger.info("Generated " + generatorIdentifier + " into " + destinationIdentifier + " [" + parameters + "] in " + (endTime - startTime) + " ms");
+ aLogger.debug("Generated " + generatorIdentifier + " into " + destinationIdentifier + " [" + parameters + "] in " + (endTime - startTime) + " ms");
+ reportChange(destinationIdentifier);
}
finally {
mirMap.put("generator", oldGenerator);
}
}
catch (Throwable t) {
- aLogger.error(" error while generating: " + t.getClass().getName() + ": " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ aLogger.error(" error while generating", t);
}
}
+
+ private void reportChange(String aPath) {
+ ChangeTracker changeTracker = MirGlobal.getChangeEngine().getTracker();
+ changeTracker.addChange(aPath, ChangeType.MODIFICATION);
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
import mir.util.RewindableIterator;
+import java.util.Collection;
+import java.util.Iterator;
+
public class ListEnumeratingProducerNode extends ProducerNodeDecorator {
private String key;
private String listExpression;
listExpression = aListExpression;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc {
Iterator browser;
Object list;
try {
- list = ParameterExpander.evaluateExpression(aValueMap, listExpression);
+ list = ParameterExpander.evaluateExpression(aProductionContext.getValueSet(), listExpression);
if (list != null) {
- if (list instanceof Collection)
+ if (list instanceof Collection) {
browser = ( (Collection) list).iterator();
- else if (list instanceof Iterator)
+ }
+ else if (list instanceof Iterator) {
browser = (Iterator) list;
- else
+ }
+ else {
throw new ProducerExc("Can't enumarate a " + list.getClass().getName());
+ }
if (browser instanceof RewindableIterator) {
- ( (RewindableIterator) browser).rewind();
+ ((RewindableIterator) browser).rewind();
}
- while (browser.hasNext() && !isAborted(aValueMap)) {
- ParameterExpander.setValueForKey(aValueMap, key, browser.next());
- super.produce(aValueMap, aVerb, aLogger);
+ while (browser.hasNext() && !isAborted(aProductionContext)) {
+ ParameterExpander.setValueForKey(aProductionContext.getValueSet(), key, browser.next());
+
+ super.produce(aProductionContext);
}
}
}
catch (Throwable t) {
- aLogger.error("Exception occurred inside an ListEnumeratingProducerNode: " + t.getMessage());
+ aProductionContext.getLogger().warn("Exception occurred inside an ListEnumeratingProducerNode", t);
}
- };
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
-public class LoggingProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class LoggingProducerNode extends AbstractProducerNode {
private String expression;
private int messageType;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
import mir.util.ParameterExpander;
condition = aCondition;
}
-
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure {
int loopNr;
int maxNrLoops;
try {
loopNr = 0;
- maxNrLoops = ParameterExpander.evaluateIntegerExpressionWithDefault(aValueMap, limit, 1000);
- while (ParameterExpander.evaluateBooleanExpression(aValueMap, condition) &&
- (loopNr<maxNrLoops) &&
- !isAborted(aValueMap)) {
- super.produce(aValueMap, aVerb, aLogger);
+ maxNrLoops = ParameterExpander.evaluateIntegerExpressionWithDefault(aProductionContext.getValueSet(), limit, 1000);
+ while (ParameterExpander.evaluateBooleanExpression(aProductionContext.getValueSet(), condition) &&
+ (loopNr<maxNrLoops) && !isAborted(aProductionContext)) {
+ super.produce(aProductionContext);
+
loopNr++;
}
}
catch (Throwable t) {
- aLogger.error("LoopProducerNode raised an exception: " + t.getMessage());
+ aProductionContext.getLogger().warn("LoopProducerNode raised an exception", t);
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.HashMap;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
+/**
+ * <p>A NodedProducer is the root of a tree of ProducerNodes.</p>
+ *
+ * <p>There used to be a time when there were Producers that weren't
+ * NodedProducers, however they have been phased out.</p>
+ */
public class NodedProducer implements Producer {
private ProducerNode rootNode;
- private String verb;
- private Map baseValues;
private boolean isAborted;
private boolean isFinished;
protected final static String PRODUCER_KEY = "$producer";
- public NodedProducer( ProducerNode aRootNode, String aVerb, Map aBaseValues) {
+ public NodedProducer(ProducerNode aRootNode) {
rootNode = aRootNode;
- verb = aVerb;
- baseValues = aBaseValues;
isAborted = false;
}
- public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc {
- Map valueMap;
-
- valueMap = new HashMap();
- valueMap.putAll(baseValues);
- valueMap.put(PRODUCER_KEY, this);
-
- rootNode.produce(valueMap, verb, aLogger);
+ public boolean execute(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc {
+ rootNode.produce(aProductionContext);
synchronized(this) {
isFinished=true;
+
return !isAborted;
}
- };
+ }
- public void abort() {
+ public void abort(ProductionContext aContext) {
synchronized(this) {
if (!isFinished)
isAborted=true;
return isAborted;
}
}
-
- public boolean getIsFinished() {
- synchronized(this) {
- return isFinished;
- }
- }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import mir.log.LoggerWrapper;
-
+/**
+ * <p>A Producer is a set of tasks, scripted in xml. Producers allow
+ * mir installations to have their own actions that can be called for
+ * instance when a new article is posted. Originally producers were
+ * mostly used to generate pages, but they are used for a lot of
+ * other tasks such as pulling rss feeds for the global wire on
+ * indymedia.org. </p>
+ *
+ * <p>Producers can be easily added and configured through the
+ * producers.xml file.</p>
+ *
+ * <p>In the admin web interface, producers appear, for example, on
+ * the admin->"Generate manually"->"advanced page": (as Tasks)</p>
+ *
+ * <p>Architecture: a "poducer" tag in the producers.xml file defines
+ * a small program. This program (or script) may contain constructs
+ * such as if, loop, and variables... The program is parsed into a
+ * tree of ProducerNodes. The root of this tree is defined in a
+ * NodedProducer (which is the only class that currently implements
+ * the Producer interface). When the Producer is executed, the
+ * "produce" methods of each node are recursively called, effectively
+ * executing the program as it was scripted</p>
+ */
public interface Producer {
/**
- *
- *
- * @param aLogger
- * @return <code>false</code> if aborted,<code>true</code> if not
- * @throws ProducerFailure
- * @throws ProducerExc
+ * Execute the producer
+ */
+ public boolean execute(ProductionContext aContext) throws ProducerFailure, ProducerExc;
+
+ /**
+ * Abort the execution of the producer. Will be called from a different
+ * thread and implementations should take this into account.
*/
- public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc;
- public void abort();
+ public void abort(ProductionContext aContext);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
public ProducerExc(String aMessage) {
super(aMessage);
}
+
+ public ProducerExc(String aMessage, Throwable aCause) {
+ super(aMessage, aCause);
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Map;
import java.util.List;
+import java.util.Map;
+/**
+ *
+ */
public interface ProducerFactory {
public interface ProducerVerb {
String getName();
public Producer makeProducer(String aVerb, Map aStartingValues) throws ProducerFailure, ProducerExc;
/**
- * The set of pre-defined verbs. Returns a list of {@link ProducerVerb}s
+ * The set of pre-defined verbs. Returns a <code>List</code> of {@link ProducerVerb}s
*/
public List verbs();
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
import multex.Failure;
public class ProducerFailure extends Failure {
-
- public ProducerFailure(String msg,Throwable cause) {
+ public ProducerFailure(String msg,Throwable cause) {
super(msg,cause);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
-
/**
- * A <code>ProducerNode</code> is an atom of a noded producer factory.
- *
+ * A <code>ProducerNode</code> forms a building block of a noded producer factory.
*/
public interface ProducerNode {
/**
- * Perform the operations of the producer node, based on a verb and a value set.
- * The supplied logger object should be used for any logging.
+ * Perform the operations of the producer node, using the {@link ProductionContext}.
*/
- public void produce(Map aValueSet, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure;
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure;
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
-
-public class ProducerNodeDecorator implements ProducerNode {
+public abstract class ProducerNodeDecorator implements ProducerNode {
private ProducerNode slave;
protected ProducerNodeDecorator(ProducerNode aSlave) {
slave = aSlave;
}
- protected boolean isAborted(Map aValueMap) {
- Object producerValue = aValueMap.get(NodedProducer.PRODUCER_KEY);
+ protected boolean isAborted(ProductionContext aProductionContext) {
return (
- (producerValue instanceof NodedProducer) &&
- ((NodedProducer) producerValue).getIsAborted());
+ (aProductionContext.getProducer() instanceof NodedProducer) &&
+ ((NodedProducer) aProductionContext.getProducer()).getIsAborted());
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
- if (slave!=null)
- slave.produce(aValueMap, aVerb, aLogger);
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure {
+ if (slave!=null) {
+ slave.produce(aProductionContext);
+ }
}
}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.producer;\r
+\r
+import mir.log.LoggerWrapper;\r
+\r
+import java.util.Map;\r
+\r
+/**\r
+ * <code>ProductionContext</code> incorporates all facilities available\r
+ * to a producer during production\r
+ */\r
+public interface ProductionContext {\r
+ ProducerFactory getFactory();\r
+ Producer getProducer();\r
+ String getVerb();\r
+ LoggerWrapper getLogger();\r
+ Map getValueSet();\r
+ // ProductionSpace getProductionSpace();\r
+}\r
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.List;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.rss.RSSAggregator;
-import mir.util.ExceptionFunctions;
+import mir.util.ExceptionRoutines;
import mir.util.ParameterExpander;
-public class RDFAggregatorProducerNode implements ProducerNode {
+import java.util.List;
+import java.util.Map;
+
+public class RDFAggregatorProducerNode extends AbstractProducerNode {
private String key;
private String source;
- private String order;
- private String filter;
- public RDFAggregatorProducerNode(String aKey, String aSource, String anOrder, String aFilter) {
+ public RDFAggregatorProducerNode(String aKey, String aSource) {
key = aKey;
source=aSource;
- order=anOrder;
- filter=aFilter;
}
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
try {
aLogger.debug(source);
String evaluatedKey = ParameterExpander.expandExpression( aValueMap, key );
- String evaluatedOrder = ParameterExpander.expandExpression( aValueMap, order );
Object evaluatedSource = ParameterExpander.evaluateExpression( aValueMap, source );
Object aggregator = aValueMap.get(evaluatedKey);
throw new ProducerExc("RSSAggregator expected, " + aggregator.toString() + " found");
}
catch (Throwable t) {
- Throwable s = ExceptionFunctions.traceCauseException(t);
+ Throwable s = ExceptionRoutines.traceCauseException(t);
aLogger.error("Error while aggregating RDF data: " + s.getClass().getName()+","+ s.getMessage());
}
- };
+ }
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer;
-import java.util.Map;
-
import mir.log.LoggerWrapper;
import mir.rss.RSS091Reader;
import mir.rss.RSSData;
import mir.rss.RSSReader;
-import mir.util.ExceptionFunctions;
import mir.util.ParameterExpander;
-public class RSSProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class RSSProducerNode extends AbstractProducerNode {
private String key;
private String url;
private String version;
ParameterExpander.setValueForKey(aValueMap, expandedKey, rssData);
}
catch (Throwable t) {
- Throwable s = ExceptionFunctions.traceCauseException(t);
- aLogger.error("Error while processing RSS data: " + s.getClass().getName()+","+ s.getMessage());
+ aLogger.warn("Error while processing RSS data", t);
}
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
+++ /dev/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 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;
-
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
-
-public class ValuesMapProducerNode extends ProducerNodeDecorator {
- private String key;
- private String bundleIdentifier;
- private Map map;
-
- public ValuesMapProducerNode(Map aMap, ProducerNode aSubNode) {
- super(aSubNode);
- }
-
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
- try {
- aValueMap.putAll(map);
-
- super.produce(aValueMap, aVerb, aLogger);
- }
- catch (Throwable t) {
- throw new ProducerFailure(t.getMessage(), t);
- }
- };
-}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer.reader;
+import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.io.File;
import mir.entity.adapter.EntityAdapterModel;
import mir.generator.Generator;
import mir.generator.WriterEngine;
import mir.log.LoggerWrapper;
+import mir.producer.BundleProducerNode;
import mir.producer.ConditionalProducerNode;
import mir.producer.DirCopyingProducerNode;
import mir.producer.EntityBatchingProducerNode;
import mir.producer.EntityListProducerNode;
import mir.producer.EntityModifyingProducerNode;
import mir.producer.EvaluatedAssignmentProducerNode;
+import mir.producer.ExecuteProgramProducerNode;
import mir.producer.ExpandedAssignmentProducerNode;
import mir.producer.ExternalDbProducerNode;
import mir.producer.FileDateSettingProducerNode;
import mir.producer.ProducerNode;
import mir.producer.RDFAggregatorProducerNode;
import mir.producer.RSSProducerNode;
-import mir.producer.BundleProducerNode;
-import mir.producer.ExecuteProgramProducerNode;
import mir.util.StringRoutines;
import mir.util.xml.XMLParserExc;
import mir.util.xml.XMLReaderTool;
public static void registerBuilders(ProducerNodeBuilderLibrary aBuilderLibrary,
EntityAdapterModel aModel, Generator.Library aGeneratorLibrary,
+ Generator.Interceptor anInterceptor,
WriterEngine aWriterEngine, File aSourceBasePath, File aDestinationBasePath) throws ProducerConfigExc {
aBuilderLibrary.registerBuilder("Set", EvaluatedAssignmentProducerNodeBuilder.class);
aBuilderLibrary.registerFactory("CreateEntity", new CreateEntityProducerNodeBuilder.factory(aModel));
aBuilderLibrary.registerFactory("DeleteEntity", new DeleteEntityProducerNodeBuilder.factory(aModel));
- aBuilderLibrary.registerFactory("Generate", new GeneratingProducerNodeBuilder.factory(aGeneratorLibrary, aWriterEngine));
+ aBuilderLibrary.registerFactory("Generate", new GeneratingProducerNodeBuilder.factory(aGeneratorLibrary,
+ aWriterEngine, anInterceptor));
}
public static abstract class AbstractProducerNodeBuilder implements ProducerNodeBuilder {
public void setSubNode(String aName, ProducerNode aNode) {
subNodes.put(aName, aNode);
- };
+ }
public Set getAvailableSubNodes() {
return availableSubnodes;
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
key = (String) anAttributes.get(ASSIGNMENT_KEY_ATTRIBUTE);
value = (String) anAttributes.get(ASSIGNMENT_VALUE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new ExpandedAssignmentProducerNode(key, value);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
key = (String) anAttributes.get(ASSIGNMENT_KEY_ATTRIBUTE);
value = (String) anAttributes.get(ASSIGNMENT_VALUE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new EvaluatedAssignmentProducerNode(key, value);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
if (parts.size() > 1)
mainTablePrefix = (String) parts.get(1);
}
- };
+ }
public ProducerNode constructNode() {
if (definition!=null)
return new EntityEnumeratingProducerNode(key, model, mainTablePrefix, extraTables, definition, selection, order, limit, skip, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
- else
- return new ListEnumeratingProducerNode(key, list, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
- };
+ return new ListEnumeratingProducerNode(key, list, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
fieldValues.putAll(anAttributes);
fieldValues.remove(UPDATE_KEY_ATTRIBUTE);
fieldValues.remove(UPDATE_DEFINITION_ATTRIBUTE);
- };
-
+ }
public ProducerNode constructNode() {
return new EntityModifyingProducerNode(model, false, definition, key, fieldValues);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
fieldValues.putAll(anAttributes);
fieldValues.remove(CREATEENTITY_KEY_ATTRIBUTE);
fieldValues.remove(CREATEENTITY_DEFINITION_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new EntityModifyingProducerNode(model, true, definition, key, fieldValues);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
condition = (String) anAttributes.get(LOOP_CONDITION_ATTRIBUTE);
limit = XMLReaderTool.getStringAttributeWithDefault(anAttributes, LOOP_LIMIT_ATTRIBUTE, "");
- };
+ }
public ProducerNode constructNode() {
return new LoopProducerNode(condition, limit, getSubNode( LOOP_DEFAULT_SUBNODE ));
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
if (parts.size()>0) definition=(String)parts.get(0);
if (parts.size()>1) mainTablePrefix=(String)parts.get(1);
- };
+ }
public ProducerNode constructNode() {
return new EntityListProducerNode(key, model, mainTablePrefix, extraTables, definition, selection, order, limit, skip, null );
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
definition = (String) anAttributes.get(DELETEENTITY_DEFINITION_ATTRIBUTE);
selection = XMLReaderTool.getStringAttributeWithDefault(anAttributes, DELETEENTITY_SELECTION_ATTRIBUTE, "");
- };
+ }
public ProducerNode constructNode() {
return new EntityDeletingProducerNode(model, definition, selection);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
}
else
type = LoggerWrapper.INFO_MESSAGE;
- };
+ }
public ProducerNode constructNode() {
return new LoggingProducerNode(message, type);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
}
else
type = FreeQueryProducerNode.QUERY_TYPE_SET;
- };
+ }
public ProducerNode constructNode() {
return new FreeQueryProducerNode(key, query, limit, type);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
}
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
- String typeString;
-
XMLReaderTool.checkAttributes(anAttributes, EXTDB_REQUIRED_ATTRIBUTES, EXTDB_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(EXTDB_KEY_ATTRIBUTE);
username = (String) anAttributes.get(EXTDB_USERNAME_ATTRIBUTE);
password = (String) anAttributes.get(EXTDB_PASSWORD_ATTRIBUTE);
query = (String) anAttributes.get(EXTDB_QUERY_ATTRIBUTE);
-
- };
+ }
public ProducerNode constructNode() {
return new ExternalDbProducerNode(key, driver, host, port, database, username, password, query, getSubNode(EXTDB_DEFAULT_SUBNODE));
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
key = (String) anAttributes.get(RESOURCEBUNDLE_KEY_ATTRIBUTE);
bundle = (String) anAttributes.get(RESOURCEBUNDLE_BUNDLE_ATTRIBUTE);
language = (String) anAttributes.get(RESOURCEBUNDLE_LANGUAGE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new BundleProducerNode(key, bundle, language);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
fileNameKey = (String) anAttributes.get(FILEDATESETTING_FILE_ATTRIBUTE);
dateKey = (String) anAttributes.get(FILEDATESETTING_DATE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new FileDateSettingProducerNode(fileNameKey, dateKey);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
XMLReaderTool.checkAttributes(anAttributes, FILEDELETING_REQUIRED_ATTRIBUTES, FILEDELETING_OPTIONAL_ATTRIBUTES);
fileNameKey = (String) anAttributes.get(FILEDELETING_FILE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new FileDeletingProducerNode(fileNameKey);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
time = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXECUTEPROGRAM_MAXTIME_ATTRIBUTE, null);
resultvar = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXECUTEPROGRAM_RESULTVAR_ATTRIBUTE, null);
returnValueVar = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXECUTEPROGRAM_RETURNVALUE_ATTRIBUTE, null);
- };
+ }
public ProducerNode constructNode() {
return new
ExecuteProgramProducerNode(command, time, resultvar, returnValueVar);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
source = (String) anAttributes.get(DIRCOPY_SOURCE_ATTRIBUTE);
destination = (String) anAttributes.get(DIRCOPY_DESTINATION_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new DirCopyingProducerNode(sourceBasePath, destinationBasePath, source, destination);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private File sourceBasePath;
private String parameters;
private Generator.Library generatorLibrary;
private WriterEngine writerEngine;
+ private Generator.Interceptor interceptor;
- public GeneratingProducerNodeBuilder(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine) {
+ public GeneratingProducerNodeBuilder(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine,
+ Generator.Interceptor anInterceptor) {
super(GENERATION_SUBNODES);
writerEngine = aWriterEngine;
generatorLibrary = aGeneratorLibrary;
+ interceptor = anInterceptor;
}
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
generator = (String) anAttributes.get(GENERATION_GENERATOR_ATTRIBUTE);
destination = (String) anAttributes.get(GENERATION_DESTINATION_ATTRIBUTE);
parameters = XMLReaderTool.getStringAttributeWithDefault(anAttributes, GENERATION_PARAMETERS_ATTRIBUTE, "" );
- };
+ }
public ProducerNode constructNode() {
- return new GeneratingProducerNode(generatorLibrary, writerEngine, generator, destination, parameters);
- };
+ return new GeneratingProducerNode(generatorLibrary, writerEngine, interceptor, generator, destination, parameters);
+ }
public static class factory implements ProducerNodeBuilderFactory {
private Generator.Library generatorLibrary;
private WriterEngine writerEngine;
+ private Generator.Interceptor interceptor;
- public factory(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine) {
+ public factory(Generator.Library aGeneratorLibrary, WriterEngine aWriterEngine, Generator.Interceptor anInterceptor) {
writerEngine = aWriterEngine;
generatorLibrary = aGeneratorLibrary;
+ interceptor = anInterceptor;
}
public ProducerNodeBuilder makeBuilder() {
- return new GeneratingProducerNodeBuilder(generatorLibrary, writerEngine);
+ return new GeneratingProducerNodeBuilder(generatorLibrary, writerEngine, interceptor);
}
}
}
skip = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_SKIP_ATTRIBUTE, "0" );
process = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_PROCESS_ATTRIBUTE, "-1" );
- extraTables = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_EXTRATABLES_ATTRIBUTE,"");
+ extraTables = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_EXTRATABLES_ATTRIBUTE, "");
- List parts = StringRoutines.splitString(definition.trim()," ");
- if (parts.size()>0) definition=(String)parts.get(0);
- if (parts.size()>1) mainTablePrefix=(String)parts.get(1);
- };
+ List parts = StringRoutines.splitString(definition.trim(), " ");
+ if (parts.size()>0) definition = (String) parts.get(0);
+ if (parts.size()>1) mainTablePrefix = (String) parts.get(1);
+ }
public ProducerNode constructNode() {
return new EntityBatchingProducerNode(
getSubNode( BATCHER_BATCH_SUBNODE ),
getSubNode( BATCHER_BATCHLIST_SUBNODE )
);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private EntityAdapterModel model;
XMLReaderTool.checkAttributes(anAttributes, IF_REQUIRED_ATTRIBUTES, IF_OPTIONAL_ATTRIBUTES);
condition = (String) anAttributes.get( IF_CONDITION_ATTRIBUTE );
- };
+ }
public ProducerNode constructNode() {
return new ConditionalProducerNode(
getSubNode( IF_TRUE_SUBNODE ),
getSubNode( IF_FALSE_SUBNODE )
);
- };
+ }
}
url = (String) anAttributes.get( RSS_URL_ATTRIBUTE );
version = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RSS_VERSION_ATTRIBUTE, "1.0");
encoding = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RSS_ENCODING_ATTRIBUTE, null);
- };
+ }
public ProducerNode constructNode() {
return new RSSProducerNode(key, url, version, encoding);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
public static class RDFAggregatorProducerNodeBuilder extends AbstractProducerNodeBuilder {
private final static String RDF_AGGREGATOR_KEY_ATTRIBUTE = KEY_ATTRIBUTE;
private final static String RDF_AGGREGATOR_SOURCE_ATTRIBUTE = "source";
- private final static String RDF_AGGREGATOR_ORDER_ATTRIBUTE = ORDER_ATTRIBUTE;
- private final static String RDF_AGGREGATOR_FILTER_ATTRIBUTE = "filter";
private final static String[] RDF_AGGREGATOR_REQUIRED_ATTRIBUTES = { RDF_AGGREGATOR_KEY_ATTRIBUTE, RDF_AGGREGATOR_SOURCE_ATTRIBUTE };
- private final static String[] RDF_AGGREGATOR_OPTIONAL_ATTRIBUTES = { RDF_AGGREGATOR_ORDER_ATTRIBUTE, RDF_AGGREGATOR_FILTER_ATTRIBUTE };
+ private final static String[] RDF_AGGREGATOR_OPTIONAL_ATTRIBUTES = { };
private final static String[] RDF_AGGREGATOR_SUBNODES = { };
private String key;
key = (String) anAttributes.get( RDF_AGGREGATOR_KEY_ATTRIBUTE );
source = (String) anAttributes.get( RDF_AGGREGATOR_SOURCE_ATTRIBUTE );
- order = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RDF_AGGREGATOR_SOURCE_ATTRIBUTE, "");
- filter = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RDF_AGGREGATOR_FILTER_ATTRIBUTE, "");
- };
+ }
public ProducerNode constructNode() {
- return new RDFAggregatorProducerNode(key, source, order, filter);
- };
+ return new RDFAggregatorProducerNode(key, source);
+ }
}
////////////////////////////////////////////////////////////////////////////////
}
public void setSubNode(String aName, ProducerNode aNode) {
- };
+ }
public Set getAvailableSubNodes() {
return new HashSet();
- };
+ }
public void setAttributes(Map anAttributes) throws ProducerConfigExc {
if (!anAttributes.isEmpty())
throw new ProducerConfigExc("No parameters allowed here");
- };
+ }
public ProducerNode constructNode() {
return new ScriptedProducerNodeDefinition.NodeParameterProducerNode(scriptedNodeName, parameterName);
- };
+ }
}
////////////////////////////////////////////////////////////////////////////////
public void setSubNode(String aName, ProducerNode aNode) {
nodeParameterValues.put(aName, aNode);
- };
+ }
public Set getAvailableSubNodes() {
return definition.getNodeParameters();
- };
+ }
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributeSet(anAttributes.keySet(), definition.getRequiredAttributes(), definition.getOptionalAttributes());
else
stringParameterValues.put(entry.getKey(), entry.getValue());
}
- };
+ }
public ProducerNode constructNode() {
return new ScriptedProducerNode(definition, stringParameterValues, integerParameterValues, nodeParameterValues);
- };
+ }
public static class factory implements ProducerNodeBuilderFactory {
private ScriptedProducerNodeDefinition definition;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer.reader;
+import mir.producer.CompositeProducerNode;
+import mir.producer.ProducerFactory;
+import mir.producer.ProducerNode;
+import mir.producer.SimpleProducerVerb;
+import mir.util.ExceptionRoutines;
+import mir.util.xml.XMLParserEngine;
+import mir.util.xml.XMLParserExc;
+import mir.util.xml.XMLParserFailure;
+
import java.io.File;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
-import mir.producer.CompositeProducerNode;
-import mir.producer.ProducerFactory;
-import mir.producer.ProducerNode;
-import mir.producer.SimpleProducerVerb;
-import mir.util.ExceptionFunctions;
-import mir.util.xml.XMLParserEngine;
-import mir.util.xml.XMLParserExc;
-import mir.util.xml.XMLParserFailure;
-
public class ProducerConfigReader {
private ProducerNodeBuilderLibrary builderLibrary;
private ProducerNodeBuilderLibrary scriptedNodeBuilderLibrary;
public ProducerConfigReader() {
super();
- };
+ }
public void parse(Reader aReader, ProducerNodeBuilderLibrary aBuilderLibrary, List aProducerFactories) throws ProducerConfigFailure {
try {
}
catch (Throwable e) {
- Throwable root = ExceptionFunctions.traceCauseException(e);
+ Throwable root = ExceptionRoutines.traceCauseException(e);
if ((root instanceof XMLParserExc) && ((XMLParserExc) root).getHasLocation()) {
XMLParserExc f = (XMLParserExc) root;
}
catch (Throwable e) {
- Throwable root = ExceptionFunctions.traceCauseException(e);
+ Throwable root = ExceptionRoutines.traceCauseException(e);
if ((root instanceof XMLParserExc) && ((XMLParserExc) root).getHasLocation()) {
XMLParserExc f = (XMLParserExc) root;
if (aTag.equals("producers")) {
return new ProducersSectionHandler(producers);
}
- else
- throw new XMLParserExc("Tag 'producers' expected, tag '"+aTag+"' found");
+ throw new XMLParserExc("Tag 'producers' expected, tag '"+aTag+"' found");
}
public void endElement(mir.util.xml.SectionHandler aHandler) {
throw new XMLParserExc("Verbs already processed");
if (body!=null)
throw new XMLParserExc("Verbs should come before body");
- else
- return new ProducerVerbsSectionHandler();
+ return new ProducerVerbsSectionHandler();
}
else if (aTag.equals("body")) {
if (body==null)
return new ProducerNodeSectionHandler();
- else
- throw new XMLParserExc("Body already processed");
+ throw new XMLParserExc("Body already processed");
}
throw new XMLParserExc("Unexpected tag: '"+aTag+"'");
}
return new ProducerNodeSectionHandler();
}
- else
- throw new XMLParserExc("Only 'verb' tags allowed here, '" + aTag + "' encountered.");
+ throw new XMLParserExc("Only 'verb' tags allowed here, '" + aTag + "' encountered.");
}
public void endElement(mir.util.xml.SectionHandler aHandler) {
if (producerNode.getNrSubNodes()==1) {
return producerNode.getSubNode(0);
}
- else {
- return producerNode;
- }
+ return producerNode;
}
public void finishSection() {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer.reader;
-import java.util.Map;
-import java.util.Set;
-
import mir.producer.ProducerNode;
import mir.util.xml.XMLParserExc;
+import java.util.Map;
+import java.util.Set;
+
public interface ProducerNodeBuilder {
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc;
public void setSubNode(String aName, ProducerNode aNode) throws ProducerConfigExc;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
nodeBuilders = new HashMap();
}
+ /**
+ * Register a builder
+ * @param aName
+ * @param aProducerNodeBuilderClass
+ * @throws ProducerConfigExc
+ * @throws ProducerConfigFailure
+ */
public void registerBuilder(String aName, Class aProducerNodeBuilderClass) throws ProducerConfigExc, ProducerConfigFailure {
try {
registerFactory(aName, new ProducerNodeBuilder.DefaultProducerNodeBuilderFactory( aProducerNodeBuilderClass ));
}
}
- public void registerFactory(String aName, ProducerNodeBuilder.ProducerNodeBuilderFactory aFactory) {
- nodeBuilders.put(aName, aFactory);
+ /**
+ * Register a {@link ProducerNodeBuilder.ProducerNodeBuilderFactory} for {@link mir.producer.ProducerNode}s
+ * @param aTag the tag to bind this factory to: every producers.xml tag with the name <code>aTag</code>
+ * will be directed to this factory.
+ *
+ * @param aFactory the factory to bind the tag to.
+ */
+ public void registerFactory(String aTag, ProducerNodeBuilder.ProducerNodeBuilderFactory aFactory) {
+ nodeBuilders.put(aTag, aFactory);
}
public boolean hasBuilderForName(String aName) {
public ProducerNodeBuilder constructBuilder(String aName) throws ProducerConfigExc {
if (hasBuilderForName(aName))
return ((ProducerNodeBuilder.ProducerNodeBuilderFactory) nodeBuilders.get(aName)).makeBuilder();
- else
- throw new ProducerConfigExc("ProducerNodeBuilder: no builder with name '" + aName + "' found.");
+ throw new ProducerConfigExc("ProducerNodeBuilder: no builder with name '" + aName + "' found.");
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.producer.reader;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
import mir.producer.CompositeProducerNode;
import mir.producer.NodedProducer;
import mir.producer.Producer;
import mir.producer.ProducerFailure;
import mir.producer.ProducerNode;
+import java.util.List;
+import java.util.Map;
+
public class ScriptedProducerFactory implements ProducerFactory {
private List verbs;
private Map verbNodes;
rootNode.addSubNode(verbNode);
rootNode.addSubNode(body);
- return new NodedProducer(rootNode, aVerb, aStartingValues);
- };
+ return new NodedProducer(rootNode);
+ }
public List verbs() {
return verbs;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
import mir.producer.ProducerExc;
import mir.producer.ProducerFailure;
import mir.producer.ProducerNode;
+import mir.producer.ProductionContext;
import mir.util.ParameterExpander;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * <p> A ScriptedProducerNode is a ProducerNode which is defined in
+ * producers.xml file by the <nodedefinition> statement. </p>
+ *
+ * <p>It Acts as a "function" (or "macro") that can be "called"
+ * elsewhere in a producer. More precisely, it is a way to define a
+ * new producer node type inside the producers.xml file. (check the
+ * Language node in that file for an example).</p>
+ */
public class ScriptedProducerNode implements ProducerNode {
private ScriptedProducerNodeDefinition definition;
private Map integerParameterValues;
nodeParameterValues.putAll(aNodeParameterValues);
}
- public void produce(Map aValues, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc {
try {
Map oldValues = new HashMap();
- ScriptedProducerNodeTool.saveMapValues(oldValues, aValues, definition.getStringParameters().keySet());
- ScriptedProducerNodeTool.saveMapValues(oldValues, aValues, definition.getIntegerParameters().keySet());
+ ScriptedProducerNodeTool.saveMapValues(oldValues,
+ aProductionContext.getValueSet(), definition.getStringParameters().keySet());
+ ScriptedProducerNodeTool.saveMapValues(oldValues,
+ aProductionContext.getValueSet(), definition.getIntegerParameters().keySet());
try {
Iterator i = stringParameterValues.entrySet().iterator();
Map.Entry entry = (Map.Entry) i.next();
if (entry.getValue() instanceof String) {
- aValues.put(entry.getKey(), ParameterExpander.expandExpression(aValues, (String) entry.getValue()));
+ aProductionContext.getValueSet().put(entry.getKey(),
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(),
+ (String) entry.getValue()));
}
}
Map.Entry entry = (Map.Entry) i.next();
if (entry.getValue() instanceof String) {
- aValues.put(entry.getKey(), ParameterExpander.evaluateExpression(aValues, (String) entry.getValue()));
+ aProductionContext.getValueSet().put(entry.getKey(),
+ ParameterExpander.evaluateExpression(aProductionContext.getValueSet(), (String) entry.getValue()));
}
}
- ScriptedProducerNodeTool.pushNodeParameterValues(aValues, definition.getName(), nodeParameterValues);
+ ScriptedProducerNodeTool.pushNodeParameterValues(aProductionContext.getValueSet(),
+ definition.getName(), nodeParameterValues);
try {
- definition.getBody().produce(aValues, aVerb, aLogger);
+ definition.getBody().produce(aProductionContext);
}
finally {
- ScriptedProducerNodeTool.popNodeParameterValues(aValues, definition.getName());
+ ScriptedProducerNodeTool.popNodeParameterValues(aProductionContext.getValueSet(), definition.getName());
}
}
finally {
- ScriptedProducerNodeTool.restoreMapValues(aValues, definition.getIntegerParameters().keySet(), oldValues);
- ScriptedProducerNodeTool.restoreMapValues(aValues, definition.getStringParameters().keySet(), oldValues);
+ ScriptedProducerNodeTool.restoreMapValues(aProductionContext.getValueSet(), definition.getIntegerParameters().keySet(), oldValues);
+ ScriptedProducerNodeTool.restoreMapValues(aProductionContext.getValueSet(), definition.getStringParameters().keySet(), oldValues);
}
}
catch (Exception e) {
- aLogger.error("Scripted producer node " + definition.getName() + " caused an exception: " + e.getMessage());
+ aProductionContext.getLogger().error("Scripted producer node " + definition.getName() + " caused an exception", e);
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
+import mir.producer.*;
-import mir.log.LoggerWrapper;
-import mir.producer.CompositeProducerNode;
-import mir.producer.ProducerExc;
-import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
+import java.util.*;
public class ScriptedProducerNodeDefinition {
private Map integerParameters; // name -> default value
return result;
}
-
protected static class NodeParameterProducerNode implements ProducerNode {
private String parameterName;
private String definitionName;
parameterName = aParameterName;
}
- public void produce(Map aValues, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure {
+ public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure {
ProducerNode producerNode;
- Map runTimeData = (Map) ((Map) aValues.get(SCRIPTED_PRODUCERNODE_RUNTIMEDATA_KEY)).get(definitionName);
+ Map runTimeData = (Map) ((Map) aProductionContext.getValueSet().get(SCRIPTED_PRODUCERNODE_RUNTIMEDATA_KEY)).get(definitionName);
Map parameters = (Map) ((Stack) runTimeData.get( SCRIPTED_PRODUCERNODE_RUNTIMESTACK_KEY )).peek();
producerNode = (ProducerNode) parameters.get(parameterName);
- if (producerNode != null)
- producerNode.produce(aValues, aVerb, aLogger);
+ if (producerNode != null) {
+ producerNode.produce(aProductionContext);
+ }
}
public Set buildVerbSet() {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.rss;
+import mir.util.HTTPClientHelper;
+import mir.util.xml.XMLParserEngine;
+import mir.util.xml.XMLParserExc;
+import mir.util.xml.XMLParserFailure;
+
import java.io.InputStream;
-import java.net.URL;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
-
-import mir.util.HTTPClientHelper;
-import mir.util.xml.*;
-import mir.util.xml.XMLParserEngine;
/**
*
if (aTag.getLocalName().equals("rss")) {
return new RSS091SectionHandler(data);
}
- else
- throw new XMLParserFailure(new RSSExc("'rss' tag expected"));
- };
+ throw new XMLParserFailure(new RSSExc("'rss' tag expected"));
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
private class RSS091SectionHandler extends mir.util.xml.AbstractSectionHandler {
return new RSS091ChannelSectionHandler(data);
else
throw new XMLParserExc("channel tag expected, " + aTag.getLocalName() + " found");
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
private class RSS091ChannelSectionHandler extends mir.util.xml.AbstractSectionHandler {
public RSS091ChannelSectionHandler(RSSData aData) {
data = aData;
- items = new Vector();
+ items = new ArrayList();
channel = new RDFResource("rss:channel");
attributes = new HashMap();
}
}
else
return new DiscardingSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof PCDATASectionHandler) {
else if (aHandler instanceof RSS091ItemSectionHandler) {
items.add((((RSS091ItemSectionHandler) aHandler).getItem()));
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
Iterator i = items.iterator();
while (i.hasNext()) {
data.addResource((RDFResource) i.next());
}
- };
+ }
}
private class RSS091ItemSectionHandler extends mir.util.xml.AbstractSectionHandler {
currentTag=(String) mappedItemProperties.get(tag);
return new PCDATASectionHandler();
}
- else
- return new DiscardingSectionHandler();
- };
+ return new DiscardingSectionHandler();
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof PCDATASectionHandler) {
attributes.put(currentTag, (((PCDATASectionHandler) aHandler).getData()));
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
item = new RDFResource("rss:item", (String) attributes.get("rss:link"));
item.set((String) entry.getKey(), entry.getValue());
}
- };
+ }
public RDFResource getItem() {
return item;
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
throw new XMLParserFailure(new RSSExc("No subtags allowed here"));
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
data.append(aCharacters);
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public String getData() {
return data.toString();
private List items;
public RDFSequenceSectionHandler() {
- items = new Vector();
+ items = new ArrayList();
}
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
}
return new DiscardingSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public List getItems() {
return items;
private class DiscardingSectionHandler extends mir.util.xml.AbstractSectionHandler {
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
return this;
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.rss;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.ArrayList;
public class RSSData {
private List resources;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.rss;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import mir.util.DateTimeFunctions;
+import mir.util.DateTimeRoutines;
import mir.util.HTTPClientHelper;
import mir.util.xml.XMLParserEngine;
import mir.util.xml.XMLParserExc;
import mir.util.xml.XMLParserFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class RSSReader {
public static final String RDF_NAMESPACE_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
public RSSData parseUrl(String anUrl) throws RSSExc, RSSFailure {
try {
- HTTPClientHelper httpClientHelper = new HTTPClientHelper();
+ HTTPClientHelper httpClientHelper = new HTTPClientHelper();
InputStream inputStream = httpClientHelper.getUrl(anUrl);
if (inputStream==null)
throw new RSSExc("RSSChannel.parseUrl: Can't get url content");
if (aTag.getLocalName().equals("RDF")) {
return new RDFSectionHandler(data);
}
- else
- throw new XMLParserFailure(new RSSExc("'RDF' tag expected"));
- };
+ throw new XMLParserFailure(new RSSExc("'RDF' tag expected"));
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
private class RDFSectionHandler extends mir.util.xml.AbstractSectionHandler {
String rdfClass = makeQualifiedName(aTag);
return new RDFResourceSectionHandler(rdfClass, identifier);
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof RDFResourceSectionHandler) {
data.addResource(((RDFResourceSectionHandler) aHandler).getResource());
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
private mir.util.xml.SectionHandler makePropertyValueSectionHandler(mir.util.xml.XMLName aTag, Map anAttributes) {
currentTag = aTag;
return makePropertyValueSectionHandler(aTag, anAttributes);
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof PropertyValueSectionHandler) {
usePropertyValueSectionHandler(resource, (PropertyValueSectionHandler) aHandler, currentTag);
// resource.set(makeQualifiedName(currentTag), ( (PropertyValueSectionHandler) aHandler).getFieldValue());
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public RDFResource getResource() {
if ((resource.getIdentifier()==null || resource.getIdentifier().length()==0) && resource.get("rss:link")!=null) {
return new RDFSequenceSectionHandler();
else
return new DiscardingSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof RDFSequenceSectionHandler) {
structuredData= ((RDFSequenceSectionHandler) aHandler).getItems();
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
stringData.append(aCharacters);
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public String getData() {
return stringData.toString();
public Object getValue() {
if (structuredData==null)
return stringData.toString();
- else
- return structuredData;
+ return structuredData;
}
}
return new RDFSequenceSectionHandler();
else
return new DiscardingSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
if (aHandler instanceof RDFSequenceSectionHandler) {
items.addAll(((RDFSequenceSectionHandler) aHandler).getItems());
}
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
if (aCharacters.trim().length()>0)
throw new XMLParserExc("No character data allowed here");
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public List getItems() {
return items;
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
throw new XMLParserFailure(new RSSExc("No subtags allowed here"));
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
data.append(aCharacters);
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public String getData() {
return data.toString();
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
throw new XMLParserFailure(new RSSExc("No subtags allowed here"));
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
data.append(aCharacters);
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public Object getValue() {
try {
String expression = data.toString().trim();
- return DateTimeFunctions.parseW3CDTFString(expression);
+ return DateTimeRoutines.parseW3CDTFString(expression);
}
catch (Throwable t) {
}
return new DiscardingSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public List getItems() {
return items;
data.append("<"+tag+">");
return new RDFLiteralSectionHandler();
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
data.append(((RDFLiteralSectionHandler) aHandler).getData());
data.append("</"+tag+">");
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
data.append(aCharacters);
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
public Object getValue() {
return data.toString();
private class DiscardingSectionHandler extends mir.util.xml.AbstractSectionHandler {
public mir.util.xml.SectionHandler startElement(String aTag, Map anAttributes) throws XMLParserExc {
return this;
- };
+ }
public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc {
- };
+ }
public void characters(String aCharacters) throws XMLParserExc {
- };
+ }
public void finishSection() throws XMLParserExc {
- };
+ }
}
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.servlet;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.sql.Connection;
-import java.util.Locale;
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
+import mircoders.global.MirGlobal;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.log.LoggerWrapper;
-import mircoders.global.MirGlobal;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.util.Locale;
/**
* Title: Mir
* Copyright: Copyright (c) 2001, 2002
* Company: Mir-coders group
* @author idfx, the Mir-coders group
- * @version $Id: AbstractServlet.java,v 1.32 2004/11/06 19:33:15 idfx Exp $
+ * @version $Id: AbstractServlet.java,v 1.33 2007/04/08 21:46:44 idfx Exp $
*/
public abstract class AbstractServlet extends HttpServlet {
}
protected void setNoCaching(HttpServletResponse aResponse) {
- //nothing in Mir can or should be cached as it's all dynamic...
- //
- //this needs to be done here and not per page (via meta tags) as some
- //browsers have problems w/ it per-page -mh
-
aResponse.setHeader("Pragma", "no-cache");
aResponse.setDateHeader("Expires", 0);
aResponse.setHeader("Cache-Control", "no-cache");
/**
* Bind the language to the session
*/
- protected void setLanguage(HttpSession session, String language) {
- logger.debug("setting language to " + language);
-
- session.setAttribute("language", language);
- session.setAttribute("locale", new Locale(language, ""));
- }
-
- /**
- * Get the session-bound language
- */
- protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
- String language = (String) session.getAttribute("language");
-
- if (language == null || language.length()==0) {
- language = getAcceptLanguage(aRequest);
- }
-
- return language;
+ protected void setLanguage(HttpSession aRequest, String aLanguage) {
+ aRequest.setAttribute("language", aLanguage);
+ aRequest.setAttribute("locale", new Locale(aLanguage, ""));
}
/**
* else it returns the standard-language
*/
protected String getAcceptLanguage(HttpServletRequest aRequest) {
- Locale loc = aRequest.getLocale();
- String lang = loc.getLanguage();
- return lang;
+ Locale locale = aRequest.getLocale();
+
+ return locale.getLanguage();
}
/**
* @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
*/
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
+ public void init(ServletConfig aConfiguration) throws ServletException {
+ super.init(aConfiguration);
- MirPropertiesConfiguration.setContext(config.getServletContext());
+ MirPropertiesConfiguration.setContext(aConfiguration.getServletContext());
try {
configuration = MirPropertiesConfiguration.instance();
}
throw new ServletException("can't get localizer: " + t.toString());
}
- Connection connection;
try {
- connection = MirGlobal.getDatabaseEngine().obtainConnection();
+ Connection connection = MirGlobal.getDatabaseEngine().obtainConnection();
MirGlobal.getDatabaseEngine().releaseConnection(connection);
}
catch (Throwable t) {
}
}
- private void setEncoding(HttpServletRequest request){
+ private void setEncoding(HttpServletRequest aRequest) {
try {
- logger.info("Request has encoding: " + request.getCharacterEncoding());
+ logger.info("Request has encoding: " + aRequest.getCharacterEncoding());
logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));
- Class reqClass = request.getClass();
- Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
+
+ Class requestClass = aRequest.getClass();
+ Method method = requestClass.getMethod("setCharacterEncoding", new Class[]{String.class});
String encoding = configuration.getString("Mir.DefaultHTMLCharset");
- method.invoke(request, new Object[]{encoding});
- logger.info("Request now has encoding: " + request.getCharacterEncoding());
+ method.invoke(aRequest, new Object[]{encoding});
+ logger.info("Request now has encoding: " + aRequest.getCharacterEncoding());
}
catch (NoSuchMethodException e) {
- // TODO set the encoding in a zapata-way
}
catch (SecurityException e) {
- logger.error(e.getMessage());
- e.printStackTrace();
+ logger.error(e.getMessage(), e);
}
catch (IllegalArgumentException e) {
- logger.error(e.getMessage());
- e.printStackTrace();
+ logger.error(e.getMessage(), e);
}
catch (IllegalAccessException e) {
- logger.error(e.getMessage());
- e.printStackTrace();
+ logger.error(e.getMessage(), e);
}
catch (InvocationTargetException e) {
- logger.error(e.getMessage());
- e.printStackTrace();
+ logger.error(e.getMessage(), e);
}
}
- protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
+ protected final void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException {
+ doPost(aRequest, aResponse);
}
- protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {
- configuration.setProperty("RootUri", request.getContextPath());
+ protected final void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException {
+ if ((configuration.getString("RootUri") == null) ||
+ configuration.getString("RootUri").equals("")) {
+ configuration.setProperty("RootUri", aRequest.getContextPath());
}
- setEncoding(request);
- process(request, response);
+
+ setEncoding(aRequest);
+ process(aRequest, aResponse);
}
- abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
+ public abstract void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException;
/**
* Selects the language for the response.
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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 mir.entity.adapter.EntityAdapterEngine;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.module.AbstractModule;
+import mir.module.ModuleExc;
+import mir.storage.Database;
+import mir.util.HTTPRequestParser;
+import mir.util.URLBuilder;
+import mir.util.StringRoutines;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.servlet.ServletHelper;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Collections;
+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.io.IOException;
+
+/**
+ *
+ */
+
+public abstract class AdminServletModule extends ServletModule {
+ protected AbstractModule mainModule;
+ protected String definition;
+ private EntityAdapterModel model;
+
+ protected String listGenerator;
+ protected String editGenerator;
+ protected String deleteConfirmationGenerator;
+ protected int nrEntitiesPerListPage;
+
+ /** the list of parameters that need to be propagated in the list */
+ private Set propagatedParameters = new HashSet();
+
+ protected void addPropagatedParameter(String aParameter) {
+ propagatedParameters.add(aParameter);
+ }
+
+ protected AdminServletModule(){
+ addPropagatedParameter("searchfield");
+ addPropagatedParameter("searchtext");
+ addPropagatedParameter("searchispublished");
+ addPropagatedParameter("searchstatus");
+ addPropagatedParameter("searchorder");
+
+ definition = null;
+ try {
+ model = MirGlobal.localizer().dataModel().adapterModel();
+ }
+ catch (MirLocalizerExc e) {
+ getLogger().error("Can't create model: " + e.toString());
+
+ throw new ServletModuleFailure("Can't retrieve model", e);
+ }
+
+ listGenerator = getConfiguration().getString("ServletModule." + getName() + ".ListTemplate");
+ editGenerator = getConfiguration().getString("ServletModule." + getName() + ".EditTemplate");
+ deleteConfirmationGenerator = getConfiguration().getString("ServletModule." + getName() + ".DeleteConfirmationTemplate");
+ nrEntitiesPerListPage =
+ getConfiguration().getInt("ServletModule."+getName()+".ListSize",
+ getConfiguration().getInt("ServletModule.Default.ListSize", 20));
+
+ }
+
+ protected EntityAdapterModel getModel() {
+ return model;
+ }
+
+ protected void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {
+ MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + anObject, aDescription);
+ }
+
+ /**
+ * Function to specify the default ordering for lists. May be overridden.
+ */
+ protected String getDefaultListOrdering() {
+
+ if (mainModule!=null && mainModule.getStorageObject()!=null &&
+ mainModule.getStorageObject().hasField("webdb_create")) {
+ return "webdb_create desc";
+ }
+ else {
+ return "id asc";
+ }
+ }
+
+ /**
+ * Generic list servlet method
+ */
+
+ public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+ String where = requestParser.getParameter("where");
+ String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());
+ int offset = requestParser.getIntegerWithDefault("offset", 0);
+ String mainTablePrefix = requestParser.getParameter("mainTablePrefix");
+ String extraTables = requestParser.getParameter("extraTables");
+
+ returnList(aRequest, aResponse, where, order, offset, Collections.EMPTY_MAP, mainTablePrefix, extraTables);
+ }
+
+
+ public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
+ returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, Collections.EMPTY_MAP);
+ }
+
+ public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String aWhereClause, String anOrderByClause, int anOffset,
+ Map anOverridingRequestParameters) throws ServletModuleExc {
+ returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, anOverridingRequestParameters, "", null);
+ }
+ public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String aWhereClause, String anOrderByClause, int anOffset,
+ Map anOverridingRequestParameters, String aMainTablePrefix, String someExtraTables) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest, anOverridingRequestParameters);
+ URLBuilder urlBuilder = new URLBuilder();
+
+ try {
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+ List extraTables = null;
+ if (someExtraTables!=null && someExtraTables.length() > 0) {
+ extraTables = StringRoutines.splitString(someExtraTables, ",");
+ }
+
+ List list =
+ EntityAdapterEngine.retrieveAdapterList(model, definition, aMainTablePrefix, extraTables, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
+
+ responseData.put("nexturl", null);
+ responseData.put("prevurl", null);
+ responseData.put("module", getName());
+
+ urlBuilder.setValue("module", getName());
+ urlBuilder.setValue("do", "list");
+ urlBuilder.setValue("where", aWhereClause);
+ urlBuilder.setValue("order", anOrderByClause);
+ urlBuilder.setValue("extraTables", someExtraTables);
+ urlBuilder.setValue("mainTablePrefix", aMainTablePrefix);
+
+
+ urlBuilder.setValue("offset", anOffset);
+ responseData.put("offset" , Integer.toString(anOffset));
+ responseData.put("thisurl" , urlBuilder.getQuery());
+
+ propagateFields(requestParser, urlBuilder, responseData);
+
+ if (list.size()>=nrEntitiesPerListPage) {
+ urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
+ responseData.put("nexturl" , urlBuilder.getQuery());
+ }
+
+ if (anOffset>0) {
+ urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
+ responseData.put("prevurl" , urlBuilder.getQuery());
+ }
+
+ responseData.put("entities", list);
+ responseData.put("from" , Integer.toString(anOffset+1));
+ responseData.put("count", "?");
+ responseData.put("to", Integer.toString(anOffset+list.size()-1));
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {
+ try {
+ editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ URLBuilder urlBuilder = new URLBuilder();
+
+ try {
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+ responseData.put("module", getName());
+ responseData.put("entity", anObject);
+ responseData.put("new", new Boolean(anIsNew));
+
+
+ urlBuilder.setValue("module", getName());
+ urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
+ if (anIsNew) {
+ urlBuilder.setValue("do", "add");
+ }
+ else {
+ urlBuilder.setValue("id", anId);
+ urlBuilder.setValue("do", "edit");
+ }
+ responseData.put("returnurl", requestParser.getParameter("returnurl"));
+ responseData.put("thisurl", urlBuilder.getQuery());
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ /**
+ * Generic add servlet method
+ */
+ public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+
+ Map object = new HashMap();
+
+ Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
+
+ while (i.hasNext()) {
+ object.put(i.next(), "");
+ }
+
+ initializeNewObject(object, aRequest, aResponse);
+
+ editObject(aRequest, aResponse, object, true, null);
+ }
+
+ protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ }
+
+ /**
+ * Generic edit servlet method
+ */
+ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ edit(aRequest, aResponse, aRequest.getParameter("id"));
+ }
+
+ /**
+ */
+ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ try {
+ editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ /**
+ * Generic update servlet method
+ */
+ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ try {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+ String id = aRequest.getParameter("id");
+ Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
+ mainModule.set(withValues);
+
+ logAdminUsage(aRequest, id, "object modified");
+
+ String returnUrl = requestParser.getParameter("returnurl");
+
+ if (returnUrl!=null) {
+ ServletHelper.redirect(aResponse, returnUrl);
+ }
+ else {
+ edit(aRequest, aResponse, id);
+ }
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ /**
+ * Generic insert servlet method
+ */
+ public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ try {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+ Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());
+
+ String id = processInstertedObject(object, aRequest, aResponse);
+
+ logAdminUsage(aRequest, id, "object inserted");
+
+ String returnUrl = requestParser.getParameter("returnurl");
+
+ if (returnUrl!=null) {
+ ServletHelper.redirect(aResponse, returnUrl);
+ }
+ else {
+ edit(aRequest, aResponse, id);
+ }
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ /**
+ *
+ */
+ public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ try {
+ return mainModule.add(anObject);
+ }
+ catch (ModuleExc t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ /**
+ * Generic delete confirmation servlet method
+ */
+ public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ try {
+ String idParam = aRequest.getParameter("id");
+ String confirmParam = aRequest.getParameter("confirm");
+
+ if (confirmParam != null && !"".equals(confirmParam)) {
+ mainModule.deleteById(idParam);
+ logAdminUsage(aRequest, idParam, "object deleted");
+ ServletHelper.redirect(aResponse, aRequest.getParameter("okurl"));
+ }
+ else {
+ ServletHelper.redirect(aResponse, aRequest.getParameter("cancelurl"));
+ }
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ /**
+ * Generic delete servlet method
+ */
+ public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ String idParam = aRequest.getParameter("id");
+
+ if (idParam == null) {
+ throw new ServletModuleExc("Invalid call to delete: no id supplied");
+ }
+
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+ responseData.put("module", getName());
+ responseData.put("id", idParam);
+ responseData.put("cancelurl", aRequest.getParameter("cancelurl"));
+ responseData.put("okurl", aRequest.getParameter("okurl"));
+
+ try {
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);
+ }
+ catch (IOException e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ /**
+ * Gets the fields from a httprequest and matches them with the metadata from
+ * the database object. Returns the keys that match, with their values.
+ *
+ * @return Map with the values
+ */
+ public Map getIntersectingValues(HttpServletRequest aRequest, Database aDatabase)
+ throws ServletModuleExc, ServletModuleFailure {
+
+ HTTPRequestParser parser = new HTTPRequestParser(aRequest);
+
+ List fields = aDatabase.getFieldNames();
+
+ Map result = new HashMap();
+ for (int i = 0; i < fields.size(); i++) {
+ String aField = (String) fields.get(i);
+
+ String aValue = parser.getParameter(aField);
+ if (aValue != null) {
+ result.put(aField, aValue);
+ }
+ }
+
+ return result;
+ }
+
+ private void propagateFields(HTTPRequestParser aRequest, URLBuilder aUrlBuilder, Map aResponseData) {
+ Iterator i = propagatedParameters.iterator();
+ while (i.hasNext()) {
+ String parameter = (String) i.next();
+ String value = aRequest.getParameter(parameter);
+ aUrlBuilder.setValue(parameter, value);
+ aResponseData.put(parameter, value);
+ }
+ }
+}
\ No newline at end of file
-/*
- * 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 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.util.HashMap;
-import java.util.Iterator;
-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 mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityAdapterEngine;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.storage.StorageObject;
-import mir.util.HTTPRequestParser;
-import mir.util.URLBuilder;
-import mircoders.global.MirGlobal;
-import mircoders.servlet.ServletHelper;
-import mircoders.localizer.MirLocalizerExc;
-import multex.Failure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public abstract class ServletModule {
- public String defaultAction;
- protected LoggerWrapper logger;
- protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
- private static Locale fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");
-
- protected AbstractModule mainModule;
- protected String definition;
- protected EntityAdapterModel model;
-
- protected String listGenerator;
- protected String editGenerator;
- protected String deleteConfirmationGenerator;
- protected int nrEntitiesPerListPage;
-
-
- public ServletModule(){
- definition = null;
- try {
- model = MirGlobal.localizer().dataModel().adapterModel();
- }
- catch (MirLocalizerExc e) {
- logger.error("Can't create model: " + e.toString());
- throw new ServletModuleFailure("Can't retrieve model", e);
- }
-
-
-
- listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate");
- editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate");
- deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate");
- nrEntitiesPerListPage =
- configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize",
- configuration.getInt("ServletModule.Default.ListSize", 20));
-
- }
-
-
- public void logAdminUsage(HttpServletRequest aRequest, String anObject, String aDescription) {
- MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getOperationModuleName() + ":" + anObject, aDescription);
- }
-
- /**
- * Singleton instance retrievel method. MUST be overridden in subclasses.
- *
- * @return ServletModule the single instance of the servletmodule class
- */
- public static ServletModule getInstance() {
- return null;
- }
-
- /**
- * Return the module name
- */
- protected String getOperationModuleName() {
- return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
- }
-
- public static Locale[] getLocales(HttpServletRequest aRequest) {
- return new Locale[] { getLocale(aRequest), fallbackLocale };
- }
-
- /**
- * Return the locale either from the session or the accept-language header ot the request
- * this supersedes getLanguage for the new i18n
- */
- public static Locale getLocale(HttpServletRequest aRequest) {
- Locale loc = null;
- HttpSession session = aRequest.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 = aRequest.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 aRequest) {
- return fallbackLocale;
- }
-
- /**
- * Function to specify the default ordering for lists. May be overridden.
- *
- *
- * @return
- */
- public String getDefaultListOrdering() {
-
- if (mainModule!=null && mainModule.getStorageObject()!=null){
- if (mainModule.getStorageObject().getFields().contains("webdb_create"))
- return "webdb_create desc";
- }
-
- return "id asc";
- }
-
- /**
- * Generic list servlet method
- */
-
- public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
- String where = requestParser.getParameter("where");
- String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());
- int offset = requestParser.getIntegerWithDefault("offset", 0);
-
- returnList(aRequest, aResponse, where, order, offset);
- }
-
-
- public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
- String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
-
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- URLBuilder urlBuilder = new URLBuilder();
- int count;
-
- try {
- Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
- List list =
- EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
-
- responseData.put("nexturl", null);
- responseData.put("prevurl", null);
- responseData.put("module", getOperationModuleName());
-
- count=mainModule.getSize(aWhereClause);
-
- urlBuilder.setValue("module", getOperationModuleName());
- urlBuilder.setValue("do", "list");
- urlBuilder.setValue("where", aWhereClause);
- urlBuilder.setValue("order", anOrderByClause);
-
- urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
- urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));
- urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
- urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));
- urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
-
- responseData.put("searchfield", requestParser.getParameter("searchfield"));
- responseData.put("searchtext", requestParser.getParameter("searchtext"));
- responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
- responseData.put("searchstatus", requestParser.getParameter("searchstatus"));
- responseData.put("searchorder", requestParser.getParameter("searchorder"));
-
- urlBuilder.setValue("offset", anOffset);
- responseData.put("offset" , new Integer(anOffset).toString());
- responseData.put("thisurl" , urlBuilder.getQuery());
-
- if (count>anOffset+nrEntitiesPerListPage) {
- urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
- responseData.put("nexturl" , urlBuilder.getQuery());
- }
-
- if (anOffset>0) {
- urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));
- responseData.put("prevurl" , urlBuilder.getQuery());
- }
-
- responseData.put("entities", list);
- responseData.put("from" , Integer.toString(anOffset+1));
- responseData.put("count", Integer.toString(count));
- responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
-
- ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) throws ServletModuleExc {
- try {
- editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anId)), false, anId);
- }
- catch (Throwable t) {
- throw new ServletModuleFailure(t);
- }
- }
-
- public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- URLBuilder urlBuilder = new URLBuilder();
-
- try {
- Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
- responseData.put("module", getOperationModuleName());
- responseData.put("entity", anObject);
- responseData.put("new", new Boolean(anIsNew));
-
-
- urlBuilder.setValue("module", getOperationModuleName());
- urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
- if (anIsNew)
- urlBuilder.setValue("do", "add");
- else {
- urlBuilder.setValue("id", anId);
- urlBuilder.setValue("do", "edit");
- }
- responseData.put("returnurl", requestParser.getParameter("returnurl"));
- responseData.put("thisurl", urlBuilder.getQuery());
-
- ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- /**
- * Generic add servlet method
- */
- public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-
- Map object = new HashMap();
-
- Iterator i = mainModule.getStorageObject().getFields().iterator();
-
- while (i.hasNext())
- object.put(i.next(), "");
-
- initializeNewObject(object, aRequest, aResponse);
-
- editObject(aRequest, aResponse, object, true, null);
- }
-
- protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
- }
-
- /**
- * Generic edit servlet method
- */
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- edit(aRequest, aResponse, aRequest.getParameter("id"));
- }
-
- /**
- */
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- try {
- editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- /**
- * Generic update servlet method
- */
- public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- try {
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
- String id = aRequest.getParameter("id");
- Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
- mainModule.set(withValues);
-
- logAdminUsage(aRequest, id, "object modified");
-
- String returnUrl = requestParser.getParameter("returnurl");
-
- if (returnUrl!=null) {
- ServletHelper.redirect(aResponse, returnUrl);
- }
- else {
- edit(aRequest, aResponse, id);
- }
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- /**
- * Generic insert servlet method
- */
- public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- try {
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
- Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());
-
- String id = processInstertedObject(object, aRequest, aResponse);
-
- logAdminUsage(aRequest, id, "object inserted");
-
- String returnUrl = requestParser.getParameter("returnurl");
-
- if (returnUrl!=null) {
- ServletHelper.redirect(aResponse, returnUrl);
- }
- else {
- edit(aRequest, aResponse, id);
- }
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- /**
- *
- */
- public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
- try {
- return mainModule.add(anObject);
- }
- catch (ModuleExc t) {
- throw new ServletModuleFailure(t);
- }
- };
-
- /**
- * Generic delete confirmation servlet method
- */
- public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
- try {
- String idParam = aRequest.getParameter("id");
- String confirmParam = aRequest.getParameter("confirm");
-
- if (confirmParam != null && !confirmParam.equals("")) {
- mainModule.deleteById(idParam);
- logAdminUsage(aRequest, idParam, "object deleted");
- ServletHelper.redirect(aResponse, aRequest.getParameter("okurl"));
- }
- else
- ServletHelper.redirect(aResponse, aRequest.getParameter("cancelurl"));
- }
- catch (Throwable t) {
- throw new ServletModuleFailure(t);
- }
- }
-
- /**
- * Generic delete servlet method
- */
- public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- try {
- String idParam = aRequest.getParameter("id");
-
- if (idParam == null)
- throw new ServletModuleExc("Invalid call to delete: no id supplied");
-
- Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
-
- responseData.put("module", getOperationModuleName());
- responseData.put("id", idParam);
- responseData.put("cancelurl", aRequest.getParameter("cancelurl"));
- responseData.put("okurl", aRequest.getParameter("okurl"));
-
- ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- /**
- */
- 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 aRequest, StorageObject theStorage)
- throws ServletModuleExc, ServletModuleFailure {
-
- HTTPRequestParser parser;
- List theFieldList;
-
- parser = new HTTPRequestParser(aRequest);
-
- theFieldList = theStorage.getFields();
-
- Map withValues = new HashMap();
- String aField, aValue;
-
- for (int i = 0; i < theFieldList.size(); i++) {
- aField = (String) theFieldList.get(i);
-
- aValue = parser.getParameter(aField);
- if (aValue != null)
- withValues.put(aField, aValue);
- }
- return withValues;
- }
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.config.MirPropertiesConfiguration;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+import java.lang.reflect.Method;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Locale;\r
+\r
+public abstract class ServletModule {\r
+ private LoggerWrapper logger = new LoggerWrapper("ServletModule." + getName());\r
+ private MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
+ private final Locale fallbackLocale = new Locale(\r
+ getConfiguration().getString("Mir.Admin.FallbackLanguage", "en"), "");\r
+\r
+ protected ServletModule() {\r
+ }\r
+\r
+ /**\r
+ * Return the name of this module\r
+ */\r
+ protected String getName() {\r
+ return getClass().getName().substring("mircoders.servlet.ServletModule".length());\r
+ }\r
+\r
+ /**\r
+ * Return the logger for this module\r
+ */\r
+ protected LoggerWrapper getLogger() {\r
+ return logger;\r
+ }\r
+\r
+ /**\r
+ * Return the global mir configuration\r
+ */\r
+ protected MirPropertiesConfiguration getConfiguration() {\r
+ return configuration;\r
+ }\r
+\r
+ /**\r
+ * signature of request handling methods\r
+ */\r
+ private static final Class[] HANDLER_METHOD_SIGNATURE = {\r
+ HttpServletRequest.class, HttpServletResponse.class\r
+ };\r
+\r
+ protected void defaultAction(HttpServletRequest aRequest,\r
+ HttpServletResponse aResponse)\r
+ throws ServletModuleExc, ServletModuleFailure, ServletModuleUserExc {\r
+ throw new ServletModuleExc("default action not defined for module " + getName());\r
+ }\r
+\r
+ /**\r
+ * get the locale either from the session or the accept-language header ot the request\r
+ * this supersedes getLanguage for the new i18n\r
+ */\r
+ protected Locale getFallbackLocale(HttpServletRequest aRequest) {\r
+ return fallbackLocale;\r
+ }\r
+\r
+ public Locale[] getLocales(HttpServletRequest aRequest) {\r
+ return new Locale[] { getLocale(aRequest), fallbackLocale };\r
+ }\r
+\r
+ /**\r
+ * Return the locale either from the session or the accept-language header ot the request\r
+ * this supersedes getLanguage for the new i18n\r
+ */\r
+ public static Locale getLocale(HttpServletRequest aRequest) {\r
+ Locale locale = null;\r
+ HttpSession session = aRequest.getSession(false);\r
+ if (session != null) {\r
+ // session can be null in case of logout\r
+ locale = (Locale) session.getAttribute("locale");\r
+ }\r
+ // if there is nothing in the session get it fron the accept-language\r
+ if (locale == null) {\r
+ locale = aRequest.getLocale();\r
+ }\r
+ return locale;\r
+ }\r
+\r
+ public void handleRequest(HttpServletRequest aRequest,\r
+ HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {\r
+ // look for requested method's name in the "do" http request param,\r
+ // if not present, use default action\r
+ String handlerName = aRequest.getParameter("do");\r
+ getLogger().debug("ServletModuleDispatch: " + getClass().getName() + "." + handlerName);\r
+\r
+ if (handlerName ==null) {\r
+ handlerName = "defaultAction";\r
+ }\r
+\r
+ Method method;\r
+ try {\r
+ method = getClass().getMethod(handlerName, HANDLER_METHOD_SIGNATURE);\r
+ }\r
+ catch (NoSuchMethodException e) {\r
+ throw new ServletModuleFailure("No handler found", e);\r
+ }\r
+\r
+ // ok, we have the method's name, now call it\r
+ try {\r
+ method.invoke(this, new Object[] { aRequest,aResponse });\r
+ }\r
+ catch (InvocationTargetException e) {\r
+ getLogger().error("Error while dispatching: " + e.getTargetException().getMessage(),\r
+ e.getTargetException());\r
+\r
+ throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());\r
+ }\r
+ catch (IllegalAccessException e) {\r
+ throw new ServletModuleFailure(e);\r
+ }\r
+ }\r
+\r
+}\r
+++ /dev/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 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.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-
-
-/**
- * Dispatcher, calls the method passed to ServletModule Class, through the "do"
- * Parameter (via POST or GET)
- *
- * @version $Id: ServletModuleDispatch.java,v 1.16 2003/09/03 18:29:03 zapata Exp $
- *
- * @Author rk
- *
- */
-public final class ServletModuleDispatch {
-
- private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Dispatch");
- private static final Class[] SIGNATURE = { HttpServletRequest.class, HttpServletResponse.class };
-
- /**
- * private parameter-less constructor to prevent unwanted instantiation
- */
-
- private ServletModuleDispatch () {
- }
-
- /**
- * Method to dispatch servletmodule requests.
- *
- * @param aServletModule
- * @param aRequest
- * @param aResponse
- * @throws ServletModuleExc
- * @throws ServletModuleUserExc
- * @throws ServletModuleFailure
- */
-
- public static void dispatch(ServletModule aServletModule, HttpServletRequest aRequest,
- HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
- {
- String doParam = aRequest.getParameter("do");
- logger.info("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam);
- if (doParam == null) {
- if (aServletModule.defaultAction() != null)
- doParam = aServletModule.defaultAction();
- else
- throw new ServletModuleExc("no parameter do supplied!");
- }
-
- try {
- Method method = aServletModule.getClass().getMethod(doParam,SIGNATURE);
- if (method != null) {
- method.invoke(aServletModule,new Object[] {aRequest,aResponse} );
- return;
- }
- else logger.debug("method lookup unsuccesful");
- }
- catch ( InvocationTargetException e) {
- logger.error( "invocation target exception: " + e.toString());
- e.getTargetException().printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
- throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());
- }
- catch (Throwable t) {
- logger.error( "ServletModuleDispatch: " + t.toString());
- throw new ServletModuleFailure(t);
- }
- }
-}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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 multex.Exc;
public class ServletModuleExc extends Exc {
+ public ServletModuleExc(String aMessage, Exception aCause) {
+ super(aMessage, aCause);
+ }
+
public ServletModuleExc(String aMessage) {
super(aMessage);
}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
+import mir.util.IORoutines;
import org.apache.commons.fileupload.FileItem;
import java.io.File;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
public class CommonsUploadedFileAdapter implements UploadedFile {
private FileItem fileItem;
}
}
+ public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure {
+ try {
+ IORoutines.copyStream(fileItem.getInputStream(), aStream);
+ }
+ catch (Exception e) {
+ throw new SessionFailure(e);
+ }
+ }
+
public InputStream getInputStream() throws SessionExc, SessionFailure {
try {
return fileItem.getInputStream();
public String getContentType() {
return fileItem.getContentType();
- };
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.session;
-import java.util.*;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
import mir.util.HTTPParsedRequest;
import org.apache.commons.fileupload.FileItem;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+
public class HTTPAdapters {
public static class HTTPRequestAdapter implements Request {
private HttpServletRequest request;
+ private String cachedHostName = null;
public HTTPRequestAdapter(HttpServletRequest aRequest) {
request = aRequest;
return request.getRemoteAddr();
if (aHeaderName.equals("hostname")) {
- return request.getRemoteAddr();
+ if (aHeaderName.equals("hostname")) {
+ if (cachedHostName==null) {
+ try {
+ cachedHostName = InetAddress.getByName(request.getRemoteAddr()).getHostName();
+ }
+ catch (UnknownHostException e) {
+ cachedHostName = request.getRemoteAddr();
+ }
+ }
+
+ return cachedHostName;
+ }
+
}
return request.getHeader(aHeaderName);
- };
+ }
public String getParameter(String aName) {
return request.getParameter(aName);
- };
+ }
public List getPrefixedParameterNames(String aPrefix) {
List result = new ArrayList();
}
return result;
- };
+ }
public List getUploadedFiles() {
return Collections.EMPTY_LIST;
- };
+ }
public List getParameters(String aName) {
return Arrays.asList(request.getParameterValues(aName));
- };
+ }
public HttpServletRequest getRequest() {
return request;
public static class HTTPParsedRequestAdapter implements Request {
private HTTPParsedRequest request;
+ private String cachedHostName = null;
public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {
request = aRequest;
}
public String getHeader(String aHeaderName) {
- if (aHeaderName.equals("ip"))
- return request.getRequest().getRemoteAddr();
+ if (aHeaderName.equals("ip")) {
+ // transparent proxies propagate the originating ip in the x-forwarded-for
+ // header. So if it's there, we should use it.
+ Enumeration headers = request.getRequest().getHeaders("x-forwarded-for");
+ if (headers.hasMoreElements()) {
+ return (String) headers.nextElement();
+ }
+ return request.getRequest().getRemoteAddr();
+ }
if (aHeaderName.equals("hostname")) {
- return request.getRequest().getRemoteAddr();
+ if (cachedHostName==null) {
+ try {
+ cachedHostName = InetAddress.getByName(getHeader("ip")).getHostName();
+ }
+ catch (UnknownHostException e) {
+ cachedHostName = request.getRequest().getRemoteAddr();
+ }
+ }
+
+ return cachedHostName;
}
return request.getHeader(aHeaderName);
public String getParameter(String aName) {
return request.getParameter(aName);
- };
+ }
public List getParameters(String aName) {
return request.getParameterList(aName);
- };
+ }
public List getPrefixedParameterNames(String aPrefix) {
List result = new ArrayList();
result.add(name);
}
}
-
return result;
- };
+ }
public List getUploadedFiles() {
List result = new ArrayList();
}
return result;
- };
+ }
public HttpServletRequest getRequest() {
return request.getRequest();
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.session;
import java.io.File;
import java.io.InputStream;
+import java.io.OutputStream;
public interface UploadedFile {
/**
public void writeToFile(File aFile) throws SessionExc, SessionFailure;
/**
+ * Writes the uploaded content to a file
+ */
+ public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure;
+
+ /**
* Creates an <code>InputStream</code> to access the uploaded content
*/
public InputStream getInputStream() throws SessionExc, SessionFailure;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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.session;
import java.util.Arrays;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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.session;
import java.util.List;
aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
return false;
}
- else
- return true;
+ return true;
}
/**
* Convenience validation method to test wether a field is numeric
-
- * @param aRequest
- * @param aFieldName
- * @param anErrorMessageResource
- * @param aValidationResults
- * @return
*/
-
- public static boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
+ public static boolean testFieldIsNumeric(Request aRequest, String aFieldName,
+ String anErrorMessageResource, List aValidationResults) {
Object value = aRequest.getParameter(aFieldName);
if (value!=null) {
try {
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
package mir.storage;
import mir.config.MirPropertiesConfiguration;
+import mir.entity.AbstractEntity;
import mir.entity.Entity;
import mir.entity.EntityList;
import mir.entity.StorableObjectEntity;
import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
import mir.storage.store.*;
import mir.util.JDBCStringRoutines;
+import mir.util.StreamCopier;
import mircoders.global.MirGlobal;
+import org.apache.commons.dbcp.DelegatingConnection;
+import org.postgresql.PGConnection;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
+import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
/**
* Implements database access.
*
+ * @version $Id: Database.java,v 1.48 2007/04/08 21:46:37 idfx Exp $
* @author rk
+ * @author Zapata
*
*/
-public class Database implements StorageObject {
- private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
+public class Database {
+ private static final int DEFAULT_LIMIT = 20;
+ private static final Class GENERIC_ENTITY_CLASS = StorableObjectEntity.class;
protected static final ObjectStore o_store = ObjectStore.getInstance();
- private static final int _millisPerHour = 60 * 60 * 1000;
protected LoggerWrapper logger;
- protected MirPropertiesConfiguration configuration;
protected String mainTable;
- protected String primaryKeySequence = null;
protected String primaryKeyField = "id";
- protected boolean evaluatedMetaData = false;
- protected ArrayList metadataFields;
- protected ArrayList metadataLabels;
- protected ArrayList metadataNotNullFields;
- protected int[] metadataTypes;
- protected Class theEntityClass;
- protected boolean hasTimestamp = true;
- private int defaultLimit;
+ private List fieldNames;
+ private int[] fieldTypes;
+ private Map fieldNameToType;
- TimeZone timezone;
- SimpleDateFormat internalDateFormat;
- SimpleDateFormat userInputDateFormat;
+ protected Class entityClass;
- /**
- * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
- * Aus diesem file werden <code>Database.Logfile</code>,
- * <code>Database.Username</code>,<code>Database.Password</code>,
- * <code>Database.Host</code> und <code>Database.Adaptor</code>
- * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
- * erzeugt.
- */
- public Database() throws StorageObjectFailure {
- configuration = MirPropertiesConfiguration.instance();
+ //
+ private Set binaryFields;
+
+ private TimeZone timezone;
+ private SimpleDateFormat userInputDateFormat;
+
+ public Database() throws DatabaseFailure {
+ MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
logger = new LoggerWrapper("Database");
timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));
- internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- internalDateFormat.setTimeZone(timezone);
userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
userInputDateFormat.setTimeZone(timezone);
- String theAdaptorName = configuration.getString("Database.Adaptor");
- defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
+ binaryFields = new HashSet();
+
+ String adapterName = configuration.getString("Database.Adaptor");
try {
- theEntityClass = GENERIC_ENTITY_CLASS;
+ entityClass = GENERIC_ENTITY_CLASS;
}
catch (Throwable e) {
- logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
- throw new StorageObjectFailure("Error in Database() constructor.", e);
+ logger.error("Error in Database() constructor with " + adapterName + " -- " + e.getMessage());
+ throw new DatabaseFailure("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;
+ public Class getEntityClass() {
+ return entityClass;
}
- /**
- * 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;
+ public Entity createNewEntity() throws DatabaseFailure {
+ try {
+ AbstractEntity result = (AbstractEntity) entityClass.newInstance();
+ result.setStorage(this);
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new DatabaseFailure(t);
+ }
}
- /**
- * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
- * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
- * @return Name des Primary-Keys
- */
- public String getIdName() {
+ public String getIdFieldName() {
return primaryKeyField;
}
- /**
- * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
- *
- * @return Name der Tabelle
- */
public String getTableName() {
return mainTable;
}
/**
- * Returns the id that was most recently added to the database
+ * Returns a list of field names for this <code>Database</code>
*/
- private String getLatestInsertedId(Connection aConnection) throws SQLException {
- if (primaryKeySequence==null)
- primaryKeySequence = mainTable+"_id_seq";
-
- PreparedStatement statement = aConnection.prepareStatement("select currval('" + primaryKeySequence + "')");
+ public List getFieldNames() throws DatabaseFailure {
+ if (fieldNames == null) {
+ acquireMetaData();
+ }
- ResultSet rs = statement.executeQuery();
- rs.next();
- return rs.getString(1);
+ return fieldNames;
}
- /**
- * Liefert eine Liste der Felder der Tabelle
- * @return ArrayList mit Feldern
- */
- public List getFields() throws StorageObjectFailure {
- if (metadataFields == null) {
- get_meta_data();
- }
-
- return metadataFields;
+ public boolean hasField(String aFieldName) {
+ return getFieldNames().contains(aFieldName);
}
/**
* Gets value out of ResultSet according to type and converts to String
- * @param rs ResultSet.
+ *
+ * @param aResultSet ResultSet.
* @param aType a type from java.sql.Types.*
- * @param valueIndex index in ResultSet
+ * @param aFieldIndex index in ResultSet
* @return returns the value as String. If no conversion is possible
* /unsupported value/ is returned
*/
- private String getValueAsString(ResultSet rs, int valueIndex, int aType)
- throws StorageObjectFailure {
+ private String getValueAsString(ResultSet aResultSet, int aFieldIndex, int aType)
+ throws DatabaseFailure {
String outValue = null;
- if (rs != null) {
+ if (aResultSet != null) {
try {
switch (aType) {
case java.sql.Types.BIT:
- outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
+ outValue = (aResultSet.getBoolean(aFieldIndex) == true) ? "1" : "0";
break;
case java.sql.Types.TINYINT:
case java.sql.Types.BIGINT:
- int out = rs.getInt(valueIndex);
+ int out = aResultSet.getInt(aFieldIndex);
- if (!rs.wasNull()) {
+ if (!aResultSet.wasNull()) {
outValue = new Integer(out).toString();
}
break;
case java.sql.Types.NUMERIC:
+ long outl = aResultSet.getLong(aFieldIndex);
- /** todo Numeric can be float or double depending upon
- * metadata.getScale() / especially with oracle */
- long outl = rs.getLong(valueIndex);
-
- if (!rs.wasNull()) {
+ if (!aResultSet.wasNull()) {
outValue = new Long(outl).toString();
}
case java.sql.Types.REAL:
- float tempf = rs.getFloat(valueIndex);
+ float tempf = aResultSet.getFloat(aFieldIndex);
- if (!rs.wasNull()) {
+ if (!aResultSet.wasNull()) {
tempf *= 10;
tempf += 0.5;
case java.sql.Types.DOUBLE:
- double tempd = rs.getDouble(valueIndex);
+ double tempd = aResultSet.getDouble(aFieldIndex);
- if (!rs.wasNull()) {
+ if (!aResultSet.wasNull()) {
tempd *= 10;
tempd += 0.5;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
- outValue = rs.getString(valueIndex);
+ outValue = aResultSet.getString(aFieldIndex);
break;
case java.sql.Types.LONGVARBINARY:
- outValue = rs.getString(valueIndex);
+ outValue = aResultSet.getString(aFieldIndex);
break;
// 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));
+ Timestamp timestamp = (aResultSet.getTimestamp(aFieldIndex));
- if (!rs.wasNull()) {
+ if (!aResultSet.wasNull()) {
java.util.Date date = new java.util.Date(timestamp.getTime());
-
- Calendar calendar = new GregorianCalendar();
- calendar.setTime(date);
- calendar.setTimeZone(timezone);
- outValue = internalDateFormat.format(date);
-
- int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
- String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);
-
- if (offset<0)
- outValue = outValue + "-";
- else
- outValue = outValue + "+";
- outValue = outValue + tzOffset;
+ outValue = DatabaseHelper.convertDateToInternalRepresenation(date);
}
break;
default:
outValue = "<unsupported value>";
- logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
+ logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")");
}
- } catch (SQLException e) {
- throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
+ }
+ catch (SQLException e) {
+ throw new DatabaseFailure("Could not get Value out of Resultset -- ",
e);
}
}
}
/**
- * select-Operator um einen Datensatz zu bekommen.
- * @param id Primaerschluessel des Datensatzes.
- * @return liefert EntityObject des gefundenen Datensatzes oder null.
+ * Return an entity specified by id, or <code>null</code> if no such
+ * entity exists.
*/
- public Entity selectById(String id) throws StorageObjectExc {
- if ((id == null) || id.equals("")) {
- throw new StorageObjectExc("Database.selectById: Missing id");
+ public Entity selectById(String anId) throws DatabaseExc {
+ if ((anId == null) || anId.equals("")) {
+ throw new DatabaseExc("Database.selectById: Missing id");
}
// ask object store for object
- if (StoreUtil.extendsStorableEntity(theEntityClass)) {
- String uniqueId = id;
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ String uniqueId = anId;
- if (theEntityClass.equals(StorableObjectEntity.class)) {
+ if (entityClass.equals(StorableObjectEntity.class)) {
uniqueId += ("@" + mainTable);
}
- StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
+ StoreIdentifier search_sid = new StoreIdentifier(entityClass, uniqueId);
logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
Entity hit = (Entity) o_store.use(search_sid);
}
}
- Statement stmt = null;
Connection con = obtainConnection();
Entity returnEntity = null;
+ PreparedStatement statement = null;
try {
ResultSet rs;
+ String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?";
- /** todo better prepared statement */
- String selectSql =
- "select * from " + mainTable + " where " + primaryKeyField + "=" + id;
- stmt = con.createStatement();
- rs = executeSql(stmt, selectSql);
+ statement = con.prepareStatement(query);
+ statement.setString(1, anId);
- if (rs != null) {
- if (evaluatedMetaData == false) {
- evalMetaData(rs.getMetaData());
- }
+ logQueryBefore(query);
+
+ long startTime = System.currentTimeMillis();
+ try {
+ rs = statement.executeQuery();
+
+ logQueryAfter(query, (System.currentTimeMillis() - startTime));
+ }
+ catch (SQLException e) {
+ logQueryError(query, (System.currentTimeMillis() - startTime), e);
+ throw e;
+ }
+ if (rs != null) {
if (rs.next()) {
returnEntity = makeEntityFromResultSet(rs);
}
else {
- logger.warn("No data for id: " + id + " in table " + mainTable);
+ logger.warn("No data for id: " + anId + " in table " + mainTable);
}
rs.close();
}
else {
- logger.warn("No Data for Id " + id + " in Table " + mainTable);
+ logger.warn("No Data for Id " + anId + " in Table " + mainTable);
}
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "selectById");
- return null;
- }
- catch (NumberFormatException e) {
- logger.error("ID is no number: " + id);
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
- freeConnection(con, stmt);
+ freeConnection(con, statement);
}
return returnEntity;
}
- /**
- * This method makes it possible to make selects across multiple tables
- *
- * @param mainTablePrefix prefix for the mainTable
- * @param extraTables a vector of tables for relational select
- * @param aWhereClause whereClause
- * @return EntityList of selected Objects
- * @throws StorageObjectFailure
- */
-
- public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix,
- List extraTables, String aWhereClause )
- throws StorageObjectFailure {
- return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit);
+ public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT);
}
- public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
+ public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure {
return selectByFieldValue(aField, aValue, 0);
}
- public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
+ public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure {
return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset);
}
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
- * Also offset wird der erste Datensatz genommen.
- *
- * @param where where-Clause
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
- public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
+ public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure {
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 whereClause where-Clause
- * @param offset ab welchem Datensatz.
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
- public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
+ public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure {
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 where where-Clause
- * @param order orderBy-Clause
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
- public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
- return selectByWhereClause(where, order, 0);
- }
-
- public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws StorageObjectFailure {
- return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, defaultLimit);
+ public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, DEFAULT_LIMIT);
}
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
- * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
- *
- * @param whereClause where-Clause
- * @param orderBy orderBy-Clause
- * @param offset ab welchem Datensatz
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
- public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
- return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
+ public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure {
+ return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT);
}
- /**
- * select-Operator returns EntityList with matching rows in Database.
- * @param aWhereClause where-Clause
- * @param anOrderByClause orderBy-Clause
- * @param offset ab welchem Datensatz
- * @param limit wieviele Datens?tze
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
- int offset, int limit) throws StorageObjectFailure {
+ int offset, int limit) throws DatabaseExc, DatabaseFailure {
return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit);
}
-
- /**
- * select-Operator returns EntityList with matching rows in Database.
- * @param aWhereClause where-Clause
- * @param anOrderByClause orderBy-Clause
- * @param offset ab welchem Datensatz
- * @param limit wieviele Datens?tze
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectFailure
- */
- public EntityList selectByWhereClause(String mainTablePrefix, List extraTables,
+ public EntityList selectByWhereClause(
+ String aMainTablePrefix, List anExtraTables,
String aWhereClause, String anOrderByClause,
- int offset, int limit) throws StorageObjectFailure {
-
- // TODO get rid of emtpy Strings in extraTables
- // make extraTables null, if single empty String in it
- // cause StringUtil.splitString puts in emptyString
- if (extraTables != null && ((String)extraTables.get(0)).trim().equals(""))
- {
- logger.debug("+++ made extraTables to null!");
- extraTables=null;
- }
+ int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure {
- String useTable = mainTable;
- String selectStar = "*";
- if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
- useTable+=" "+mainTablePrefix;
- selectStar=mainTablePrefix.trim() + ".*";
- }
+ if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){
+ anExtraTables=null;
+ }
// check o_store for entitylist
// only if no relational select
- if (extraTables==null) {
- if (StoreUtil.extendsStorableEntity(theEntityClass)) {
- StoreIdentifier searchSid = new StoreIdentifier(theEntityClass,
+ if (anExtraTables==null) {
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreIdentifier searchSid = new StoreIdentifier(entityClass,
StoreContainerType.STOC_TYPE_ENTITYLIST,
StoreUtil.getEntityListUniqueIdentifierFor(mainTable,
- aWhereClause, anOrderByClause, offset, limit));
+ aWhereClause, anOrderByClause, anOffset, aLimit));
EntityList hit = (EntityList) o_store.use(searchSid);
if (hit != null) {
}
}
- // local
- EntityList theReturnList = null;
- Connection con = null;
- Statement stmt = null;
- ResultSet rs;
- int offsetCount = 0;
- int count = 0;
-
- // build sql-statement
+ RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix);
- if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
- aWhereClause = null;
- }
+ EntityList result = null;
+ Connection connection = null;
- StringBuffer countSql =
- new StringBuffer("select count(*) from ").append(useTable);
- StringBuffer selectSql =
- new StringBuffer("select "+selectStar+" from ").append(useTable);
-
- // append extratables, if necessary
- if (extraTables!=null) {
- for (int i=0;i < extraTables.size();i++) {
- if (!extraTables.get(i).equals("")) {
- countSql.append( ", " + extraTables.get(i));
- selectSql.append( ", " + extraTables.get(i));
+ if (anExtraTables!=null) {
+ Iterator i = anExtraTables.iterator();
+ while (i.hasNext()) {
+ String table = (String) i.next();
+ if (!"".equals(table)) {
+ retriever.addExtraTable(table);
}
}
}
if (aWhereClause != null) {
- selectSql.append(" where ").append(aWhereClause);
- countSql.append(" where ").append(aWhereClause);
+ retriever.appendWhereClause(aWhereClause);
}
if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
- selectSql.append(" order by ").append(anOrderByClause);
+ retriever.appendOrderByClause(anOrderByClause);
}
- if ((limit > -1) && (offset > -1)) {
- selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
+ if (anOffset>-1 && aLimit>-1) {
+ retriever.setLimit(aLimit+1);
+ retriever.setOffset(anOffset);
+ }
+
+ Iterator i = getFieldNames().iterator();
+ while (i.hasNext()) {
+ retriever.addField((String) i.next());
}
// execute sql
try {
- con = obtainConnection();
- 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
- count = offsetCount;
-
- if (theReturnList != null) {
- // now we decide if we have to know an overall count...
- count = offsetCount;
+ connection = obtainConnection();
+ ResultSet resultSet = retriever.execute(connection);
- if ((limit > -1) && (offset > -1)) {
- if (offsetCount == limit) {
- rs = executeSql(stmt, countSql.toString());
+ boolean hasMore = false;
- if (rs != null) {
- if (rs.next()) {
- count = rs.getInt(1);
- }
+ if (resultSet != null) {
+ result = new EntityList();
+ Entity entity;
+ int position = 0;
- rs.close();
- }
- else {
- logger.error("Could not count: " + countSql);
- }
- }
+ while (((aLimit == -1) || (position<aLimit)) && resultSet.next()) {
+ entity = makeEntityFromResultSet(resultSet);
+ result.add(entity);
+ position++;
}
- theReturnList.setCount(count);
- theReturnList.setOffset(offset);
- theReturnList.setWhere(aWhereClause);
- theReturnList.setOrder(anOrderByClause);
- theReturnList.setStorage(this);
- theReturnList.setLimit(limit);
+ hasMore = resultSet.next();
+ resultSet.close();
+ }
- if (offset >= limit) {
- theReturnList.setPrevBatch(offset - limit);
- }
+ if (result != null) {
+ result.setOffset(anOffset);
+ result.setWhere(aWhereClause);
+ result.setOrder(anOrderByClause);
+ result.setStorage(this);
+ result.setLimit(aLimit);
- if ((offset + offsetCount) < count) {
- theReturnList.setNextBatch(offset + limit);
+ if (hasMore) {
+ result.setNextBatch(anOffset + aLimit);
}
- if (extraTables==null && StoreUtil.extendsStorableEntity(theEntityClass)) {
- StoreIdentifier sid = theReturnList.getStoreIdentifier();
+ if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
+ StoreIdentifier sid = result.getStoreIdentifier();
logger.debug("CACHE (add): " + sid.toString());
o_store.add(sid);
}
}
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "selectByWhereClause");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
try {
- if (con != null) {
- freeConnection(con, stmt);
+ if (connection != null) {
+ freeConnection(connection);
}
} catch (Throwable t) {
}
}
- return theReturnList;
+ return result;
}
- /**
- * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
- *
- * @param rs Das ResultSetObjekt.
- * @return Entity Die Entity.
- */
- private Entity makeEntityFromResultSet(ResultSet rs)
- throws StorageObjectFailure {
- Map theResultHash = new HashMap();
+ private Entity makeEntityFromResultSet(ResultSet rs) {
+ Map fields = new HashMap();
String theResult = null;
- int theType;
+ int type;
Entity returnEntity = null;
try {
- if (StoreUtil.extendsStorableEntity(theEntityClass)) {
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
StoreIdentifier searchSid = StorableObjectEntity.getStoreIdentifier(this,
- theEntityClass, rs);
+ entityClass, rs);
Entity hit = (Entity) o_store.use(searchSid);
if (hit != null) return hit;
}
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ type = fieldTypes[i];
- 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) {
+ if (type == java.sql.Types.LONGVARBINARY) {
InputStreamReader is =
(InputStreamReader) rs.getCharacterStream(i + 1);
is.close();
theResult = theResultString.toString();
- } else {
+ }
+ else {
theResult = null;
}
- } else {
- theResult = getValueAsString(rs, (i + 1), theType);
+ }
+ else {
+ theResult = getValueAsString(rs, (i + 1), type);
}
if (theResult != null) {
- theResultHash.put(metadataFields.get(i), theResult);
+ fields.put(getFieldNames().get(i), theResult);
}
}
- if (theEntityClass != null) {
- returnEntity = (Entity) theEntityClass.newInstance();
- returnEntity.setStorage(this);
- returnEntity.setFieldValues(theResultHash);
+ if (entityClass != null) {
+ returnEntity = createNewEntity();
+ returnEntity.setFieldValues(fields);
if (returnEntity instanceof StorableObject) {
logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
}
- } else {
- throwStorageObjectException("Internal Error: theEntityClass not set!");
+ }
+ else {
+ throw new DatabaseExc("Internal Error: entityClass 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;
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
return returnEntity;
/**
* Inserts an entity into the database.
*
- * @param theEntity
- * @return der Wert des Primary-keys der eingef?gten Entity
+ * @param anEntity
+ * @return the value of the primary key of the inserted record
*/
- public String insert(Entity theEntity) throws StorageObjectFailure {
+ public String insert(Entity anEntity) throws DatabaseFailure {
invalidateStore();
+ RecordInserter inserter =
+ new RecordInserter(mainTable, getPrimaryKeySequence());
+
String returnId = null;
Connection con = null;
- PreparedStatement pstmt = null;
try {
- StringBuffer f = new StringBuffer();
- StringBuffer v = new StringBuffer();
- String aField;
- String aValue;
- boolean firstField = true;
+ String fieldName;
// make sql-string
- for (int i = 0; i < getFields().size(); i++) {
- aField = (String) getFields().get(i);
-
- if (!aField.equals(primaryKeyField)) {
- aValue = null;
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ fieldName = (String) getFieldNames().get(i);
+ if (!fieldName.equals(primaryKeyField)) {
// exceptions
- if (!theEntity.hasFieldValue(aField) && (
- aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange"))) {
- aValue = "NOW()";
+ if (!anEntity.hasFieldValue(fieldName) && (
+ fieldName.equals("webdb_create") ||
+ fieldName.equals("webdb_lastchange"))) {
+ inserter.assignVerbatim(fieldName, "now()");
}
else {
- if (theEntity.hasFieldValue(aField)) {
- aValue =
- "'" +
- JDBCStringRoutines.escapeStringLiteral(theEntity.getFieldValue(aField)) + "'";
- }
- }
-
- // wenn Wert gegeben, dann einbauen
- if (aValue != null) {
- if (firstField == false) {
- f.append(",");
- v.append(",");
+ if (anEntity.hasFieldValue(fieldName)) {
+ inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
}
- else {
- firstField = false;
- }
-
- f.append(aField);
- v.append(aValue);
}
}
}
- // end for
-
- // insert into db
- StringBuffer sqlBuf =
- new StringBuffer("insert into ").append(mainTable).append("(").append(f)
- .append(") values (").append(v).append(")");
- String sql = sqlBuf.toString();
- logger.info("INSERT: " + sql);
con = obtainConnection();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql);
-
- int ret = pstmt.executeUpdate();
+ returnId = inserter.execute(con);
- if (ret == 0) {
- //insert failed
- return null;
- }
-
-// pstmt = con.prepareStatement("select currval('" + + "_id_seq')");
-
- returnId = getLatestInsertedId(con);
- theEntity.setId(returnId);
- }
- catch (SQLException sqe) {
- throwSQLException(sqe, "insert");
+ anEntity.setId(returnId);
}
finally {
- try {
- con.setAutoCommit(true);
- }
- catch (Exception e) {
- }
-
- freeConnection(con, pstmt);
+ freeConnection(con);
}
- /** todo store entity in o_store */
return returnId;
}
*
* @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*/
-
+ public void update(Entity theEntity) throws DatabaseFailure {
invalidateStore();
- String id = theEntity.getId();
- String aField;
- StringBuffer fv = new StringBuffer();
- boolean firstField = true;
+ RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
// build sql statement
- for (int i = 0; i < getFields().size(); i++) {
- aField = (String) metadataFields.get(i);
-
- // only normal cases
- // todo if entity.hasFieldValue returns false, then the value should be stored as null
- if (!(aField.equals(primaryKeyField) ||
- aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange"))) {
- if (theEntity.hasFieldValue(aField)) {
- if (firstField == false) {
- fv.append(", ");
- }
- else {
- firstField = false;
- }
+ for (int i = 0; i < getFieldNames().size(); i++) {
+ String field = (String) getFieldNames().get(i);
- fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral(theEntity.getFieldValue(aField))).append("'");
+ if (!(field.equals(primaryKeyField) ||
+ "webdb_create".equals(field) ||
+ "webdb_lastchange".equals(field) ||
+ binaryFields.contains(field))) {
- // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getFieldValue(aField))).append("'");
+ if (theEntity.hasFieldValue(field)) {
+ generator.assignString(field, theEntity.getFieldValue(field));
}
}
}
- StringBuffer sql =
- new StringBuffer("update ").append(mainTable).append(" set ").append(fv);
-
// exceptions
- if (metadataFields.contains("webdb_lastchange")) {
- sql.append(",webdb_lastchange=NOW()");
+ if (hasField("webdb_lastchange")) {
+ generator.assignVerbatim("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") &&
+ if (hasField("webdb_create") &&
theEntity.hasFieldValue("webdb_create")) {
// minimum of 10 (yyyy-mm-dd)...
if (theEntity.getFieldValue("webdb_create").length() >= 10) {
// TimeStamp stuff
try {
java.util.Date d = userInputDateFormat.parse(dateString);
-// Timestamp tStamp = new Timestamp(d.getTime());
- sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");
+ generator.assignDateTime("webdb_create", d);
}
catch (ParseException e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
}
-
- sql.append(" where id=").append(id);
- logger.info("UPDATE: " + sql);
+ Connection connection = null;
try {
- con = obtainConnection();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql.toString());
-
- pstmt.executeUpdate();
- }
- catch (SQLException sqe) {
- throwSQLException(sqe, "update");
+ connection = obtainConnection();
+ generator.execute(connection);
}
finally {
- try {
- con.setAutoCommit(true);
- }
- catch (Exception e) {
- ;
- }
-
- freeConnection(con, pstmt);
+ freeConnection(connection);
}
}
-
- /*
- * delete-Operator
- * @param id des zu loeschenden Datensatzes
- * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
- */
- public boolean delete(String id) throws StorageObjectFailure {
+
+ private void invalidateObject(String anId) {
// ostore send notification
- if (StoreUtil.extendsStorableEntity(theEntityClass)) {
- String uniqueId = id;
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
+ String uniqueId = anId;
- if (theEntityClass.equals(StorableObjectEntity.class)) {
+ if (entityClass.equals(StorableObjectEntity.class)) {
uniqueId += ("@" + mainTable);
}
- logger.debug("CACHE: (del) " + id);
+ logger.debug("CACHE: (del) " + anId);
StoreIdentifier search_sid =
- new StoreIdentifier(theEntityClass,
+ new StoreIdentifier(entityClass,
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 " + mainTable + " where " + primaryKeyField + "='" + id + "'";
+ /*
+ * delete-Operator
+ * @param id des zu loeschenden Datensatzes
+ * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
+ */
+ public boolean delete(String id) throws DatabaseFailure {
+ invalidateObject(id);
+
+ int resultCode = 0;
+ Connection connection = obtainConnection();
+ PreparedStatement statement = null;
- logger.debug("DELETE " + sql);
try {
- con = obtainConnection();
- stmt = con.createStatement();
- res = stmt.executeUpdate(sql);
+ statement = connection.prepareStatement("delete from " + mainTable + " where " + primaryKeyField + "=?");
+ statement.setInt(1, Integer.parseInt(id));
+ logQueryBefore("delete from " + mainTable + " where " + primaryKeyField + "=" + id + "");
+ resultCode = statement.executeUpdate();
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "delete");
+ catch (SQLException e) {
+ logger.warn("Can't delete record", e);
}
finally {
- freeConnection(con, stmt);
+ freeConnection(connection, statement);
}
invalidateStore();
- return (res > 0) ? true : false;
+ return (resultCode > 0) ? true : false;
}
/**
* Deletes entities based on a where clause
- *
- * @param aWhereClause
- * @return
- * @throws StorageObjectFailure
*/
- public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {
+ public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure {
invalidateStore();
Statement stmt = null;
stmt = con.createStatement();
res = stmt.executeUpdate(sql);
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "delete");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
freeConnection(con, stmt);
return false;
}
- /**
- * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
- * @param stmt Statemnt
- * @param sql Sql-String
- */
public ResultSet executeSql(Statement stmt, String sql)
- throws StorageObjectFailure, SQLException {
+ throws DatabaseFailure, SQLException {
ResultSet rs;
+ logQueryBefore(sql);
long startTime = System.currentTimeMillis();
-
try {
rs = stmt.executeQuery(sql);
- logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+ logQueryAfter(sql, (System.currentTimeMillis() - startTime));
}
catch (SQLException e) {
- logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+ logQueryError(sql, (System.currentTimeMillis() - startTime), e);
throw e;
}
return rs;
}
- private Map processRow(ResultSet aResultSet) throws StorageObjectFailure {
+ private Map processRow(ResultSet aResultSet) throws DatabaseFailure {
try {
Map result = new HashMap();
ResultSetMetaData metaData = aResultSet.getMetaData();
return result;
}
catch (Throwable e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
- public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
+ /**
+ * Executes 1 sql statement and returns the results as a <code>List</code> of
+ * <code>Map</code>s
+ */
+ public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc {
Connection connection = null;
Statement statement = null;
try {
return result;
}
catch (Throwable e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
finally {
if (connection!=null) {
freeConnection(connection, statement);
}
}
- };
+ }
- public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
+ /**
+ * Executes 1 sql statement and returns the first result row as a <code>Map</code>s
+ * (<code>null</code> if there wasn't any row)
+ */
+ public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc {
try {
List resultList = executeFreeSql(anSqlStatement, 1);
try {
if (resultList.size()>0)
return (Map) resultList.get(0);
- else
- return null;
+ return null;
}
finally {
}
}
catch (Throwable t) {
- throw new StorageObjectFailure(t);
+ throw new DatabaseFailure(t);
}
- };
+ }
- public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
+ /**
+ * Executes 1 sql statement and returns the first column of the first result row as a <code>String</code>s
+ * (<code>null</code> if there wasn't any row)
+ */
+ public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc {
Map row = executeFreeSingleRowSql(sql);
if (row==null)
Iterator i = row.values().iterator();
if (i.hasNext())
return (String) i.next();
- else
- return null;
- };
+ return null;
+ }
- public int getSize(String where) throws SQLException, StorageObjectFailure {
+ public int getSize(String where) throws SQLException, DatabaseFailure {
return getSize("", null, where);
}
/**
* returns the number of rows in the table
*/
- public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure {
-
- long startTime = System.currentTimeMillis();
+ public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure {
String useTable = mainTable;
if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) {
- useTable+=" "+mainTablePrefix;
+ useTable+=" "+mainTablePrefix;
}
StringBuffer countSql =
new StringBuffer("select count(*) from ").append(useTable);
Connection con = null;
Statement stmt = null;
int result = 0;
+ logQueryBefore(countSql.toString());
+ long startTime = System.currentTimeMillis();
try {
con = obtainConnection();
finally {
freeConnection(con, stmt);
}
- logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + countSql);
+ logQueryAfter(countSql.toString(), (System.currentTimeMillis() - startTime));
return result;
}
public int executeUpdate(Statement stmt, String sql)
- throws StorageObjectFailure, SQLException {
+ throws DatabaseFailure, SQLException {
int rs;
+
+ logQueryBefore(sql);
long startTime = System.currentTimeMillis();
try {
rs = stmt.executeUpdate(sql);
- logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+ logQueryAfter(sql, (System.currentTimeMillis() - startTime));
}
catch (SQLException e) {
- logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
+ logQueryError(sql, (System.currentTimeMillis() - startTime), e);
throw e;
}
}
public int executeUpdate(String sql)
- throws StorageObjectFailure, SQLException {
+ throws DatabaseFailure, SQLException {
int result = -1;
- long startTime = System.currentTimeMillis();
Connection con = null;
PreparedStatement pstmt = null;
+ logQueryBefore(sql);
+ long startTime = System.currentTimeMillis();
try {
con = obtainConnection();
pstmt = con.prepareStatement(sql);
result = pstmt.executeUpdate();
+ logQueryAfter(sql, System.currentTimeMillis() - startTime);
}
catch (Throwable e) {
- logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
- throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
+ logQueryError(sql, System.currentTimeMillis() - startTime, e);
+ throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
}
finally {
freeConnection(con, pstmt);
}
-
- logger.info((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
return result;
}
/**
- * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
- * @param md ResultSetMetaData
+ * Processes the metadata for the table this Database object is responsible for.
*/
- private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
- this.evaluatedMetaData = true;
- this.metadataFields = new ArrayList();
- this.metadataLabels = new ArrayList();
- this.metadataNotNullFields = new ArrayList();
+ private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure {
+ fieldNames = new ArrayList();
+ fieldNameToType = new HashMap();
try {
- int numFields = md.getColumnCount();
- this.metadataTypes = new int[numFields];
-
- String aField;
- int aType;
+ int numFields = aMetaData.getColumnCount();
+ fieldTypes = new int[numFields];
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(primaryKeyField)) {
- }
-
- if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
- metadataNotNullFields.add(aField);
- }
+ fieldNames.add(aMetaData.getColumnName(i));
+ fieldTypes[i - 1] = aMetaData.getColumnType(i);
+ fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i)));
}
}
- catch (SQLException e) {
- throwSQLException(e, "evalMetaData");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
}
/**
- * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
- * um die alle Columns und Typen einer Tabelle zu ermitteln.
+ * Retrieves metadata from the table this Database object represents
*/
- private void get_meta_data() throws StorageObjectFailure {
- Connection con = null;
- PreparedStatement pstmt = null;
+ private void acquireMetaData() throws DatabaseFailure {
+ Connection connection = null;
+ PreparedStatement statement = null;
String sql = "select * from " + mainTable + " where 0=1";
try {
- con = obtainConnection();
- pstmt = con.prepareStatement(sql);
+ connection = obtainConnection();
+ statement = connection.prepareStatement(sql);
logger.debug("METADATA: " + sql);
- ResultSet rs = pstmt.executeQuery();
- evalMetaData(rs.getMetaData());
- rs.close();
+ ResultSet resultSet = statement.executeQuery();
+ try {
+ processMetaData(resultSet.getMetaData());
+ }
+ finally {
+ resultSet.close();
+ }
}
- catch (SQLException e) {
- throwSQLException(e, "get_meta_data");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
- freeConnection(con, pstmt);
+ freeConnection(connection, statement);
}
}
- public Connection obtainConnection() throws StorageObjectFailure {
+ public Connection obtainConnection() throws DatabaseFailure {
try {
return MirGlobal.getDatabaseEngine().obtainConnection();
}
catch (Exception e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
- public void freeConnection(Connection aConnection, Statement aStatement) throws StorageObjectFailure {
- try {
- aStatement.close();
- }
- catch (Throwable t) {
- logger.warn("Can't close statemnet: " + t.toString());
- }
-
+ public void freeConnection(Connection aConnection) throws DatabaseFailure {
try {
MirGlobal.getDatabaseEngine().releaseConnection(aConnection);
}
}
}
- /**
- * Wertet SQLException aus und wirft dannach eine StorageObjectException
- * @param sqe SQLException
- * @param aFunction Funktonsname, in der die SQLException geworfen wurde
- */
- 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();
+ public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure {
+ try {
+ aStatement.close();
+ }
+ catch (Throwable t) {
+ logger.warn("Can't close statement", t);
}
- String information =
- "SQL Error: " +
- "state= " + state +
- ", vendor= " + vendor +
- ", message=" + message +
- ", function= " + aFunction;
-
- logger.error(information);
-
- throw new StorageObjectFailure(information, sqe);
+ freeConnection(aConnection);
}
protected void _throwStorageObjectException(Exception e, String aFunction)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
if (e != null) {
logger.error(e.getMessage() + aFunction);
- throw new StorageObjectFailure(aFunction, e);
+ throw new DatabaseFailure(aFunction, e);
}
}
- /**
- * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
- * eine StorageObjectException
- * @param aMessage Nachricht mit dem Fehler
- * @exception StorageObjectFailure
- */
- void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
- logger.error(aMessage);
- throw new StorageObjectFailure(aMessage, null);
- }
/**
* Invalidates any cached entity list
*/
private void invalidateStore() {
- // invalidating all EntityLists corresponding with theEntityClass
- if (StoreUtil.extendsStorableEntity(theEntityClass)) {
+ // invalidating all EntityLists corresponding with entityClass
+ if (StoreUtil.extendsStorableEntity(entityClass)) {
StoreContainerType stoc_type =
- StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
+ StoreContainerType.valueOf(entityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);
o_store.invalidate(stoc_type);
}
}
/**
* Retrieves a binary value
*/
- public InputStream getBinaryField(String aQuery) throws StorageObjectFailure, SQLException {
+ public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException {
Connection connection=null;
Statement statement=null;
InputStream inputStream;
- InputStream imageInputStream = null;
try {
connection = obtainConnection();
if(resultSet!=null) {
if (resultSet.next()) {
- inputStream = resultSet.getBlob(1).getBinaryStream();
- imageInputStream = new BinaryFieldInputStream(inputStream, connection, statement);
+ if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
+ return resultSet.getBytes(1);
+ }
+ else {
+ inputStream = resultSet.getBlob(1).getBinaryStream();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ StreamCopier.copy(inputStream, outputStream);
+ return outputStream.toByteArray();
+ }
}
resultSet.close();
}
}
finally {
+ try {
+ connection.setAutoCommit(true);
+ }
+ catch (Throwable e) {
+ logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
+ e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ }
+
+ try {
+ freeConnection(connection, statement);
+ }
+ catch (Throwable e) {
+ logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
+ }
+
}
}
catch (Throwable t) {
logger.error("EntityImages.getImage failed: " + t.toString());
t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- try {
- connection.setAutoCommit(true);
- }
- catch (Throwable e) {
- logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- }
-
- try {
- freeConnection(connection, statement);
- }
- catch (Throwable e) {
- logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
- }
-
- throw new StorageObjectFailure(t);
+ throw new DatabaseFailure(t);
}
- return imageInputStream;
+ return new byte[0];
}
/**
- * Sets a binary value. The query is supposed to contain 1 ? denoting where the
- * binary value should be inserted.
- *
- * e.g. <code>update images set image_data = ? where id= 22</code>
+ * Sets a binary value for a particular field in a record specified by its identifier
*/
- public void setBinaryField(String aQuery, byte aData[]) throws StorageObjectFailure, SQLException {
+ public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException {
PreparedStatement statement = null;
Connection connection = obtainConnection();
+
try {
connection.setAutoCommit(false);
try {
- statement = connection.prepareStatement(aQuery);
- statement.setBinaryStream(1, new ByteArrayInputStream(aData), aData.length);
- statement.execute();
- connection.commit();
+ // are we using bytea ?
+ if (getFieldType(aFieldName) == java.sql.Types.BINARY) {
+ statement = connection.prepareStatement(
+ "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
+ statement.setBytes(1, aData);
+ statement.execute();
+ connection.commit();
+ }
+ // or the old oid's
+ else {
+ PGConnection postgresqlConnection = (org.postgresql.PGConnection) ((DelegatingConnection) connection).getDelegate();
+ LargeObjectManager lobManager = postgresqlConnection.getLargeObjectAPI();
+ int oid = lobManager.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
+ LargeObject obj = lobManager.open(oid, LargeObjectManager.WRITE); // Now open the file File file =
+ obj.write(aData);
+ obj.close();
+ statement = connection.prepareStatement(
+ "update " + mainTable + " set " + aFieldName + " = ? where " + getIdFieldName() + "=" + Integer.parseInt(anObjectId));
+ statement.setInt(1, oid);
+ statement.execute();
+ connection.commit();
+ }
}
finally {
connection.setAutoCommit(true);
}
/**
- * a small wrapper class that allows us to store the DB connection resources
- * that the BlobInputStream is using and free them upon closing of the stream
+ * Can be overridden to specify a primary key sequence name not named according to
+ * the convention (tablename _id_seq)
*/
- private class BinaryFieldInputStream extends InputStream {
- InputStream inputStream;
- Connection connection;
- Statement statement;
+ protected String getPrimaryKeySequence() {
+ return mainTable+"_id_seq";
+ }
- public BinaryFieldInputStream(InputStream aBlobInputStream, Connection aConnection, Statement aStatement ) {
- inputStream = aBlobInputStream;
- connection = aConnection;
- statement = aStatement;
- }
+ /**
+ * Can be called by subclasses to specify fields that are binary, and that shouldn't
+ * be updated outside of {@link #setBinaryField}
+ *
+ * @param aBinaryField The field name of the binary field
+ */
+ protected void markBinaryField(String aBinaryField) {
+ binaryFields.add(aBinaryField);
+ }
- public void close () throws IOException {
- inputStream.close();
- try {
- connection.setAutoCommit(true);
- freeConnection(connection, statement);
- }
- catch (Exception e) {
- throw new IOException("close(): "+e.toString());
- }
- }
+ private void logQueryBefore(String aQuery) {
+ logger.debug("about to perform QUERY " + aQuery);
+// (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ }
- public int read() throws IOException {
- return inputStream.read();
+ private void logQueryAfter(String aQuery, long aTime) {
+ logger.info("QUERY " + aQuery + " took " + aTime + "ms.");
+ }
+
+ private void logQueryError(String aQuery, long aTime, Throwable anException) {
+ logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());
+ }
+
+ private int getFieldType(String aFieldName) {
+ if (fieldNameToType == null) {
+ acquireMetaData();
}
+
+ return ((Integer) fieldNameToType.get(aFieldName)).intValue();
}
}
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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 multex.Exc;
+
+public class DatabaseExc extends Exc {
+ public DatabaseExc(String aMessage) {
+ super(aMessage);
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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 multex.Failure;
+
+/**
+ * Exception for all failures in the database-layer
+ * @author idefix
+ */
+public class DatabaseFailure extends Failure {
+ public DatabaseFailure(Throwable e) {
+ super("", e);
+ }
+
+ public DatabaseFailure() {
+ super("A failure occured", null);
+ }
+
+ public DatabaseFailure(String msg, Throwable e) {
+ super(msg, e);
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.misc.StringUtil;\r
+\r
+import java.text.DateFormat;\r
+import java.text.SimpleDateFormat;\r
+import java.util.Date;\r
+import java.util.TimeZone;\r
+import java.util.GregorianCalendar;\r
+import java.util.Calendar;\r
+\r
+public class DatabaseHelper {\r
+ public static final TimeZone INTERNAL_TIMEZONE = TimeZone.getTimeZone(\r
+ MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));\r
+ public static final DateFormat INTERNAL_DATE_FORMAT =\r
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
+\r
+ private DatabaseHelper() {\r
+ }\r
+\r
+ static {\r
+ INTERNAL_DATE_FORMAT.setTimeZone(INTERNAL_TIMEZONE);\r
+ }\r
+\r
+ public static String convertDateToInternalRepresenation(Date aDate) {\r
+ Calendar calendar = new GregorianCalendar();\r
+ calendar.setTime(aDate);\r
+ calendar.setTimeZone(INTERNAL_TIMEZONE);\r
+ int offset = calendar.get(Calendar.ZONE_OFFSET);\r
+ boolean positive = true;\r
+ if (offset<0) {\r
+ positive=false;\r
+ offset = -offset;\r
+ }\r
+ int offsethours = offset / (60*60*1000);\r
+\r
+ return INTERNAL_DATE_FORMAT.format(aDate) + (positive?"+":"-") +\r
+ StringUtil.zeroPaddingNumber((long) offsethours, 2, 2);\r
+ }\r
+\r
+ public static String getInternalTimeZoneOffset(Date aDate) {\r
+ Calendar calendar = new GregorianCalendar();\r
+ calendar.setTime(aDate);\r
+ calendar.setTimeZone(INTERNAL_TIMEZONE);\r
+\r
+ int offset = calendar.get(Calendar.DST_OFFSET);\r
+ boolean positive = true;\r
+ if (offset<0) {\r
+ positive=false;\r
+ offset = -offset;\r
+ }\r
+ int offsethours = offset / 60*60*1000;\r
+ int offsetminutes = ( offset / 60*1000 ) % 60;\r
+\r
+ return (positive?"+":"-") +\r
+ StringUtil.zeroPaddingNumber((long) offsethours, 2, 2) + ":" +\r
+ StringUtil.zeroPaddingNumber((long) offsetminutes, 2, 2);\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.util.Date;\r
+\r
+/**\r
+ * Class to generate insert statements\r
+ */\r
+public class RecordInserter extends StatementGenerator {\r
+\r
+ public RecordInserter(String aTableName, String aSequenceName) {\r
+ tableName = aTableName;\r
+ sequenceName = aSequenceName;\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a string typed field\r
+ */\r
+ public void assignString(String aFieldName, String aValue) {\r
+ assignObject(aFieldName, aValue);\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a date/time typed field\r
+ */\r
+ public void assignDate(String aFieldName, Date aDate) {\r
+ assignObject(aFieldName, new java.sql.Date(aDate.getTime()));\r
+ }\r
+\r
+ public void assignVerbatim(String aFieldName, String aText) {\r
+ if (firstAssignment) {\r
+ appendQuery("insert into " + tableName + "(");\r
+ firstAssignment = false;\r
+ }\r
+ else {\r
+ appendQuery(",");\r
+ values.append(",");\r
+ }\r
+\r
+ values.append(aText);\r
+\r
+ appendQuery(aFieldName);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns the id of the insterted record.\r
+ */\r
+ public String execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(")");\r
+ appendQuery(CRLF);\r
+ appendQuery("values (");\r
+ appendQuery(values.toString());\r
+ appendQuery(")");\r
+\r
+ try {\r
+ int modified = executeWithModifiedCount(aConnection);\r
+ if (modified!=1) {\r
+ throw new Exception("modified count != 1 after insert");\r
+ }\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement("select currval('" + sequenceName + "')");\r
+ ResultSet rs = statement.executeQuery();\r
+ rs.next();\r
+ return rs.getString(1);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ }\r
+\r
+ private void assignObject(String aFieldName, Object anObject) {\r
+ appendParameter(anObject);\r
+\r
+ assignVerbatim(aFieldName, "?");\r
+ }\r
+\r
+ private String tableName;\r
+ private static final String CRLF = "\n\r";\r
+ private boolean firstAssignment = true;\r
+ private String sequenceName;\r
+ private StringBuffer values = new StringBuffer();\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.util.*;\r
+\r
+/**\r
+ * Class to generate update statements\r
+ */\r
+public class RecordRetriever extends StatementGenerator {\r
+ public RecordRetriever(String aTableName, String aPrefix) {\r
+ tableName = aTableName;\r
+ prefix = aPrefix;\r
+ if (prefix == null || "".equals(prefix)) {\r
+ prefix = null;\r
+ }\r
+ extraTables = new ArrayList();\r
+ whereClause = new StringBuffer();\r
+ orderByClause = new StringBuffer();\r
+\r
+ appendQuery("SELECT ");\r
+ }\r
+\r
+ public void addExtraTable(String aTableSpecification) {\r
+ extraTables.add(aTableSpecification);\r
+ }\r
+\r
+ public void addField(String aField) {\r
+ if (firstField) {\r
+ firstField = false;\r
+ }\r
+ else {\r
+ appendQuery(", ");\r
+ }\r
+ if (prefix!=null) {\r
+ appendQuery(prefix);\r
+ appendQuery(".");\r
+ }\r
+\r
+ appendQuery(aField);\r
+ }\r
+\r
+ public void appendStringParameter(String aValue) {\r
+ appendParameter(aValue);\r
+ }\r
+\r
+ public void appendWhereClause(String aPart) {\r
+ whereClause.append(aPart);\r
+ }\r
+\r
+ public void appendOrderByClause(String aPart) {\r
+ orderByClause.append(aPart);\r
+ }\r
+\r
+ public void setLimit(int aLimit) {\r
+ limit = aLimit;\r
+ }\r
+\r
+ public void setOffset(int anOffset) {\r
+ offset = anOffset;\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns then number of records\r
+ * changed\r
+ */\r
+ public ResultSet execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(CRLF);\r
+ appendQuery("FROM ");\r
+ appendQuery(tableName);\r
+ if (prefix!=null) {\r
+ appendQuery(" ");\r
+ appendQuery(prefix);\r
+ }\r
+\r
+ Iterator i = extraTables.iterator();\r
+ while (i.hasNext()) {\r
+ appendQuery(", ");\r
+ appendQuery((String) i.next());\r
+ }\r
+\r
+ if (whereClause.toString().trim().length()>0) {\r
+ appendQuery(CRLF);\r
+ appendQuery("WHERE ");\r
+ appendQuery(whereClause.toString());\r
+ }\r
+\r
+ if (orderByClause.toString().trim().length()>0) {\r
+ appendQuery(CRLF);\r
+ appendQuery("ORDER BY ");\r
+ appendQuery(orderByClause.toString());\r
+ }\r
+\r
+ if (limit > -1) {\r
+ appendQuery(CRLF);\r
+ appendQuery("LIMIT ");\r
+ appendQuery(Integer.toString(limit));\r
+ }\r
+\r
+ if (offset > -1) {\r
+ appendQuery(CRLF);\r
+ appendQuery("OFFSET ");\r
+ appendQuery(Integer.toString(offset));\r
+ }\r
+\r
+ return executeWithResultSet(aConnection);\r
+ }\r
+\r
+ private String tableName;\r
+ private String prefix;\r
+ private List extraTables;\r
+ private boolean firstField = true;\r
+ private StringBuffer whereClause;\r
+ private StringBuffer orderByClause;\r
+ private int limit = -1;\r
+ private int offset = -1;\r
+\r
+ private static final String CRLF = "\n\r";\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.util.*;\r
+\r
+/**\r
+ * Class to generate update statements\r
+ */\r
+public class RecordUpdater extends StatementGenerator{\r
+ public RecordUpdater(String aTableName, String aRecordId) {\r
+ tableName = aTableName;\r
+ recordId = aRecordId;\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a string typed field\r
+ */\r
+ public void assignString(String aFieldName, String aValue) {\r
+ assignObject(aFieldName, aValue);\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a date/time typed field\r
+ */\r
+ public void assignDateTime(String aFieldName, Date aDate) {\r
+ assignObject(aFieldName, new java.sql.Timestamp(aDate.getTime()));\r
+ }\r
+\r
+ /**\r
+ * Assigns a verbatim value to a field. Use with case: no quoting/escaping\r
+ * will be performed\r
+ **/\r
+ public void assignVerbatim(String aFieldName, String aValue) {\r
+ if (firstAssignment) {\r
+ appendQuery("update " + tableName + " set ");\r
+ firstAssignment = false;\r
+ }\r
+ else {\r
+ appendQuery(",");\r
+ }\r
+\r
+ appendQuery(CRLF);\r
+ appendQuery(" " + aFieldName + " = " + aValue);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns then number of records\r
+ * changed\r
+ */\r
+ public int execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(CRLF);\r
+ appendQuery("where id = ?");\r
+ appendParameter(recordId);\r
+\r
+ return executeWithModifiedCount(aConnection);\r
+ }\r
+\r
+ private void assignObject(String aFieldName, Object anObject) {\r
+ appendParameter(anObject);\r
+ assignVerbatim(aFieldName, "?");\r
+ }\r
+\r
+ private String tableName;\r
+ private static final String CRLF = "\n\r";\r
+ private String recordId;\r
+ private boolean firstAssignment = true;\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+/**\r
+ * Base class for (sql) statement generators\r
+ */\r
+public class StatementGenerator {\r
+ private static LoggerWrapper logger = new LoggerWrapper("Database.Statements");\r
+\r
+ public StatementGenerator() {\r
+ query = new StringBuffer();\r
+ parameters = new ArrayList();\r
+ }\r
+\r
+ protected void appendQuery(String aPart) {\r
+ query.append(aPart);\r
+ }\r
+\r
+ protected void appendParameter(Object aParameter) {\r
+ parameters.add(aParameter);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns the number of modified records.\r
+ */\r
+ protected int executeWithModifiedCount(Connection aConnection) throws DatabaseFailure {\r
+ long start = System.currentTimeMillis();\r
+\r
+ try {\r
+ aConnection.setAutoCommit(false);\r
+ logQueryBefore(query.toString());\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement(query.toString());\r
+\r
+ int index = 1;\r
+ Iterator i = parameters.iterator();\r
+\r
+ while (i.hasNext()) {\r
+ statement.setObject(index, i.next());\r
+ index++;\r
+ }\r
+\r
+ int result = statement.executeUpdate();\r
+\r
+ logQueryAfter(query.toString(), System.currentTimeMillis() - start);\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable e) {\r
+ logQueryError(query.toString(), System.currentTimeMillis() - start, e);\r
+ System.out.println(e.toString());\r
+\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ finally {\r
+ try {\r
+ aConnection.setAutoCommit(true);\r
+ }\r
+ catch (Exception e) {\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns a resultset.\r
+ */\r
+ protected ResultSet executeWithResultSet(Connection aConnection) throws DatabaseFailure {\r
+ long start = System.currentTimeMillis();\r
+\r
+ try {\r
+ logQueryBefore(query.toString());\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement(query.toString());\r
+\r
+ int index = 1;\r
+ Iterator i = parameters.iterator();\r
+\r
+ while (i.hasNext()) {\r
+ statement.setObject(index, i.next());\r
+ index++;\r
+ }\r
+\r
+ ResultSet result = statement.executeQuery();\r
+\r
+ logQueryAfter(query.toString(), System.currentTimeMillis() - start);\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable e) {\r
+ logQueryError(query.toString(), System.currentTimeMillis() - start, e);\r
+ System.out.println(e.toString());\r
+\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ }\r
+\r
+ private void logQueryBefore(String aQuery) {\r
+ logger.debug("about to perform QUERY " + aQuery);\r
+ }\r
+\r
+ private void logQueryAfter(String aQuery, long aTime) {\r
+ logger.info("QUERY " + aQuery + " took " + aTime + "ms.");\r
+ }\r
+\r
+ private void logQueryError(String aQuery, long aTime, Throwable anException) {\r
+ logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());\r
+ }\r
+\r
+\r
+ private StringBuffer query;\r
+ private List parameters;\r
+}\r
+++ /dev/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 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.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.List;
-import java.util.Map;
-import java.io.InputStream;
-
-import mir.entity.Entity;
-import mir.entity.EntityList;
-
-/**
- * Interface for low-level database actions.
- */
-
-public interface StorageObject {
- public Entity selectById(String id) throws StorageObjectExc;
-
- public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure;
-
- public EntityList selectByWhereClause(String whereClause) throws StorageObjectFailure;
-
- public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure;
-
- public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure;
-
- public EntityList selectByWhereClause(String whereClause, String orderBy, int offset, int limit) throws StorageObjectFailure;
-
- public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String aWhereClause, String anOrderByClause, int offset, int limit) throws StorageObjectFailure;
-
- public boolean delete(String id) throws StorageObjectFailure;
-
- /**
- * Deletes entities based on a where clause
- */
- public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure;
-
- public List getFields() throws StorageObjectFailure;
-
- public void update(Entity a) throws StorageObjectFailure;
-
- public String insert(Entity a) throws StorageObjectFailure;
-
- public Class getEntityClass();
-
- public String getIdName();
-
- public String getTableName();
-
- public Connection obtainConnection() throws StorageObjectFailure;
-
- public ResultSet executeSql(Statement a, String sql) throws StorageObjectFailure, SQLException;
-
- /**
- * Executes 1 sql statement and returns the results as a <code>List</code> of
- * <code>Map</code>s
- */
- public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc;
-
- /**
- * Executes 1 sql statement and returns the first result row as a <<code>Map</code>s
- * (<code>null</code> if there wasn't any row)
- */
- public Map executeFreeSingleRowSql(String sql) throws StorageObjectFailure, StorageObjectExc ;
-
- /**
- * Executes 1 sql statement and returns the first column of the first result row as a <<code>String</code>s
- * (<code>null</code> if there wasn't any row)
- */
- public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc ;
-
- public void freeConnection(Connection con, Statement stmt) throws StorageObjectFailure;
-
- public int executeUpdate(Statement a, String sql) throws StorageObjectFailure, SQLException;
-
- public int executeUpdate(String sql) throws StorageObjectFailure, SQLException;
-
- public int getSize(String where) throws SQLException, StorageObjectFailure;
-
- public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure;
-
- public InputStream getBinaryField(String aQuery) throws SQLException, StorageObjectFailure;
-
- public void setBinaryField(String aQuery, byte aData[]) throws StorageObjectFailure, SQLException;
-}
+++ /dev/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 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 multex.Exc;
-
-
-/**
- * @author idefix
- */
-public class StorageObjectExc extends Exc {
- public StorageObjectExc() {
- super("Something gone wrong");
- }
-
- public StorageObjectExc(String msg) {
- super(msg);
- }
-}
+++ /dev/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 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 multex.Failure;
-
-
-/**
- * Exception for all occuring failures in the storage-layer
- * @author idefix
- */
-public class StorageObjectFailure extends Failure {
- /**
- * Constructor StorageObjectException.
- * @param e
- */
- public StorageObjectFailure(Throwable e) {
- super("", e);
- }
-
- /**
- * Standard constructor
- */
- public StorageObjectFailure() {
- super("A failure occured", null);
- }
-
- /**
- * Construktor with message
- * @param String msg
- */
- public StorageObjectFailure(String msg, Throwable e) {
- super(msg, e);
- }
-}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
import java.util.Iterator;
import java.util.Map;
import java.util.MissingResourceException;
+
import javax.servlet.http.HttpServletRequest;
import mir.config.MirPropertiesConfiguration;
*/
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();
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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;
/**
* @version 1.0
*/
-import java.util.LinkedList;
-import java.util.ListIterator;
-
-import javax.servlet.http.HttpServletRequest;
-
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
+import javax.servlet.http.HttpServletRequest;
+import java.util.LinkedList;
+import java.util.ListIterator;
+
public class StoreContainer {
private final static int DEFAULT_SIZE = 10;
private static int uniqueCounter = 10000;
protected LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore");
// avoid construction without parameters
- private StoreContainer() {};
+ private StoreContainer() {}
public StoreContainer(StoreContainerType stoc_type) {
/**
* Method: toString()
* Description: gives out statistical Information, viewable via
- * @see ServletStoreInfo.
+ * @see ServletStoreInfo
*
* @return String
*/
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
* @version 1.0
*/
+import mir.misc.StringUtil;
+
import java.util.HashMap;
import java.util.Map;
-import mir.misc.StringUtil;
-
public class StoreContainerType {
public final static int STOC_TYPE_UNKNOWN = -1;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
* @author rk
* @version 1.0
*/
-import java.util.Iterator;
-import java.util.Set;
-
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
-public class StoreIdentifier {
+import java.util.Iterator;
+import java.util.Set;
- /** @todo check if invalidating already to avoid deadlocks
- * what about concurrency? */
+public class StoreIdentifier {
+ /** todo check if invalidating already to avoid deadlocks what about concurrency? */
private static ObjectStore o_store = ObjectStore.getInstance();
private long timesUsed;
private boolean invalidating = false;
- protected LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore");
-
- /** @todo initialize logfile */
-
- private StoreIdentifier() {}
+ protected static LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore");
public StoreIdentifier(StorableObject reference, int storeType,
String uniqueIdentifier) {
this.stocType = StoreContainerType.valueOf(theClass, storeType);
}
- /**
- * Method: ivalidate
- * Description:
- *
- * @return
- */
public void invalidate() {
logger.info("Invalidating: " + toString());
// avoid deadlock due to propagation.
id.append(" (" + timesUsed).append(") times used.");
return id.toString();
}
-
-
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.test;
* @version 1.0
*/
-import java.util.HashSet;
-import java.util.Set;
-
import mir.storage.store.StorableObject;
import mir.storage.store.StoreContainerType;
import mir.storage.store.StoreIdentifier;
+import java.util.HashSet;
+import java.util.Set;
+
public class EntityC1 implements StorableObject {
String id;
// simulates a relation to EntityC2 with uniqueIdentifier "1"
notifiees.add(new StoreIdentifier(EntityC2.class,"1"));
notifiees.add(new StoreIdentifier(EntityC2.class,"18"));
- return (Set)notifiees;
+ return notifiees;
}
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.test;
* @version 1.0
*/
-import java.util.Set;
-
import mir.storage.store.StorableObject;
import mir.storage.store.StoreContainerType;
import mir.storage.store.StoreIdentifier;
+import java.util.Set;
+
public class EntityC2 implements StorableObject {
String id;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.test;
* @version 1.0
*/
-import java.util.Set;
-
import mir.storage.store.StorableObject;
import mir.storage.store.StoreContainerType;
import mir.storage.store.StoreIdentifier;
+import java.util.Set;
+
public class EntityC3 implements StorableObject {
String id;
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
* 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 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.
+ * the code of this program with any library licensed under the Apache Software License,
+ * 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.test;
public class TestStore {
- private static ObjectStore o_store = ObjectStore.getInstance();
+ private static ObjectStore o_store = ObjectStore.getInstance();
- public TestStore() {
+ public TestStore() {
- }
+ }
- public static void main(String[] args) {
- long startTime = System.currentTimeMillis();
- System.out.println("Starting testrun on ObjectStore...");
- TestStore testStore1 = new TestStore();
- testStore1.startTest();
- System.out.println("Finished testrun on ObjectStore. ("
- + (System.currentTimeMillis() - startTime) + " ms)");
- }
+ public static void main(String[] args) {
+ long startTime = System.currentTimeMillis();
+ System.out.println("Starting testrun on ObjectStore...");
+ TestStore testStore1 = new TestStore();
+ testStore1.startTest();
+ System.out.println("Finished testrun on ObjectStore. ("
+ + (System.currentTimeMillis() - startTime) + " ms)");
+ }
- public void startTest() {
+ public void startTest() {
- EntityC1 c1 = new EntityC1("1");
- o_store.add(c1.getStoreIdentifier());
- EntityC1 c12 = new EntityC1("2");
- o_store.add(c12.getStoreIdentifier());
+ EntityC1 c1 = new EntityC1("1");
+ o_store.add(c1.getStoreIdentifier());
+ EntityC1 c12 = new EntityC1("2");
+ o_store.add(c12.getStoreIdentifier());
o_store.add(c12.getStoreIdentifier()); // should not be added as it's there already
EntityC2 c2;
- for (int i=0; i<20; i++) {
- c2 = new EntityC2(""+i);
+ for (int i = 0; i < 20; i++) {
+ c2 = new EntityC2("" + i);
o_store.add(c2.getStoreIdentifier());
} // should contain only 10
- // test cycle: search in store
+// test cycle: search in store
- StorableObject reference; StoreIdentifier search_sid;
+ StorableObject reference;
+ StoreIdentifier search_sid;
- // search for EntityC1
- search_sid=new StoreIdentifier(EntityC1.class,"1");
- reference=o_store.use(search_sid);
- if (reference==null)
+// search for EntityC1
+ search_sid = new StoreIdentifier(EntityC1.class, "1");
+ reference = o_store.use(search_sid);
+ if (reference == null)
System.out.println("--- should have found" + search_sid.toString());
- search_sid=new StoreIdentifier(EntityC1.class,"A");
- reference=o_store.use(search_sid);
- if (reference!=null)
+ search_sid = new StoreIdentifier(EntityC1.class, "A");
+ reference = o_store.use(search_sid);
+ if (reference != null)
System.out.println("--- should not have found" + search_sid.toString());
- search_sid=new StoreIdentifier(EntityC3.class,"1");
- reference=o_store.use(search_sid);
- if (reference!=null)
+ search_sid = new StoreIdentifier(EntityC3.class, "1");
+ reference = o_store.use(search_sid);
+ if (reference != null)
System.out.println("--- should not have found" + search_sid.toString());
- // test cycle: invalidation */
- search_sid=new StoreIdentifier(EntityC1.class,"1");
+// test cycle: invalidation */
+ search_sid = new StoreIdentifier(EntityC1.class, "1");
o_store.invalidate(search_sid);
- System.out.println(o_store.toString());
- /** @todo compare values of store and state failed if values are not
- * right*/
+ System.out.println(o_store.toString());
-
-
- }
+ }
}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.util;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.Vector;
-import java.util.ArrayList;
public class CachingRewindableIterator implements RewindableIterator {
private Iterator master;
public void rewind() {
iterationPosition=0;
- };
+ }
}
\ No newline at end of file
-/*
- * 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 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.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.TimeZone;
-
-public class DateTimeFunctions {
- /**
- * private parameter-less constructor to prevent construction
- */
-// private static LoggerWrapper logger = new LoggerWrapper("Utility.DatTimeFunctions");
-
-
- private DateTimeFunctions() {
- }
-
- /**
- * Function to parse a <a href="http://www.w3.org/TR/NOTE-datetime">W3CDTF</a> formatted string.
- *
- *
- * YYYY[-MM[-DD[Thh:mm[:ss[.s*]]TZD]]]
- *
- * @param aString
- * @return
- */
- private final static String SPACE = "[\t\n\r ]*";
- private final static String NUMBER = "[0-9]*";
- private final static String TWODIGITNUMBER = "[0-9][0-9]";
- private final static String FOURDIGITNUMBER = "[0-9][0-9][0-9][0-9]";
- private final static String FRACTION = "(\\.[0-9]*)|)";
- private final static String SIGN = "[-+]";
- private final static String TZD = "(Z|(+|-)([0-9][0-9]:[0-9][0-9]|[0-9][0-9][0-9][0-9]))";
-
- public static Date parseW3CDTFString(String aString) throws UtilExc, UtilFailure {
- try {
- int year = 1;
- int month = 1;
- int day = 1;
- int hour = 0;
- int minute = 0;
- int second = 0;
- int millisecond = 0;
- int houroffset = 0;
- int minuteoffset = 0;
- boolean negativeOffset = false;
-
-
- SimpleParser parser = new SimpleParser(aString.trim());
- String part = parser.parse(NUMBER);
- year=Integer.parseInt(part);
- if (parser.parses("-")) {
- parser.skip("-");
- part = parser.parse(NUMBER);
- month = Integer.parseInt(part);
- if (parser.parses("-")) {
- parser.skip("-");
- part = parser.parse(NUMBER);
- day = Integer.parseInt(part);
- if (parser.parses("T")) {
- parser.skip("T");
- part = parser.parse(NUMBER);
- hour = Integer.parseInt(part);
- parser.skip(":");
- part = parser.parse(NUMBER);
- minute = Integer.parseInt(part);
- if (parser.parses(":")) {
- parser.skip(":");
- part = parser.parse(NUMBER);
- second = Integer.parseInt(part);
- if (parser.parses("\\.")) {
- parser.skip("\\.");
- part = parser.parse(NUMBER).substring(0,3);
- while (part.length()<3)
- part = "0" + part;
- millisecond = Integer.parseInt(part);
- }
- }
- if (parser.parses("Z|\\+|-")) {
- String sign = parser.parse("Z|\\+|-");
- if (sign.equals("+") || sign.equals("-")) {
- if (parser.parses(TWODIGITNUMBER)) {
- part = parser.parse(TWODIGITNUMBER);
- houroffset = Integer.parseInt(part);
- }
- if (parser.parses(":"))
- parser.skip(":");
- if (parser.parses(TWODIGITNUMBER)) {
- part = parser.parse(TWODIGITNUMBER);
- minuteoffset = Integer.parseInt(part);
- }
-
- if (sign.equals("-")) {
- negativeOffset=true;
- }
- }
- }
- }
- }
- }
-
-
-
- String timeZoneID = "GMT";
- if (negativeOffset)
- timeZoneID = timeZoneID+"-";
- timeZoneID = timeZoneID + StringRoutines.padStringLeft(Integer.toString(houroffset), 2, '0') +
- StringRoutines.padStringLeft(Integer.toString(minuteoffset), 2, '0');
-
-
- TimeZone zone = TimeZone.getTimeZone(timeZoneID);
-
- Calendar calendar = new GregorianCalendar(zone);
- calendar.set(year, month-1, day, hour, minute, second);
- calendar.set(Calendar.MILLISECOND, millisecond);
-
- return calendar.getTime();
- }
- catch (Throwable t) {
-// logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString());
-
- throw new UtilFailure(t);
- }
- }
-
- public static String advancedDateFormat(String aFormat, Date aDate, String aTimeZone) {
- return advancedDateFormat(aFormat, aDate, TimeZone.getTimeZone(aTimeZone));
- }
-
- public static String advancedDateFormat(String aFormat, Date aDate, TimeZone aTimeZone) {
- SimpleDateFormat simpleFormat = new SimpleDateFormat(aFormat);
-
- simpleFormat.setTimeZone(aTimeZone);
- return simpleFormat.format(aDate);
- }
-
- public static String dateToSortableString(Date aDate) {
- return advancedDateFormat("yyyyMMddHHmmss", aDate, "GMT");
- }
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+/**\r
+ * @deprecated Use mir.util.DateTimeRoutines instead\r
+ */\r
+public class DateTimeFunctions extends DateTimeRoutines {\r
+}\r
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+public class DateTimeRoutines {
+ /**
+ * private parameter-less constructor to prevent construction
+ */
+ protected DateTimeRoutines() {
+ }
+
+ private final static String NUMBER = "[0-9]*";
+ private final static String TWODIGITNUMBER = "[0-9][0-9]";
+
+ /**
+ * Function to parse a <a href="http://www.w3.org/TR/NOTE-datetime">W3CDTF</a> formatted string.
+ *
+ *
+ * YYYY[-MM[-DD[Thh:mm[:ss[.s*]]TZD]]]
+ *
+ * @param aString
+ * @return Date
+ */
+ public static Date parseW3CDTFString(String aString) throws UtilExc, UtilFailure {
+ try {
+ int year = 1;
+ int month = 1;
+ int day = 1;
+ int hour = 0;
+ int minute = 0;
+ int second = 0;
+ int millisecond = 0;
+ int houroffset = 0;
+ int minuteoffset = 0;
+ boolean negativeOffset = false;
+
+
+ SimpleParser parser = new SimpleParser(aString.trim());
+ String part = parser.parse(NUMBER);
+ year=Integer.parseInt(part);
+ if (parser.parses("-")) {
+ parser.skip("-");
+ part = parser.parse(NUMBER);
+ month = Integer.parseInt(part);
+ if (parser.parses("-")) {
+ parser.skip("-");
+ part = parser.parse(NUMBER);
+ day = Integer.parseInt(part);
+ if (parser.parses("T")) {
+ parser.skip("T");
+ part = parser.parse(NUMBER);
+ hour = Integer.parseInt(part);
+ parser.skip(":");
+ part = parser.parse(NUMBER);
+ minute = Integer.parseInt(part);
+ if (parser.parses(":")) {
+ parser.skip(":");
+ part = parser.parse(NUMBER);
+ second = Integer.parseInt(part);
+ if (parser.parses("\\.")) {
+ parser.skip("\\.");
+ part = parser.parse(NUMBER).substring(0,3);
+ while (part.length()<3)
+ part = "0" + part;
+ millisecond = Integer.parseInt(part);
+ }
+ }
+ if (parser.parses("Z|\\+|-")) {
+ String sign = parser.parse("Z|\\+|-");
+ if (sign.equals("+") || sign.equals("-")) {
+ if (parser.parses(TWODIGITNUMBER)) {
+ part = parser.parse(TWODIGITNUMBER);
+ houroffset = Integer.parseInt(part);
+ }
+ if (parser.parses(":"))
+ parser.skip(":");
+ if (parser.parses(TWODIGITNUMBER)) {
+ part = parser.parse(TWODIGITNUMBER);
+ minuteoffset = Integer.parseInt(part);
+ }
+
+ if (sign.equals("-")) {
+ negativeOffset=true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ String timeZoneID = "GMT";
+ if (negativeOffset)
+ timeZoneID = timeZoneID+"-";
+ timeZoneID = timeZoneID + StringRoutines.padStringLeft(Integer.toString(houroffset), 2, '0') +
+ StringRoutines.padStringLeft(Integer.toString(minuteoffset), 2, '0');
+
+
+ TimeZone zone = TimeZone.getTimeZone(timeZoneID);
+
+ Calendar calendar = new GregorianCalendar(zone);
+ calendar.set(year, month-1, day, hour, minute, second);
+ calendar.set(Calendar.MILLISECOND, millisecond);
+
+ return calendar.getTime();
+ }
+ catch (Throwable t) {
+// logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString());
+
+ throw new UtilFailure(t);
+ }
+ }
+
+ public static String advancedDateFormat(String aFormat, Date aDate, String aTimeZone) {
+ return advancedDateFormat(aFormat, aDate, TimeZone.getTimeZone(aTimeZone));
+ }
+
+ public static String advancedDateFormat(String aFormat, Date aDate, TimeZone aTimeZone) {
+ SimpleDateFormat simpleFormat = new SimpleDateFormat(aFormat);
+
+ simpleFormat.setTimeZone(aTimeZone);
+ return simpleFormat.format(aDate);
+ }
+
+ public static String dateToSortableString(Date aDate) {
+ return advancedDateFormat("yyyyMMddHHmmss", aDate, "GMT");
+ }
+}
\ No newline at end of file
/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
*\r
* This file is part of Mir.\r
*\r
*\r
* In addition, as a special exception, The Mir-coders gives permission to link\r
* the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
* and distribute linked combinations including the two. You must obey the\r
* GNU General Public License in all respects for all of the code used other than\r
* the above mentioned libraries. If you modify this file, you may extend this\r
-/*
- * 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 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.lang.reflect.InvocationTargetException;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import multex.Failure;
-
-import org.xml.sax.SAXException;
-
-/**
- *
- * <p>Title: ExceptionFunctions </p>
- * <p>Description: Functions to assist handling and throwing exceptions</p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: Mir coders</p>
- * @author Zapata
- * @version 1.0
- */
-
-public class ExceptionFunctions {
- private ExceptionFunctions() {
- }
-
- /**
- * Traces an exception to it's root cause, using all known exception types that support
- * cause exceptions.
- *
- * @return the cause (if found)
- */
-
- public static Throwable traceCauseException(Throwable anException) {
- Throwable result = anException;
-
- while (true) {
- if ((result instanceof Failure) && (((Failure) result).getCause()!=null)) {
- result = ((Failure) result).getCause();
- }
- else if ((result instanceof SAXException) && (((SAXException) result).getException()!=null)) {
- result = ((SAXException) result).getException();
- }
- else if ((result instanceof InvocationTargetException) && (((InvocationTargetException) result).getTargetException()!=null)) {
- result = ((InvocationTargetException) result).getTargetException();
- }
- else
- break;
- }
-
- return result;
- }
-
- /**
- * Prints an exception's stacktrace to a <code>String</code>
- */
- public static String getStackTrace(Throwable aThrowable) {
- StringWriter writer = new StringWriter();
- aThrowable.printStackTrace(new PrintWriter(writer));
- return writer.toString();
- }
-}
+/*\r
+ * Copyright (C) 2001-2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+/**\r
+ * @deprecated Use mir.util.ExceptionRoutines instead\r
+ */\r
+public class ExceptionFunctions extends ExceptionRoutines {\r
+}\r
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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 multex.Failure;
+import org.xml.sax.SAXException;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Routines to assist in handling and throwing exceptions</p>
+ */
+
+public class ExceptionRoutines {
+ protected ExceptionRoutines() {
+ }
+
+ /**
+ * Traces an exception to it's root cause, using all known exception types that support
+ * cause exceptions.
+ *
+ * @return the cause (if found)
+ */
+
+ public static Throwable traceCauseException(Throwable anException) {
+ Throwable result = anException;
+
+ while (true) {
+ if ((result instanceof Failure) && (((Failure) result).getCause()!=null)) {
+ result = ((Failure) result).getCause();
+ }
+ else if ((result instanceof SAXException) && (((SAXException) result).getException()!=null)) {
+ result = ((SAXException) result).getException();
+ }
+ else if ((result instanceof InvocationTargetException) && (((InvocationTargetException) result).getTargetException()!=null)) {
+ result = ((InvocationTargetException) result).getTargetException();
+ }
+ else
+ break;
+ }
+
+ return result;
+ }
+
+ /**
+ * Prints an exception's stacktrace to a <code>String</code>
+ */
+ public static String getStackTrace(Throwable aThrowable) {
+ StringWriter writer = new StringWriter();
+ aThrowable.printStackTrace(new PrintWriter(writer));
+ return writer.toString();
+ }
+}
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.util;
-import java.io.*;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-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 {
- BufferedInputStream inputStream;
- BufferedOutputStream outputStream;
- int nrBytesRead;
- byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE];
-
- inputStream = new BufferedInputStream(
- new FileInputStream(aSourceFile));
- try {
- File directory = new File(aDestinationFile.getParent());
- if (directory!=null && !directory.exists()){
- directory.mkdirs();
- }
- outputStream = new BufferedOutputStream(
- new FileOutputStream(aDestinationFile),8192);
- 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; i<files.length; i++) {
- sourceFile = files[i];
- destinationFile=new File(aDestinationDirectory, sourceFile.getName());
- if (sourceFile.isDirectory()) {
- if (!destinationFile.exists())
- destinationFile.mkdir();
- copyDirectory(sourceFile, destinationFile);
- }
- else {
- copyFile(sourceFile, destinationFile);
- }
- }
- }
-
- public static void copy(File aSource, File aDestination) throws IOException {
- if (aSource.isDirectory()) {
- copyDirectory(aSource, aDestination);
- }
- else if (aDestination.isDirectory()) {
- copyFile(aSource, new File(aDestination, aSource.getName()));
- }
- else {
- copyFile(aSource, aDestination);
- }
- }
-
- /**
- * Copy the contents of an {@link InputStream} to a {@link File}
- */
- public static void copy(InputStream aSource, File aDestination) throws IOException {
- BufferedOutputStream outputStream =
- new BufferedOutputStream(new FileOutputStream(aDestination), 8192);
-
- int read;
- byte[] buf = new byte[8 * 1024];
-
- while ((read = aSource.read(buf)) != -1) {
- outputStream.write(buf, 0, read);
- }
-
- aSource.close();
- outputStream.close();
- }
-
- /**
- * Moves a {@link File} to a new location
- */
- public static void move(File aSource, File aDestination) throws IOException {
- aDestination.getParentFile().mkdirs();
- if (!aSource.renameTo(aDestination)) {
- byte[] buffer = new byte[16384];
- FileInputStream inputStream = new FileInputStream(aSource);
- FileOutputStream outputStream = new FileOutputStream(aDestination);
- try {
- while (inputStream.read(buffer)>0) {
- outputStream.write(buffer);
- }
- }
- finally {
- outputStream.close();
- inputStream.close();
- }
- aSource.delete();
- };
- }
-
- public static class RegExpFileFilter implements FilenameFilter {
- private RE expression;
-
- public RegExpFileFilter(String anExpression) {
- try {
- expression = new RE(anExpression);
- }
- catch (Throwable t) {
- throw new RuntimeException(t.getMessage());
- }
- }
-
- public boolean accept(File aDir, String aName) {
- return expression.isMatch(aName) && !new File(aDir, aName).isDirectory();
- }
- }
-
- public static class DirectoryFilter implements FilenameFilter {
- public DirectoryFilter() {
- }
-
- public boolean accept(File aDir, String aName) {
- return new File(aDir, aName).isDirectory();
- }
- }
-
- public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) {
- Object[] contents = aDirectory.list(aFilter);
- if (contents==null)
- return Collections.EMPTY_LIST;
- else
- return Arrays.asList(contents);
- }
-
- public static String getExtension(String aPath) {
- int position = aPath.lastIndexOf('.');
- if (position>=0) {
- return aPath.substring(position+1);
- }
- else {
- return "";
- }
- }
-
- public static boolean isAbsolutePath(String aPath) {
- return new File(aPath).isAbsolute();
- }
-
- public static File getAbsoluteOrRelativeFile(File aParentIfRelative, String aPath) {
- if (isAbsolutePath(aPath)) {
- return new File(aPath);
- }
- else {
- return new File(aParentIfRelative, aPath);
- }
- }
+/**
+ * @deprecated Use mir.util.FileRoutines instead
+ */
+public class FileFunctions extends FileRoutines {
}
\ No newline at end of file
+++ /dev/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 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.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-public class FileMonitor {
- private Map files;
-
- public FileMonitor() {
- files = new HashMap();
- }
-
- public void addFile(File aFile) {
- files.put(aFile, new Long(aFile.lastModified()));
- }
-
- public void clear() {
- files.clear();
- }
-
- public boolean hasChanged() {
- Iterator i = files.entrySet().iterator();
-
- while (i.hasNext()) {
- Map.Entry entry = (Map.Entry) i.next();
- File file = (File) entry.getKey();
- Long lastModified = (Long) entry.getValue();
-
- if (lastModified.longValue()!=file.lastModified())
- return true;
- }
-
- return false;
- }
-}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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 java.io.*;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class FileRoutines {
+ protected static final int FILE_COPY_BUFFER_SIZE = 65536;
+
+ protected FileRoutines() {
+ }
+
+ /**
+ * Copy a file
+ */
+ public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException {
+ BufferedInputStream inputStream;
+ BufferedOutputStream outputStream;
+ int nrBytesRead;
+ byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE];
+
+ inputStream = new BufferedInputStream(new FileInputStream(aSourceFile));
+ try {
+ File directory = new File(aDestinationFile.getParent());
+ if (directory != null && !directory.exists()) {
+ directory.mkdirs();
+ }
+ outputStream = new BufferedOutputStream(new FileOutputStream(aDestinationFile), 8192);
+ try {
+ do {
+ nrBytesRead = inputStream.read(buffer);
+ if (nrBytesRead > 0)
+ outputStream.write(buffer, 0, nrBytesRead);
+ }
+ while (nrBytesRead >= 0);
+ }
+ finally {
+ outputStream.close();
+ }
+ }
+ finally {
+ inputStream.close();
+ }
+ }
+
+ /**
+ * Copy a directory recursively
+ */
+ 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 < files.length; i++) {
+ sourceFile = files[i];
+ destinationFile = new File(aDestinationDirectory, sourceFile.getName());
+ if (sourceFile.isDirectory()) {
+ if (!destinationFile.exists())
+ destinationFile.mkdir();
+ copyDirectory(sourceFile, destinationFile);
+ }
+ else {
+ copyFile(sourceFile, destinationFile);
+ }
+ }
+ }
+
+ /**
+ * Copy a file or directory. If the source is a file and the destination
+ * a directory, the file is copied using the same file name into the\
+ * directory.
+ *
+ * @param aSource the source file
+ * @param aDestination the destination file
+ */
+ public static void copy(File aSource, File aDestination) throws IOException {
+ if (aSource.isDirectory()) {
+ copyDirectory(aSource, aDestination);
+ }
+ else if (aDestination.isDirectory()) {
+ copyFile(aSource, new File(aDestination, aSource.getName()));
+ }
+ else {
+ copyFile(aSource, aDestination);
+ }
+ }
+
+ /**
+ * Copy the contents of an {@link InputStream} to a {@link File}
+ */
+ public static void copy(InputStream aSource, File aDestination) throws IOException {
+ BufferedOutputStream outputStream =
+ new BufferedOutputStream(new FileOutputStream(aDestination), 8192);
+
+ int read;
+ byte[] buf = new byte[8 * 1024];
+
+ while ((read = aSource.read(buf)) != -1) {
+ outputStream.write(buf, 0, read);
+ }
+
+ aSource.close();
+ outputStream.close();
+ }
+
+ /**
+ * Moves a {@link File} to a new location
+ */
+ public static void move(File aSource, File aDestination) throws IOException {
+ aDestination.getParentFile().mkdirs();
+ if (!aSource.renameTo(aDestination)) {
+ byte[] buffer = new byte[16384];
+ FileInputStream inputStream = new FileInputStream(aSource);
+ FileOutputStream outputStream = new FileOutputStream(aDestination);
+ try {
+ int count = inputStream.read(buffer);
+ while (count > 0) {
+ outputStream.write(buffer, 0, count);
+ count = inputStream.read(buffer);
+ }
+ }
+ finally {
+ outputStream.close();
+ inputStream.close();
+ }
+ aSource.delete();
+ }
+ }
+
+ public static class RegExpFileFilter implements FilenameFilter {
+ private RE expression;
+
+ public RegExpFileFilter(String anExpression) {
+ try {
+ expression = new RE(anExpression);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+
+ public boolean accept(File aDir, String aName) {
+ return expression.isMatch(aName) && !new File(aDir, aName).isDirectory();
+ }
+ }
+
+ public static class DirectoryFilter implements FilenameFilter {
+ public DirectoryFilter() {
+ }
+
+ public boolean accept(File aDir, String aName) {
+ return new File(aDir, aName).isDirectory();
+ }
+ }
+
+ /**
+ * Return all files in a directory
+ *
+ * @param aDirectory The directory to list
+ * @param aFilter the filter to apply to files
+ * @return a <code>List</code> of filenames of type <code>String</code>
+ */
+ public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) {
+ Object[] contents = aDirectory.list(aFilter);
+
+ if (contents == null) {
+ return Collections.EMPTY_LIST;
+ }
+
+ return Arrays.asList(contents);
+ }
+
+ /**
+ * Return the extension of a path. (e.g. <code>getExtension("example.txt")</code> will
+ * return <code>"txt"</code>
+ */
+ public static String getExtension(String aPath) {
+ int position = aPath.lastIndexOf('.');
+ if (position >= 0) {
+ return aPath.substring(position + 1);
+ }
+ return "";
+ }
+
+ public static boolean isAbsolutePath(String aPath) {
+ return new File(aPath).isAbsolute();
+ }
+
+ /**
+ * Transforms an absolute or relative path into an absolute
+ * {@link File}.
+ *
+ * @param aBasePath The base path to use for relative paths
+ * @param aPath The path to transform
+ * @return An absolute representation of the supplied path
+ */
+ public static File getAbsoluteOrRelativeFile(File aBasePath, String aPath) {
+ if (isAbsolutePath(aPath)) {
+ return new File(aPath);
+ }
+
+ return new File(aBasePath, aPath);
+ }
+
+ /**
+ * Reads the content of a file into an array of bytes
+ */
+ public static byte[] readFileIntoByteArray(File aFile) throws IOException {
+ InputStream input = new FileInputStream(aFile);
+ ByteArrayOutputStream result = new ByteArrayOutputStream();
+
+ IORoutines.copyStream(input, result);
+
+ return result.toByteArray();
+ }
+
+ /**
+ * Reads the content of a file into an array of bytes
+ */
+ public static void writeByteArrayIntoFile(byte[] anArray, File aFile) throws IOException {
+ OutputStream output = new FileOutputStream(aFile);
+
+ try {
+ ByteArrayInputStream input = new ByteArrayInputStream(anArray);
+ try {
+ IORoutines.copyStream(input, output);
+ }
+ finally {
+ input.close();
+ }
+ }
+ finally {
+ output.close();
+ }
+ }
+
+
+
+ /**
+ * Creates all parent directories of a file if they do not exist
+ */
+ public static void createParentDirectories(File aFile) {
+ if (aFile.getParentFile() != null && !aFile.getParentFile().exists()) {
+ aFile.getParentFile().mkdirs();
+ }
+ }
+}
\ No newline at end of file
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2006 The Mir-coders group
*
* This file is part of Mir.
*
*
* In addition, as a special exception, The Mir-coders gives permission to link
* the code of this program with 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
*/
package mir.util;
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.generator.GeneratorFailure;
+
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
-import mir.generator.Generator;
-import mir.generator.GeneratorExc;
-import mir.generator.GeneratorFailure;
-
public class GeneratorDateTimeFunctions {
private GeneratorDateTimeFunctions() {
}
}
public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
- try {
- if (aParameters.size()<2 || aParameters.size()>3)
- throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: 2 or 3 parameters expected");
-
- if (!(aParameters.get(0) instanceof Date) ||
- !(aParameters.get(1) instanceof String) ||
- ( aParameters.size()>2 &&
- !(aParameters.get(2) instanceof String)))
- throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: type mismatch");
+ if (aParameters.size()<2 || aParameters.size()>3) {
+ throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: 2 or 3 parameters expected");
+ }
+ if (!(aParameters.get(0) instanceof Date) || !(aParameters.get(1) instanceof String) ||
+ (aParameters.size() > 2 && !(aParameters.get(2) instanceof String))) {
+ throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: type mismatch");
+ }
- Date date = (Date) aParameters.get(0);
- SimpleDateFormat dateFormat = new SimpleDateFormat( (String) (aParameters.get(1)));
+ Date date = (Date) aParameters.get(0);
+ SimpleDateFormat dateFormat = new SimpleDateFormat( (String) (aParameters.get(1)));
- String timezoneString = "";
- if (aParameters.size()>2)
- timezoneString = (String) aParameters.get(2);
- else
- timezoneString = defaultTimezone;
+ String timezoneString = defaultTimezone;
+ if (aParameters.size()>2) {
+ timezoneString = (String) aParameters.get(2);
+ }
- TimeZone timezone = null;
- try {
- timezone = TimeZone.getTimeZone(defaultTimezone);
- }
- catch (Throwable t) {
- }
+ TimeZone timezone = TimeZone.getTimeZone(timezoneString);
- if (timezone == null)
- timezone = TimeZone.getDefault();
+ if (timezone == null) {
+ timezone = TimeZone.getDefault();
+ }
- dateFormat.setTimeZone(timezone);
+ dateFormat.setTimeZone(timezone);
- return dateFormat.format(date);
- }
- catch (GeneratorExc e) {
- throw e;
- }
- catch (Throwable t) {
- throw new GeneratorFailure("encodeURIGeneratorFunction: " + t.getMessage(), t);
- }
- };
+ return dateFormat.format(date);
+ }
}
catch (Throwable t) {
throw new GeneratorFailure("NumberFormattingFunction: " + t.getMessage(), t);
}
- };
+ }
}
}
catch (Throwable t) {
throw new GeneratorFailure("DateFormattingFunction: " + t.getMessage(), t);
}
- };
+ }
}
/**
package mir.util;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HTMLRoutines {
+ private HTMLRoutines() {
+ }
+
+ private static Method encodeURLMethod;
+ static {
+ try {
+ encodeURLMethod = URLEncoder.class.getMethod("encode", new Class[] {String.class});
+ }
+ catch (NoSuchMethodException e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
/**
* Encodes a URL: escapes reserved URL characters like &, = into % escape
* constructions.
*/
public static String encodeURL(String aString) {
- return URLEncoder.encode(aString);
- }
-
- public static String encodeURL(String aString, String anEncoding) {
try {
- return URLEncoder.encode(aString);
+ return (String) encodeURLMethod.invoke(URLEncoder.class, new Object[] {aString});
}
- catch (Throwable t) {
- throw new RuntimeException(t.getMessage());
+ catch (IllegalAccessException e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ catch (InvocationTargetException e) {
+ throw new RuntimeException(e.getMessage());
}
}
- public static String encodeHTML(String aText) {
- final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"' };
- final String[] ESCAPE_CODES = { "&", "<", ">", """ };
+ public static String encodeURL(String aString, String anEncoding) {
+ return encodeURL(aString);
+ }
+ private static final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"' };
+ private static final String[] ESCAPE_CODES = { "&", "<", ">", """ };
+
+ public static String encodeHTML(String aText) {
return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES);
}
public static String prettyEncodeHTML(String aText) throws UtilExc {
- return
- StringRoutines.performRegularExpressionReplacement(encodeHTML(aText), "\\n", "<br>\n");
+ return StringRoutines.performRegularExpressionReplacement(
+ encodeHTML(aText), "\\n", "<br>\n");
}
public static String encodeXML(String aText) {
--- /dev/null
+/*\r
+ * Copyright (C) 2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+import org.apache.oro.text.regex.Pattern;\r
+import org.apache.oro.text.regex.Perl5Compiler;\r
+import org.apache.oro.text.regex.Perl5Matcher;\r
+import org.apache.oro.text.regex.Perl5Substitution;\r
+import org.apache.oro.text.regex.Util;\r
+\r
+/**\r
+ * Class used to enrich text-based content with HTML links\r
+ * according to a set of rules\r
+ */\r
+public class HTMLStripper {\r
+\r
+ private Pattern newLineExpression;\r
+ private Pattern doubleBRExpression;\r
+ private Pattern emailAddressExpression;\r
+ private Pattern urlExpression;\r
+ private Pattern htmlTagExpression;\r
+\r
+ public HTMLStripper() {\r
+ Perl5Compiler compiler = new Perl5Compiler();\r
+\r
+ try {\r
+ newLineExpression =\r
+ compiler.compile("(\r?\n){1}", Perl5Compiler.READ_ONLY_MASK);\r
+ doubleBRExpression =\r
+ compiler.compile("(<br>\r?\n<br>){1,}", Perl5Compiler.READ_ONLY_MASK);\r
+ emailAddressExpression =\r
+ compiler.compile("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b", Perl5Compiler.READ_ONLY_MASK);\r
+ urlExpression =\r
+ compiler.compile("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])", Perl5Compiler.READ_ONLY_MASK);\r
+ htmlTagExpression =\r
+ compiler.compile("<[^>]*>", Perl5Compiler.CASE_INSENSITIVE_MASK | Perl5Compiler.READ_ONLY_MASK);\r
+ }\r
+ catch (Exception e) {\r
+ throw new RuntimeException(e.getMessage());\r
+ }\r
+ }\r
+\r
+ /**\r
+ * this routine takes text in url format and makes\r
+ * a clickaeble "<href>" link removing any "illegal" html tags\r
+ * @param haystack the url\r
+ * @param title the href link text\r
+ * @param imageRoot the place to find icons\r
+ * @param extImage the url of the icon to show next to the link\r
+ * @return a String containing the url\r
+ */\r
+ private String createURLLinks(String haystack, String title, String imageRoot, String extImage) {\r
+ if (title == null) {\r
+ return substituteAll(haystack, urlExpression,\r
+ "<img src=\"" + imageRoot + "/" + extImage + "\" border=\"0\"/> <a href=\"$0\">$0</a>");\r
+ }\r
+\r
+ title = removeHTMLTags(title);\r
+\r
+ return substituteAll(haystack, urlExpression,\r
+ "<img src=\"" + imageRoot + "/" + extImage + "\" border=\"0\"/> <a href=\"$0\">" + title + "</a>");\r
+ }\r
+\r
+ private String substituteAll(String anInput, Pattern anExpression, String aReplacement) {\r
+ Perl5Matcher matcher = new Perl5Matcher();\r
+\r
+ return Util.substitute(\r
+ matcher, anExpression,\r
+ new Perl5Substitution(aReplacement), anInput,\r
+ Util.SUBSTITUTE_ALL);\r
+ }\r
+\r
+ /**\r
+ * Remove all HTML tags\r
+ */\r
+ public String removeHTMLTags(String haystack){\r
+ return substituteAll(haystack, htmlTagExpression, "");\r
+ }\r
+\r
+\r
+ /**\r
+ * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)\r
+ * in den html-tag <p>\r
+ * nur sinnvoll, wenn text nicht im html-format eingegeben\r
+ */\r
+ private String convertNewline2P(String haystack) {\r
+ return substituteAll(haystack, doubleBRExpression, "\n</p><p>");\r
+ }\r
+\r
+ /**\r
+ * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)\r
+ * in den html-tag <br>\r
+ * nur sinnvoll, wenn text nicht im html-format eingegeben\r
+ */\r
+ private String convertNewline2Break(String haystack) {\r
+ return substituteAll(haystack, newLineExpression, "$0<br />");\r
+ }\r
+\r
+\r
+ /**\r
+ * createMailLinks wandelt text im email-adressenformat\r
+ * in einen klickbaren link um\r
+ * nur sinnvoll, wenn text nicht im html-format eingegeben\r
+ */\r
+ private String createMailLinks(String haystack, String imageRoot, String mailImage) {\r
+ return substituteAll(haystack, emailAddressExpression,\r
+ "<img src=\"" + imageRoot + "/" + mailImage + "\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");\r
+ }\r
+\r
+\r
+ /**\r
+ * this routine takes text in url format and makes\r
+ * a clickaeble "<href>" link removing any "illegal" html tags\r
+ * @param haystack the url\r
+ * @param imageRoot the place to find icons\r
+ * @param extImage the url of the icon to show next to the link\r
+ * @param intImage unused\r
+ * @return a String containing the url\r
+ */\r
+ private String createURLLinks(String haystack, String title, String imageRoot,String extImage, String intImage) {\r
+ return createURLLinks(haystack, title, imageRoot, extImage);\r
+ }\r
+\r
+ /**\r
+ */\r
+ public String createHTML(String content, String producerDocRoot, String mailImage, String extImage, String intImage){\r
+ content = convertNewline2Break(content);\r
+ content = convertNewline2P(content);\r
+ content = createMailLinks(content, producerDocRoot, mailImage);\r
+ content = createURLLinks(content, null, producerDocRoot,\r
+ extImage, intImage);\r
+\r
+ return content;\r
+ }\r
+\r
+\r
+}\r
package mir.util;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
-import mir.util.UtilExc;
-
public class HTTPClientHelper {
private HttpClient client;
private HttpMethod method;
-
+
public HTTPClientHelper() {
- client = new HttpClient();
- client.setConnectionTimeout(5000);
- client.setTimeout(5000);
+ client = new HttpClient();
+ client.setConnectionTimeout(5000);
+ client.setTimeout(5000);
}
-
- public InputStream getUrl(String anUrl) throws UtilExc{
- try{
+ public InputStream getUrl(String anUrl) throws UtilExc {
+ try {
method = new GetMethod(anUrl);
method.setFollowRedirects(true);
method.setStrictMode(false);
client.executeMethod(method);
- InputStream inputStream = method.getResponseBodyAsStream();
+ InputStream inputStream = method.getResponseBodyAsStream();
return inputStream;
}
- catch (IOException e){
- throw new UtilExc(e.getMessage());
+ catch (IOException e) {
+ throw new UtilExc(e.getMessage());
}
}
-
+
public void releaseHTTPConnection() {
method.releaseConnection();
method.recycle();
*/
package mir.util;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
import mir.log.LoggerWrapper;
+
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
-import javax.servlet.http.HttpServletRequest;
-import java.util.*;
-
public class HTTPParsedRequest {
static final String MULTIPART_FORMDATA_CONTENTTYPE = "multipart/form-data";
package mir.util;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
+
import javax.servlet.http.HttpServletRequest;
public class HTTPRequestParser {
private HttpServletRequest request;
- private String encoding;
+ private Map overridingParameters;
public HTTPRequestParser(HttpServletRequest aRequest) {
- this(aRequest, aRequest.getCharacterEncoding());
+ this(aRequest, Collections.EMPTY_MAP);
}
- public HTTPRequestParser(HttpServletRequest aRequest, String anEncoding) {
+ public HTTPRequestParser(HttpServletRequest aRequest, Map anOverridingParameters) {
request = aRequest;
- encoding = anEncoding;
+ overridingParameters = anOverridingParameters;
}
public boolean hasParameter(String aName) {
- return request.getParameter(aName)!=null;
+ return (request.getParameter(aName)!=null) || overridingParameters.containsKey(aName);
}
public String getParameterWithDefault(String aName, String 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);
-// }
+ if (result==null) {
+ result = (String) overridingParameters.get(aName);
+ }
return result;
}
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+import java.io.OutputStream;\r
+import java.io.InputStream;\r
+import java.io.IOException;\r
+\r
+public class IORoutines {\r
+ private IORoutines() {\r
+ }\r
+\r
+ public static void copyStream(InputStream anInputStream, OutputStream anOutputStream) throws IOException {\r
+ byte[] buffer = new byte[128*1024];\r
+ int size;\r
+\r
+ while ( (size = anInputStream.read(buffer)) > 0) {\r
+ anOutputStream.write(buffer, 0, size);\r
+ }\r
+ }\r
+\r
+ public static void writeStream(String aData, String anEncoding, OutputStream anOutputStream) throws IOException {\r
+ anOutputStream.write(aData.getBytes(anEncoding));\r
+ }\r
+\r
+}\r
-/*
- * 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.List;
-import java.net.InetAddress;
-
-public class InternetFunctions {
- private InternetFunctions() {
- }
-
- public static boolean isIpAddressInNetwork(String anIpAddress, String aNetwork) throws Exception {
- long ipAddress = parseHostNameOrIPAddress(anIpAddress);
- long network = 0;
- long netMask = (1L<<32)-1;
- List networkParts = StringRoutines.separateString(aNetwork, "/");
-
- network = parseHostNameOrIPAddress((String) networkParts.get(0));
- if (networkParts.size()>=2) {
- netMask=parseNetmask((String) networkParts.get(1));
- }
-
- return (ipAddress & netMask ) == (network & netMask);
- }
-
- public static long parseHostNameOrIPAddress(String aHostName) throws Exception {
- InetAddress addr = InetAddress.getByName(aHostName.trim());
- return
- ((((long) addr.getAddress()[0])&255) << 24) +
- ((((long) addr.getAddress()[1])&255) << 16) +
- ((((long) addr.getAddress()[2])&255) << 8) +
- ((((long) addr.getAddress()[3])&255));
- }
-
- public static long parseIPAddress(String anIpAddress) throws Exception {
- int[] parts = {0,0,0,0};
- int i;
- List stringParts = StringRoutines.splitString(anIpAddress, ".");
-
- if (stringParts.size()!=4)
- throw new Exception("Not a valid IP Address: " + anIpAddress);
-
- try {
- for (i=0; i<4; i++) {
- parts[i] = Integer.parseInt(((String) stringParts.get(i)).trim());
- }
- }
- catch (Throwable t) {
- throw new Exception("Not a valid IP Address: " + anIpAddress);
- }
- for (i=0; i<4; i++) {
- if (parts[i]<0 || parts[i]>255)
- throw new Exception("Not a valid IP Address: " + anIpAddress);
- }
-
- return parts[0]<<24 | parts[1]<<16 | parts[2]<<8 | parts[3];
- }
-
- public static long parseNetmask(String anIpAddress) throws Exception {
- try {
- return parseIPAddress(anIpAddress);
- }
- catch (Throwable t) {
- }
-
- try {
- int size = Integer.parseInt(anIpAddress);
-
- if (size<=32)
- return ((1L<<size)-1)<<(32-size);
- }
- catch (Throwable t) {
- }
-
- return (1L<<32)-1;
- }
-
-}
\ No newline at end of file
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License.\r
+ * You must obey the GNU General Public License in all respects for all of the code used\r
+ * other than the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+/**\r
+ * @deprecated Use mir.util.InternetRoutines instead\r
+ */\r
+public class InternetFunctions extends InternetRoutines {\r
+}\r
--- /dev/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.util;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.List;
+
+public class InternetRoutines {
+ protected InternetRoutines() {
+ }
+
+ public static boolean isIpAddressInNetwork(String anIpAddress, String aNetwork) throws Exception {
+ long ipAddress = parseHostNameOrIPAddress(anIpAddress);
+ long network = 0;
+ long netMask = (1L<<32)-1;
+ List networkParts = StringRoutines.separateString(aNetwork, "/");
+
+ network = parseHostNameOrIPAddress((String) networkParts.get(0));
+ if (networkParts.size()>=2) {
+ netMask=parseNetmask((String) networkParts.get(1));
+ }
+
+ return (ipAddress & netMask ) == (network & netMask);
+ }
+
+ public static long parseHostNameOrIPAddress(String aHostName) throws Exception {
+ InetAddress addr = InetAddress.getByName(aHostName.trim());
+ return
+ ((((long) addr.getAddress()[0])&255) << 24) +
+ ((((long) addr.getAddress()[1])&255) << 16) +
+ ((((long) addr.getAddress()[2])&255) << 8) +
+ ((((long) addr.getAddress()[3])&255));
+ }
+
+ public static long parseIPAddress(String anIpAddress) throws Exception {
+ int[] parts = {0,0,0,0};
+ int i;
+ List stringParts = StringRoutines.splitString(anIpAddress, ".");
+
+ if (stringParts.size()!=4)
+ throw new Exception("Not a valid IP Address: " + anIpAddress);
+
+ try {
+ for (i=0; i<4; i++) {
+ parts[i] = Integer.parseInt(((String) stringParts.get(i)).trim());
+ }
+ }
+ catch (Throwable t) {
+ throw new Exception("Not a valid IP Address: " + anIpAddress);
+ }
+ for (i=0; i<4; i++) {
+ if (parts[i]<0 || parts[i]>255)
+ throw new Exception("Not a valid IP Address: " + anIpAddress);
+ }
+
+ return parts[0]<<24 | parts[1]<<16 | parts[2]<<8 | parts[3];
+ }
+
+ public static long parseNetmask(String anIpAddress) throws Exception {
+ try {
+ return parseIPAddress(anIpAddress);
+ }
+ catch (Throwable t) {
+ }
+
+ try {
+ int size = Integer.parseInt(anIpAddress);
+
+ if (size<=32)
+ return ((1L<<size)-1)<<(32-size);
+ }
+ catch (Throwable t) {
+ }
+
+ return (1L<<32)-1;
+ }
+}
\ No newline at end of file
--- /dev/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 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.IOException;
+
+/**
+ * Class to do locking by way of a file:
+ * existence of the file means the lock is enabled.
+ */
+public class LockFile {
+ private File file;
+
+ /**
+ * Creates an instance based on a filename
+ */
+ public LockFile(String aFileName) {
+ file = new File(aFileName);
+ }
+
+ public LockFile(File aFile) {
+ file = new File(aFile.getAbsolutePath());
+ }
+
+ /**
+ * Tries to enable the lock. Returns <code>true</code> on success.
+ */
+ public boolean lock() throws IOException {
+ if (file.createNewFile()) {
+ file.deleteOnExit();
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns <code>true</code> if locked, either by external parties
+ * or by this object.
+ */
+ public boolean isLocked() {
+ return file.exists();
+ }
+
+ /**
+ * Removes the lock, wether it was enabled by this object or by
+ * an external party.
+ */
+ public void unlock() {
+ file.delete();
+ }
+}
+++ /dev/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 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.Writer;
-
-public class NullWriter extends Writer {
-
- public NullWriter() {
- }
-
- public void close() {
- }
-
- public void flush() {
- }
-
- public void write(char[] cbuf, int off, int len) {
- }
-}
\ No newline at end of file
*/
package mir.util;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
import mir.generator.Generator;
import mir.generator.GeneratorExc;
private static abstract class Token {
}
- public static abstract class PunctuationToken extends Token { public PunctuationToken() { }; }
- private static class LeftSquareBraceToken extends PunctuationToken {};
- private static class RightSquareBraceToken extends PunctuationToken {};
- private static class EqualsToken extends PunctuationToken {};
- private static class EqualsNotToken extends PunctuationToken {};
- private static class NOTToken extends PunctuationToken {};
- private static class LeftParenthesisToken extends PunctuationToken {};
- private static class RightParenthesisToken extends PunctuationToken {};
- private static class CommaToken extends PunctuationToken {};
- private static class PeriodToken extends PunctuationToken {};
- private static class PlusToken extends PunctuationToken {};
- private static class TimesToken extends PunctuationToken {};
- private static class DivideToken extends PunctuationToken {};
- private static class MinusToken extends PunctuationToken {};
- private static class ConcatenateToken extends PunctuationToken {};
- private static class LessThanOrEqualsToken extends PunctuationToken {};
- private static class GreaterThanOrEqualsToken extends PunctuationToken {};
- private static class LessThanToken extends PunctuationToken {};
- private static class GreaterThanToken extends PunctuationToken {};
+ public static abstract class PunctuationToken extends Token { public PunctuationToken() { } }
+ private static class LeftSquareBraceToken extends PunctuationToken {}
+ private static class RightSquareBraceToken extends PunctuationToken {}
+ private static class EqualsToken extends PunctuationToken {}
+ private static class EqualsNotToken extends PunctuationToken {}
+ private static class NOTToken extends PunctuationToken {}
+ private static class LeftParenthesisToken extends PunctuationToken {}
+ private static class RightParenthesisToken extends PunctuationToken {}
+ private static class CommaToken extends PunctuationToken {}
+ private static class PeriodToken extends PunctuationToken {}
+ private static class PlusToken extends PunctuationToken {}
+ private static class TimesToken extends PunctuationToken {}
+ private static class DivideToken extends PunctuationToken {}
+ private static class MinusToken extends PunctuationToken {}
+ private static class ConcatenateToken extends PunctuationToken {}
+ private static class LessThanOrEqualsToken extends PunctuationToken {}
+ private static class GreaterThanOrEqualsToken extends PunctuationToken {}
+ private static class LessThanToken extends PunctuationToken {}
+ private static class GreaterThanToken extends PunctuationToken {}
private static class IdentifierToken extends Token {
public void skipWhitespace() {
while (reader.hasNext() && Character.isWhitespace(reader.peek().charValue()))
reader.getNext();
- };
+ }
private boolean isIdentifierStart(char c) {
return Character.isLetter(c) || (c == '_');
private List parseList() {
Token token;
Object expression;
- List result = new Vector();
+ List result = new ArrayList();
token = scanner.scan();
if (!(token instanceof LeftParenthesisToken)) {
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
+import java.util.ArrayList;
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;
private Map values;
public PropertiesManipulator() {
- entries = new Vector();
+ entries = new ArrayList();
values = new HashMap();
}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mir.util;\r
-\r
-import org.apache.commons.beanutils.MethodUtils;\r
-\r
-import java.lang.reflect.InvocationTargetException;\r
-\r
-public class ReflectionRoutines {\r
- private ReflectionRoutines() {\r
- }\r
-\r
- /**\r
- * Method to overcome a shortcoming in {@link org.apache.commons.beanutils}'s\r
- * {@link MethodUtils#invokeMethod(Object, String, Object[])} involving\r
- * parameters that are <code>null</code> \r
- */\r
- public static Object invokeMethod(Object aTarget, String aMethodName, Object[] aParameters)\r
- throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {\r
- Class parameterTypes[] = new Class[aParameters.length];\r
-\r
- for (int i=0; i<aParameters.length; i++) {\r
- if (aParameters[i] == null) {\r
- parameterTypes[i] = Object.class;\r
- }\r
- else {\r
- parameterTypes[i] = aParameters[i].getClass();\r
- }\r
- }\r
-\r
- return MethodUtils.invokeMethod(aTarget, aMethodName, aParameters, parameterTypes);\r
- }\r
-}\r
+/*
+ * 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 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.lang.reflect.InvocationTargetException;
+
+import org.apache.commons.beanutils.MethodUtils;
+
+public class ReflectionRoutines {
+ private ReflectionRoutines() {
+ }
+
+ /**
+ * Method to overcome a shortcoming in {@link org.apache.commons.beanutils}'s
+ * {@link MethodUtils#invokeMethod(Object, String, Object[])} involving
+ * parameters that are <code>null</code>
+ */
+ public static Object invokeMethod(Object aTarget, String aMethodName, Object[] aParameters)
+ throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ Class parameterTypes[] = new Class[aParameters.length];
+
+ for (int i=0; i<aParameters.length; i++) {
+ if (aParameters[i] == null) {
+ parameterTypes[i] = Object.class;
+ }
+ else {
+ parameterTypes[i] = aParameters[i].getClass();
+ }
+ }
+
+ return MethodUtils.invokeMethod(aTarget, aMethodName, aParameters, parameterTypes);
+ }
+}
--- /dev/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 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 mir.log.LoggerWrapper;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.Reader;
+
+/**
+ * Execute system commands. Warning: the current implementation is
+ * unix specific.
+ */
+public class ShellRoutines {
+ protected ShellRoutines() {
+ }
+
+ /**
+ * Executes a full command (including arguments) in a subshell
+ * and returns the output of the command in a string. Output is
+ * redirected into a temporary fil which is then read into the string
+ */
+ public static String execIntoString(String command) throws IOException {
+ return new String(execIntoByteArray(command));
+ }
+
+ /**
+ * Executes a full command (including arguments) in a subshell
+ * and returns the output of the command in an array of
+ * bytes. Output is redirected into a temporary file which is then
+ * read into an array of bytes
+ */
+ public static byte[] execIntoByteArray(String command) throws IOException {
+ File commandOutput = File.createTempFile("mircmd", "");
+ try {
+ int exitStatus;
+ try {
+ // WARNING: unix specific
+
+ exitStatus = Runtime.getRuntime().exec(new String[]{
+ "/bin/sh", "-c",
+ command + " " +
+ ">" + commandOutput.getAbsolutePath()
+ }).waitFor();
+ }
+ catch (InterruptedException e) {
+ throw new IOException(e.toString());
+ }
+ if (exitStatus != 0) {
+ throw new IOException("command exit satus:" + exitStatus);
+ }
+ return FileRoutines.readFileIntoByteArray
+ (commandOutput.getAbsoluteFile());
+ }
+ finally {
+ commandOutput.delete();
+ }
+ }
+
+ /**
+ * Executes a full command (including arguments) in a subshell.
+ * Standard input and output go to /dev/null
+ */
+ public static void simpleExec(String command) throws IOException {
+ int exitStatus;
+ try {
+ // WARNING: unix specific
+// exitStatus =
+ Process process = Runtime.getRuntime().exec(
+ new String[]{
+ "/bin/sh", "-c", command
+ });
+ Reader errorStreamReader = new InputStreamReader(process.getErrorStream());
+ ReaderLogger logger =
+ new ReaderLogger(errorStreamReader, new LoggerWrapper("Utility"));
+
+ new Thread(logger).start();
+
+ Reader outputStreamReader = new InputStreamReader(process.getInputStream());
+ logger = new ReaderLogger(outputStreamReader, new LoggerWrapper("Utility"));
+ new Thread(logger).start();
+
+ exitStatus = process.waitFor();
+ }
+ catch (InterruptedException e) {
+ throw new IOException("Interrupted");
+ }
+
+ if (exitStatus != 0) {
+ throw new IOException("command exit satus:" + exitStatus);
+ }
+ }
+
+ private static class ReaderLogger implements Runnable {
+ private Reader reader;
+ private PrintWriter writer;
+
+ ReaderLogger(Reader aReader, LoggerWrapper aLogger) {
+ reader = aReader;
+ writer = aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE);
+ }
+
+ public void run() {
+ try {
+ int size;
+ char[] buffer = new char[1024];
+ while ((size = reader.read(buffer)) >= 0) {
+ writer.write(buffer,0,size);
+ }
+ }
+ catch (IOException e) {
+ }
+
+ writer.close();
+ try {
+ reader.close();
+ }
+ catch (Exception e) {
+ }
+ }
+ }
+
+}
import multex.Failure;
/**
- * a class to do some basic, regexp based parsing of character data
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * Simple parser. Can be used to parse a <code>String</code> based using
+ * regular epxression.
*/
-
public class SimpleParser {
private String data;
private int position;
/**
- *
- * @param aData
+ * Initialize a new <code>SimpleParser</code>, with <code>aData</code>
+ * as the text to parse.
*/
public SimpleParser(String aData) {
}
/**
- *
- * @param aRegularExpression
- * @return
- * @throws SimpleParserExc
+ * Parses a regular expression. Uses suppled <code>aMessage</code> parameter
+ * in case of an error.
*/
-
- 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)
+ if (match==null || match.getStartIndex()!=position) {
throw new SimpleParserExc(aMessage+" at position "+position+" in '"+data+"'");
+ }
position=match.getEndIndex();
}
/**
+ * Attempts to match the data right after the parsing position to
+ * a regular expression
*
- * @param aRegularExpression
- * @return
- * @throws SimpleParserExc
+ * @throws SimpleParserExc if no match could be found for the given regular
+ * expression.
*/
-
public String parse(RE aRegularExpression) throws SimpleParserExc {
return parse( aRegularExpression, "No match found for '"+aRegularExpression.toString()+"'");
}
/**
+ * Attempts to skip data at the parsing position matching the supplied regular expression
*
- * @param aRegularExpression
- * @throws SimpleParserExc
+ * @throws SimpleParserExc if no match could be found for the given regular
+ * expression.
*/
public void skip(RE aRegularExpression) throws SimpleParserExc {
}
/**
- *
- * @param anExpression
- * @return
- * @throws SimpleParserExc
+ * Returns <code>true</code> if the data at the parsing position matches the given
+ * regular expression.
*/
-
public boolean parses(String anExpression) throws SimpleParserExc {
try {
return parses(new RE(anExpression));
}
/**
- *
- * @param anExpression
- * @return
- * @throws SimpleParserExc
- * @throws SimpleParserFailure
+ * Returns <code>true</code> if the data at the parsing position matches the given
+ * regular expression.
*/
+ public boolean parses(RE aRegularExpression) throws SimpleParserExc {
+ REMatch match = aRegularExpression.getMatch(data, position);
+
+ return (match!=null && match.getStartIndex()==position) ;
+ }
+ /**
+ * Attempts to match the data right after the parsing position to
+ * a regular expression
+ *
+ * @throws SimpleParserExc if no match could be found for the given regular
+ * expression.
+ */
public String parse(String anExpression) throws SimpleParserExc, SimpleParserFailure {
try {
return parse(new RE(anExpression));
}
}
+
/**
- *
- * @param anExpression
- * @param aMessage
- * @return
- * @throws SimpleParserExc
- * @throws SimpleParserFailure
+ * Parses text at the current parsing position matching the given <code>anExpression</code>.
+ * Will apply the supplied message to an exception if no match could be found.
*/
-
public String parse(String anExpression, String aMessage) throws SimpleParserExc, SimpleParserFailure {
try {
return parse(new RE(anExpression), aMessage);
}
/**
- *
- * @param anExpression
- * @throws SimpleParserExc
- * @throws SimpleParserFailure
+ * Skips (i.e. discards) text matching the supplied regular expression
*/
public void skip(String anExpression) throws SimpleParserExc, SimpleParserFailure {
}
/**
- *
- * @return true if the parser is at the end of the data
+ * returns <code>true</code> if the parser is at the end of the data
*/
-
public boolean isAtEnd() {
return position>=data.length();
}
/**
- *
- * @return
+ * Returns the "remaining" data: the data after the current position
*/
public String remainingData() {
return data.substring(position);
}
/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * Unchecked exception thrown from <code>SimpleParser</code>
*/
public static class SimpleParserFailure extends Failure {
}
}
+ /**
+ * Checked exception thrown from <code>SimpleParser</code>
+ */
public static class SimpleParserExc extends Exc {
public SimpleParserExc(String aMessage) {
super(aMessage);
*/
package mir.util;
+import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.IOException;
public class StreamCopier {
public static void copy(InputStream aSource, OutputStream aDestination) throws IOException {
package mir.util;
+import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Map;
import java.util.List;
-import java.util.ArrayList;
+import java.util.Map;
public class StringParseRoutines {
import gnu.regexp.RE;
-import java.util.List;
import java.util.ArrayList;
+import java.util.List;
public class StringRoutines {
}
}
- public static String performCaseInsensitiveRegularExpressionReplacement(String aSource, String aSearchExpression, String aReplacement) {
- try {
- RE regularExpression;
-
- regularExpression = new RE(aSearchExpression, RE.REG_ICASE);
-
- return regularExpression.substituteAll(aSource, aReplacement);
- }
- catch (Throwable t) {
- throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
- }
- }
-
- public static boolean performRegularExpressionSearch(String aSource, String aSearchExpression) {
- try {
- RE regularExpression;
-
- regularExpression = new RE(aSearchExpression);
-
- return regularExpression.isMatch(aSource);
- }
- catch (Throwable t) {
- throw new UtilFailure("StringRoutines.performRegularExpressionSearch: " + t.toString(), t);
- }
- }
-
/**
* Separates a string based on a separator:
* <code>seperateString("a:b:c", ":");</code> will lead to
public static String padStringLeft(String aString, int aLength, char aPadCharacter) {
if (aString.length()<aLength)
return replicateChar(aPadCharacter, aLength-aString.length()) + aString;
- else
- return aString;
+ return aString;
}
private static final char HEX_CHARACTERS[] = {
package mir.util;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
/**
}
public static List parseList(Scanner aScanner) {
- List result = new Vector();
+ List result = new ArrayList();
aScanner.skipSpace();
if (aScanner.peek() == '[')
aScanner.scan();
*/
package mir.util;
-import java.util.List;
import java.util.NoSuchElementException;
public class SubsetIterator implements RewindableIterator {
private RewindableIterator master;
- private List cachedItems;
private int position;
private int skip;
private int maxLength;
public Object next() {
if (hasNext())
return getNext();
- else
- throw new NoSuchElementException();
+ throw new NoSuchElementException();
}
public void remove() {
public void rewind() {
position=0;
master.rewind();
- };
+ }
}
\ No newline at end of file
+++ /dev/null
-// todo....figure out what license changes need to be made here...
-
-// HTMLParser Library v1_3_20030511 - A java-based parser for HTML
-// Copyright (C) Dec 31, 2000 Somik Raha
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library 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
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// For any questions or suggestions, you can write to me at :
-// Email :somik@industriallogic.com
-//
-// Postal Address :
-// Somik Raha
-// Extreme Programmer & Coach
-// Industrial Logic Corporation
-// 2583 Cedar Street, Berkeley,
-// CA 94708, USA
-// Website : http://www.industriallogic.com
-//
-// This class was contributed by
-// Derrick Oswald
-//
-
-package mir.util;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Translate numeric character references and character entity references to unicode characters.
- * Based on tables found at <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">
- * http://www.w3.org/TR/REC-html40/sgml/entities.html</a>
- * <p><b>Note: Do not edit! This class is created by the Generate class.</b>
- * <p>Typical usage:
- * <pre>
- * String s = Translate.decode (getTextFromHtmlPage ());
- * </pre>
- * @author <a href='mailto:DerrickOswald@users.sourceforge.net?subject=Character Reference Translation class'>Derrick Oswald</a>
- */
-public class Translate
-{
- /**
- * Table mapping entity reference kernel to character.
- * <p><code>String</code>-><code>Character</code>
- */
- protected static Map refChar;
- static
- {
- refChar = new HashMap(1000);
-
- // Portions © International Organization for Standardization 1986
- // Permission to copy in any form is granted for use with
- // conforming SGML systems and applications as defined in
- // ISO 8879, provided this notice is included in all copies.
- // Character entity set. Typical invocation:
- // <!ENTITY % HTMLlat1 PUBLIC
- // "-//W3C//ENTITIES Latin 1//EN//HTML">
- // %HTMLlat1;
- refChar.put ("nbsp", new Character ('\u00a0')); // no-break space = non-breaking space, U+00A0 ISOnum
- refChar.put ("iexcl", new Character ('\u00a1')); // inverted exclamation mark, U+00A1 ISOnum
- refChar.put ("cent", new Character ('\u00a2')); // cent sign, U+00A2 ISOnum
- refChar.put ("pound", new Character ('\u00a3')); // pound sign, U+00A3 ISOnum
- refChar.put ("curren", new Character ('\u00a4')); // currency sign, U+00A4 ISOnum
- refChar.put ("yen", new Character ('\u00a5')); // yen sign = yuan sign, U+00A5 ISOnum
- refChar.put ("brvbar", new Character ('\u00a6')); // broken bar = broken vertical bar, U+00A6 ISOnum
- refChar.put ("sect", new Character ('\u00a7')); // section sign, U+00A7 ISOnum
- refChar.put ("uml", new Character ('\u00a8')); // diaeresis = spacing diaeresis, U+00A8 ISOdia
- refChar.put ("copy", new Character ('\u00a9')); // copyright sign, U+00A9 ISOnum
- refChar.put ("ordf", new Character ('\u00aa')); // feminine ordinal indicator, U+00AA ISOnum
- refChar.put ("laquo", new Character ('\u00ab')); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum
- refChar.put ("not", new Character ('\u00ac')); // not sign, U+00AC ISOnum
- refChar.put ("shy", new Character ('\u00ad')); // soft hyphen = discretionary hyphen, U+00AD ISOnum
- refChar.put ("reg", new Character ('\u00ae')); // registered sign = registered trade mark sign, U+00AE ISOnum
- refChar.put ("macr", new Character ('\u00af')); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia
- refChar.put ("deg", new Character ('\u00b0')); // degree sign, U+00B0 ISOnum
- refChar.put ("plusmn", new Character ('\u00b1')); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum
- refChar.put ("sup2", new Character ('\u00b2')); // superscript two = superscript digit two = squared, U+00B2 ISOnum
- refChar.put ("sup3", new Character ('\u00b3')); // superscript three = superscript digit three = cubed, U+00B3 ISOnum
- refChar.put ("acute", new Character ('\u00b4')); // acute accent = spacing acute, U+00B4 ISOdia
- refChar.put ("micro", new Character ('\u00b5')); // micro sign, U+00B5 ISOnum
- refChar.put ("para", new Character ('\u00b6')); // pilcrow sign = paragraph sign, U+00B6 ISOnum
- refChar.put ("middot", new Character ('\u00b7')); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum
- refChar.put ("cedil", new Character ('\u00b8')); // cedilla = spacing cedilla, U+00B8 ISOdia
- refChar.put ("sup1", new Character ('\u00b9')); // superscript one = superscript digit one, U+00B9 ISOnum
- refChar.put ("ordm", new Character ('\u00ba')); // masculine ordinal indicator, U+00BA ISOnum
- refChar.put ("raquo", new Character ('\u00bb')); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum
- refChar.put ("frac14", new Character ('\u00bc')); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum
- refChar.put ("frac12", new Character ('\u00bd')); // vulgar fraction one half = fraction one half, U+00BD ISOnum
- refChar.put ("frac34", new Character ('\u00be')); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum
- refChar.put ("iquest", new Character ('\u00bf')); // inverted question mark = turned question mark, U+00BF ISOnum
- refChar.put ("Agrave", new Character ('\u00c0')); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1
- refChar.put ("Aacute", new Character ('\u00c1')); // latin capital letter A with acute, U+00C1 ISOlat1
- refChar.put ("Acirc", new Character ('\u00c2')); // latin capital letter A with circumflex, U+00C2 ISOlat1
- refChar.put ("Atilde", new Character ('\u00c3')); // latin capital letter A with tilde, U+00C3 ISOlat1
- refChar.put ("Auml", new Character ('\u00c4')); // latin capital letter A with diaeresis, U+00C4 ISOlat1
- refChar.put ("Aring", new Character ('\u00c5')); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1
- refChar.put ("AElig", new Character ('\u00c6')); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
- refChar.put ("Ccedil", new Character ('\u00c7')); // latin capital letter C with cedilla, U+00C7 ISOlat1
- refChar.put ("Egrave", new Character ('\u00c8')); // latin capital letter E with grave, U+00C8 ISOlat1
- refChar.put ("Eacute", new Character ('\u00c9')); // latin capital letter E with acute, U+00C9 ISOlat1
- refChar.put ("Ecirc", new Character ('\u00ca')); // latin capital letter E with circumflex, U+00CA ISOlat1
- refChar.put ("Euml", new Character ('\u00cb')); // latin capital letter E with diaeresis, U+00CB ISOlat1
- refChar.put ("Igrave", new Character ('\u00cc')); // latin capital letter I with grave, U+00CC ISOlat1
- refChar.put ("Iacute", new Character ('\u00cd')); // latin capital letter I with acute, U+00CD ISOlat1
- refChar.put ("Icirc", new Character ('\u00ce')); // latin capital letter I with circumflex, U+00CE ISOlat1
- refChar.put ("Iuml", new Character ('\u00cf')); // latin capital letter I with diaeresis, U+00CF ISOlat1
- refChar.put ("ETH", new Character ('\u00d0')); // latin capital letter ETH, U+00D0 ISOlat1
- refChar.put ("Ntilde", new Character ('\u00d1')); // latin capital letter N with tilde, U+00D1 ISOlat1
- refChar.put ("Ograve", new Character ('\u00d2')); // latin capital letter O with grave, U+00D2 ISOlat1
- refChar.put ("Oacute", new Character ('\u00d3')); // latin capital letter O with acute, U+00D3 ISOlat1
- refChar.put ("Ocirc", new Character ('\u00d4')); // latin capital letter O with circumflex, U+00D4 ISOlat1
- refChar.put ("Otilde", new Character ('\u00d5')); // latin capital letter O with tilde, U+00D5 ISOlat1
- refChar.put ("Ouml", new Character ('\u00d6')); // latin capital letter O with diaeresis, U+00D6 ISOlat1
- refChar.put ("times", new Character ('\u00d7')); // multiplication sign, U+00D7 ISOnum
- refChar.put ("Oslash", new Character ('\u00d8')); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1
- refChar.put ("Ugrave", new Character ('\u00d9')); // latin capital letter U with grave, U+00D9 ISOlat1
- refChar.put ("Uacute", new Character ('\u00da')); // latin capital letter U with acute, U+00DA ISOlat1
- refChar.put ("Ucirc", new Character ('\u00db')); // latin capital letter U with circumflex, U+00DB ISOlat1
- refChar.put ("Uuml", new Character ('\u00dc')); // latin capital letter U with diaeresis, U+00DC ISOlat1
- refChar.put ("Yacute", new Character ('\u00dd')); // latin capital letter Y with acute, U+00DD ISOlat1
- refChar.put ("THORN", new Character ('\u00de')); // latin capital letter THORN, U+00DE ISOlat1
- refChar.put ("szlig", new Character ('\u00df')); // latin small letter sharp s = ess-zed, U+00DF ISOlat1
- refChar.put ("agrave", new Character ('\u00e0')); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1
- refChar.put ("aacute", new Character ('\u00e1')); // latin small letter a with acute, U+00E1 ISOlat1
- refChar.put ("acirc", new Character ('\u00e2')); // latin small letter a with circumflex, U+00E2 ISOlat1
- refChar.put ("atilde", new Character ('\u00e3')); // latin small letter a with tilde, U+00E3 ISOlat1
- refChar.put ("auml", new Character ('\u00e4')); // latin small letter a with diaeresis, U+00E4 ISOlat1
- refChar.put ("aring", new Character ('\u00e5')); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1
- refChar.put ("aelig", new Character ('\u00e6')); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1
- refChar.put ("ccedil", new Character ('\u00e7')); // latin small letter c with cedilla, U+00E7 ISOlat1
- refChar.put ("egrave", new Character ('\u00e8')); // latin small letter e with grave, U+00E8 ISOlat1
- refChar.put ("eacute", new Character ('\u00e9')); // latin small letter e with acute, U+00E9 ISOlat1
- refChar.put ("ecirc", new Character ('\u00ea')); // latin small letter e with circumflex, U+00EA ISOlat1
- refChar.put ("euml", new Character ('\u00eb')); // latin small letter e with diaeresis, U+00EB ISOlat1
- refChar.put ("igrave", new Character ('\u00ec')); // latin small letter i with grave, U+00EC ISOlat1
- refChar.put ("iacute", new Character ('\u00ed')); // latin small letter i with acute, U+00ED ISOlat1
- refChar.put ("icirc", new Character ('\u00ee')); // latin small letter i with circumflex, U+00EE ISOlat1
- refChar.put ("iuml", new Character ('\u00ef')); // latin small letter i with diaeresis, U+00EF ISOlat1
- refChar.put ("eth", new Character ('\u00f0')); // latin small letter eth, U+00F0 ISOlat1
- refChar.put ("ntilde", new Character ('\u00f1')); // latin small letter n with tilde, U+00F1 ISOlat1
- refChar.put ("ograve", new Character ('\u00f2')); // latin small letter o with grave, U+00F2 ISOlat1
- refChar.put ("oacute", new Character ('\u00f3')); // latin small letter o with acute, U+00F3 ISOlat1
- refChar.put ("ocirc", new Character ('\u00f4')); // latin small letter o with circumflex, U+00F4 ISOlat1
- refChar.put ("otilde", new Character ('\u00f5')); // latin small letter o with tilde, U+00F5 ISOlat1
- refChar.put ("ouml", new Character ('\u00f6')); // latin small letter o with diaeresis, U+00F6 ISOlat1
- refChar.put ("divide", new Character ('\u00f7')); // division sign, U+00F7 ISOnum
- refChar.put ("oslash", new Character ('\u00f8')); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1
- refChar.put ("ugrave", new Character ('\u00f9')); // latin small letter u with grave, U+00F9 ISOlat1
- refChar.put ("uacute", new Character ('\u00fa')); // latin small letter u with acute, U+00FA ISOlat1
- refChar.put ("ucirc", new Character ('\u00fb')); // latin small letter u with circumflex, U+00FB ISOlat1
- refChar.put ("uuml", new Character ('\u00fc')); // latin small letter u with diaeresis, U+00FC ISOlat1
- refChar.put ("yacute", new Character ('\u00fd')); // latin small letter y with acute, U+00FD ISOlat1
- refChar.put ("thorn", new Character ('\u00fe')); // latin small letter thorn, U+00FE ISOlat1
- refChar.put ("yuml", new Character ('\u00ff')); // latin small letter y with diaeresis, U+00FF ISOlat1
- // Mathematical, Greek and Symbolic characters for HTML
- // Character entity set. Typical invocation:
- // <!ENTITY % HTMLsymbol PUBLIC
- // "-//W3C//ENTITIES Symbols//EN//HTML">
- // %HTMLsymbol;
- // Portions © International Organization for Standardization 1986:
- // Permission to copy in any form is granted for use with
- // conforming SGML systems and applications as defined in
- // ISO 8879, provided this notice is included in all copies.
- // Relevant ISO entity set is given unless names are newly introduced.
- // New names (i.e., not in ISO 8879 list) do not clash with any
- // existing ISO 8879 entity names. ISO 10646 character numbers
- // are given for each character, in hex. CDATA values are decimal
- // conversions of the ISO 10646 values and refer to the document
- // character set. Names are ISO 10646 names.
- // Latin Extended-B
- refChar.put ("fnof", new Character ('\u0192')); // latin small f with hook = function = florin, U+0192 ISOtech
- // Greek
- refChar.put ("Alpha", new Character ('\u0391')); // greek capital letter alpha, U+0391
- refChar.put ("Beta", new Character ('\u0392')); // greek capital letter beta, U+0392
- refChar.put ("Gamma", new Character ('\u0393')); // greek capital letter gamma, U+0393 ISOgrk3
- refChar.put ("Delta", new Character ('\u0394')); // greek capital letter delta, U+0394 ISOgrk3
- refChar.put ("Epsilon", new Character ('\u0395')); // greek capital letter epsilon, U+0395
- refChar.put ("Zeta", new Character ('\u0396')); // greek capital letter zeta, U+0396
- refChar.put ("Eta", new Character ('\u0397')); // greek capital letter eta, U+0397
- refChar.put ("Theta", new Character ('\u0398')); // greek capital letter theta, U+0398 ISOgrk3
- refChar.put ("Iota", new Character ('\u0399')); // greek capital letter iota, U+0399
- refChar.put ("Kappa", new Character ('\u039a')); // greek capital letter kappa, U+039A
- refChar.put ("Lambda", new Character ('\u039b')); // greek capital letter lambda, U+039B ISOgrk3
- refChar.put ("Mu", new Character ('\u039c')); // greek capital letter mu, U+039C
- refChar.put ("Nu", new Character ('\u039d')); // greek capital letter nu, U+039D
- refChar.put ("Xi", new Character ('\u039e')); // greek capital letter xi, U+039E ISOgrk3
- refChar.put ("Omicron", new Character ('\u039f')); // greek capital letter omicron, U+039F
- refChar.put ("Pi", new Character ('\u03a0')); // greek capital letter pi, U+03A0 ISOgrk3
- refChar.put ("Rho", new Character ('\u03a1')); // greek capital letter rho, U+03A1
- // there is no Sigmaf, and no U+03A2 character either
- refChar.put ("Sigma", new Character ('\u03a3')); // greek capital letter sigma, U+03A3 ISOgrk3
- refChar.put ("Tau", new Character ('\u03a4')); // greek capital letter tau, U+03A4
- refChar.put ("Upsilon", new Character ('\u03a5')); // greek capital letter upsilon, U+03A5 ISOgrk3
- refChar.put ("Phi", new Character ('\u03a6')); // greek capital letter phi, U+03A6 ISOgrk3
- refChar.put ("Chi", new Character ('\u03a7')); // greek capital letter chi, U+03A7
- refChar.put ("Psi", new Character ('\u03a8')); // greek capital letter psi, U+03A8 ISOgrk3
- refChar.put ("Omega", new Character ('\u03a9')); // greek capital letter omega, U+03A9 ISOgrk3
- refChar.put ("alpha", new Character ('\u03b1')); // greek small letter alpha, U+03B1 ISOgrk3
- refChar.put ("beta", new Character ('\u03b2')); // greek small letter beta, U+03B2 ISOgrk3
- refChar.put ("gamma", new Character ('\u03b3')); // greek small letter gamma, U+03B3 ISOgrk3
- refChar.put ("delta", new Character ('\u03b4')); // greek small letter delta, U+03B4 ISOgrk3
- refChar.put ("epsilon", new Character ('\u03b5')); // greek small letter epsilon, U+03B5 ISOgrk3
- refChar.put ("zeta", new Character ('\u03b6')); // greek small letter zeta, U+03B6 ISOgrk3
- refChar.put ("eta", new Character ('\u03b7')); // greek small letter eta, U+03B7 ISOgrk3
- refChar.put ("theta", new Character ('\u03b8')); // greek small letter theta, U+03B8 ISOgrk3
- refChar.put ("iota", new Character ('\u03b9')); // greek small letter iota, U+03B9 ISOgrk3
- refChar.put ("kappa", new Character ('\u03ba')); // greek small letter kappa, U+03BA ISOgrk3
- refChar.put ("lambda", new Character ('\u03bb')); // greek small letter lambda, U+03BB ISOgrk3
- refChar.put ("mu", new Character ('\u03bc')); // greek small letter mu, U+03BC ISOgrk3
- refChar.put ("nu", new Character ('\u03bd')); // greek small letter nu, U+03BD ISOgrk3
- refChar.put ("xi", new Character ('\u03be')); // greek small letter xi, U+03BE ISOgrk3
- refChar.put ("omicron", new Character ('\u03bf')); // greek small letter omicron, U+03BF NEW
- refChar.put ("pi", new Character ('\u03c0')); // greek small letter pi, U+03C0 ISOgrk3
- refChar.put ("rho", new Character ('\u03c1')); // greek small letter rho, U+03C1 ISOgrk3
- refChar.put ("sigmaf", new Character ('\u03c2')); // greek small letter final sigma, U+03C2 ISOgrk3
- refChar.put ("sigma", new Character ('\u03c3')); // greek small letter sigma, U+03C3 ISOgrk3
- refChar.put ("tau", new Character ('\u03c4')); // greek small letter tau, U+03C4 ISOgrk3
- refChar.put ("upsilon", new Character ('\u03c5')); // greek small letter upsilon, U+03C5 ISOgrk3
- refChar.put ("phi", new Character ('\u03c6')); // greek small letter phi, U+03C6 ISOgrk3
- refChar.put ("chi", new Character ('\u03c7')); // greek small letter chi, U+03C7 ISOgrk3
- refChar.put ("psi", new Character ('\u03c8')); // greek small letter psi, U+03C8 ISOgrk3
- refChar.put ("omega", new Character ('\u03c9')); // greek small letter omega, U+03C9 ISOgrk3
- refChar.put ("thetasym", new Character ('\u03d1')); // greek small letter theta symbol, U+03D1 NEW
- refChar.put ("upsih", new Character ('\u03d2')); // greek upsilon with hook symbol, U+03D2 NEW
- refChar.put ("piv", new Character ('\u03d6')); // greek pi symbol, U+03D6 ISOgrk3
- // General Punctuation
- refChar.put ("bull", new Character ('\u2022')); // bullet = black small circle, U+2022 ISOpub
- // bullet is NOT the same as bullet operator, U+2219
- refChar.put ("hellip", new Character ('\u2026')); // horizontal ellipsis = three dot leader, U+2026 ISOpub
- refChar.put ("prime", new Character ('\u2032')); // prime = minutes = feet, U+2032 ISOtech
- refChar.put ("Prime", new Character ('\u2033')); // double prime = seconds = inches, U+2033 ISOtech
- refChar.put ("oline", new Character ('\u203e')); // overline = spacing overscore, U+203E NEW
- refChar.put ("frasl", new Character ('\u2044')); // fraction slash, U+2044 NEW
- // Letterlike Symbols
- refChar.put ("weierp", new Character ('\u2118')); // script capital P = power set = Weierstrass p, U+2118 ISOamso
- refChar.put ("image", new Character ('\u2111')); // blackletter capital I = imaginary part, U+2111 ISOamso
- refChar.put ("real", new Character ('\u211c')); // blackletter capital R = real part symbol, U+211C ISOamso
- refChar.put ("trade", new Character ('\u2122')); // trade mark sign, U+2122 ISOnum
- refChar.put ("alefsym", new Character ('\u2135')); // alef symbol = first transfinite cardinal, U+2135 NEW
- // alef symbol is NOT the same as hebrew letter alef,
- // U+05D0 although the same glyph could be used to depict both characters
- // Arrows
- refChar.put ("larr", new Character ('\u2190')); // leftwards arrow, U+2190 ISOnum
- refChar.put ("uarr", new Character ('\u2191')); // upwards arrow, U+2191 ISOnum
- refChar.put ("rarr", new Character ('\u2192')); // rightwards arrow, U+2192 ISOnum
- refChar.put ("darr", new Character ('\u2193')); // downwards arrow, U+2193 ISOnum
- refChar.put ("harr", new Character ('\u2194')); // left right arrow, U+2194 ISOamsa
- refChar.put ("crarr", new Character ('\u21b5')); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW
- refChar.put ("lArr", new Character ('\u21d0')); // leftwards double arrow, U+21D0 ISOtech
- // ISO 10646 does not say that lArr is the same as the 'is implied by' arrow
- // but also does not have any other character for that function. So ? lArr can
- // be used for 'is implied by' as ISOtech suggests
- refChar.put ("uArr", new Character ('\u21d1')); // upwards double arrow, U+21D1 ISOamsa
- refChar.put ("rArr", new Character ('\u21d2')); // rightwards double arrow, U+21D2 ISOtech
- // ISO 10646 does not say this is the 'implies' character but does not have
- // another character with this function so ?
- // rArr can be used for 'implies' as ISOtech suggests
- refChar.put ("dArr", new Character ('\u21d3')); // downwards double arrow, U+21D3 ISOamsa
- refChar.put ("hArr", new Character ('\u21d4')); // left right double arrow, U+21D4 ISOamsa
- // Mathematical Operators
- refChar.put ("forall", new Character ('\u2200')); // for all, U+2200 ISOtech
- refChar.put ("part", new Character ('\u2202')); // partial differential, U+2202 ISOtech
- refChar.put ("exist", new Character ('\u2203')); // there exists, U+2203 ISOtech
- refChar.put ("empty", new Character ('\u2205')); // empty set = null set = diameter, U+2205 ISOamso
- refChar.put ("nabla", new Character ('\u2207')); // nabla = backward difference, U+2207 ISOtech
- refChar.put ("isin", new Character ('\u2208')); // element of, U+2208 ISOtech
- refChar.put ("notin", new Character ('\u2209')); // not an element of, U+2209 ISOtech
- refChar.put ("ni", new Character ('\u220b')); // contains as member, U+220B ISOtech
- // should there be a more memorable name than 'ni'?
- refChar.put ("prod", new Character ('\u220f')); // n-ary product = product sign, U+220F ISOamsb
- // prod is NOT the same character as U+03A0 'greek capital letter pi' though
- // the same glyph might be used for both
- refChar.put ("sum", new Character ('\u2211')); // n-ary sumation, U+2211 ISOamsb
- // sum is NOT the same character as U+03A3 'greek capital letter sigma'
- // though the same glyph might be used for both
- refChar.put ("minus", new Character ('\u2212')); // minus sign, U+2212 ISOtech
- refChar.put ("lowast", new Character ('\u2217')); // asterisk operator, U+2217 ISOtech
- refChar.put ("radic", new Character ('\u221a')); // square root = radical sign, U+221A ISOtech
- refChar.put ("prop", new Character ('\u221d')); // proportional to, U+221D ISOtech
- refChar.put ("infin", new Character ('\u221e')); // infinity, U+221E ISOtech
- refChar.put ("ang", new Character ('\u2220')); // angle, U+2220 ISOamso
- refChar.put ("and", new Character ('\u2227')); // logical and = wedge, U+2227 ISOtech
- refChar.put ("or", new Character ('\u2228')); // logical or = vee, U+2228 ISOtech
- refChar.put ("cap", new Character ('\u2229')); // intersection = cap, U+2229 ISOtech
- refChar.put ("cup", new Character ('\u222a')); // union = cup, U+222A ISOtech
- refChar.put ("int", new Character ('\u222b')); // integral, U+222B ISOtech
- refChar.put ("there4", new Character ('\u2234')); // therefore, U+2234 ISOtech
- refChar.put ("sim", new Character ('\u223c')); // tilde operator = varies with = similar to, U+223C ISOtech
- // tilde operator is NOT the same character as the tilde, U+007E,
- // although the same glyph might be used to represent both
- refChar.put ("cong", new Character ('\u2245')); // approximately equal to, U+2245 ISOtech
- refChar.put ("asymp", new Character ('\u2248')); // almost equal to = asymptotic to, U+2248 ISOamsr
- refChar.put ("ne", new Character ('\u2260')); // not equal to, U+2260 ISOtech
- refChar.put ("equiv", new Character ('\u2261')); // identical to, U+2261 ISOtech
- refChar.put ("le", new Character ('\u2264')); // less-than or equal to, U+2264 ISOtech
- refChar.put ("ge", new Character ('\u2265')); // greater-than or equal to, U+2265 ISOtech
- refChar.put ("sub", new Character ('\u2282')); // subset of, U+2282 ISOtech
- refChar.put ("sup", new Character ('\u2283')); // superset of, U+2283 ISOtech
- // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol
- // font encoding and is not included. Should it be, for symmetry?
- // It is in ISOamsn
- refChar.put ("nsub", new Character ('\u2284')); // not a subset of, U+2284 ISOamsn
- refChar.put ("sube", new Character ('\u2286')); // subset of or equal to, U+2286 ISOtech
- refChar.put ("supe", new Character ('\u2287')); // superset of or equal to, U+2287 ISOtech
- refChar.put ("oplus", new Character ('\u2295')); // circled plus = direct sum, U+2295 ISOamsb
- refChar.put ("otimes", new Character ('\u2297')); // circled times = vector product, U+2297 ISOamsb
- refChar.put ("perp", new Character ('\u22a5')); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech
- refChar.put ("sdot", new Character ('\u22c5')); // dot operator, U+22C5 ISOamsb
- // dot operator is NOT the same character as U+00B7 middle dot
- // Miscellaneous Technical
- refChar.put ("lceil", new Character ('\u2308')); // left ceiling = apl upstile, U+2308 ISOamsc
- refChar.put ("rceil", new Character ('\u2309')); // right ceiling, U+2309 ISOamsc
- refChar.put ("lfloor", new Character ('\u230a')); // left floor = apl downstile, U+230A ISOamsc
- refChar.put ("rfloor", new Character ('\u230b')); // right floor, U+230B ISOamsc
- refChar.put ("lang", new Character ('\u2329')); // left-pointing angle bracket = bra, U+2329 ISOtech
- // lang is NOT the same character as U+003C 'less than'
- // or U+2039 'single left-pointing angle quotation mark'
- refChar.put ("rang", new Character ('\u232a')); // right-pointing angle bracket = ket, U+232A ISOtech
- // rang is NOT the same character as U+003E 'greater than'
- // or U+203A 'single right-pointing angle quotation mark'
- // Geometric Shapes
- refChar.put ("loz", new Character ('\u25ca')); // lozenge, U+25CA ISOpub
- // Miscellaneous Symbols
- refChar.put ("spades", new Character ('\u2660')); // black spade suit, U+2660 ISOpub
- // black here seems to mean filled as opposed to hollow
- refChar.put ("clubs", new Character ('\u2663')); // black club suit = shamrock, U+2663 ISOpub
- refChar.put ("hearts", new Character ('\u2665')); // black heart suit = valentine, U+2665 ISOpub
- refChar.put ("diams", new Character ('\u2666')); // black diamond suit, U+2666 ISOpub
- // Special characters for HTML
- // Character entity set. Typical invocation:
- // <!ENTITY % HTMLspecial PUBLIC
- // "-//W3C//ENTITIES Special//EN//HTML">
- // %HTMLspecial;
- // Portions © International Organization for Standardization 1986:
- // Permission to copy in any form is granted for use with
- // conforming SGML systems and applications as defined in
- // ISO 8879, provided this notice is included in all copies.
- // Relevant ISO entity set is given unless names are newly introduced.
- // New names (i.e., not in ISO 8879 list) do not clash with any
- // existing ISO 8879 entity names. ISO 10646 character numbers
- // are given for each character, in hex. CDATA values are decimal
- // conversions of the ISO 10646 values and refer to the document
- // character set. Names are ISO 10646 names.
- // C0 Controls and Basic Latin
- refChar.put ("quot", new Character ('\u0022')); // quotation mark = APL quote, U+0022 ISOnum
- refChar.put ("amp", new Character ('\u0026')); // ampersand, U+0026 ISOnum
- refChar.put ("lt", new Character ('\u003c')); // less-than sign, U+003C ISOnum
- refChar.put ("gt", new Character ('\u003e')); // greater-than sign, U+003E ISOnum
- // Latin Extended-A
- refChar.put ("OElig", new Character ('\u0152')); // latin capital ligature OE, U+0152 ISOlat2
- refChar.put ("oelig", new Character ('\u0153')); // latin small ligature oe, U+0153 ISOlat2
- // ligature is a misnomer, this is a separate character in some languages
- refChar.put ("Scaron", new Character ('\u0160')); // latin capital letter S with caron, U+0160 ISOlat2
- refChar.put ("scaron", new Character ('\u0161')); // latin small letter s with caron, U+0161 ISOlat2
- refChar.put ("Yuml", new Character ('\u0178')); // latin capital letter Y with diaeresis, U+0178 ISOlat2
- // Spacing Modifier Letters
- refChar.put ("circ", new Character ('\u02c6')); // modifier letter circumflex accent, U+02C6 ISOpub
- refChar.put ("tilde", new Character ('\u02dc')); // small tilde, U+02DC ISOdia
- // General Punctuation
- refChar.put ("ensp", new Character ('\u2002')); // en space, U+2002 ISOpub
- refChar.put ("emsp", new Character ('\u2003')); // em space, U+2003 ISOpub
- refChar.put ("thinsp", new Character ('\u2009')); // thin space, U+2009 ISOpub
- refChar.put ("zwnj", new Character ('\u200c')); // zero width non-joiner, U+200C NEW RFC 2070
- refChar.put ("zwj", new Character ('\u200d')); // zero width joiner, U+200D NEW RFC 2070
- refChar.put ("lrm", new Character ('\u200e')); // left-to-right mark, U+200E NEW RFC 2070
- refChar.put ("rlm", new Character ('\u200f')); // right-to-left mark, U+200F NEW RFC 2070
- refChar.put ("ndash", new Character ('\u2013')); // en dash, U+2013 ISOpub
- refChar.put ("mdash", new Character ('\u2014')); // em dash, U+2014 ISOpub
- refChar.put ("lsquo", new Character ('\u2018')); // left single quotation mark, U+2018 ISOnum
- refChar.put ("rsquo", new Character ('\u2019')); // right single quotation mark, U+2019 ISOnum
- refChar.put ("sbquo", new Character ('\u201a')); // single low-9 quotation mark, U+201A NEW
- refChar.put ("ldquo", new Character ('\u201c')); // left double quotation mark, U+201C ISOnum
- refChar.put ("rdquo", new Character ('\u201d')); // right double quotation mark, U+201D ISOnum
- refChar.put ("bdquo", new Character ('\u201e')); // double low-9 quotation mark, U+201E NEW
- refChar.put ("dagger", new Character ('\u2020')); // dagger, U+2020 ISOpub
- refChar.put ("Dagger", new Character ('\u2021')); // double dagger, U+2021 ISOpub
- refChar.put ("permil", new Character ('\u2030')); // per mille sign, U+2030 ISOtech
- refChar.put ("lsaquo", new Character ('\u2039')); // single left-pointing angle quotation mark, U+2039 ISO proposed
- // lsaquo is proposed but not yet ISO standardized
- refChar.put ("rsaquo", new Character ('\u203a')); // single right-pointing angle quotation mark, U+203A ISO proposed
- // rsaquo is proposed but not yet ISO standardized
- refChar.put ("euro", new Character ('\u20ac')); // euro sign, U+20AC NEW
- }
-
- /**
- * Table mapping character to entity reference kernel.
- * <p><code>Character</code>-><code>String</code>
- */
- protected static Map charRefTable;
- static
- {
- charRefTable = new HashMap (refChar.size ());
- Iterator iterator = refChar.keySet ().iterator ();
- while (iterator.hasNext ())
- {
- String key = (String)iterator.next ();
- Character character = (Character)refChar.get (key);
- charRefTable.put (character, key);
- }
- }
-
- /**
- * Private constructor.
- * This class is fully static and thread safe.
- */
- private Translate ()
- {
- }
-
- /**
- * Convert a reference to a unicode character.
- * Convert a single numeric character reference or character entity reference
- * to a unicode character.
- * @param string The string to convert. Of the form &xxxx; or &#xxxx; with
- * or without the leading ampersand or trailing semi-colon.
- * @return The converted character or '\0' (zero) if the string is an
- * invalid reference.
- */
- public static char convertToChar (String string)
- {
- int length;
- Character item;
- char ret;
-
- ret = 0;
-
- length = string.length ();
- if (0 < length)
- {
- if ('&' == string.charAt (0))
- {
- string = string.substring (1);
- length--;
- }
- if (0 < length)
- {
- if (';' == string.charAt (length - 1))
- string = string.substring (0, --length);
- if (0 < length)
- {
- if ('#' == string.charAt (0))
- try
- {
- ret = (char)Integer.parseInt (string.substring (1));
- }
- catch (NumberFormatException nfe)
- {
- /* failed conversion, return 0 */
- }
- else
- {
- item = (Character)refChar.get (string);
- if (null != item)
- ret = item.charValue ();
- }
- }
- }
- }
-
- return (ret);
- }
-
- /**
- * Decode a string containing references.
- * Change all numeric character reference and character entity references
- * to unicode characters.
- * @param string The string to translate.
- */
- public static String decode (String string)
- {
- int index;
- int length;
- int amp;
- int semi;
- String code;
- char character;
- StringBuffer ret;
- ret = new StringBuffer (string.length ());
- index = 0;
- length = string.length ();
- while ((index < length) && (-1 != (amp = string.indexOf ('&', index))))
- {
- ret.append (string.substring (index, amp));
- index = amp + 1;
- if (amp < length - 1)
- {
- semi = string.indexOf (';', amp);
- if (-1 != semi)
- code = string.substring (amp, semi + 1);
- else
- code = string.substring (amp);
- if (0 != (character = convertToChar (code)))
- index += code.length () - 1;
- else
- character = '&';
- }
- else
- character = '&';
- ret.append (character);
- }
- if (index < length)
- ret.append (string.substring (index));
- return (ret.toString ());
- }
-
- /**
- * Convert a character to a character entity reference.
- * Convert a unicode character to a character entity reference of
- * the form &xxxx;.
- * @param character The character to convert.
- * @return The converted character or <code>null</code> if the character
- * is not one of the known entity references.
- */
- public static String convertToString (Character character)
- {
- StringBuffer buffer;
- String ret;
- if (null != (ret = (String)charRefTable.get (character)))
- {
- buffer = new StringBuffer (ret.length () + 2);
- buffer.append ('&');
- buffer.append (ret);
- buffer.append (';');
- ret = buffer.toString ();
- }
- return (ret);
- }
-
- /**
- * Convert a character to a numeric character reference.
- * Convert a unicode character to a numeric character reference of
- * the form &#xxxx;.
- * @param character The character to convert.
- * @return The converted character.
- */
- public static String convertToString (int character)
- {
- StringBuffer ret;
- ret = new StringBuffer (13); /* � */
- ret.append ("&#");
- ret.append (character);
- ret.append (';');
- return (ret.toString ());
- }
-
- /**
- * Encode a string to use references.
- * Change all characters that are not ASCII to their numeric character
- * reference or character entity reference.
- * This implementation is inefficient, allocating a new
- * <code>Character</code> for each character in the string,
- * but this class is primarily intended to decode strings
- * so efficiency and speed in the encoding was not a priority.
- * @param string The string to translate.
- */
- public static String encode (String string)
- {
- int length;
- char c;
- Character character;
- String value;
- StringBuffer ret;
- ret = new StringBuffer (string.length () * 6);
- length = string.length ();
- for (int i = 0; i < length; i++)
- {
- c = string.charAt (i);
- character = new Character (c);
- if (null != (value = convertToString (character)))
- ret.append (value);
- else if (!((c > 0x001F) && (c < 0x007F)))
- {
- value = convertToString (c);
- ret.append (value);
- }
- else
- ret.append (character);
- }
- return (ret.toString ());
- }
-}
}
public void setValue(String aKey, String aValue) {
- if (aValue!=null)
+ if (aValue!=null) {
keyValues.put(aKey, aValue);
- else
+ }
+ else {
deleteKey(aKey);
+ }
}
public void setValue(String aKey, int aValue) {
public String getQuery() {
StringBuffer query = new StringBuffer();
- Iterator i;
-
- i = keyValues.entrySet().iterator();
+ Iterator i = keyValues.entrySet().iterator();
while(i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
query.append("=");
query.append(HTMLRoutines.encodeURL((String) entry.getValue()));
- if (i.hasNext())
+ if (i.hasNext()) {
query.append("&");
+ }
}
return query.toString();
*/
package mir.util.generator;
+import java.util.ArrayList;
+import java.util.List;
+
import mir.bundle.Bundle;
import mir.generator.Generator;
import mir.generator.GeneratorExc;
-import java.util.ArrayList;
-import java.util.List;
-
/**
*
*/
*/\r
package mir.util.generator;\r
\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.List;\r
+\r
import mir.generator.Generator;\r
import mir.generator.GeneratorExc;\r
import mir.generator.GeneratorFailure;\r
import mir.util.ReflectionRoutines;\r
\r
-import java.util.List;\r
-import java.lang.reflect.InvocationTargetException;\r
-\r
-import org.apache.commons.beanutils.MethodUtils;\r
-\r
/**\r
* Class to adapt methods with some name to a\r
* {@link Generator.Function}\r
-package mir.util.xml;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public abstract class AbstractSectionHandler implements SectionHandler {\r
- public void extra(String anExtraData) throws XMLParserExc, XMLParserFailure {\r
- }\r
-\r
- public SectionHandler startElement(XMLName aTag, java.util.Map anAttributes) throws XMLParserExc{\r
- return startElement(aTag.getLocalName(), XMLReaderTool.convertXMLAttributeMap(anAttributes));\r
- };\r
-\r
- public SectionHandler startElement(String aLocalName, java.util.Map anAttributes) throws XMLParserExc{\r
- return new AbstractSectionHandler() {};\r
- };\r
-\r
- public void endElement(SectionHandler aHandler) throws XMLParserExc{\r
- };\r
-\r
- public void startSection() throws XMLParserExc{\r
- }\r
-\r
- public void finishSection() throws XMLParserExc{\r
- }\r
-\r
- public void characters(String aCharacters) throws XMLParserExc{\r
- if ( aCharacters.trim().length() > 0) {\r
- throw new XMLParserExc("Text not allowed");\r
- }\r
- }\r
-}\r
+package mir.util.xml;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public abstract class AbstractSectionHandler implements SectionHandler {
+ public void extra(String anExtraData) throws XMLParserExc, XMLParserFailure {
+ }
+
+ public SectionHandler startElement(XMLName aTag, java.util.Map anAttributes) throws XMLParserExc{
+ return startElement(aTag.getLocalName(), XMLReaderTool.convertXMLAttributeMap(anAttributes));
+ }
+
+ public SectionHandler startElement(String aLocalName, java.util.Map anAttributes) throws XMLParserExc{
+ return new AbstractSectionHandler() {};
+ }
+
+ public void endElement(SectionHandler aHandler) throws XMLParserExc{
+ }
+
+ public void startSection() throws XMLParserExc{
+ }
+
+ public void finishSection() throws XMLParserExc{
+ }
+
+ public void characters(String aCharacters) throws XMLParserExc{
+ if ( aCharacters.trim().length() > 0) {
+ throw new XMLParserExc("Text not allowed");
+ }
+ }
+}
-package mir.util.xml;\r
-\r
-/**\r
- * Class to encapsulate an XML-style name (either for tagnames,\r
- * or attribute names).\r
- *\r
- * <p>\r
- * Usage requirements:\r
- * <ul>\r
- * <li> Namespace aware parsers must supply a local name\r
- * and a namespace URI\r
- * <li> Non-namespace aware parsers should supply a local name,\r
- * and, if present and applicable, also a prefix\r
- * </ul>\r
- */\r
-\r
-public class XMLName {\r
- private String namespaceURI;\r
- private String localName;\r
- private String prefix;\r
-\r
- public XMLName(String aLocalName) {\r
- this(null, null, aLocalName);\r
- }\r
-\r
- public XMLName(String aNamespaceURI, String aPrefix, String aLocalName) {\r
- localName="";\r
- prefix="";\r
- namespaceURI="";\r
-\r
- if (aLocalName!=null)\r
- localName = aLocalName;\r
- if (aPrefix!=null)\r
- prefix = aPrefix;\r
- if (aNamespaceURI!=null)\r
- namespaceURI = aNamespaceURI;\r
- }\r
-\r
- public XMLName(String aNamespaceURI, String aLocalName) {\r
- this (aNamespaceURI, null, aLocalName);\r
- }\r
-\r
- /**\r
- * Returns the namespace URI if available\r
- */\r
- public String getNamespaceURI() {\r
- return namespaceURI;\r
- }\r
-\r
- /**\r
- * Returns the name of the tag, stripped from prefix\r
- */\r
- public String getLocalName() {\r
- return localName;\r
- }\r
-\r
- /**\r
- * Returns the prefix of the tag, if present\r
- */\r
- public String getPrefix() {\r
- return prefix;\r
- }\r
-\r
- public int hashCode() {\r
- if (namespaceURI == null)\r
- return localName.hashCode() + 3*prefix.hashCode();\r
- else\r
- return localName.hashCode() + 3*namespaceURI.hashCode();\r
- }\r
-\r
- public String toString() {\r
- return ((namespaceURI.length()>0)? "["+namespaceURI+"]":"")+((prefix.length()>0)?prefix+":":"")+localName;\r
- }\r
-\r
- public boolean equals(Object anObject) {\r
- if (anObject instanceof mir.util.xml.XMLName) {\r
- if (namespaceURI==null)\r
- return (((mir.util.xml.XMLName) anObject).namespaceURI == null) &&\r
- prefix.equals(((mir.util.xml.XMLName) anObject).prefix) &&\r
- localName.equals(((mir.util.xml.XMLName) anObject).localName);\r
- else\r
- return namespaceURI.equals(((mir.util.xml.XMLName) anObject).namespaceURI) &&\r
- localName.equals(((mir.util.xml.XMLName) anObject).localName);\r
- }\r
- else\r
- return false;\r
- }\r
-}\r
+package mir.util.xml;
+
+/**
+ * Class to encapsulate an XML-style name (either for tagnames,
+ * or attribute names).
+ *
+ * <p>
+ * Usage requirements:
+ * <ul>
+ * <li> Namespace aware parsers must supply a local name
+ * and a namespace URI
+ * <li> Non-namespace aware parsers should supply a local name,
+ * and, if present and applicable, also a prefix
+ * </ul>
+ */
+
+public class XMLName {
+ private String namespaceURI;
+ private String localName;
+ private String prefix;
+
+ public XMLName(String aLocalName) {
+ this(null, null, aLocalName);
+ }
+
+ public XMLName(String aNamespaceURI, String aPrefix, String aLocalName) {
+ localName="";
+ prefix="";
+ namespaceURI="";
+
+ if (aLocalName!=null)
+ localName = aLocalName;
+ if (aPrefix!=null)
+ prefix = aPrefix;
+ if (aNamespaceURI!=null)
+ namespaceURI = aNamespaceURI;
+ }
+
+ public XMLName(String aNamespaceURI, String aLocalName) {
+ this (aNamespaceURI, null, aLocalName);
+ }
+
+ /**
+ * Returns the namespace URI if available
+ */
+ public String getNamespaceURI() {
+ return namespaceURI;
+ }
+
+ /**
+ * Returns the name of the tag, stripped from prefix
+ */
+ public String getLocalName() {
+ return localName;
+ }
+
+ /**
+ * Returns the prefix of the tag, if present
+ */
+ public String getPrefix() {
+ return prefix;
+ }
+
+ public int hashCode() {
+ if (namespaceURI == null)
+ return localName.hashCode() + 3*prefix.hashCode();
+ return localName.hashCode() + 3*namespaceURI.hashCode();
+ }
+
+ public String toString() {
+ return ((namespaceURI.length()>0)? "["+namespaceURI+"]":"")+((prefix.length()>0)?prefix+":":"")+localName;
+ }
+
+ public boolean equals(Object anObject) {
+ if (anObject instanceof mir.util.xml.XMLName) {
+ if (namespaceURI==null)
+ return (((mir.util.xml.XMLName) anObject).namespaceURI == null) &&
+ prefix.equals(((mir.util.xml.XMLName) anObject).prefix) &&
+ localName.equals(((mir.util.xml.XMLName) anObject).localName);
+ else
+ return namespaceURI.equals(((mir.util.xml.XMLName) anObject).namespaceURI) &&
+ localName.equals(((mir.util.xml.XMLName) anObject).localName);
+ }
+ return false;
+ }
+}
package mir.util.xml;
import java.io.BufferedInputStream;
+import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
-import java.io.StringReader;
-import java.io.File;
-import java.io.Reader;
import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
-
import java.util.Stack;
-import mir.util.ExceptionFunctions;
+import mir.util.ExceptionRoutines;
import mir.util.xml.html.XMLHTMLParserProvider;
public class XMLParserEngine {
provider.parse(aReader, runner);
}
catch (Throwable e) {
- Throwable t = ExceptionFunctions.traceCauseException(e);
+ Throwable t = ExceptionRoutines.traceCauseException(e);
if (t instanceof XMLParserExc && runner.getLocator()!=null) {
((XMLParserExc) t).setLocation(runner.getLocator().getLineNr(), runner.getLocator().getColumnNr());
-package mir.util.xml;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class XMLParserFailure extends multex.Failure {\r
- public XMLParserFailure(String aMessage, Throwable aCause) {\r
- super(aMessage, aCause);\r
- }\r
-\r
- public XMLParserFailure(Throwable aCause) {\r
- super(aCause.getMessage(), aCause);\r
- }\r
-}\r
+package mir.util.xml;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+public class XMLParserFailure extends multex.Failure {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public XMLParserFailure(String aMessage, Throwable aCause) {
+ super(aMessage, aCause);
+ }
+
+ public XMLParserFailure(Throwable aCause) {
+ super(aCause.getMessage(), aCause);
+ }
+}
if (parts.size()==1)
return (String) parts.get(0);
- else
- return (String) parts.get(1);
+ return (String) parts.get(1);
}
/**
-package mir.util.xml;\r
-\r
-import java.util.*;\r
-\r
-import org.xml.sax.InputSource;\r
-import org.xml.sax.SAXException;\r
-import org.xml.sax.Locator;\r
-import org.xml.sax.SAXParseException;\r
-import mir.util.ExceptionFunctions;\r
-\r
-/**\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-class XMLSAXParserProvider implements XMLParserEngine.XMLParserProvider {\r
- private boolean nameSpaceAware;\r
-\r
- public XMLSAXParserProvider(boolean aNameSpaceAware) {\r
- nameSpaceAware = aNameSpaceAware;\r
- }\r
-\r
- public void parse(java.io.Reader aReader, XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {\r
- try {\r
- javax.xml.parsers.SAXParserFactory parserFactory = javax.xml.parsers.SAXParserFactory.newInstance();\r
-\r
- parserFactory.setNamespaceAware(true);\r
- parserFactory.setValidating(true);\r
- javax.xml.parsers.SAXParser parser = parserFactory.newSAXParser();\r
-\r
- parser.parse(new InputSource(aReader), new SAXHandler(aReceiver));\r
- }\r
- catch (org.xml.sax.SAXException e) {\r
- Throwable t = ExceptionFunctions.traceCauseException(e);\r
-\r
- if (t instanceof XMLParserExc) {\r
- throw (XMLParserExc) t;\r
- }\r
-\r
- if (t instanceof XMLParserFailure) {\r
- throw (XMLParserFailure) t;\r
- }\r
-\r
- if (t instanceof SAXParseException) {\r
- throw new XMLParserExc(t.getMessage());\r
- }\r
-\r
- throw new XMLParserFailure(t);\r
- }\r
- catch (Throwable t) {\r
- throw new XMLParserFailure(t);\r
- }\r
- }\r
-\r
- private class SAXHandler extends org.xml.sax.helpers.DefaultHandler {\r
- private XMLParserEngine.XMLParserReceiver receiver;\r
-\r
- public SAXHandler(XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {\r
- super();\r
-\r
- receiver = aReceiver;\r
- receiver.startDocument();\r
- }\r
-\r
- public void setDocumentLocator(final Locator aLocator) {\r
- receiver.setLocator(\r
- new XMLParserEngine.XMLLocator() {\r
- public int getLineNr() {\r
- return aLocator.getLineNumber();\r
- }\r
-\r
- public int getColumnNr() {\r
- return aLocator.getColumnNumber();\r
- }\r
- }\r
- );\r
- }\r
-\r
- public void startElement(String aUri, String aLocalName, String aQualifiedName, org.xml.sax.Attributes anAttributes) throws org.xml.sax.SAXException {\r
- try {\r
- Map attributes = new java.util.HashMap();\r
-\r
- XMLName tag;\r
- if (nameSpaceAware) {\r
- tag = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName), aLocalName);\r
- for (int i=0; i<anAttributes.getLength(); i++)\r
- attributes.put(\r
- new XMLName(anAttributes.getURI(i),\r
- XMLReaderTool.getPrefixFromQualifiedName(anAttributes.getQName(i)),\r
- anAttributes.getLocalName(i)),\r
- anAttributes.getValue(i));\r
- }\r
- else {\r
- tag = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName),\r
- XMLReaderTool.getLocalNameFromQualifiedName(aQualifiedName));\r
- for (int i=0; i<anAttributes.getLength(); i++)\r
- attributes.put(\r
- new XMLName(anAttributes.getURI(i),\r
- XMLReaderTool.getPrefixFromQualifiedName(anAttributes.getQName(i)),\r
- XMLReaderTool.getLocalNameFromQualifiedName(anAttributes.getQName(i))),\r
- anAttributes.getValue(i));\r
- }\r
-\r
- receiver.startElement(tag, attributes);\r
- }\r
- catch (XMLParserExc e) {\r
- throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);\r
- }\r
- catch (Exception e) {\r
- throw new SAXException(e);\r
- }\r
- }\r
-\r
- public void endElement(String aUri, String aLocalName, String aQualifiedName) throws org.xml.sax.SAXException {\r
- try\r
- {\r
- XMLName element = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName), aLocalName);\r
-\r
- receiver.endElement(element);\r
- }\r
- catch (XMLParserExc e) {\r
- throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);\r
- }\r
- catch (Exception e) {\r
- throw new org.xml.sax.SAXException(e);\r
- }\r
- }\r
-\r
- public void endDocument() throws org.xml.sax.SAXException {\r
- try\r
- {\r
- receiver.endDocument();\r
- }\r
- catch (XMLParserExc e) {\r
- throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);\r
- }\r
- catch (Exception e) {\r
- throw new org.xml.sax.SAXException(e);\r
- }\r
- }\r
-\r
- public void characters(char[] aBuffer, int aStart, int anEnd) throws org.xml.sax.SAXException {\r
- try {\r
- String text = new String(aBuffer, aStart, anEnd);\r
-\r
- receiver.text(text);\r
- }\r
- catch (XMLParserExc e) {\r
- throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);\r
- }\r
- catch (Exception e) {\r
- throw new org.xml.sax.SAXException(e);\r
- }\r
- }\r
- }\r
-}\r
+package mir.util.xml;
+
+import java.util.Map;
+
+import mir.util.ExceptionRoutines;
+
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+class XMLSAXParserProvider implements XMLParserEngine.XMLParserProvider {
+ private boolean nameSpaceAware;
+
+ public XMLSAXParserProvider(boolean aNameSpaceAware) {
+ nameSpaceAware = aNameSpaceAware;
+ }
+
+ public void parse(java.io.Reader aReader, XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {
+ try {
+ javax.xml.parsers.SAXParserFactory parserFactory = javax.xml.parsers.SAXParserFactory.newInstance();
+
+ parserFactory.setNamespaceAware(true);
+ parserFactory.setValidating(true);
+ javax.xml.parsers.SAXParser parser = parserFactory.newSAXParser();
+
+ parser.parse(new InputSource(aReader), new SAXHandler(aReceiver));
+ }
+ catch (org.xml.sax.SAXException e) {
+ Throwable t = ExceptionRoutines.traceCauseException(e);
+
+ if (t instanceof XMLParserExc) {
+ throw (XMLParserExc) t;
+ }
+
+ if (t instanceof XMLParserFailure) {
+ throw (XMLParserFailure) t;
+ }
+
+ if (t instanceof SAXParseException) {
+ throw new XMLParserExc(t.getMessage());
+ }
+
+ throw new XMLParserFailure(t);
+ }
+ catch (Throwable t) {
+ throw new XMLParserFailure(t);
+ }
+ }
+
+ private class SAXHandler extends org.xml.sax.helpers.DefaultHandler {
+ private XMLParserEngine.XMLParserReceiver receiver;
+
+ public SAXHandler(XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {
+ super();
+
+ receiver = aReceiver;
+ receiver.startDocument();
+ }
+
+ public void setDocumentLocator(final Locator aLocator) {
+ receiver.setLocator(
+ new XMLParserEngine.XMLLocator() {
+ public int getLineNr() {
+ return aLocator.getLineNumber();
+ }
+
+ public int getColumnNr() {
+ return aLocator.getColumnNumber();
+ }
+ }
+ );
+ }
+
+ public void startElement(String aUri, String aLocalName, String aQualifiedName, org.xml.sax.Attributes anAttributes) throws org.xml.sax.SAXException {
+ try {
+ Map attributes = new java.util.HashMap();
+
+ XMLName tag;
+ if (nameSpaceAware) {
+ tag = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName), aLocalName);
+ for (int i=0; i<anAttributes.getLength(); i++)
+ attributes.put(
+ new XMLName(anAttributes.getURI(i),
+ XMLReaderTool.getPrefixFromQualifiedName(anAttributes.getQName(i)),
+ anAttributes.getLocalName(i)),
+ anAttributes.getValue(i));
+ }
+ else {
+ tag = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName),
+ XMLReaderTool.getLocalNameFromQualifiedName(aQualifiedName));
+ for (int i=0; i<anAttributes.getLength(); i++)
+ attributes.put(
+ new XMLName(anAttributes.getURI(i),
+ XMLReaderTool.getPrefixFromQualifiedName(anAttributes.getQName(i)),
+ XMLReaderTool.getLocalNameFromQualifiedName(anAttributes.getQName(i))),
+ anAttributes.getValue(i));
+ }
+
+ receiver.startElement(tag, attributes);
+ }
+ catch (XMLParserExc e) {
+ throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);
+ }
+ catch (Exception e) {
+ throw new SAXException(e);
+ }
+ }
+
+ public void endElement(String aUri, String aLocalName, String aQualifiedName) throws org.xml.sax.SAXException {
+ try
+ {
+ XMLName element = new XMLName(aUri, XMLReaderTool.getPrefixFromQualifiedName(aQualifiedName), aLocalName);
+
+ receiver.endElement(element);
+ }
+ catch (XMLParserExc e) {
+ throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);
+ }
+ catch (Exception e) {
+ throw new org.xml.sax.SAXException(e);
+ }
+ }
+
+ public void endDocument() throws org.xml.sax.SAXException {
+ try
+ {
+ receiver.endDocument();
+ }
+ catch (XMLParserExc e) {
+ throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);
+ }
+ catch (Exception e) {
+ throw new org.xml.sax.SAXException(e);
+ }
+ }
+
+ public void characters(char[] aBuffer, int aStart, int anEnd) throws org.xml.sax.SAXException {
+ try {
+ String text = new String(aBuffer, aStart, anEnd);
+
+ receiver.text(text);
+ }
+ catch (XMLParserExc e) {
+ throw new org.xml.sax.SAXParseException(e.getMessage(), null, e);
+ }
+ catch (Exception e) {
+ throw new org.xml.sax.SAXException(e);
+ }
+ }
+ }
+}
package mir.util.xml.html;
-import java.io.*;
-import java.util.*;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Stack;
/**
*
package mir.util.xml.html;
+import mir.util.HTMLRoutines;
+
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
-import mir.util.HTMLRoutines;
-
public class HTMLScanner {
private ReaderWrapper reader;
private ScannerReceiver receiver;
reader.get();
readEndTag();
break;
+ case '<':
+ receiver.handleCData(new String(new char[] {c }));
+ break;
default:
readTag();
}
if (result.length()==0)
return null;
- else
- return result.toString();
+ return result.toString();
}
private String getAttributeValue() throws IOException {
return;
}
- else {
- result.append('-');
- }
+ result.append('-');
}
while (!reader.isAtEnd() && reader.peek()!='>') {
result.append(reader.get());
}
-
-
receiver.handleCData(HTMLRoutines.resolveHTMLEntites(result.toString()));
}
package mir.util.xml.html;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class HTMLSchemaInformation {
private Map tags;
-package mir.util.xml.html;\r
-\r
-import java.io.IOException;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-\r
-import mir.util.xml.XMLParserEngine;\r
-import mir.util.xml.XMLParserExc;\r
-import mir.util.xml.XMLParserFailure;\r
-import mir.util.xml.XMLReaderTool;\r
-import mir.util.xml.XMLName;\r
-\r
-/**\r
- */\r
-\r
-public class XMLHTMLParserProvider implements XMLParserEngine.XMLParserProvider {\r
- public XMLHTMLParserProvider() {\r
- }\r
-\r
- public void parse(java.io.Reader aReader, final XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {\r
- HTMLParser parser = new HTMLParser();\r
-\r
- try {\r
- aReceiver.startDocument();\r
-\r
- parser.parse(aReader, new HTMLParser.ParserReceiver() {\r
- public void dtd(String aDTD) throws HTMLParserExc {\r
- try {\r
- aReceiver.extra(aDTD);\r
- }\r
- catch (XMLParserExc t) {\r
- throw new HTMLParserFailure(t);\r
- }\r
- }\r
-\r
- public void openTag(String aTag, Map anAttributes) {\r
- Map attributes = new HashMap();\r
- Iterator i = anAttributes.entrySet().iterator();\r
-\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
- XMLName key = XMLReaderTool.getXMLNameForQualifiedName((String) entry.getKey());\r
- String value = (String) entry.getValue();\r
- if (value==null)\r
- value = key.getLocalName();\r
-\r
- attributes.put(key, value);\r
- }\r
-\r
- try {\r
- aReceiver.startElement(XMLReaderTool.getXMLNameForQualifiedName(aTag), attributes);\r
- }\r
- catch (XMLParserExc e) {\r
- throw new HTMLParserFailure(e);\r
- }\r
- }\r
-\r
- public void closeTag(String aTag) {\r
- try {\r
- aReceiver.endElement(XMLReaderTool.getXMLNameForQualifiedName(aTag));\r
- }\r
- catch (XMLParserExc e) {\r
- throw new HTMLParserFailure(e);\r
- }\r
- }\r
-\r
- public void comment(String aData) {\r
- try {\r
- aReceiver.extra("<!--"+aData+"-->");\r
- }\r
- catch (XMLParserExc e) {\r
- throw new HTMLParserFailure(e);\r
- }\r
- }\r
-\r
- public void cdata(String aData) {\r
- try {\r
- aReceiver.text(aData);\r
- }\r
- catch (XMLParserExc e) {\r
- throw new HTMLParserFailure(e);\r
- }\r
- }\r
- });\r
-\r
- aReceiver.endDocument();\r
- }\r
- catch (IOException e) {\r
- throw new XMLParserFailure(e);\r
- }\r
- catch (HTMLParserExc e) {\r
- throw new XMLParserFailure(e);\r
- }\r
- }\r
-}\r
+package mir.util.xml.html;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import mir.util.xml.XMLName;
+import mir.util.xml.XMLParserEngine;
+import mir.util.xml.XMLParserExc;
+import mir.util.xml.XMLParserFailure;
+import mir.util.xml.XMLReaderTool;
+
+/**
+ */
+
+public class XMLHTMLParserProvider implements XMLParserEngine.XMLParserProvider {
+ public XMLHTMLParserProvider() {
+ }
+
+ public void parse(java.io.Reader aReader, final XMLParserEngine.XMLParserReceiver aReceiver) throws XMLParserExc, XMLParserFailure {
+ HTMLParser parser = new HTMLParser();
+
+ try {
+ aReceiver.startDocument();
+
+ parser.parse(aReader, new HTMLParser.ParserReceiver() {
+ public void dtd(String aDTD) throws HTMLParserExc {
+ try {
+ aReceiver.extra(aDTD);
+ }
+ catch (XMLParserExc t) {
+ throw new HTMLParserFailure(t);
+ }
+ }
+
+ public void openTag(String aTag, Map anAttributes) {
+ Map attributes = new HashMap();
+ Iterator i = anAttributes.entrySet().iterator();
+
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry) i.next();
+ XMLName key = XMLReaderTool.getXMLNameForQualifiedName((String) entry.getKey());
+ String value = (String) entry.getValue();
+ if (value==null)
+ value = key.getLocalName();
+
+ attributes.put(key, value);
+ }
+
+ try {
+ aReceiver.startElement(XMLReaderTool.getXMLNameForQualifiedName(aTag), attributes);
+ }
+ catch (XMLParserExc e) {
+ throw new HTMLParserFailure(e);
+ }
+ }
+
+ public void closeTag(String aTag) {
+ try {
+ aReceiver.endElement(XMLReaderTool.getXMLNameForQualifiedName(aTag));
+ }
+ catch (XMLParserExc e) {
+ throw new HTMLParserFailure(e);
+ }
+ }
+
+ public void comment(String aData) {
+ try {
+ aReceiver.extra("<!--"+aData+"-->");
+ }
+ catch (XMLParserExc e) {
+ throw new HTMLParserFailure(e);
+ }
+ }
+
+ public void cdata(String aData) {
+ try {
+ aReceiver.text(aData);
+ }
+ catch (XMLParserExc e) {
+ throw new HTMLParserFailure(e);
+ }
+ }
+ });
+
+ aReceiver.endDocument();
+ }
+ catch (IOException e) {
+ throw new XMLParserFailure(e);
+ }
+ catch (HTMLParserExc e) {
+ throw new XMLParserFailure(e);
+ }
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.abuse;\r
+\r
+\r
+public abstract class AbstractFilterType implements FilterType {\r
+ private String name;\r
+\r
+ public AbstractFilterType(String aName) {\r
+ name = aName;\r
+ }\r
+\r
+ public String getName() {\r
+ return name;\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License, \r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library \r
+ * (or with modified versions of the above that use the same license as the above), \r
+ * and distribute linked combinations including the two. You must obey the \r
+ * GNU General Public License in all respects for all of the code used other than \r
+ * the above mentioned libraries. If you modify this file, you may extend this \r
+ * exception to your version of the file, but you are not obligated to do so. \r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.abuse;\r
+\r
+import multex.Exc;\r
+\r
+public class AbuseExc extends Exc {\r
+ public AbuseExc(String aMessage) {\r
+ super(aMessage);\r
+ }\r
+}\r
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License, \r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library \r
+ * (or with modified versions of the above that use the same license as the above), \r
+ * and distribute linked combinations including the two. You must obey the \r
+ * GNU General Public License in all respects for all of the code used other than \r
+ * the above mentioned libraries. If you modify this file, you may extend this \r
+ * exception to your version of the file, but you are not obligated to do so. \r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.abuse;\r
+\r
+import multex.Failure;\r
+\r
+public class AbuseFailure extends Failure {\r
+\r
+ public AbuseFailure(String msg,Throwable cause) {\r
+ super(msg,cause);\r
+ }\r
+\r
+ public AbuseFailure(Throwable aCause) {\r
+ this (aCause.getMessage(), aCause);\r
+ }\r
+}\r
--- /dev/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 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.abuse;
+
+import mir.entity.Entity;
+import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.storage.DatabaseExc;
+import mir.storage.DatabaseHelper;
+import mircoders.global.MirGlobal;
+import mircoders.storage.DatabaseFilter;
+import mircoders.storage.DatabaseFilterGroup;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+/** The FilterEngine manages a list of all filters and filter groups.
+ * Use the testPosting() method to apply all filters on an
+ * Entity (for ex. an article or a comment)
+ */
+public class FilterEngine {
+ private final Map filterTypes = new HashMap();
+ private final List filterTypeIds = new ArrayList();
+
+ private final List filterGroups = new ArrayList();
+ private final Map idToFilterGroup = new HashMap();
+ private final LoggerWrapper logger = new LoggerWrapper("Global.Abuse.FilterEngine");
+ private EntityAdapterModel model;
+
+ public FilterEngine(EntityAdapterModel aModel) {
+ try {
+ Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
+ while (i.hasNext()) {
+ FilterType filterType = (FilterType) i.next();
+
+ filterTypes.put(filterType.getName(), filterType);
+ filterTypeIds.add(filterType.getName());
+ }
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+
+ model = aModel;
+
+ reload();
+ }
+
+ /** applies all filters from all filter groups to an Entity.
+ * The entity may be, for example, an article, or a comment.
+ * It returns a filter that matches if it finds one, null otherwise
+ */
+ public synchronized Filter testPosting(Entity anEntity, Request aRequest) {
+ Iterator i = filterGroups.iterator();
+ while (i.hasNext()) {
+ FilterGroup group = (FilterGroup) i.next();
+
+ Iterator j = group.getFilters().iterator();
+ while (j.hasNext()) {
+ Filter filter = (Filter) j.next();
+ try {
+ if (filter.test(anEntity, aRequest)) {
+ return filter;
+ }
+ }
+ catch (Throwable t) {
+ logger.warn("Exception thrown while testing filter " + filter.getType() + " ( " + filter.getExpression() + ") " + t.toString());
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public List getFilterTypes() {
+ try {
+ List result = new ArrayList();
+
+ Iterator i = filterTypeIds.iterator();
+ while (i.hasNext()) {
+ String id = (String) i.next();
+
+ Map action = new HashMap();
+ action.put("resource", id);
+ action.put("identifier", id);
+
+ result.add(action);
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException("can't get article actions: " + t.getMessage());
+ }
+ }
+ /** This class reflects a row of the filter_group
+ * database table. Filters groups allow you to organize
+ * your filters. For example: group1=spammer ,
+ * group2=nazis etc.
+ */
+ public class FilterGroup {
+ private List filters;
+ private Entity entity;
+ private Map idToFilter;
+
+ public FilterGroup(Entity anEntity) {
+ this (anEntity, Collections.EMPTY_LIST);
+ }
+
+ public FilterGroup(Entity anEntity, List aFilters) {
+ entity = anEntity;
+ filters = new ArrayList();
+ idToFilter = new HashMap();
+ Iterator i = aFilters.iterator();
+
+ while (i.hasNext()) {
+ Entity entity = (Entity) i.next();
+ try {
+ Filter filter = new Filter(entity);
+ introduceFilter(filter);
+ }
+ catch (AbuseExc e) {
+ }
+ }
+ }
+
+ public Entity getEntity() {
+ return entity;
+ }
+
+ public EntityAdapter getEntityAdapter() {
+ return model.makeEntityAdapter("filterGroup", entity);
+ }
+
+ public List getFilterEntityAdapterList() {
+ List result = new ArrayList();
+
+ Iterator i = filters.iterator();
+ while (i.hasNext()) {
+ Filter filter = (Filter) i.next();
+ result.add(filter.getEntityAdapter());
+ }
+
+ return result;
+ }
+
+ public List getFilters() {
+ return filters;
+ }
+
+ public Filter getFilterForId(String anId) {
+ Filter result = (Filter) idToFilter.get(anId);
+ if (result==null) {
+ throw new NullPointerException("No such filter");
+ }
+
+ return result;
+ }
+
+ private void introduceFilter(Filter aFilter) {
+ filters.add(aFilter);
+ idToFilter.put(aFilter.getEntity().getId(), aFilter);
+ }
+
+ private void removeFilter(Filter aFilter) {
+ filters.remove(aFilter);
+ idToFilter.remove(aFilter.getEntity().getId());
+ }
+
+ private void deleteFilter(String anId) {
+ Filter filter = getFilterForId(anId);
+ removeFilter(filter);
+ DatabaseFilter.getInstance().delete(anId);
+ }
+
+ public void populateFilterEntity(Entity anEntity, String aType, String anExpression,
+ String aComments, String aTag, String anArticleAction,
+ String aCommentAction) {
+
+ anEntity.setFieldValue("type", aType);
+ anEntity.setFieldValue("expression", anExpression);
+ anEntity.setFieldValue("comment", aComments);
+ anEntity.setFieldValue("tag", aTag);
+ anEntity.setFieldValue("articleaction", anArticleAction);
+ anEntity.setFieldValue("commentaction", aCommentAction);
+ }
+
+ public String updateFilter(String anId, String aType, String anExpression,
+ String aComments, String aTag, String anArticleAction,
+ String aCommentAction) {
+
+ try {
+ getFilterTypeForId(aType).constructFilterInstance(anExpression);
+ }
+ catch (AbuseExc e) {
+ return e.getMessage();
+ }
+
+ Entity entity = getFilterForId(anId).getEntity();
+ populateFilterEntity(entity, aType, anExpression, aComments, aTag,
+ anArticleAction, aCommentAction);
+ entity.update();
+
+ return "";
+ }
+
+ public String createFilter(String aType, String anExpression,
+ String aComments, String aTag, String anArticleAction,
+ String aCommentAction) throws DatabaseExc {
+ FilterInstance instance;
+
+ try {
+ instance = getFilterTypeForId(aType).constructFilterInstance(anExpression);
+ }
+ catch (AbuseExc e) {
+ return e.getMessage();
+ }
+
+ Entity entity = DatabaseFilter.getInstance().createNewEntity();
+ populateFilterEntity(entity, aType, anExpression, aComments, aTag,
+ anArticleAction, aCommentAction);
+
+
+ String priority = "1";
+
+ if (filters.size() > 0) {
+ try {
+ String lastPriorityString = ((Filter) filters.get(filters.size()-1)).getEntity().getFieldValue("priority");
+ int lastPriority = Integer.parseInt(lastPriorityString);
+ priority = Integer.toString(lastPriority + 1);
+ }
+ catch (Exception e) {
+ }
+ }
+
+ entity.setFieldValue("priority", priority);
+ entity.setFieldValue("filter_group_id", getEntity().getId());
+ entity.insert();
+
+ Filter filter = new Filter(entity, instance);
+ introduceFilter(filter);
+
+ return "";
+ }
+
+ public String moveFilterUp(String anId) {
+ Filter filter = getFilterForId(anId);
+ String priority = filter.getEntity().getFieldValue("priority");
+ int index = filters.indexOf(filter);
+ if (index>=1) {
+ Filter filterBefore= (Filter) filters.remove(index-1);
+ filters.add(index, filterBefore);
+ filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
+ filterBefore.getEntity().setFieldValue("priority", priority);
+ filter.getEntity().update();
+ filterBefore.getEntity().update();
+ }
+
+ return "";
+ }
+
+ public String moveFilterToTop(String anId) {
+ Filter filter = getFilterForId(anId);
+ String priority = filter.getEntity().getFieldValue("priority");
+ int index = filters.indexOf(filter);
+ if (index>0) {
+ filters.remove(index);
+ Filter filterBefore= (Filter) filters.get(0);
+ filters.add(0, filter);
+ filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
+ filterBefore.getEntity().setFieldValue("priority", priority);
+ filter.getEntity().update();
+ filterBefore.getEntity().update();
+ }
+
+ return "";
+ }
+
+ public String moveFilterDown(String anId) {
+ Filter filter = getFilterForId(anId);
+ String priority = filter.getEntity().getFieldValue("priority");
+ int index = filters.indexOf(filter);
+ if (index<filters.size()-1) {
+ Filter filterAfter = (Filter) filters.remove(index+1);
+ filters.add(index, filterAfter);
+ filter.getEntity().setFieldValue("priority", filterAfter.getEntity().getFieldValue("priority"));
+ filterAfter.getEntity().setFieldValue("priority", priority);
+ filter.getEntity().update();
+ filterAfter.getEntity().update();
+ }
+
+ return "";
+ }
+
+ public String moveFilterToBottom(String anId) {
+ Filter filter = getFilterForId(anId);
+ String priority = filter.getEntity().getFieldValue("priority");
+ int index = filters.indexOf(filter);
+ if (index>=0 && index<filters.size()-1) {
+ filters.remove(index);
+ Filter filterBefore= (Filter) filters.get(filters.size()-1);
+ filters.add(filters.size(), filter);
+ filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
+ filterBefore.getEntity().setFieldValue("priority", priority);
+ filter.getEntity().update();
+ filterBefore.getEntity().update();
+ }
+
+ return "";
+ }
+
+
+ public String getName() {
+ return entity.getFieldValue("name");
+ }
+ }
+
+ /** This class reflects a row of the filter database table.
+ * To actually run a filter on data, use the test() method.
+ * This class will automatically retreive and use the correct
+ * filter type.
+ */
+ public class Filter {
+ private Entity entity;
+ private FilterInstance instance;
+
+ public Filter(Entity anEntity) throws AbuseExc {
+ this(anEntity, getFilterTypeForId(anEntity.getFieldValue("type")).constructFilterInstance(anEntity.getFieldValue("expression")));
+ }
+
+ public Filter(Entity anEntity, FilterInstance anInstance) {
+ entity = anEntity;
+ instance = anInstance;
+ }
+
+ public Entity getEntity() {
+ return entity;
+ }
+
+ public EntityAdapter getEntityAdapter() {
+ return model.makeEntityAdapter("filter", entity);
+ }
+
+ public void update(String aType, String anExpression, String aComments, String aTag,
+ String anArticleAction, String aCommentAction) throws AbuseExc {
+
+ instance = getFilterTypeForId(aType).constructFilterInstance(anExpression);
+
+ entity.setFieldValue("type", aType);
+ entity.setFieldValue("expression", anExpression);
+ entity.setFieldValue("tag", aType);
+ entity.setFieldValue("comment", aComments);
+ entity.setFieldValue("articleaction", anArticleAction);
+ entity.setFieldValue("commentaction", aCommentAction);
+ entity.setFieldValue("last_hit", null);
+ entity.update();
+ }
+
+ public void updateLastHit(Date aDate) {
+ entity.setFieldValue("last_hit",
+ DatabaseHelper.convertDateToInternalRepresenation(
+ new Date(System.currentTimeMillis())));
+ entity.update();
+ }
+
+ public String getType() {
+ return entity.getFieldValue("type");
+ }
+
+ public String getExpression() {
+ return entity.getFieldValue("expression");
+ }
+
+ public String getTag() {
+ return entity.getFieldValue("tag");
+ }
+
+ public String getComment() {
+ return entity.getFieldValue("comment");
+ }
+
+ public String getArticleAction() {
+ return entity.getFieldValue("articleaction");
+ }
+
+ public String getCommentAction() {
+ return entity.getFieldValue("commentaction");
+ }
+
+ public FilterInstance getInstance() {
+ return instance;
+ }
+
+ public boolean test(Entity anEntity, Request aRequest) {
+ return instance.test(anEntity, aRequest);
+ }
+ }
+
+ public synchronized void reload() {
+ filterGroups.clear();
+ idToFilterGroup.clear();
+
+ try {
+ Iterator i = new EntityIteratorAdapter("", "priority asc", 100, model, "filterGroup");
+ while (i.hasNext()) {
+ EntityAdapter entityAdapter = (EntityAdapter) i.next();
+ List filters = new ArrayList();
+ Iterator j = (Iterator) entityAdapter.getIterator("to_filters");
+ while (j.hasNext()) {
+ filters.add(((EntityAdapter) j.next()).getEntity());
+ }
+
+ FilterGroup filterGroup = new FilterGroup(entityAdapter.getEntity(), filters);
+ introduceFilterGroup(filterGroup);
+ }
+ }
+ catch (Throwable e) {
+ logger.error("Can't load filters: " + e.getMessage(), e);
+ }
+ }
+
+ public synchronized List getFilterGroups() {
+ List result = new ArrayList();
+ Iterator i = filterGroups.iterator();
+ while (i.hasNext()) {
+ result.add(((FilterGroup) i.next()).getEntityAdapter());
+ }
+
+ return result;
+ }
+
+ public synchronized void updateFilterGroup(String anId, String aName) {
+ FilterGroup filterGroup = getFilterGroupForId(anId);
+ filterGroup.getEntity().setFieldValue("name", aName);
+ filterGroup.getEntity().update();
+ }
+
+ public synchronized void addFilterGroup(String aName) throws DatabaseExc {
+ Entity entity = DatabaseFilterGroup.getInstance().createNewEntity();
+ entity.setFieldValue("name", aName);
+
+ String priority = "1";
+
+ if (filterGroups.size() > 0) {
+ try {
+ String lastPriorityString = ((FilterGroup) filterGroups.get(filterGroups.size()-1)).getEntity().getFieldValue("priority");
+ int lastPriority = Integer.parseInt(lastPriorityString);
+ priority = Integer.toString(lastPriority + 1);
+ }
+ catch (Exception e) {
+ }
+ }
+ entity.setFieldValue("priority", priority);
+ entity.insert();
+
+ FilterGroup filterGroup = new FilterGroup(entity);
+ introduceFilterGroup(filterGroup);
+ }
+
+ public synchronized void moveFilterGroupUp(String anId) {
+ FilterGroup group = (FilterGroup) idToFilterGroup.get(anId);
+ String priority = group.getEntity().getFieldValue("priority");
+ int index = filterGroups.indexOf(group);
+ if (index>=1) {
+ FilterGroup groupBefore = (FilterGroup) filterGroups.remove(index-1);
+ filterGroups.add(index, groupBefore);
+ group.getEntity().setFieldValue("priority", groupBefore.getEntity().getFieldValue("priority"));
+ groupBefore.getEntity().setFieldValue("priority", priority);
+ group.getEntity().update();
+ groupBefore.getEntity().update();
+ }
+ }
+
+ public synchronized void moveFilterGroupDown(String anId) {
+ FilterGroup group = (FilterGroup) idToFilterGroup.get(anId);
+ String priority = group.getEntity().getFieldValue("priority");
+ int index = filterGroups.indexOf(group);
+ if (index<filterGroups.size()-1) {
+ FilterGroup groupAfter = (FilterGroup) filterGroups.remove(index+1);
+ filterGroups.add(index, groupAfter);
+ group.getEntity().setFieldValue("priority", groupAfter.getEntity().getFieldValue("priority"));
+ groupAfter.getEntity().setFieldValue("priority", priority);
+ group.getEntity().update();
+ groupAfter.getEntity().update();
+ }
+ }
+
+ public synchronized void deleteFilterGroup(String anId) {
+
+ FilterGroup filterGroup = getFilterGroupForId(anId);
+ removeFilterGroup(filterGroup);
+ DatabaseFilter.getInstance().deleteByWhereClause("filter_group_id = " + anId);
+ DatabaseFilterGroup.getInstance().delete(anId);
+ }
+
+ public synchronized void deleteFilter(String aGroupId, String anId) {
+ getFilterGroupForId(aGroupId).deleteFilter(anId);
+ }
+
+
+ public synchronized String updateFilter(String aGroupId, String anId,
+ String aType, String anExpression,
+ String aComments,
+ String aTag,
+ String anArticleAction,
+ String aCommentAction) {
+ return getFilterGroupForId(aGroupId).updateFilter(anId, aType,
+ anExpression, aComments, aTag, anArticleAction, aCommentAction);
+ }
+
+ public synchronized String addFilter(String aGroupId,
+ String aType, String anExpression,
+ String aComments,
+ String aTag,
+ String anArticleAction,
+ String aCommentAction) throws DatabaseExc {
+ return getFilterGroupForId(aGroupId).createFilter(aType, anExpression,
+ aComments, aTag, anArticleAction, aCommentAction);
+ }
+
+ public synchronized String moveFilterUp(String aGroupId, String anId) {
+ return getFilterGroupForId(aGroupId).moveFilterUp(anId);
+ }
+
+ public synchronized String moveFilterDown(String aGroupId, String anId) {
+ return getFilterGroupForId(aGroupId).moveFilterDown(anId);
+ }
+
+ public synchronized String moveFilterToTop(String aGroupId, String anId) {
+ return getFilterGroupForId(aGroupId).moveFilterToTop(anId);
+ }
+
+ public synchronized String moveFilterToBottom(String aGroupId, String anId) {
+ return getFilterGroupForId(aGroupId).moveFilterToBottom(anId);
+ }
+
+
+
+ public FilterGroup getFilterGroupForId(String anId) {
+ FilterGroup result = (FilterGroup) idToFilterGroup.get(anId);
+ if (result == null) {
+ throw new NullPointerException("No such filter group");
+ }
+
+ return result;
+ }
+
+ public Filter getFilterForId(String aGroupId, String anId) {
+ return getFilterGroupForId(aGroupId).getFilterForId(anId);
+ }
+
+
+ public List getFilters(String aFilterGroupId) {
+ return getFilterGroupForId(aFilterGroupId).getFilterEntityAdapterList();
+ }
+
+ private synchronized void introduceFilterGroup(FilterGroup aFilterGroup) {
+ filterGroups.add(aFilterGroup);
+ idToFilterGroup.put(aFilterGroup.getEntity().getId(), aFilterGroup);
+ }
+
+ private synchronized void removeFilterGroup(FilterGroup aFilterGroup) {
+ filterGroups.remove(aFilterGroup);
+ idToFilterGroup.remove(aFilterGroup.getEntity().getId());
+ }
+
+ private FilterType getFilterTypeForId(String anId) {
+ return (FilterType) filterTypes.get(anId);
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.abuse;\r
+\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+/**\r
+ * Classes implementing this interface provide the test() method\r
+ * that actually does the filtering work (ie. matching the \r
+ * data). The description of a filter is found in classes \r
+ * implementing FilterType \r
+ */\r
+public interface FilterInstance {\r
+ /**\r
+ * Must return <code>true</code> if the posting matches the filter.\r
+ */\r
+ public boolean test(Entity anEntity, Request aRequest);\r
+\r
+ /**\r
+ * May return a desription of the "status" of this filter. (E.g. the number\r
+ * of hits)\r
+ */\r
+ public String status();\r
+}\r
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.abuse;\r
+\r
+public class FilterParseExc extends AbuseExc {\r
+ public FilterParseExc(String aMessage) {\r
+ super(aMessage);\r
+ }\r
+}\r
--- /dev/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 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.abuse;
+
+
+
+/**
+ * Interface to define filter types for the anti-abuse system.
+ * Implementing classes provide a description of the filter.
+ * The actual filtering work is done by classes implementing
+ * the FilterInstance interface. That class is provided by the
+ * constructFilterInstance method
+ */
+
+public interface FilterType {
+ /**
+ * The identifying name of the filter type. Must be unique.
+ *
+ * @return
+ */
+ public String getName();
+
+ /**
+ * Must construct a filter instance or throw an exception if
+ * <code>anExpression</code> is not a valid expression.
+ */
+ public FilterInstance constructFilterInstance(String anExpression) throws AbuseExc;
+}
\ No newline at end of file
--- /dev/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 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.abuse;
+
+import mir.entity.Entity;
+import mir.session.Request;
+import mir.util.InternetRoutines;
+
+/**
+ * A basic ip filter type. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.
+ */
+public class IPFilterType extends AbstractFilterType {
+ public IPFilterType(String aName) {
+ super(aName);
+ }
+
+ /**
+ *
+ */
+ public boolean validate(String anExpression) {
+ try {
+ InternetRoutines.isIpAddressInNetwork("1.1.1.1", anExpression);
+ return true;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ }
+
+ public FilterInstance constructFilterInstance(final String anExpression) throws AbuseExc {
+ try {
+ InternetRoutines.isIpAddressInNetwork("1.1.1.1", anExpression);
+ }
+ catch (Throwable t) {
+ throw new AbuseExc("Invalid expression: " + anExpression);
+ }
+
+ return new FilterInstance() {
+ public boolean test(Entity anEntity, Request aRequest) {
+ try {
+ return InternetRoutines.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);
+ }
+ catch (Exception e) {
+ return false;
+ }
+ }
+
+ public String status() {
+ return "";
+ }
+ };
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.abuse;\r
+\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+\r
+import java.util.Iterator;\r
+\r
+/**\r
+ * A description of a regular expression filter.\r
+ */\r
+public class PostingSizeFilterType extends AbstractFilterType {\r
+ public PostingSizeFilterType(String aName) {\r
+ super(aName);\r
+ }\r
+\r
+ public FilterInstance constructFilterInstance(final String anExpression) throws AbuseExc {\r
+ final long maxSize;\r
+ try {\r
+ maxSize = Long.parseLong(anExpression);\r
+ }\r
+ catch (NumberFormatException e) {\r
+ throw new AbuseExc("Not an integer: " + anExpression);\r
+ }\r
+\r
+ return new FilterInstance() {\r
+\r
+ public boolean test(Entity anEntity, Request aRequest) {\r
+ long totalSize = 0L;\r
+ Iterator j = anEntity.getFieldNames().iterator();\r
+\r
+ while (j.hasNext()) {\r
+ String field = anEntity.getFieldValue( (String) j.next());\r
+ if (field!=null) {\r
+ totalSize += (long) field.length();\r
+ }\r
+ }\r
+\r
+ return totalSize > maxSize;\r
+ }\r
+\r
+ public String status() {\r
+ return null;\r
+ }\r
+ };\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2001-2006 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 any library licensed under the Apache Software License,
+ * 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.abuse;
+
+import gnu.regexp.RE;
+import mir.entity.Entity;
+import mir.session.Request;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+
+/**
+ * A description of a regular expression filter.
+ */
+ public class RegularExpressionFilterType extends AbstractFilterType {
+ private boolean exactMatch;
+ private boolean caseSensitive;
+ private int fieldKind;
+ private List selectedFields;
+
+ public static final int ENTITY_FIELDS = 0;
+ public static final int REQUEST_HEADERS = 2;
+
+ public RegularExpressionFilterType(String aName) {
+ this(aName, false, false, null);
+ }
+
+ public RegularExpressionFilterType(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {
+ this (aName, aCaseSensitive, anExactMatch, ENTITY_FIELDS, aSelectedFields);
+ }
+
+ public RegularExpressionFilterType(String aName, boolean aCaseSensitive, boolean anExactMatch, int aFieldKind, String[] aSelectedFields) {
+ super(aName);
+
+ fieldKind = aFieldKind;
+
+ caseSensitive = aCaseSensitive;
+ exactMatch = anExactMatch;
+ if (aSelectedFields==null) {
+ selectedFields = null;
+ }
+ else {
+ selectedFields = Arrays.asList(aSelectedFields);
+ }
+ }
+
+
+ public FilterInstance constructFilterInstance(final String anExpression) throws AbuseExc {
+ try {
+ new RE(anExpression);
+
+ return new FilterInstance() {
+
+ public boolean test(Entity anEntity, Request aRequest) {
+
+ try {
+ Iterator j;
+ int flags = 0;
+
+ if (!caseSensitive) {
+ flags |= RE.REG_ICASE;
+ }
+
+ RE regularExpression = new RE(anExpression, flags);
+
+ switch (fieldKind) {
+ case REQUEST_HEADERS:
+ if (selectedFields != null) {
+ j = selectedFields.iterator();
+
+ while (j.hasNext()) {
+ String fieldName = (String) j.next();
+ String field = aRequest.getHeader(fieldName);
+
+ if (exactMatch) {
+ if (field != null && regularExpression.isMatch(field)) {
+ return true;
+ }
+ }
+ else {
+ if (field != null && regularExpression.getMatch(field) != null) {
+ return true;
+ }
+ }
+ }
+ }
+ break;
+ case ENTITY_FIELDS:
+ if (selectedFields != null) {
+ j = selectedFields.iterator();
+ }
+ else {
+ j = anEntity.getFieldNames().iterator();
+ }
+
+ while (j.hasNext()) {
+ String field = anEntity.getFieldValue( (String) j.next());
+
+ if (exactMatch) {
+ if (field != null && regularExpression.isMatch(field)) {
+ return true;
+ }
+ }
+ else {
+ if (field != null && regularExpression.getMatch(field) != null) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ catch (Throwable t) {
+ }
+ return false;
+ }
+
+ public String status() {
+ return null;
+ }
+ };
+ }
+ catch (Throwable t) {
+ throw new AbuseExc("Invalid expression: " + t.getMessage());
+ }
+ }
+}
\ No newline at end of file
--- /dev/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 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.abuse;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import mir.entity.Entity;
+import mir.session.Request;
+import mir.util.StringRoutines;
+
+/**
+ * A ip-based throttling filter.
+ *
+ * <p>
+ * Expressions have the form <time in minutes>:<posting limit>
+ */
+public class ThrottleFilter extends AbstractFilterType {
+
+ public ThrottleFilter(String aName) {
+ super(aName);
+ }
+
+ public FilterInstance constructFilterInstance(String anExpression) throws AbuseExc {
+ List parts = StringRoutines.splitString(anExpression.trim(), ":");
+
+ if (parts.size()==2) {
+ try {
+ final int interval = Integer.parseInt((String) parts.get(0));
+ final int limit = Integer.parseInt((String) parts.get(1));
+
+ if (interval<1) {
+ throw new AbuseExc("Interval should be larger than 0");
+ }
+ if (limit<1) {
+ throw new AbuseExc("Limit should be larger than 0");
+ }
+ final ThrottleManager manager = new ThrottleManager(interval*1000*60);
+
+ return new FilterInstance() {
+ public boolean test(Entity anEntity, Request aRequest) {
+ manager.addMessage(aRequest.getHeader("ip"));
+ if (manager.count(aRequest.getHeader("ip")) > limit) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public String status() {
+ return Integer.toString(manager.messages.size()) + " messages";
+ }
+ };
+ }
+ catch (AbuseExc e) {
+ throw e;
+ }
+ catch (Throwable t) {
+ throw new AbuseExc("Invalid expression: <interval>:<limit> expected");
+ }
+ }
+ throw new AbuseExc("Invalid expression: <interval>:<limit> expected");
+ }
+
+ private class ThrottleManager {
+ private long horizon;
+ private List messages;
+
+ public ThrottleManager(long aHorizon) {
+ horizon = aHorizon;
+
+ messages = new ArrayList();
+ }
+
+ public void flush() {
+ long limit = System.currentTimeMillis() - horizon;
+
+ while (messages.size()>0 && ((Message) messages.get(0)).getTime()<=limit) {
+ messages.remove(0);
+ }
+ }
+
+ public void addMessage(String anIp) {
+ Message newMessage = new Message(anIp, System.currentTimeMillis());
+ messages.add(newMessage);
+ }
+
+ public int count(String anIp) {
+ flush();
+
+ int result = 0;
+ Iterator i = messages.iterator();
+ while (i.hasNext()) {
+ Message message = (Message) i.next();
+ if (message.getIp().equals(anIp)) {
+ result = result + 1;
+ }
+ }
+
+ return result;
+ }
+
+ private class Message {
+ private String ip;
+ private long time;
+
+ public Message(String anIp, long aTime) {
+ ip = anIp;
+ time = aTime;
+ }
+
+ public String getIp() {
+ return ip;
+ }
+
+ public long getTime() {
+ return time;
+ }
+ }
+ }
+}
--- /dev/null
+package mircoders.abuse;\r
+\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+import org.apache.oro.text.regex.MalformedPatternException;\r
+import org.apache.oro.text.regex.MatchResult;\r
+import org.apache.oro.text.regex.Pattern;\r
+import org.apache.oro.text.regex.PatternMatcherInput;\r
+import org.apache.oro.text.regex.Perl5Compiler;\r
+import org.apache.oro.text.regex.Perl5Matcher;\r
+\r
+import java.net.InetAddress;\r
+import java.net.UnknownHostException;\r
+import java.util.Arrays;\r
+import java.util.Collection;\r
+import java.util.HashSet;\r
+import java.util.Iterator;\r
+import java.util.Set;\r
+\r
+/**\r
+ * URL Blacklist filter type. Will perform a DNS request on URLs contained\r
+ * in a posting appended by the filter expression. An existing domain will\r
+ * cause in a positive filter outcome.\r
+ */\r
+public class URLBlacklistFilterType extends AbstractFilterType {\r
+ public URLBlacklistFilterType(String aName, Collection aWhiteList) {\r
+ super(aName);\r
+\r
+ whiteList = new HashSet(aWhiteList);\r
+ }\r
+\r
+ /**\r
+ *\r
+ */\r
+ public boolean validate(String anExpression) {\r
+ return anExpression.trim().length() > 0;\r
+ }\r
+\r
+ public FilterInstance constructFilterInstance(final String anExpression) throws AbuseExc {\r
+ return new FilterInstance() {\r
+ public boolean test(Entity anEntity, Request aRequest) {\r
+ Set domains = new HashSet();\r
+\r
+ Iterator i = anEntity.getFieldNames().iterator();\r
+\r
+ while (i.hasNext()) {\r
+ String field = anEntity.getFieldValue( (String) i.next());\r
+ if (field != null) {\r
+ harvestURLDomains(field, domains);\r
+ }\r
+ }\r
+\r
+ domains.removeAll(whiteList);\r
+\r
+ i = domains.iterator();\r
+ while (i.hasNext()) {\r
+ String domain = (String) i.next();\r
+\r
+ try {\r
+ InetAddress.getByName(domain + "." + anExpression);\r
+\r
+ return true;\r
+ }\r
+ catch (UnknownHostException e) {\r
+ // intentionally empty: the domain was not found, so the domain isn't blacklisted\r
+ }\r
+ }\r
+\r
+ return false;\r
+ }\r
+\r
+ public String status() {\r
+ return "";\r
+ }\r
+ };\r
+ }\r
+\r
+ public static void main(String[] someArguments) {\r
+ HashSet set = new HashSet();\r
+ harvestURLDomains("[URL]https://www.nel9la41.org/informatica[/URL] [URL]http://www.ceud.org/liberi[/URL] [URL]http://www.e6tate.org/danni[/URL] [URL]http://www.e6tate.org/shakira[/URL] [URL]http://www.ceud.org/musica[/URL] [URL]http://www.nel9la41.org/troie[/URL] [URL]http://www.nel9la41.org/corriere-della-sera[/URL] [URL]http://www.e6tate.org/serie-a[/URL] [URL]http://www.nel9la41.org/calciomercato[/URL] [URL]http://www.e6tate.org/vita[/URL] [URL]http://www.e6tate.org/pene[/URL] [URL]http://www.e6tate.org/barzellette[/URL] [URL]http://www.ceud.org/pagine-bianche[/URL] [URL]http://www.e6tate.org/playboy[/URL] [URL]http://www.nel9la41.org/totti[/URL] [URL]http://www.e6tate.org/trenitalia[/URL] [URL]http://www.ceud.org/bambini[/URL] [URL]http://www.ceud.org/pornografia[/URL] [URL]http://www.e6tate.org/corriere-della-sera[/URL] [URL]http://www.nel9la41.org/musica[/URL] [URL]http://www.ceud.org/serie-a[/URL] [URL]http://www.nel9la41.org/barzellette[/URL] [URL]http://www.ceud.org/turismo[/URL] [URL]http://www.ceud.org/del-piero[/URL] [URL]http://www.nel9la41.org/calcio[/URL] [URL]http://www.nel9la41.org/google[/URL] [URL]http://www.e6tate.org/sesso[/URL] [URL]http://www.nel9la41.org/jesse-mccartney[/URL]", set);\r
+ Iterator i = set.iterator();\r
+ while (i.hasNext()) {\r
+ System.out.println(i.next());\r
+ }\r
+ }\r
+\r
+\r
+ private static void harvestURLDomains(String someText, Set someResult) {\r
+ Perl5Matcher matcher = new Perl5Matcher();\r
+\r
+ PatternMatcherInput input =\r
+ new PatternMatcherInput(someText);\r
+\r
+ while(matcher.contains(input, URL_EXPRESSION)) {\r
+ MatchResult match = matcher.getMatch();\r
+ String domain = match.group(5);\r
+ if (domain!=null) {\r
+ someResult.add(stripDomain(domain));\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Turns a domain (e.g. www.indymedia.org) into its domain just above the top level (e.g. indymedia.org)\r
+ */\r
+ private static String stripDomain(String aDomain) {\r
+ String result = aDomain;\r
+ int pos = aDomain.lastIndexOf('.');\r
+ if (pos >= 0) {\r
+ pos = aDomain.lastIndexOf('.', pos-1);\r
+\r
+ // note: pos may be -1\r
+ result = aDomain.substring(pos+1);\r
+ if (TWO_PART_TOP_LEVEL_DOMAINS.contains(result)) {\r
+ pos = aDomain.lastIndexOf('.', pos-1);\r
+\r
+ // note: pos may be -1\r
+ result = aDomain.substring(pos+1);\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ static {\r
+ Perl5Compiler compiler = new Perl5Compiler();\r
+ try {\r
+ URL_EXPRESSION =\r
+ compiler.compile("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+.[a-zA-Z0-9_.:-]+)", Perl5Compiler.READ_ONLY_MASK);\r
+ }\r
+ catch (MalformedPatternException e) {\r
+ //\r
+ }\r
+ }\r
+\r
+\r
+ private Set whiteList;\r
+\r
+ private static Pattern URL_EXPRESSION;\r
+ private static Set TWO_PART_TOP_LEVEL_DOMAINS = new HashSet(\r
+ Arrays.asList(new String[] {"com.ac", "edu.ac", "gov.ac", "net.ac", "mil.ac", "org.ac",\r
+"com.ae", "net.ae", "org.ae", "gov.ae", "ac.ae", "co.ae",\r
+"sch.ae", "pro.ae", "com.ai", "org.ai", "edu.ai", "gov.ai",\r
+"com.ar", "net.ar", "org.ar", "gov.ar", "mil.ar", "edu.ar",\r
+"int.ar", "co.at", "ac.at", "or.at", "gv.at", "priv.at",\r
+"com.au", "gov.au", "org.au", "edu.au", "id.au", "oz.au",\r
+"info.au", "net.au", "asn.au", "csiro.au", "telememo.au",\r
+"conf.au", "otc.au", "id.au", "com.az", "net.az", "org.az",\r
+"com.bb", "net.bb", "org.bb", "ac.be", "belgie.be",\r
+"dns.be", "fgov.be", "com.bh", "gov.bh", "net.bh", "edu.bh",\r
+"org.bh", "com.bm", "edu.bm", "gov.bm", "org.bm", "net.bm",\r
+"adm.br", "adv.br", "agr.br", "am.br", "arq.br", "art.br",\r
+"ato.br", "bio.br", "bmd.br", "cim.br", "cng.br", "cnt.br",\r
+"com.br", "coop.br", "ecn.br", "edu.br", "eng.br", "esp.br",\r
+"etc.br", "eti.br", "far.br", "fm.br", "fnd.br", "fot.br",\r
+"fst.br", "g12.br", "ggf.br", "gov.br", "imb.br", "ind.br",\r
+"inf.br", "jor.br", "lel.br", "mat.br", "med.br", "mil.br",\r
+"mus.br", "net.br", "nom.br", "not.br", "ntr.br", "odo.br",\r
+"org.br", "ppg.br", "pro.br", "psc.br", "psi.br", "qsl.br",\r
+"rec.br", "slg.br", "srv.br", "tmp.br", "trd.br", "tur.br",\r
+"tv.br", "vet.br", "zlg.br", "com.bs", "net.bs", "org.bs",\r
+"com.bz", "net.bz", "org.bz", "ab.ca", "bc.ca", "mb.ca",\r
+"nb.ca", "nf.ca", "nl.ca", "ns.ca", "nt.ca", "nu.ca",\r
+"on.ca", "pe.ca", "qc.ca", "sk.ca", "yk.ca", "gc.ca",\r
+"co.ck", "net.ck", "org.ck", "edu.ck", "gov.ck", "com.cn",\r
+"edu.cn", "gov.cn", "net.cn", "org.cn", "ac.cn", "ah.cn",\r
+"bj.cn", "cq.cn", "gd.cn", "gs.cn", "gx.cn", "gz.cn",\r
+"hb.cn", "he.cn", "hi.cn", "hk.cn", "hl.cn", "hn.cn",\r
+"jl.cn", "js.cn", "ln.cn", "mo.cn", "nm.cn", "nx.cn",\r
+"qh.cn", "sc.cn", "sn.cn", "sh.cn", "sx.cn", "tj.cn",\r
+"tw.cn", "xj.cn", "xz.cn", "yn.cn", "zj.cn", "arts.co",\r
+"com.co", "edu.co", "firm.co", "gov.co", "info.co",\r
+"int.co", "nom.co", "mil.co", "org.co", "rec.co",\r
+"store.co", "web.co", "ac.cr", "co.cr", "ed.cr", "fi.cr",\r
+"go.cr", "or.cr", "sa.cr", "com.cu", "net.cu", "org.cu",\r
+"ac.cy", "com.cy", "gov.cy", "net.cy", "org.cy", "co.dk",\r
+"art.do", "com.do", "edu.do", "gov.do", "gob.do", "org.do",\r
+"mil.do", "net.do", "sld.do", "web.do", "com.dz", "org.dz",\r
+"net.dz", "gov.dz", "edu.dz", "ass.dz", "pol.dz", "art.dz",\r
+"com.ec", "k12.ec", "edu.ec", "fin.ec", "med.ec", "gov.ec",\r
+"mil.ec", "org.ec", "net.ec", "com.ee", "pri.ee", "fie.ee",\r
+"org.ee", "med.ee", "com.eg", "edu.eg", "eun.eg", "gov.eg",\r
+"net.eg", "org.eg", "sci.eg", "com.er", "net.er", "org.er",\r
+"edu.er", "mil.er", "gov.er", "ind.er", "com.es", "org.es",\r
+"gob.es", "edu.es", "nom.es", "com.et", "gov.et", "org.et",\r
+"edu.et", "net.et", "biz.et", "name.et", "info.et", "ac.fj",\r
+"com.fj", "gov.fj", "id.fj", "org.fj", "school.fj",\r
+"com.fk", "ac.fk", "gov.fk", "net.fk", "nom.fk", "org.fk",\r
+"asso.fr", "nom.fr", "barreau.fr", "com.fr", "prd.fr",\r
+"presse.fr", "tm.fr", "aeroport.fr", "assedic.fr",\r
+"avocat.fr", "avoues.fr", "cci.fr", "chambagri.fr",\r
+"chirurgiens-dentistes.fr", "experts-comptables.fr",\r
+"geometre-expert.fr", "gouv.fr", "greta.fr",\r
+"huissier-justice.fr", "medecin.fr", "notaires.fr", "pharmacien.fr",\r
+"port.fr", "veterinaire.fr", "com.ge", "edu.ge", "gov.ge",\r
+"mil.ge", "net.ge", "org.ge", "pvt.ge", "co.gg", "org.gg",\r
+"sch.gg", "ac.gg", "gov.gg", "ltd.gg", "ind.gg", "net.gg",\r
+"alderney.gg", "guernsey.gg", "sark.gg", "com.gr", "edu.gr",\r
+"gov.gr", "net.gr", "org.gr", "com.gt", "edu.gt", "net.gt",\r
+"gob.gt", "org.gt", "mil.gt", "ind.gt", "com.gu", "edu.gu",\r
+"net.gu", "org.gu", "gov.gu", "mil.gu", "com.hk", "net.hk",\r
+"org.hk", "idv.hk", "gov.hk", "edu.hk", "co.hu", "2000.hu",\r
+"erotika.hu", "jogasz.hu", "sex.hu", "video.hu", "info.hu",\r
+"agrar.hu", "film.hu", "konyvelo.hu", "shop.hu", "org.hu",\r
+"bolt.hu", "forum.hu", "lakas.hu", "suli.hu", "priv.hu",\r
+"casino.hu", "games.hu", "media.hu", "szex.hu", "sport.hu",\r
+"city.hu", "hotel.hu", "news.hu", "tozsde.hu", "tm.hu",\r
+"erotica.hu", "ingatlan.hu", "reklam.hu", "utazas.hu",\r
+"ac.id", "co.id", "go.id", "mil.id", "net.id", "or.id",\r
+"co.il", "net.il", "org.il", "ac.il", "gov.il", "k12.il",\r
+"muni.il", "idf.il", "co.im", "net.im", "org.im", "ac.im",\r
+"lkd.co.im", "gov.im", "nic.im", "plc.co.im", "co.in",\r
+"net.in", "ac.in", "ernet.in", "gov.in", "nic.in", "res.in",\r
+"gen.in", "firm.in", "mil.in", "org.in", "ind.in", "ac.ir",\r
+"co.ir", "gov.ir", "id.ir", "net.ir", "org.ir", "sch.ir",\r
+"ac.je", "co.je", "net.je", "org.je", "gov.je", "ind.je",\r
+"jersey.je", "ltd.je", "sch.je", "com.jo", "org.jo",\r
+"net.jo", "gov.jo", "edu.jo", "mil.jo", "ad.jp", "ac.jp",\r
+"co.jp", "go.jp", "or.jp", "ne.jp", "gr.jp", "ed.jp",\r
+"lg.jp", "net.jp", "org.jp", "gov.jp", "hokkaido.jp",\r
+"aomori.jp", "iwate.jp", "miyagi.jp", "akita.jp",\r
+"yamagata.jp", "fukushima.jp", "ibaraki.jp", "tochigi.jp",\r
+"gunma.jp", "saitama.jp", "chiba.jp", "tokyo.jp",\r
+"kanagawa.jp", "niigata.jp", "toyama.jp", "ishikawa.jp",\r
+"fukui.jp", "yamanashi.jp", "nagano.jp", "gifu.jp",\r
+"shizuoka.jp", "aichi.jp", "mie.jp", "shiga.jp", "kyoto.jp",\r
+"osaka.jp", "hyogo.jp", "nara.jp", "wakayama.jp",\r
+"tottori.jp", "shimane.jp", "okayama.jp", "hiroshima.jp",\r
+"yamaguchi.jp", "tokushima.jp", "kagawa.jp", "ehime.jp",\r
+"kochi.jp", "fukuoka.jp", "saga.jp", "nagasaki.jp",\r
+"kumamoto.jp", "oita.jp", "miyazaki.jp", "kagoshima.jp",\r
+"okinawa.jp", "sapporo.jp", "sendai.jp", "yokohama.jp",\r
+"kawasaki.jp", "nagoya.jp", "kobe.jp", "kitakyushu.jp",\r
+"utsunomiya.jp", "kanazawa.jp", "takamatsu.jp",\r
+"matsuyama.jp", "com.kg", "net.kg", "org.kg", "edu.kg",\r
+"gov.kg", "mil.kg", "com.kh", "net.kh", "org.kh", "per.kh",\r
+"edu.kh", "gov.kh", "mil.kh", "ac.kr", "co.kr", "go.kr",\r
+"ne.kr", "or.kr", "pe.kr", "re.kr", "seoul.kr",\r
+"kyonggi.kr", "com.kw", "net.kw", "org.kw", "edu.kw",\r
+"gov.kw", "com.la", "net.la", "org.la", "com.lb", "org.lb",\r
+"net.lb", "edu.lb", "gov.lb", "mil.lb", "com.lc", "edu.lc",\r
+"gov.lc", "net.lc", "org.lc", "com.lv", "net.lv", "org.lv",\r
+"edu.lv", "gov.lv", "mil.lv", "id.lv", "asn.lv", "conf.lv",\r
+"com.ly", "net.ly", "org.ly", "co.ma", "net.ma", "org.ma",\r
+"press.ma", "ac.ma", "com.mk", "com.mm", "net.mm", "org.mm",\r
+"edu.mm", "gov.mm", "com.mn", "org.mn", "edu.mn", "gov.mn",\r
+"museum.mn", "com.mo", "net.mo", "org.mo", "edu.mo",\r
+"gov.mo", "com.mt", "net.mt", "org.mt", "edu.mt", "tm.mt",\r
+"uu.mt", "com.mx", "net.mx", "org.mx", "gob.mx", "edu.mx",\r
+"com.my", "org.my", "gov.my", "edu.my", "net.my", "com.na",\r
+"org.na", "net.na", "alt.na", "edu.na", "cul.na", "unam.na",\r
+"telecom.na", "com.nc", "net.nc", "org.nc", "ac.ng",\r
+"edu.ng", "sch.ng", "com.ng", "gov.ng", "org.ng", "net.ng",\r
+"gob.ni", "com.ni", "net.ni", "edu.ni", "nom.ni", "org.ni",\r
+"com.np", "net.np", "org.np", "gov.np", "edu.np", "ac.nz",\r
+"co.nz", "cri.nz", "gen.nz", "geek.nz", "govt.nz", "iwi.nz",\r
+"maori.nz", "mil.nz", "net.nz", "org.nz", "school.nz",\r
+"com.om", "co.om", "edu.om", "ac.om", "gov.om", "net.om",\r
+"org.om", "mod.om", "museum.om", "biz.om", "pro.om",\r
+"med.om", "com.pa", "net.pa", "org.pa", "edu.pa", "ac.pa",\r
+"gob.pa", "sld.pa", "edu.pe", "gob.pe", "nom.pe", "mil.pe",\r
+"org.pe", "com.pe", "net.pe", "com.pg", "net.pg", "ac.pg",\r
+"com.ph", "net.ph", "org.ph", "mil.ph", "ngo.ph", "aid.pl",\r
+"agro.pl", "atm.pl", "auto.pl", "biz.pl", "com.pl",\r
+"edu.pl", "gmina.pl", "gsm.pl", "info.pl", "mail.pl",\r
+"miasta.pl", "media.pl", "mil.pl", "net.pl",\r
+"nieruchomosci.pl", "nom.pl", "org.pl", "pc.pl",\r
+"powiat.pl", "priv.pl", "realestate.pl", "rel.pl", "sex.pl",\r
+"shop.pl", "sklep.pl", "sos.pl", "szkola.pl", "targi.pl",\r
+"tm.pl", "tourism.pl", "travel.pl", "turystyka.pl",\r
+"com.pk", "net.pk", "edu.pk", "org.pk", "fam.pk", "biz.pk",\r
+"web.pk", "gov.pk", "gob.pk", "gok.pk", "gon.pk", "gop.pk",\r
+"gos.pk", "edu.ps", "gov.ps", "plo.ps", "sec.ps", "com.pt",\r
+"edu.pt", "gov.pt", "int.pt", "net.pt", "nome.pt", "org.pt",\r
+"publ.pt", "com.py", "net.py", "org.py", "edu.py", "com.qa",\r
+"net.qa", "org.qa", "edu.qa", "gov.qa", "asso.re", "com.re",\r
+"nom.re", "com.ro", "org.ro", "tm.ro", "nt.ro", "nom.ro",\r
+"info.ro", "rec.ro", "arts.ro", "firm.ro", "store.ro",\r
+"www.ro", "ac.ru", "adygeya.ru", "altai.ru", "amur.ru",\r
+"amursk.ru", "arkhangelsk.ru", "astrakhan.ru", "baikal.ru",\r
+"bashkiria.ru", "belgorod.ru", "bir.ru", "bryansk.ru",\r
+"buryatia.ru", "cbg.ru", "chel.ru", "chelyabinsk.ru",\r
+"chita.ru", "chukotka.ru", "chuvashia.ru", "cmw.ru",\r
+"com.ru", "dagestan.ru", "dudinka.ru", "e-burg.ru",\r
+"edu.ru", "fareast.ru", "gov.ru", "grozny.ru", "int.ru",\r
+"irkutsk.ru", "ivanovo.ru", "izhevsk.ru", "jamal.ru",\r
+"jar.ru", "joshkar-ola.ru", "k-uralsk.ru", "kalmykia.ru",\r
+"kaluga.ru", "kamchatka.ru", "karelia.ru", "kazan.ru",\r
+"kchr.ru", "kemerovo.ru", "khabarovsk.ru", "khakassia.ru",\r
+"khv.ru", "kirov.ru", "kms.ru", "koenig.ru", "komi.ru",\r
+"kostroma.ru", "krasnoyarsk.ru", "kuban.ru", "kurgan.ru",\r
+"kursk.ru", "kustanai.ru", "kuzbass.ru", "lipetsk.ru",\r
+"magadan.ru", "magnitka.ru", "mari-el.ru", "mari.ru",\r
+"marine.ru", "mil.ru", "mordovia.ru", "mosreg.ru", "msk.ru",\r
+"murmansk.ru", "mytis.ru", "nakhodka.ru", "nalchik.ru",\r
+"net.ru", "nkz.ru", "nnov.ru", "norilsk.ru", "nov.ru",\r
+"novosibirsk.ru", "nsk.ru", "omsk.ru", "orenburg.ru",\r
+"org.ru", "oryol.ru", "oskol.ru", "palana.ru", "penza.ru",\r
+"perm.ru", "pp.ru", "pskov.ru", "ptz.ru", "pyatigorsk.ru",\r
+"rnd.ru", "rubtsovsk.ru", "ryazan.ru", "sakhalin.ru",\r
+"samara.ru", "saratov.ru", "simbirsk.ru", "smolensk.ru",\r
+"snz.ru", "spb.ru", "stavropol.ru", "stv.ru", "surgut.ru",\r
+"syzran.ru", "tambov.ru", "tatarstan.ru", "test.ru",\r
+"tom.ru", "tomsk.ru", "tsaritsyn.ru", "tsk.ru", "tula.ru",\r
+"tuva.ru", "tver.ru", "tyumen.ru", "udm.ru", "udmurtia.ru",\r
+"ulan-ude.ru", "vdonsk.ru", "vladikavkaz.ru", "vladimir.ru",\r
+"vladivostok.ru", "volgograd.ru", "vologda.ru",\r
+"voronezh.ru", "vrn.ru", "vyatka.ru", "yakutia.ru",\r
+"yamal.ru", "yaroslavl.ru", "yekaterinburg.ru",\r
+"yuzhno-sakhalinsk.ru", "zgrad.ru", "com.sa", "edu.sa", "sch.sa",\r
+"med.sa", "gov.sa", "net.sa", "org.sa", "pub.sa", "com.sb",\r
+"net.sb", "org.sb", "edu.sb", "gov.sb", "com.sd", "net.sd",\r
+"org.sd", "edu.sd", "sch.sd", "med.sd", "gov.sd", "tm.se",\r
+"press.se", "parti.se", "brand.se", "fh.se", "fhsk.se",\r
+"fhv.se", "komforb.se", "kommunalforbund.se", "komvux.se",\r
+"lanarb.se", "lanbib.se", "naturbruksgymn.se", "sshn.se",\r
+"org.se", "pp.se", "com.sg", "net.sg", "org.sg", "edu.sg",\r
+"gov.sg", "per.sg", "com.sh", "net.sh", "org.sh", "edu.sh",\r
+"gov.sh", "mil.sh", "gov.st", "saotome.st", "principe.st",\r
+"consulado.st", "embaixada.st", "org.st", "edu.st",\r
+"net.st", "com.st", "store.st", "mil.st", "co.st", "com.sv",\r
+"org.sv", "edu.sv", "gob.sv", "red.sv", "com.sy", "net.sy",\r
+"org.sy", "gov.sy", "ac.th", "co.th", "go.th", "net.th",\r
+"or.th", "com.tn", "net.tn", "org.tn", "edunet.tn",\r
+"gov.tn", "ens.tn", "fin.tn", "nat.tn", "ind.tn", "info.tn",\r
+"intl.tn", "rnrt.tn", "rnu.tn", "rns.tn", "tourism.tn",\r
+"com.tr", "net.tr", "org.tr", "edu.tr", "gov.tr", "mil.tr",\r
+"bbs.tr", "k12.tr", "gen.tr", "co.tt", "com.tt", "org.tt",\r
+"net.tt", "biz.tt", "info.tt", "pro.tt", "int.tt",\r
+"coop.tt", "jobs.tt", "mobi.tt", "travel.tt", "museum.tt",\r
+"aero.tt", "name.tt", "gov.tt", "edu.tt", "nic.tt", "us.tt",\r
+"uk.tt", "ca.tt", "eu.tt", "es.tt", "fr.tt", "it.tt",\r
+"se.tt", "dk.tt", "be.tt", "de.tt", "at.tt", "au.tt",\r
+"co.tv", "com.tw", "net.tw", "org.tw", "edu.tw", "idv.tw",\r
+"gov.tw", "com.ua", "gov.ua", "net.ua", "edu.ua", "org.ua",\r
+"in.ua", "cherkassy.ua", "ck.ua", "chernigov.ua", "cn.ua",\r
+"chernovtsy.ua", "cv.ua", "crimea.ua", "dnepropetrovsk.ua",\r
+"dp.ua", "donetsk.ua", "dn.ua", "ivano-frankivsk.ua",\r
+"if.ua", "kharkov.ua", "kh.ua", "kherson.ua", "ks.ua",\r
+"khmelnitskiy.ua", "km.ua", "kiev.ua", "kv.ua",\r
+"kirovograd.ua", "kr.ua", "lugansk.ua", "lg.ua", "lutsk.ua",\r
+"lviv.ua", "nikolaev.ua", "mk.ua", "odessa.ua", "od.ua",\r
+"poltava.ua", "pl.ua", "rovno.ua", "rv.ua", "sebastopol.ua",\r
+"sumy.ua", "ternopil.ua", "te.ua", "uzhgorod.ua",\r
+"vinnica.ua", "vn.ua", "zaporizhzhe.ua", "zp.ua",\r
+"zhitomir.ua", "zt.ua", "ac.ug", "co.ug", "or.ug", "go.ug",\r
+"co.uk", "me.uk", "org.uk", "edu.uk", "ltd.uk", "plc.uk",\r
+"net.uk", "sch.uk", "nic.uk", "ac.uk", "gov.uk", "nhs.uk",\r
+"police.uk", "mod.uk", "dni.us", "fed.us", "com.uy",\r
+"edu.uy", "net.uy", "org.uy", "gub.uy", "mil.uy", "com.ve",\r
+"net.ve", "org.ve", "co.ve", "edu.ve", "gov.ve", "mil.ve",\r
+"arts.ve", "bib.ve", "firm.ve", "info.ve", "int.ve",\r
+"nom.ve", "rec.ve", "store.ve", "tec.ve", "web.ve", "co.vi",\r
+"net.vi", "org.vi", "com.vn", "biz.vn", "edu.vn", "gov.vn",\r
+"net.vn", "org.vn", "int.vn", "ac.vn", "pro.vn", "info.vn",\r
+"health.vn", "name.vn", "com.vu", "edu.vu", "net.vu",\r
+"org.vu", "de.vu", "ch.vu", "fr.vu", "com.ws", "net.ws",\r
+"org.ws", "gov.ws", "edu.ws", "ac.yu", "co.yu", "edu.yu",\r
+"org.yu", "com.ye", "net.ye", "org.ye", "gov.ye", "edu.ye",\r
+"mil.ye", "ac.za", "alt.za", "bourse.za", "city.za",\r
+"co.za", "edu.za", "gov.za", "law.za", "mil.za", "net.za",\r
+"ngo.za", "nom.za", "org.za", "school.za", "tm.za",\r
+"web.za", "co.zw", "ac.zw", "org.zw", "gov.zw", "eu.org",\r
+"au.com", "br.com", "cn.com", "de.com", "de.net", "eu.com",\r
+"gb.com", "gb.net", "hu.com", "no.com", "qc.com", "ru.com",\r
+"sa.com", "se.com", "uk.com", "uk.net", "us.com", "uy.com",\r
+"za.com", "dk.org", "tel.no", "fax.nr", "mob.nr",\r
+"mobil.nr", "mobile.nr", "tel.nr", "tlf.nr", "e164.arpa"\r
+ })\r
+ );\r
+}\r
+\r
package mircoders.accesscontrol;
+import java.util.List;
+import java.util.Vector;
+
import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
import mircoders.entity.EntityUsers;
import mircoders.module.ModuleContent;
-import java.util.List;
-import java.util.Vector;
-
public class AccessControl {
private UserAccessControl user;
private GeneralAccessControl general;
import java.util.Map;
-import mir.storage.StorageObject;
-
/**
- * This class handles storage of audio data and meta data
+ * This class handles database of audio data and meta data
*
* @author mh
- * @version $Id: EntityAudio.java,v 1.12 2004/11/06 19:56:13 idfx Exp $
+ * @version $Id: EntityAudio.java,v 1.13 2007/04/08 21:46:43 idfx Exp $
*/
super();
}
- public EntityAudio(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
import java.util.Map;
import mir.entity.AbstractEntity;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseCommentToMedia;
import mircoders.storage.DatabaseContent;
* This class maps one line of the comment-table to a java-object.
*
* @author $Author: idfx $
- * @version $Revision: 1.18 $ $Date: 2004/11/06 19:56:13 $
+ * @version $Revision: 1.19 $ $Date: 2007/04/08 21:46:43 $
*/
super();
}
- public EntityComment(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
-
/**
* overridden method setFieldValues to patch creator_main_url
*/
/**
* Deattaches media from a comment
- *
- * @param aCommentId
- * @param aMediaId
- * @throws StorageObjectFailure
*/
- public void dettach(String aCommentId,String aMediaId) throws StorageObjectFailure
- {
+ public void dettach(String aCommentId,String aMediaId) throws DatabaseFailure {
if (aMediaId!=null){
DatabaseCommentToMedia.getInstance().delete(aCommentId, aMediaId);
DatabaseContent.getInstance().setUnproduced("id="+getFieldValue("to_media"));
}
/**
- *
- * @param aMediaId
- * @throws StorageObjectFailure
+ * Attaches media to a comment
*/
- public void attach(String aMediaId) throws StorageObjectFailure
+ public void attach(String aMediaId) throws DatabaseFailure
{
if (aMediaId!=null) {
DatabaseCommentToMedia.getInstance().addMedia(getId(), aMediaId);
DatabaseContent.getInstance().setUnproduced("id="+getFieldValue("to_media"));
}
else {
- logger.error("EntityContent: attach without mid");
+ getLogger().error("EntityContent: attach without mid");
}
}
}
import mir.entity.AbstractEntity;
import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseContentToMedia;
/**
* this class implements mapping of one line of the database table content
* to a java object
*
- * @version $Id: EntityContent.java,v 1.21 2004/11/06 19:56:13 idfx Exp $
+ * @version $Id: EntityContent.java,v 1.22 2007/04/08 21:46:43 idfx Exp $
* @author mir-coders group
*
*/
public class EntityContent extends AbstractEntity {
- // constructors
-
- public EntityContent()
- {
- super();
-
- logger = new LoggerWrapper("Entity.Content");
- }
-
- public EntityContent(StorageObject theStorage) {
- this();
-
- setStorage(theStorage);
- }
-
/**
* set is_produced flag for the article
*/
- public void setProduced(boolean yesno) throws StorageObjectFailure
+ public void setProduced(boolean yesno) throws DatabaseFailure
{
String value = (yesno) ? "1":"0";
if (value.equals( getFieldValue("is_produced") )) return;
Connection con=null;Statement stmt=null;
String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
try {
- con = storageObject.obtainConnection();
+ con = database.obtainConnection();
/** todo should be preparedStatement: faster!! */
stmt = con.createStatement();
- storageObject.executeUpdate(stmt,sql);
+ database.executeUpdate(stmt,sql);
}
- catch (StorageObjectFailure e) {
+ catch (DatabaseFailure e) {
throw e;
}
catch (SQLException e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
finally {
- storageObject.freeConnection(con,stmt);
+ database.freeConnection(con,stmt);
}
}
*
* @param anArticleId
* @param aMediaId
- * @throws StorageObjectFailure
+ * @throws DatabaseFailure
*/
- public void dettach(String anArticleId, String aMediaId) throws StorageObjectFailure
+ public void dettach(String anArticleId, String aMediaId) throws DatabaseFailure
{
if (aMediaId!=null){
DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId);
* Attaches media to the article
*/
- public void attach(String aMediaId) throws StorageObjectFailure
+ public void attach(String aMediaId) throws DatabaseFailure
{
if (aMediaId!=null) {
DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId);
setProduced(false);
}
else {
- logger.error("EntityContent: attach without mid");
+ getLogger().error("EntityContent: attach without mid");
}
}
package mircoders.entity;
+import mir.media.image.ImageMagickImageProcessor;
+import mir.media.image.ImageProcessor;
+import mir.media.MediaExc;
+import mir.storage.DatabaseFailure;
+
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
+import java.io.IOException;
import java.sql.SQLException;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import mir.util.StreamCopier;
-import mircoders.media.ImageProcessor;
-
-/**
- *
- * @author RK, mh, mir-coders
- * @version $Id: EntityImages.java,v 1.23 2004/11/06 19:56:13 idfx Exp $
- */
-
-
public class EntityImages extends EntityUploadedMedia
{
private int maxImageSize = configuration.getInt("Producer.Image.MaxSize");
public EntityImages()
{
super();
-
- logger = new LoggerWrapper("Entity.UploadedMedia.Images");
- }
-
- public EntityImages(StorageObject theStorage) {
- this();
- setStorage(theStorage);
}
/**
* Retrieves the image data
*/
- public InputStream getImage() throws StorageObjectFailure {
+ public byte[] getImage() throws DatabaseFailure {
try {
- return storageObject.getBinaryField("select image_data from images where id="+getId());
+ return database.getBinaryField("select image_data from images where id="+getId());
}
catch (SQLException e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
/**
* Processes and saves image data
*/
- public void setImage(InputStream anInputStream, String type) throws StorageObjectFailure {
- // todo: failures should be treated anInputStream a better way: exception -> rollback instead
- // of commit
+ public void setImage(InputStream anInputStream, String type) throws IOException, MediaExc, SQLException {
if (anInputStream != null) {
- try {
- ByteArrayOutputStream inputData = new ByteArrayOutputStream();
- StreamCopier.copy(anInputStream, inputData);
+ ImageProcessor processor = new ImageMagickImageProcessor(anInputStream);
- ImageProcessor processor = new ImageProcessor(inputData.toByteArray());
processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction);
ByteArrayOutputStream imageData = new ByteArrayOutputStream();
processor.writeScaledData(imageData, type);
- storageObject.setBinaryField("update images set image_data = ? where id = "+getId(), imageData.toByteArray());
+ database.setBinaryField("image_data", getId(), imageData.toByteArray());
- setFieldValue("img_height", new Integer(processor.getScaledHeight()).toString());
- setFieldValue("img_width", new Integer(processor.getScaledWidth()).toString());
+ setFieldValue("img_height", Integer.toString(processor.getScaledHeight()));
+ setFieldValue("img_width", Integer.toString(processor.getScaledWidth()));
imageData.reset();
processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
processor.writeScaledData(imageData, type);
- storageObject.setBinaryField("update images set icon_data = ? where id = "+getId(), imageData.toByteArray());
-
- setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
- setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
+ database.setBinaryField("icon_data", getId(), imageData.toByteArray());
+ setFieldValue("icon_height", Integer.toString(processor.getScaledHeight()));
+ setFieldValue("icon_width", Integer.toString(processor.getScaledWidth()));
+ processor.cleanup();
update();
- }
- catch (Exception e) {
- throw new StorageObjectFailure(e);
- }
}
}
*
* It will also take care of closing the OutputStream.
*/
- public InputStream getIcon() throws StorageObjectFailure {
+ public byte[] getIcon() throws DatabaseFailure {
try {
- return storageObject.getBinaryField("select icon_data from images where id="+getId());
+ return database.getBinaryField("select icon_data from images where id="+getId());
}
catch (SQLException e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
}
import java.util.Map;
-import mir.storage.StorageObject;
-
/**
- * This class handles storage of other data and meta data
+ * This class handles database of other data and meta data
*
* @author mh
* @version 11.11.2000
super();
}
- public EntityOther(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
package mircoders.entity;
import mir.entity.StorableObjectEntity;
-import mir.storage.StorageObject;
-/**
- * Diese Klasse enth?lt die Daten eines MetaObjekts
- *
- * @author RK
- * @version 29.6.1999
- */
-
public class EntityTopics extends StorableObjectEntity {
public EntityTopics(){
super();
}
-
- public EntityTopics(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
-
}
*/
package mircoders.entity;
-import java.sql.SQLException;
-import java.util.Map;
-
import mir.entity.AbstractEntity;
import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseUploadedMedia;
+import java.util.Map;
+
/**
*
* @author mh, mir-coders group
- * @version $Id: EntityUploadedMedia.java,v 1.28 2004/11/06 19:56:13 idfx Exp $
+ * @version $Id: EntityUploadedMedia.java,v 1.29 2007/04/08 21:46:43 idfx Exp $
*/
public class EntityUploadedMedia extends AbstractEntity {
- public EntityUploadedMedia() {
- super();
-
- logger = new LoggerWrapper("Entity.UploadedMedia");
- }
-
- public EntityUploadedMedia(StorageObject theStorage) {
- this();
-
- setStorage(theStorage);
- }
-
- public void update() throws StorageObjectFailure {
- super.update();
-
- try {
- storageObject.executeUpdate( "update content set is_produced='0' where exists(select * from content_x_media where content_id=content.id and media_id=" + getId()+")");
- storageObject.executeUpdate( "update content set is_produced='0' where exists(select * from comment_x_media, comment where comment_x_media.comment_id=comment.id and comment.to_media=content.id and comment_x_media.media_id=" + getId()+")");
- }
- catch (SQLException e) {
- throw new StorageObjectFailure(e);
- }
- }
-
public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
*
* @return mir.entity.Entity
*/
- public Entity getMediaType() throws StorageObjectFailure {
+ public Entity getMediaType() throws DatabaseFailure {
Entity ent = null;
try {
ent = DatabaseUploadedMedia.getInstance().getMediaType(this);
}
- catch (StorageObjectFailure e) {
- throw new StorageObjectFailure(e);
+ catch (DatabaseFailure e) {
+ throw new DatabaseFailure(e);
}
return ent;
}
*/
package mircoders.entity;
-import mir.entity.Entity;
import mir.entity.AbstractEntity;
-import mir.storage.StorageObject;
/**
* This class is objectmapping of database webdb_users
super();
}
- public EntityUsers(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
- // Methods
+ // Methods
public boolean isAdmin()
{
import java.util.Map;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-
-/**
- * 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 setFieldValues(Map theStringValues) {
- if (theStringValues != null) {
- if (!theStringValues.containsKey("is_published"))
- theStringValues.put("is_published", "0");
+public class EntityVideo extends EntityUploadedMedia {
+ public void setFieldValues(Map someFieldValues) {
+ if (someFieldValues != null) {
+ if (!someFieldValues.containsKey("is_published")) {
+ someFieldValues.put("is_published", "0");
+ }
}
- super.setFieldValues(theStringValues);
+ super.setFieldValues(someFieldValues);
}
}
\ No newline at end of file
package mircoders.global;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.GregorianCalendar;
-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.HttpServletResponse;
-
import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
+import mir.entity.adapter.EntityAdapterModel;
import mir.log.LoggerWrapper;
+import mir.module.EntityNotFoundExc;
import mir.session.Request;
-import mir.util.DateTimeFunctions;
-import mir.util.GeneratorFormatAdapters;
-import mir.util.StringRoutines;
+import mir.util.DateTimeRoutines;
import mir.util.EntityUtility;
+import mir.util.GeneratorFormatAdapters;
+import mircoders.abuse.FilterEngine;
import mircoders.entity.EntityComment;
import mircoders.entity.EntityContent;
import mircoders.localizer.MirAdminInterfaceLocalizer;
-import mircoders.localizer.MirAntiAbuseFilterType;
-
+import mircoders.module.ModuleComment;
+import mircoders.module.ModuleContent;
import org.apache.commons.collections.ExtendedProperties;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+/**
+ * This class manages abuse (spam, offending material, etc.). This
+ * is done by using a set of filters managed by the FilterEngine class.
+ * Filters may be of different types (IP, throttle, regexp...),
+ * but are created and configured in a single user interface (web page),
+ * and are stored in a single database table called "filter".
+ */
public class Abuse {
- private List filterRules;
- private Map filterTypes;
- private List filterTypeIds;
- private int maxIdentifier;
private LoggerWrapper logger;
private int logSize;
private boolean logEnabled;
private boolean cookieOnBlock;
private String articleBlockAction;
private String commentBlockAction;
- private List log;
+ private final List log = new ArrayList();
private File configFile = MirGlobal.config().getFile("Abuse.Config");
+ private FilterEngine filterEngine;
private MirPropertiesConfiguration configuration;
private static String cookieName = MirGlobal.config().getString("Abuse.CookieName");
private static int cookieMaxAge = 60 * 60 * MirGlobal.config().getInt("Abuse.CookieMaxAge");
+ private EntityAdapterModel model;
- public Abuse() {
+ public Abuse(EntityAdapterModel aModel) {
logger = new LoggerWrapper("Global.Abuse");
- filterRules = new Vector();
- maxIdentifier = 0;
- log = new Vector();
+ filterEngine = new FilterEngine(aModel);
+ model = aModel;
try {
configuration = MirPropertiesConfiguration.instance();
openPostingDisabled = false;
cookieOnBlock = false;
- try {
- filterTypes = new HashMap();
- filterTypeIds = new Vector();
-
- Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
-
- while (i.hasNext()) {
- MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();
- filterTypes.put(filterType.getName(), filterType);
- filterTypeIds.add(filterType.getName());
- }
- }
- catch (Throwable t) {
- throw new RuntimeException("Can't get filter types: " + t.getMessage());
- }
-
load();
}
+ public FilterEngine getFilterEngine() {
+ return filterEngine;
+ }
+
private void setCookie(HttpServletResponse aResponse) {
Random random = new Random();
return false;
}
-
- FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {
- Iterator iterator = filterRules.iterator();
-
- while (iterator.hasNext()) {
- FilterRule rule = (FilterRule) iterator.next();
-
- if (rule.test(anEntity, aRequest))
- return rule;
- }
-
- return null;
- }
-
+ /** Checks if there is a filter that matches a comment and takes
+ * appropriate action (as configured in the xxxxxaction field of
+ * the filter table). The actual matching is delegated to the
+ * FilterEngine class.
+ */
public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
try {
long time = System.currentTimeMillis();
- FilterRule filterRule = findMatchingFilter(aComment, aRequest);
+ FilterEngine.Filter matchingFilter = filterEngine.testPosting(aComment, aRequest);
- if (filterRule != null) {
- logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
- filterRule.setLastHit(new GregorianCalendar().getTime());
+ if (matchingFilter != null) {
+ logger.debug("Match for " + matchingFilter.getTag());
+ matchingFilter.updateLastHit(new GregorianCalendar().getTime());
StringBuffer line = new StringBuffer();
- line.append(DateTimeFunctions.advancedDateFormat(
+ line.append(DateTimeRoutines.advancedDateFormat(
configuration.getString("Mir.DefaultDateTimeFormat"),
(new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));
line.append(" ");
- line.append("filter");
-
- line.append(" ");
- line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");
+ line.append(matchingFilter.getTag());
EntityUtility.appendLineToField(aComment, "comment", line.toString());
- MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());
+ MirGlobal.performCommentOperation(null, aComment, matchingFilter.getCommentAction());
setCookie(aResponse);
save();
- logComment(aComment, aRequest, filterRule.getType(), filterRule.getExpression());
+ logComment(aComment, aRequest, matchingFilter.getTag());
}
- else
+ else {
logComment(aComment, aRequest);
+ }
-
- logger.info("checkComment: " + (System.currentTimeMillis() - time) + "ms");
+ logger.debug("checkComment: " + (System.currentTimeMillis() - time) + "ms");
}
catch (Throwable t) {
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- logger.error("Abuse.checkComment: " + t.toString());
+ logger.error("Exception thrown while checking comment", t);
}
}
-
+ /** Checks if there is a filter that matches an articleand takes
+ * appropriate action (as configured in the xxxxxaction field of
+ * the filter table). The actual matching is delegated to the
+ * FilterEngine class.
+ */
public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
try {
long time = System.currentTimeMillis();
- FilterRule filterRule = findMatchingFilter(anArticle, aRequest);
+ FilterEngine.Filter matchingFilter = filterEngine.testPosting(anArticle, aRequest);
- if (filterRule != null) {
- logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
- filterRule.setLastHit(new GregorianCalendar().getTime());
+ if (matchingFilter != null) {
+ logger.debug("Match for " + matchingFilter.getTag());
+// matchingFilter.updateLastHit(new GregorianCalendar().getTime());
StringBuffer line = new StringBuffer();
- line.append(DateTimeFunctions.advancedDateFormat(
+ line.append(DateTimeRoutines.advancedDateFormat(
configuration.getString("Mir.DefaultDateTimeFormat"),
(new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));
line.append(" ");
- line.append("filter");
-
- line.append(" ");
- line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");
+ line.append(matchingFilter.getTag());
EntityUtility.appendLineToField(anArticle, "comment", line.toString());
- MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());
+ MirGlobal.performArticleOperation(null, anArticle, matchingFilter.getArticleAction());
setCookie(aResponse);
save();
- logArticle(anArticle, aRequest, filterRule.getType(), filterRule.getExpression());
+ logArticle(anArticle, aRequest, matchingFilter.getTag());
}
- else
+ else {
logArticle(anArticle, aRequest);
+ }
logger.info("checkArticle: " + (System.currentTimeMillis() - time) + "ms");
}
catch (Throwable t) {
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- logger.error("Abuse.checkArticle: " + t.toString());
+ logger.error("Exception thrown while checking article", t);
}
}
}
public List getLog() {
+ ModuleContent contentModule = new ModuleContent();
+ ModuleComment commentModule = new ModuleComment();
+
synchronized (log) {
- try {
- 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 GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
- if (logEntry.getIsArticle())
- entry.put("type", "content");
- else
- entry.put("type", "comment");
- entry.put("browser", logEntry.getBrowserString());
- entry.put("hitfiltertype", logEntry.getHitFilterType());
- entry.put("hitfilterexpression", logEntry.getHitFilterExpression());
-
- result.add(entry);
+ List result = new ArrayList();
+
+ 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 GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
+
+ if (logEntry.getIsArticle()) {
+ entry.put("type", "content");
+ try {
+ entry.put("object",
+ model.makeEntityAdapter("content", contentModule.getById(logEntry.getId())));
+ }
+ catch (EntityNotFoundExc e) {
+ entry.put("object", null);
+ }
+ }
+ else {
+ entry.put("type", "comment");
+ try {
+ entry.put("object",
+ model.makeEntityAdapter("comment", commentModule.getById(logEntry.getId())));
+ }
+ catch (EntityNotFoundExc e) {
+ entry.put("object", null);
+ }
}
- return result;
- }
- catch (Throwable t) {
- throw new RuntimeException(t.toString());
+ entry.put("browser", logEntry.getBrowserString());
+ entry.put("filtertag", logEntry.getMatchingFilterTag());
+
+ result.add(entry);
}
+
+ return result;
}
}
public void logComment(Entity aComment, Request aRequest) {
- logComment(aComment, aRequest, null, null);
+ logComment(aComment, aRequest, null);
}
- public void logComment(Entity aComment, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+ public void logComment(Entity aComment, Request aRequest, String aMatchingFilterTag) {
String ipAddress = aRequest.getHeader("ip");
String id = aComment.getId();
String browser = aRequest.getHeader("User-Agent");
- logComment(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+ logComment(ipAddress, id, new Date(), browser, aMatchingFilterTag);
}
public void logArticle(Entity anArticle, Request aRequest) {
- logArticle(anArticle, aRequest, null, null);
+ logArticle(anArticle, aRequest, null);
}
- public void logArticle(Entity anArticle, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+ public void logArticle(Entity anArticle, Request aRequest, String aMatchingFilterTag) {
String ipAddress = aRequest.getHeader("ip");
String id = anArticle.getId();
String browser = aRequest.getHeader("User-Agent");
- logArticle(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+ logArticle(ipAddress, id, new Date(), browser, aMatchingFilterTag);
}
- public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
- appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false, aHitFilterType, aHitFilterExpression));
+ public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser, String aMatchingFilterTag) {
+ appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false, aMatchingFilterTag));
}
- public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
- appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true, aHitFilterType, aHitFilterExpression));
+ public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser, String aMatchingFilterTag) {
+ appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true, aMatchingFilterTag));
}
- public void load() {
- synchronized (filterRules) {
- try {
- ExtendedProperties configuration = new ExtendedProperties();
-
- try {
- configuration = new ExtendedProperties(configFile.getAbsolutePath());
- }
- catch (FileNotFoundException e) {
- }
-
- getFilterConfig(filterRules, "abuse.filter", configuration);
+ public synchronized void load() {
+ try {
+ ExtendedProperties configuration = new ExtendedProperties(configFile.getAbsolutePath());
- 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());
- }
+ 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", ""));
}
- }
-
- public void save() {
- synchronized (filterRules) {
- try {
- ExtendedProperties configuration = new ExtendedProperties();
-
- setFilterConfig(filterRules, "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 BufferedOutputStream(new FileOutputStream(configFile),8192), "Anti abuse configuration");
- }
- catch (Throwable t) {
- throw new RuntimeException(t.toString());
- }
+ catch (Throwable t) {
+ throw new RuntimeException(t.toString());
}
}
- public List getFilterTypes() {
+ public synchronized void save() {
try {
- List result = new Vector();
-
- Iterator i = filterTypeIds.iterator();
- while (i.hasNext()) {
- String id = (String) i.next();
+ ExtendedProperties configuration = new ExtendedProperties();
- Map action = new HashMap();
- action.put("resource", id);
- action.put("identifier", id);
-
- result.add(action);
- }
+ 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());
- return result;
+ configuration.save(new BufferedOutputStream(new FileOutputStream(configFile),8192), "Anti abuse configuration");
}
catch (Throwable t) {
- throw new RuntimeException("can't get article actions");
+ throw new RuntimeException(t.toString());
}
}
public List getArticleActions() {
try {
- List result = new Vector();
+ List result = new ArrayList();
Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
while (i.hasNext()) {
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+ MirAdminInterfaceLocalizer.EntityOperation operation =
+ (MirAdminInterfaceLocalizer.EntityOperation) i.next();
Map action = new HashMap();
action.put("resource", operation.getName());
public List getCommentActions() {
try {
- List result = new Vector();
+ List result = new ArrayList();
Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
while (i.hasNext()) {
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+ MirAdminInterfaceLocalizer.EntityOperation operation =
+ (MirAdminInterfaceLocalizer.EntityOperation) i.next();
Map action = new HashMap();
action.put("resource", operation.getName());
}
}
- public List getFilters() {
- List result = new Vector();
-
- synchronized (filterRules) {
- Iterator i = filterRules.iterator();
- while (i.hasNext()) {
- FilterRule filter = (FilterRule) i.next();
- result.add(filter.clone());
- }
- return result;
- }
- }
-
- public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
- return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);
- }
-
- public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {
- return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);
- }
-
- public FilterRule getFilter(String anId) {
- synchronized (filterRules) {
- FilterRule result = findFilter(filterRules, anId);
- if (result == null)
- return result;
- else
- return (FilterRule) result.clone();
- }
- }
-
- public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
- return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);
- }
-
- public void deleteFilter(String anIdentifier) {
- deleteFilter(filterRules, anIdentifier);
- }
-
- public void moveFilterUp(String anIdentifier) {
- moveFilter(filterRules, anIdentifier, -1);
- }
-
- public void moveFilterDown(String anIdentifier) {
- moveFilter(filterRules, anIdentifier, 1);
- }
-
- public void moveFilterToTop(String anIdentifier) {
- setFilterPosition(filterRules, anIdentifier, 0);
- }
-
- public void moveFilterToBottom(String anIdentifier) {
- setFilterPosition(filterRules, anIdentifier, Integer.MAX_VALUE);
- }
-
- private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {
- MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
-
- if (type == null)
- return "invalidtype";
-
- if (!type.validate(anExpression)) {
- return "invalidexpression";
- }
-
- FilterRule filter = new FilterRule();
-
- filter.setId(generateId());
- filter.setExpression(anExpression);
- filter.setType(aType);
- filter.setComments(aComments);
- filter.setArticleAction(anArticleAction);
- filter.setCommentAction(aCommentAction);
- filter.setLastHit(aLastHit);
-
- synchronized (aFilters) {
- aFilters.add(filter);
- }
-
- return null;
- }
-
- private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
- MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
-
- if (type == null)
- return "invalidtype";
-
- if (!type.validate(anExpression)) {
- return "invalidexpression";
- }
-
- synchronized (aFilters) {
- FilterRule filter = findFilter(aFilters, anIdentifier);
-
- if (filter != null) {
- filter.setExpression(anExpression);
- filter.setType(aType);
- filter.setCommentAction(aCommentAction);
- filter.setArticleAction(anArticleAction);
- filter.setComments(aComments);
- }
-
- return null;
- }
- }
-
- private FilterRule findFilter(List aFilters, String anIdentifier) {
- synchronized (aFilters) {
- Iterator i = aFilters.iterator();
- while (i.hasNext()) {
- FilterRule filter = (FilterRule) i.next();
-
- if (filter.getId().equals(anIdentifier)) {
- return filter;
- }
- }
- }
-
- return null;
- }
-
- private void setFilterPosition(List aFilters, String anIdentifier, int aPosition) {
- synchronized (aFilters) {
- if (aPosition<0)
- aPosition=0;
-
- for (int i = 0; i < aFilters.size(); i++) {
- FilterRule rule = (FilterRule) aFilters.get(i);
-
- if (rule.getId().equals(anIdentifier)) {
- aFilters.remove(rule);
-
- if (aPosition<aFilters.size())
- aFilters.add(aPosition, rule);
- else
- aFilters.add(rule);
- break;
- }
- }
- }
- }
-
- private void moveFilter(List aFilters, String anIdentifier, int aDirection) {
- synchronized (aFilters) {
- for (int i = 0; i < aFilters.size(); i++) {
- FilterRule rule = (FilterRule) aFilters.get(i);
-
- if (rule.getId().equals(anIdentifier) && (i + aDirection >= 0) && (i + aDirection < aFilters.size())) {
- aFilters.remove(rule);
- aFilters.add(i + aDirection, rule);
- break;
- }
- }
- }
- }
-
- private void deleteFilter(List aFilters, String anIdentifier) {
- synchronized (aFilters) {
- FilterRule filter = findFilter(aFilters, anIdentifier);
-
- if (filter != null) {
- aFilters.remove(filter);
- }
- }
- }
-
- private String generateId() {
- synchronized (this) {
- maxIdentifier = maxIdentifier + 1;
-
- return Integer.toString(maxIdentifier);
- }
- }
-
- public class FilterRule {
- private String identifier;
- private String expression;
- private String type;
- private String comments;
- private String articleAction;
- private String commentAction;
- private Date lastHit;
-
- public FilterRule() {
- expression = "";
- type = "";
- identifier = "";
- comments = "";
- articleAction = articleBlockAction;
- commentAction = commentBlockAction;
- lastHit = null;
- }
-
- public Date getLastHit() {
- return lastHit;
- }
-
- public void setLastHit(Date aDate) {
- lastHit = aDate;
- }
-
- 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;
- }
-
- public void setComments(String aComments) {
- comments = aComments;
- }
-
- public String getComments() {
- return comments;
- }
-
- public String getArticleAction() {
- return articleAction;
- }
-
- public void setArticleAction(String anArticleAction) {
- articleAction = anArticleAction;
- }
-
- public String getCommentAction() {
- return commentAction;
- }
-
- public void setCommentAction(String aCommentAction) {
- commentAction = aCommentAction;
- }
-
- public boolean test(Entity anEntity, Request aRequest) {
- MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);
- try {
- if (filterType != null)
- return filterType.test(expression, anEntity, aRequest);
- }
- catch (Throwable t) {
- logger.error("error while testing " + type + "-filter '" + expression + "'");
- }
-
- return false;
- };
-
- public Object clone() {
- FilterRule result = new FilterRule();
- result.setComments(getComments());
- result.setExpression(getExpression());
- result.setId(getId());
- result.setType(getType());
- result.setArticleAction(getArticleAction());
- result.setCommentAction(getCommentAction());
- result.setLastHit(getLastHit());
-
- return result;
- }
- }
-
- private String escapeConfigListEntry(String aFilterPart) {
- return StringRoutines.replaceStringCharacters(aFilterPart,
- new char[] {'\\', ':'},
- new String[] {"\\\\", "\\:"});
- }
-
- private String escapeFilterPart(String aFilterPart) {
- return StringRoutines.replaceStringCharacters(aFilterPart,
- new char[] {'\\', '\n', '\r', '\t', ' '},
- new String[] {"\\\\", "\\n", "\\r", "\\t", "\\ "});
- }
-
- private String deescapeFilterPart(String aFilterPart) {
- return StringRoutines.replaceEscapedStringCharacters(aFilterPart,
- '\\',
- new char[] {'\\', ':', 'n', 'r', 't', ' '},
- new String[] {"\\", ":", "\n", "\r", "\t", " "});
- }
-
- private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
- synchronized (aFilters) {
- Iterator i = aFilters.iterator();
-
- while (i.hasNext()) {
- FilterRule filter = (FilterRule) i.next();
-
- String filterconfig =
- escapeConfigListEntry(escapeFilterPart(filter.getType())) + ":" +
- escapeConfigListEntry(escapeFilterPart(filter.getExpression())) + ":" +
- escapeConfigListEntry(escapeFilterPart(filter.getArticleAction())) + ":" +
- escapeConfigListEntry(escapeFilterPart(filter.getCommentAction())) + ":" +
- escapeConfigListEntry(escapeFilterPart(filter.getComments())) + ":";
-
- if (filter.getLastHit() != null)
- filterconfig = filterconfig + filter.getLastHit().getTime();
-
- aConfiguration.addProperty(aConfigKey, filterconfig);
- }
- }
- }
-
- private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
- synchronized (aFilters) {
- aFilters.clear();
-
- if (aConfiguration.getStringArray(aConfigKey) != null) {
-
- Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).
- iterator();
-
- while (i.hasNext()) {
- String filter = (String) i.next();
- List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');
- if (parts.size() == 2) {
- parts.add(articleBlockAction);
- parts.add(commentBlockAction);
- parts.add("");
- parts.add("");
- }
-
- if (parts.size() >= 5) {
- Date lastHit = null;
-
- if (parts.size() >= 6) {
- String lastHitString = (String) parts.get(5);
-
- try {
- lastHit = new Date(Long.parseLong(lastHitString));
- }
- catch (Throwable t) {
- }
- }
-
- addFilter(deescapeFilterPart( (String) parts.get(0)),
- deescapeFilterPart( (String) parts.get(1)),
- deescapeFilterPart( (String) parts.get(4)),
- deescapeFilterPart( (String) parts.get(3)),
- deescapeFilterPart( (String) parts.get(2)), lastHit);
- }
- }
- }
- }
- }
-
private static class LogEntry {
private String ipNumber;
private String browserString;
private String id;
private Date timeStamp;
private boolean isArticle;
- private String hitFilterType;
- private String hitFilterExpression;
+ private String matchingFilterTag;
- public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle, String aHitFilterType, String aHitFilterExpression) {
+ public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle, String aMatchingFilterTag) {
ipNumber = anIpNumber;
browserString = aBrowserString;
id = anId;
isArticle = anIsArticle;
timeStamp = aTimeStamp;
- hitFilterType = aHitFilterType;
- hitFilterExpression = aHitFilterExpression;
+ matchingFilterTag = aMatchingFilterTag;
}
public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
- this(aTimeStamp, anIpNumber, aBrowserString, anId, anIsArticle, null, null);
+ this(aTimeStamp, anIpNumber, aBrowserString, anId, anIsArticle, null);
}
public String getIpNumber() {
return id;
}
- public String getHitFilterType() {
- return hitFilterType;
- }
-
- public String getHitFilterExpression() {
- return hitFilterExpression;
+ public String getMatchingFilterTag() {
+ return matchingFilterTag;
}
public Date getTimeStamp() {
}
}
}
- };
+ }
private void appendLog(LogEntry anEntry) {
synchronized (log) {
return false;
if (((CacheKey) aCacheKey).type.equals(type) && ((CacheKey) aCacheKey).selector.equals(selector))
return true;
- else
- return false;
+ return false;
}
}
--- /dev/null
+/*\r
+ * Copyright (C) 2006 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.global;\r
+\r
+import mir.changetracker.ChangeTracker;\r
+\r
+public class ChangeEngine {\r
+ private ChangeTracker tracker;\r
+\r
+ public ChangeEngine() {\r
+ tracker = new ChangeTracker();\r
+ }\r
+\r
+ /**\r
+ * Return the (global) change tracker\r
+ */\r
+ public ChangeTracker getTracker() {\r
+ return tracker;\r
+ }\r
+}\r
import java.util.Properties;
import mir.config.MirPropertiesConfiguration;
+
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;
import org.apache.commons.dbcp.PoolableConnection;
String dbHost = configuration.getString("Database.Host");
String dbPort = configuration.getString("Database.Port");
String dbName = configuration.getString("Database.Name");
- String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName+"?compatible=7.1";
+ String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;
String dbDriver = configuration.getString("Database.Driver");
Driver driver;
try {
package mircoders.global;
+import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.ArrayList;
import mir.log.LoggerWrapper;
lastCleanup = 0;
jobCleanupTreshold = 900; // seconds
queueRunner = new JobQueueRunner(logger);
- thread = new Thread(queueRunner);
+ thread = new Thread(queueRunner, "JobQueue");
thread.setDaemon(true);
thread.start();
}
public String appendJob(Job aJob, String aDescription) {
try {
- if (System.currentTimeMillis() - lastCleanup > 60000)
+ if (System.currentTimeMillis() - lastCleanup > 60000) {
cleanupJobList();
+ }
}
catch (Throwable t) {
logger.error("error while cleaning up joblist: " + t.toString());
synchronized (jobHandlers) {
JobHandler jobHandler = new JobHandler(aJob, Integer.toString(nrJobs), aDescription);
nrJobs++;
+
jobHandlers.add(jobHandler);
identifierToJobHandler.put(jobHandler.getIdentifier(), jobHandler);
+
jobHandler.setPending();
jobHandlers.notify();
}
public List getJobsInfo() {
+ if (System.currentTimeMillis() - lastCleanup > 60000) {
+ cleanupJobList();
+ }
+
List result = new ArrayList();
synchronized (jobHandlers) {
synchronized (jobHandler) {
if (jobHandler.isFinished() && jobHandler.getLastChange().before(treshold)) {
toRemove.add(jobHandler);
+ identifierToJobHandler.remove(jobHandler.getIdentifier());
}
}
}
else
setAborted();
}
- };
+ }
private void cancelOrAbortJob() {
synchronized (this) {
if (isProcessing())
job.abort();
}
- };
+ }
public int getStatus() {
synchronized(this) {
}
return true;
}
- else {
- return false;
- }
+ return false;
}
}
}
private class JobQueueRunner implements Runnable {
- private LoggerWrapper logger;
-
+
public JobQueueRunner(LoggerWrapper aLogger) {
logger = aLogger;
}
import java.util.Map;
import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.log.LoggerWrapper;
public class MRUCache {
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.global;\r
-\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.bundle.BasicBundleFactory;\r
-import mir.bundle.BundleFactory;\r
-import mir.bundle.CascadingBundleFactory;\r
-import mir.bundle.PropertiesFileBundleLoader;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.log.LoggerEngine;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.ConfigException;\r
-import mircoders.accesscontrol.AccessControl;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirCachingLocalizerDecorator;\r
-import mircoders.localizer.MirLocalizer;\r
-\r
-public class MirGlobal {\r
- static private MirLocalizer localizer;\r
- static private ProducerEngine producerEngine;\r
- static private Abuse abuse;\r
- static private MRUCache mruCache;\r
- static private AccessControl accessControl;\r
- static private Map articleOperations;\r
- static private Map commentOperations;\r
- static private Map loggedInUsers = new HashMap();\r
- static private Map loggedInUserIds = new HashMap();\r
- static private LoggerWrapper logger = new LoggerWrapper("Global");\r
- static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");\r
-// static private ChangeEngine changeEngine = new ChangeEngine();\r
- static private DatabaseEngine databaseEngine;\r
-\r
- static private BundleFactory bundleFactory =\r
- new CascadingBundleFactory(\r
- new BasicBundleFactory(\r
- new PropertiesFileBundleLoader(\r
- config().getHome())));\r
-\r
- public synchronized static MirLocalizer localizer() {\r
- String localizerClassName;\r
- Class localizerClass;\r
-\r
- if (localizer == null ) {\r
- localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");\r
-\r
- try {\r
- localizerClass = Class.forName(localizerClassName);\r
- }\r
- catch (Throwable t) {\r
- throw new ConfigException("localizer class '" +\r
- localizerClassName + "' not found: " + t.toString());\r
- }\r
-\r
- if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))\r
- throw new ConfigException("localizer class '" +\r
- localizerClassName + "' is not assignable from MirLocalizer");\r
-\r
- try {\r
- localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());\r
- }\r
- catch (Throwable t) {\r
- throw new ConfigException("localizer class '" +\r
- localizerClassName + "' cannot be instantiated: " + t.toString());\r
- }\r
- }\r
-\r
- return localizer;\r
- }\r
-\r
- /**\r
- * Returns a string that provides some global status information\r
- */\r
- public static String getStatus() {\r
- StringBuffer result = new StringBuffer();\r
-\r
- result.append((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/(1024*1024));\r
- result.append("M in use, ");\r
- result.append(Thread.currentThread().activeCount()).append(" threads, ");\r
- result.append(getDatabaseEngine().getStatus());\r
-\r
- return result.toString();\r
- }\r
-\r
- public synchronized static Abuse abuse() {\r
- if (abuse==null)\r
- abuse = new Abuse();\r
-\r
- return abuse;\r
- }\r
-\r
- /**\r
- * returns the global change engine (used to track changed files)\r
- */\r
-// public static ChangeEngine getChangeEngine() {\r
-// return changeEngine;\r
-// }\r
-\r
- public static MirPropertiesConfiguration config() {\r
- return MirPropertiesConfiguration.instance();\r
- }\r
-\r
- public synchronized static DatabaseEngine getDatabaseEngine() {\r
- if (databaseEngine==null)\r
- databaseEngine = new DatabaseEngine();\r
-\r
- return databaseEngine;\r
- }\r
-\r
- public static ProducerEngine getProducerEngine() {\r
- if (producerEngine == null) {\r
- producerEngine = new ProducerEngine();\r
- }\r
-\r
- return producerEngine;\r
- }\r
-\r
- public static MRUCache mruCache() {\r
- synchronized(MirGlobal.class) {\r
- if (mruCache == null) {\r
- mruCache = new MRUCache();\r
- }\r
- return mruCache;\r
- }\r
- }\r
-\r
- public static synchronized AccessControl accessControl() {\r
- if (accessControl == null) {\r
- accessControl=new AccessControl();\r
- }\r
-\r
- return accessControl;\r
- }\r
-\r
- public static void performArticleOperation(EntityUsers aUser, EntityContent anArticle, String anOperation) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getArticleOperationForName(anOperation);\r
-\r
- try {\r
- EntityAdapter user = null;\r
- if (aUser!=null)\r
- user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
-\r
- if (operation!=null)\r
- operation.perform(\r
- user,\r
- localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));\r
- }\r
- catch (Throwable t) {\r
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
-\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
-\r
- public static void performCommentOperation(EntityUsers aUser, EntityComment aComment, String anOperation) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getCommentOperationForName(anOperation);\r
-\r
- try {\r
- EntityAdapter user = null;\r
- if (aUser!=null)\r
- user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
-\r
- if (operation!=null)\r
- operation.perform(\r
- user,\r
- localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
-\r
- private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation\r
- getArticleOperationForName(String aName) {\r
- try {\r
- if (articleOperations == null) {\r
- articleOperations = new HashMap();\r
- Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();\r
- while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
- articleOperations.put(operation.getName(), operation);\r
- }\r
- }\r
-\r
- return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) articleOperations.get(aName);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
-\r
- private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation\r
- getCommentOperationForName(String aName) {\r
- try {\r
- if (commentOperations == null) {\r
- commentOperations = new HashMap();\r
- Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();\r
- while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
- commentOperations.put(operation.getName(), operation);\r
- }\r
- }\r
-\r
- return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) commentOperations.get(aName);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
-\r
- public static boolean isUserLoggedIn(String anId) {\r
- synchronized (loggedInUserIds) {\r
- return loggedInUserIds.containsKey(anId);\r
- }\r
- }\r
-\r
- public static List getLoggedInUsers() {\r
- List result = new Vector();\r
-\r
- synchronized (loggedInUsers) {\r
- Iterator i = loggedInUsers.entrySet().iterator();\r
-\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
-\r
- Map item = new HashMap();\r
- item.put("name", entry.getKey());\r
- item.put("count", entry.getValue());\r
- result.add(item);\r
- }\r
- }\r
-\r
- return result;\r
- }\r
-\r
- public static BundleFactory getBundleFactory() {\r
- return bundleFactory;\r
- }\r
-\r
- public static void registerLogin(String aName, String anId) {\r
- modifyLoggedInCount(aName, anId, 1);\r
- }\r
-\r
- public static void registerLogout(String aName, String anId) {\r
- modifyLoggedInCount(aName, anId, -1);\r
- }\r
-\r
- private static void modifyLoggedInCount(String aName, String anId, int aModifier) {\r
- synchronized (loggedInUsers) {\r
- Integer count = (Integer) loggedInUsers.get(aName);\r
- if (count==null)\r
- count = new Integer(0);\r
-\r
- if (count.intValue()+aModifier<=0) {\r
- loggedInUsers.remove(aName);\r
- }\r
- else {\r
- loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));\r
- }\r
- }\r
-\r
- synchronized (loggedInUserIds) {\r
- Integer count = (Integer) loggedInUserIds.get(anId);\r
- if (count==null)\r
- count = new Integer(0);\r
-\r
- if (count.intValue()+aModifier<=0) {\r
- loggedInUserIds.remove(anId);\r
- }\r
- else {\r
- loggedInUserIds.put(anId, new Integer(count.intValue() + aModifier));\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Called whenever a modifying admin action occurs. Used to log\r
- * the action, if admin activity logging is turned on,\r
- */\r
- public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {\r
- try {\r
- if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {\r
- String user = "unknown (" + aUser.toString() + ")";\r
- if (aUser != null)\r
- user = aUser.getFieldValue("login");\r
- adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);\r
- }\r
- }\r
- catch (Throwable t) {\r
- logger.error("Error while logging admin usage ("+\r
- aUser.toString()+", "+aDescription+"): " +t.toString());\r
- }\r
- }\r
-\r
- /**\r
- * Reloads all reloadable configurations, such as the producer subsystem.\r
- */\r
- public static void reloadConfigurations() throws MirGlobalExc, MirGlobalFailure {\r
- getProducerEngine().reloadConfiguration();\r
- try {\r
- LoggerEngine.reload();\r
- }\r
- catch (Throwable e) {\r
- throw new MirGlobalFailure(e);\r
- }\r
- getBundleFactory().reload();\r
- }\r
-}\r
-\r
-\r
+/*
+ * 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 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.global;
+
+import mir.bundle.BasicBundleFactory;
+import mir.bundle.BundleFactory;
+import mir.bundle.CascadingBundleFactory;
+import mir.bundle.PropertiesFileBundleLoader;
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerEngine;
+import mir.log.LoggerWrapper;
+import mircoders.accesscontrol.AccessControl;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUsers;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.LocalizerCache;
+import mircoders.localizer.MirLocalizer;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class MirGlobal {
+ static private MirLocalizer localizer;
+ static private ProducerEngine producerEngine;
+ static private Abuse abuse;
+ static private MRUCache mruCache;
+ static private AccessControl accessControl;
+ static private Map articleOperations;
+ static private Map commentOperations;
+ static private final Map loggedInUsers = new HashMap();
+ static private final Map loggedInUserIds = new HashMap();
+ static private LoggerWrapper logger = new LoggerWrapper("Global");
+ static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");
+
+ static private ChangeEngine changeEngine = new ChangeEngine();
+
+ static private DatabaseEngine databaseEngine;
+
+ static private BundleFactory bundleFactory =
+ new CascadingBundleFactory(
+ new BasicBundleFactory(
+ new PropertiesFileBundleLoader(
+ config().getHome())));
+
+ private MirGlobal() {
+ }
+
+ public synchronized static MirLocalizer localizer() {
+ String localizerClassName;
+ Class localizerClass;
+
+ if (localizer == null ) {
+ localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");
+
+ try {
+ localizerClass = Class.forName(localizerClassName);
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure("localizer class '" +
+ localizerClassName + "' not found: ", t);
+ }
+
+ if (!MirLocalizer.class.isAssignableFrom(localizerClass)) {
+ throw new MirLocalizerFailure("localizer class '" +
+ localizerClassName + "' is not assignable from MirLocalizer");
+ }
+
+ try {
+ localizer = new LocalizerCache((MirLocalizer) localizerClass.newInstance());
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure("localizer class '" +
+ localizerClassName + "' cannot be instantiated: " + t.getMessage(), t);
+ }
+ }
+
+ return localizer;
+ }
+
+ /**
+ * Returns a string that provides some global status information
+ */
+ public static String getStatus() {
+ StringBuffer result = new StringBuffer();
+
+ result.append((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/(1024*1024));
+ result.append("M in use, ");
+ result.append(Thread.activeCount()).append(" threads, ");
+ result.append(getDatabaseEngine().getStatus());
+
+ return result.toString();
+ }
+
+ synchronized public static Abuse abuse() {
+ if (abuse==null) {
+ try {
+ abuse = new Abuse(localizer().dataModel().adapterModel());
+ }
+ catch (MirLocalizerExc e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ return abuse;
+ }
+
+ /**
+ * returns the global change engine (used to track changed files)
+ */
+ public static ChangeEngine getChangeEngine() {
+ return changeEngine;
+ }
+
+ public static MirPropertiesConfiguration config() {
+ return MirPropertiesConfiguration.instance();
+ }
+
+ synchronized public static DatabaseEngine getDatabaseEngine() {
+ if (databaseEngine==null) {
+ databaseEngine = new DatabaseEngine();
+ }
+
+ return databaseEngine;
+ }
+
+ public static ProducerEngine getProducerEngine() {
+ if (producerEngine == null) {
+ producerEngine = new ProducerEngine();
+ }
+
+ return producerEngine;
+ }
+
+ public static MRUCache mruCache() {
+ synchronized(MirGlobal.class) {
+ if (mruCache == null) {
+ mruCache = new MRUCache();
+ }
+ return mruCache;
+ }
+ }
+
+ synchronized public static AccessControl accessControl() {
+ if (accessControl == null) {
+ accessControl=new AccessControl();
+ }
+
+ return accessControl;
+ }
+
+ public static void performArticleOperation(EntityUsers aUser, EntityContent anArticle, String anOperation) {
+ MirAdminInterfaceLocalizer.EntityOperation operation = getArticleOperationForName(anOperation);
+
+ try {
+ EntityAdapter user = null;
+ if (aUser!=null) {
+ user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
+ }
+
+ if (operation!=null) {
+ operation.perform(
+ user,
+ localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
+ }
+ }
+ catch (Throwable t) {
+ throw new MirGlobalFailure(t.getMessage(), t);
+ }
+ }
+
+ public static void performCommentOperation(EntityUsers aUser, EntityComment aComment, String anOperation) {
+ MirAdminInterfaceLocalizer.EntityOperation operation = getCommentOperationForName(anOperation);
+
+ try {
+ EntityAdapter user = null;
+ if (aUser!=null) {
+ user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
+ }
+
+ if (operation!=null) {
+ operation.perform(
+ user,
+ localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
+ }
+ }
+ catch (Throwable t) {
+ throw new MirGlobalFailure(t.getMessage(), t);
+ }
+ }
+
+ private synchronized static MirAdminInterfaceLocalizer.EntityOperation
+ getArticleOperationForName(String aName) {
+ try {
+ if (articleOperations == null) {
+ articleOperations = new HashMap();
+ Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();
+ while (i.hasNext()) {
+ MirAdminInterfaceLocalizer.EntityOperation operation =
+ (MirAdminInterfaceLocalizer.EntityOperation) i.next();
+ articleOperations.put(operation.getName(), operation);
+ }
+ }
+
+ return (MirAdminInterfaceLocalizer.EntityOperation) articleOperations.get(aName);
+ }
+ catch (Throwable t) {
+ throw new MirGlobalFailure(t.getMessage(), t);
+ }
+ }
+
+ private synchronized static MirAdminInterfaceLocalizer.EntityOperation
+ getCommentOperationForName(String aName) {
+ try {
+ if (commentOperations == null) {
+ commentOperations = new HashMap();
+ Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();
+ while (i.hasNext()) {
+ MirAdminInterfaceLocalizer.EntityOperation operation =
+ (MirAdminInterfaceLocalizer.EntityOperation) i.next();
+ commentOperations.put(operation.getName(), operation);
+ }
+ }
+
+ return (MirAdminInterfaceLocalizer.EntityOperation) commentOperations.get(aName);
+ }
+ catch (Throwable t) {
+ throw new MirGlobalFailure(t.getMessage(), t);
+ }
+ }
+
+ public static boolean isUserLoggedIn(String anId) {
+ synchronized (loggedInUserIds) {
+ return loggedInUserIds.containsKey(anId);
+ }
+ }
+
+ public static List getLoggedInUsers() {
+ List result = new ArrayList();
+
+ synchronized (loggedInUsers) {
+ Iterator i = loggedInUsers.entrySet().iterator();
+
+ while (i.hasNext()) {
+ Map.Entry entry = (Map.Entry) i.next();
+
+ Map item = new HashMap();
+ item.put("name", entry.getKey());
+ item.put("count", entry.getValue());
+ result.add(item);
+ }
+ }
+
+ return result;
+ }
+
+ public static BundleFactory getBundleFactory() {
+ return bundleFactory;
+ }
+
+ public static void registerLogin(String aName, String anId) {
+ modifyLoggedInCount(aName, anId, 1);
+ }
+
+ public static void registerLogout(String aName, String anId) {
+ modifyLoggedInCount(aName, anId, -1);
+ }
+
+ private static void modifyLoggedInCount(String aName, String anId, int aModifier) {
+ synchronized (loggedInUsers) {
+ Integer count = (Integer) loggedInUsers.get(aName);
+ if (count==null)
+ count = new Integer(0);
+
+ if (count.intValue()+aModifier<=0) {
+ loggedInUsers.remove(aName);
+ }
+ else {
+ loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));
+ }
+ }
+
+ synchronized (loggedInUserIds) {
+ Integer count = (Integer) loggedInUserIds.get(anId);
+ if (count==null)
+ count = new Integer(0);
+
+ if (count.intValue()+aModifier<=0) {
+ loggedInUserIds.remove(anId);
+ }
+ else {
+ loggedInUserIds.put(anId, new Integer(count.intValue() + aModifier));
+ }
+ }
+ }
+
+ /**
+ * Called whenever a modifying admin action occurs. Used to log
+ * the action, if admin activity logging is turned on,
+ */
+ public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {
+ try {
+ if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {
+ String user = "unknown (" + aUser.toString() + ")";
+ if (aUser != null)
+ user = aUser.getFieldValue("login");
+ adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);
+ }
+ }
+ catch (Throwable t) {
+ logger.error("Error while logging admin usage ("+
+ aUser.toString()+", "+aDescription+"): " +t.toString());
+ }
+ }
+
+ /**
+ * Reloads all reloadable configurations, such as the producer subsystem.
+ */
+ public static void reloadConfigurations() throws MirGlobalExc, MirGlobalFailure {
+ getProducerEngine().reloadConfiguration();
+ try {
+ LoggerEngine.reload();
+ }
+ catch (Throwable e) {
+ throw new MirGlobalFailure(e);
+ }
+ getBundleFactory().reload();
+ }
+}
+
+
super(aCause.getMessage(), aCause);
}
- public MirGlobalFailure(String msg, Exception cause){
- super(msg,cause);
+ public MirGlobalFailure(String aMessage, Throwable aCause){
+ super(aMessage,aCause);
}
+
+ public MirGlobalFailure(String aMessage){
+ super(aMessage, null);
+ }
+
}
*/
package mircoders.global;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
import mir.config.MirPropertiesConfiguration;
-import mir.log.LoggerToWriterAdapter;
import mir.log.LoggerWrapper;
import mir.producer.Producer;
import mir.producer.ProducerFactory;
+import mir.producer.ProductionContext;
import mir.util.GeneratorFormatAdapters;
import mir.util.StringRoutines;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Collections;
+
public class ProducerEngine {
- private JobQueue producerJobQueue;
- private LoggerWrapper logger;
- private Map nameToFactory;
- private List factories;
+ private final JobQueue producerJobQueue;
+ private final LoggerWrapper logger = new LoggerWrapper("Producer");
+ private final Map nameToFactory = new HashMap();;
+ private List factories = new ArrayList();
protected ProducerEngine() {
- logger = new LoggerWrapper("Producer");
producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue"));
-
- factories = new ArrayList();
- nameToFactory = new HashMap();
-
- try {
- reloadConfiguration();
- }
- catch (Throwable t) {
- }
+ reloadConfiguration();
}
/**
* Reloads the producer configuration
*/
- public void reloadConfiguration() throws MirGlobalExc, MirGlobalFailure {
+ public void reloadConfiguration() {
try {
- factories = MirGlobal.localizer().producers().loadFactories();
+ factories = new ArrayList(MirGlobal.localizer().producers().loadFactories());
synchronized (nameToFactory) {
nameToFactory.clear();
* Returns all factories
*/
public List getFactories() {
- return factories;
+ return Collections.unmodifiableList(factories);
}
/**
* Adds a producer job to the queue
*/
public void addJob(String aProducerFactory, String aVerb) throws MirGlobalExc, MirGlobalFailure {
- ProducerFactory factory;
-
- factory = getFactoryForName( aProducerFactory );
+ ProducerFactory factory = getFactoryForName( aProducerFactory );
- if (factory==null)
+ if (factory==null) {
throw new MirGlobalExc("Unknown producer: " + aProducerFactory);
+ }
- if (!factory.allowVerb(aVerb))
+ if (!factory.allowVerb(aVerb)) {
throw new MirGlobalExc("illegal producer/verb combination: " + aProducerFactory+"::"+aVerb);
+ }
producerJobQueue.appendJob(
new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb);
*/
public void cancelJobs(List aJobs) {
producerJobQueue.cancelJobs(aJobs);
- };
+ }
/**
* Cancels all jobs in the queue
*/
public void cancelAllJobs() {
producerJobQueue.cancelAllJobs();
- };
+ }
public void addTask(ProducerTask aTask) throws MirGlobalExc, MirGlobalFailure {
addJob(aTask.getProducer(), aTask.getVerb());
}
private String convertStatus(JobQueue.JobInfo aJob) {
+
switch (aJob.getStatus()) {
case JobQueue.STATUS_ABORTED:
return "aborted";
+
case JobQueue.STATUS_CANCELLED:
return "cancelled";
+
case JobQueue.STATUS_CREATED:
return "created";
+
case JobQueue.STATUS_PENDING:
return "pending";
+
case JobQueue.STATUS_PROCESSED:
return "processed";
+
case JobQueue.STATUS_PROCESSING:
return "processing";
}
+
return "unknown";
}
private Map convertJob(JobQueue.JobInfo aJob) {
try {
Map result = new HashMap();
+
result.put("identifier", aJob.getIdentifier());
result.put("description", aJob.getDescription());
result.put("priority", new Integer(aJob.getPriority()));
}
private List convertJobInfoList(List aJobInfoList) {
- List result = new Vector();
+ List result = new ArrayList();
Iterator i = aJobInfoList.iterator();
private String factoryName;
private String verb;
private Producer producer;
+ private ProductionContext productionContext;
- public ProducerJob(String aFactory, String aVerb) {
+ ProducerJob(String aFactory, String aVerb) {
factoryName = aFactory;
verb = aVerb;
producer=null;
}
public void abort() {
- if (producer!=null) {
- producer.abort();
+ if (producer!=null && productionContext!=null) {
+ producer.abort(productionContext);
}
}
public boolean run() {
- ProducerFactory factory;
- long startTime;
- long endTime;
- boolean result = false;
- Map startingMap = new HashMap();
- Map mirMap = new HashMap();
- mirMap.put("producer", factoryName);
- mirMap.put("verb", verb);
-
- startingMap.put("Mir", mirMap);
+ final Map startingMap = new HashMap();
- startTime = System.currentTimeMillis();
+ long startTime = System.currentTimeMillis();
logger.info("Producing job: "+factoryName+"."+verb);
+ boolean result = false;
try {
- factory = getFactoryForName(factoryName);
+ final ProducerFactory factory = getFactoryForName(factoryName);
if (factory!=null) {
MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap);
synchronized(factory) {
producer = factory.makeProducer(verb, startingMap);
}
+
if (producer!=null) {
- result = producer.produce(logger);
+ try {
+ MirGlobal.localizer().producers().beforeProducerTask(factoryName, verb);
+ }
+ catch (Throwable t) {
+ logger.warn("Misbehaving beforeProducerTask",t );
+ }
+
+ productionContext = new ProductionContext() {
+ public ProducerFactory getFactory() {
+ return factory;
+ }
+
+ public Producer getProducer() {
+ return producer;
+ }
+
+ public String getVerb() {
+ return verb;
+ }
+
+ public LoggerWrapper getLogger() {
+ return logger;
+ }
+
+ public Map getValueSet() {
+ return startingMap;
+ }
+ };
+
+ result = producer.execute(productionContext);
+ productionContext = null;
+ producer = null;
+
+ try {
+ MirGlobal.localizer().producers().afterProducerTask(factoryName, verb);
+ }
+ catch (Throwable t) {
+ logger.warn("Misbehaving afterProducerTask", t);
+ }
}
}
}
catch (Throwable t) {
- logger.error("Exception occurred while producing " + factoryName + "." + verb + t.getMessage());
- t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(logger, LoggerWrapper.ERROR_MESSAGE)));
+ logger.error("Exception occurred while producing " + factoryName + "." + verb, t);
}
- endTime = System.currentTimeMillis();
+ long endTime = System.currentTimeMillis();
+
logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms");
return result;
}
public static List parseProducerTaskList(String aList) throws MirGlobalExc {
- Iterator i;
- List result = new Vector();
+ List result = new ArrayList();
- i = StringRoutines.splitString(aList, ";").iterator();
+ Iterator i = StringRoutines.splitString(aList, ";").iterator();
while (i.hasNext()) {
String taskExpression = ((String) i.next()).trim();
if (taskExpression.length()>0) {
List parts = StringRoutines.splitString(taskExpression, ".");
- if (parts.size() != 2)
+ if (parts.size() != 2) {
throw new MirGlobalExc("Invalid producer expression: '" + taskExpression + "'");
- else
- result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1)));
+ }
+ result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1)));
}
}
--- /dev/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 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;
+import mir.generator.Generator;
+import mir.generator.WriterEngine;
+
+/**
+ * This was used to prevent localizers from being created
+ * all the time.
+ *
+ */
+public class LocalizerCache implements MirLocalizer {
+ private MirLocalizer localizer;
+ private MirProducerLocalizer producerLocalizer;
+ private MirGeneratorLocalizer generatorLocalizer;
+ private MirOpenPostingLocalizer openPostingsLocalizer;
+ private MirProducerAssistantLocalizer producerAssistantLocalizer;
+ private MirDataModelLocalizer dataModelLocalizer;
+ private MirAdminInterfaceLocalizer adminInterfaceLocalizer;
+ private MirMediaLocalizer mediaLocalizer;
+
+ public LocalizerCache(MirLocalizer aLocalizer) {
+ localizer = aLocalizer;
+ }
+
+ public MirProducerLocalizer producers() throws MirLocalizerFailure {
+ if (producerLocalizer==null) {
+ producerLocalizer = localizer.producers();
+ }
+
+ return producerLocalizer;
+ }
+
+ public MirGeneratorLocalizer generators() throws MirLocalizerFailure {
+ if (generatorLocalizer==null) {
+ generatorLocalizer = new MirCachingGeneratorLocalizer(localizer.generators());
+ }
+
+ return generatorLocalizer;
+ }
+
+ public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure {
+ if (openPostingsLocalizer==null) {
+ openPostingsLocalizer = localizer.openPostings();
+ }
+
+ return openPostingsLocalizer;
+ }
+
+ public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure {
+ if (producerAssistantLocalizer==null) {
+ producerAssistantLocalizer = localizer.producerAssistant();
+ }
+
+ return producerAssistantLocalizer;
+ }
+
+ public MirDataModelLocalizer dataModel() throws MirLocalizerFailure {
+ if (dataModelLocalizer==null) {
+ dataModelLocalizer = new MirCachingDatamodelLocalizer(localizer.dataModel());
+ }
+
+ return dataModelLocalizer;
+ }
+
+ public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure {
+ if (adminInterfaceLocalizer==null) {
+ adminInterfaceLocalizer = localizer.adminInterface();
+ }
+
+ return adminInterfaceLocalizer;
+ }
+
+ public MirMediaLocalizer media() throws MirLocalizerFailure {
+ if (mediaLocalizer==null) {
+ mediaLocalizer = localizer.media();
+ }
+
+ return mediaLocalizer;
+ }
+
+ private static class MirCachingDatamodelLocalizer implements MirDataModelLocalizer {
+ private MirDataModelLocalizer master;
+ private EntityAdapterModel adapterModel;
+
+ public MirCachingDatamodelLocalizer(MirDataModelLocalizer aMaster) {
+ master = aMaster;
+ adapterModel = null;
+ }
+
+ public EntityAdapterModel adapterModel() throws MirLocalizerExc, MirLocalizerFailure {
+ if (adapterModel==null) {
+ adapterModel = master.adapterModel();
+ }
+
+ return adapterModel;
+ }
+
+ }
+
+ private static class MirCachingGeneratorLocalizer implements MirGeneratorLocalizer {
+ private MirGeneratorLocalizer master;
+ private WriterEngine writerEngine;
+ private Generator.Library producerGeneratorLibrary;
+ private Generator.Library adminGeneratorLibrary;
+ private Generator.Library openPostingGeneratorLibrary;
+
+ public MirCachingGeneratorLocalizer(MirGeneratorLocalizer aMaster) {
+ master = aMaster;
+ }
+
+ public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure {
+ if (writerEngine==null) {
+ writerEngine = master.makeWriterEngine();
+ }
+
+ return writerEngine;
+ }
+
+ public Generator.Library makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ if (producerGeneratorLibrary==null) {
+ producerGeneratorLibrary = master.makeProducerGeneratorLibrary();
+ }
+
+ return producerGeneratorLibrary;
+ }
+
+ public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ if (adminGeneratorLibrary==null) {
+ adminGeneratorLibrary = master.makeAdminGeneratorLibrary();
+ }
+
+ return adminGeneratorLibrary;
+ }
+
+ public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ if (openPostingGeneratorLibrary==null) {
+ openPostingGeneratorLibrary = master.makeOpenPostingGeneratorLibrary();
+ }
+
+ return openPostingGeneratorLibrary;
+ }
+ }
+
+}
\ No newline at end of file
*/
package mircoders.localizer;
-import mir.entity.adapter.EntityAdapter;
-import mir.generator.Generator;
-
import java.util.List;
import java.util.Map;
+import mir.entity.adapter.EntityAdapter;
+import mir.generator.Generator;
+
/**
* Interface to allow for localized changed to the workings of the admin system
*
public List getPreviewPages(EntityAdapter anArticle) throws MirLocalizerExc, MirLocalizerFailure;
/**
- * Get the {@link List} of {@link MirSimpleEntityOperation}s available for comments
+ * Get the {@link List} of {@link EntityOperation}s available for comments
*/
public List simpleCommentOperations();
/**
- * Get the {@link List} of {@link MirSimpleEntityOperation}s available for articles
+ * Get the {@link List} of {@link EntityOperation}s available for articles
*/
public List simpleArticleOperations();
- public interface MirSimpleEntityOperation {
+ public interface EntityOperation {
+ /**
+ * Returns the name of the operation. Must be unique and immutable.
+ */
public String getName();
+
+ /**
+ * Is the operation valid for the given {@link EntityAdapter}
+ */
public boolean isAvailable(EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * perform the operation on the given {@link EntityAdapter} as the given user
+ */
public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure;
}
}
\ No newline at end of file
+++ /dev/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 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.Entity;
-import mir.session.Request;
-
-/**
- * Interface to define filter types for the anti-abuse system
- */
-
-public interface MirAntiAbuseFilterType {
- /**
- * The identifying name of the filter type. Must be unique.
- *
- * @return
- */
- public String getName();
-
- /**
- * Must return <code>true</code> if the expression is valid for this filter. <code>false</code> if not.
- * @param anExpression
- * @return
- */
- public boolean validate(String anExpression);
-
- /**
- * Must return <code>true</code> if the posting matches the filter.
- * @param anExpression
- * @return
- */
- public boolean test(String anExpression, Entity anEntity, Request aRequest);
-}
\ No newline at end of file
+++ /dev/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 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;
-import mir.generator.Generator;
-import mir.generator.WriterEngine;
-
-public class MirCachingLocalizerDecorator implements MirLocalizer {
- private MirLocalizer localizer;
- private MirProducerLocalizer producerLocalizer;
- private MirGeneratorLocalizer generatorLocalizer;
- private MirOpenPostingLocalizer openPostingsLocalizer;
- private MirProducerAssistantLocalizer producerAssistantLocalizer;
- private MirDataModelLocalizer dataModelLocalizer;
- private MirAdminInterfaceLocalizer adminInterfaceLocalizer;
- private MirMediaLocalizer mediaLocalizer;
-
- public MirCachingLocalizerDecorator(MirLocalizer aLocalizer) {
- localizer = aLocalizer;
- }
-
- public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc {
- if (producerLocalizer==null) {
- producerLocalizer = localizer.producers();
- }
-
- return producerLocalizer;
- }
-
- public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc {
- if (generatorLocalizer==null) {
- generatorLocalizer = new MirCachingGeneratorLocalizer(localizer.generators());
- }
-
- return generatorLocalizer;
- }
-
- public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc {
- if (openPostingsLocalizer==null) {
- openPostingsLocalizer = localizer.openPostings();
- }
-
- return openPostingsLocalizer;
- }
-
- public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc {
- if (producerAssistantLocalizer==null) {
- producerAssistantLocalizer = localizer.producerAssistant();
- }
-
- return producerAssistantLocalizer;
- }
-
- public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc {
- if (dataModelLocalizer==null) {
- dataModelLocalizer = new MirCachingDatamodelLocalizer(localizer.dataModel());
- }
-
- return dataModelLocalizer;
- }
-
- public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc {
- if (adminInterfaceLocalizer==null) {
- adminInterfaceLocalizer = localizer.adminInterface();
- }
-
- return adminInterfaceLocalizer;
- };
-
- public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
- if (mediaLocalizer==null) {
- mediaLocalizer = localizer.media();
- }
-
- return mediaLocalizer;
- }
-
- private static class MirCachingDatamodelLocalizer implements MirDataModelLocalizer {
- private MirDataModelLocalizer master;
- private EntityAdapterModel adapterModel;
-
- public MirCachingDatamodelLocalizer(MirDataModelLocalizer aMaster) {
- master = aMaster;
- adapterModel = null;
- }
-
- public EntityAdapterModel adapterModel() throws MirLocalizerExc, MirLocalizerFailure {
- if (adapterModel==null) {
- adapterModel = master.adapterModel();
- }
-
- return adapterModel;
- };
-
- }
-
- private static class MirCachingGeneratorLocalizer implements MirGeneratorLocalizer {
- private MirGeneratorLocalizer master;
- private WriterEngine writerEngine;
- private Generator.Library producerGeneratorLibrary;
- private Generator.Library adminGeneratorLibrary;
- private Generator.Library openPostingGeneratorLibrary;
-
- public MirCachingGeneratorLocalizer(MirGeneratorLocalizer aMaster) {
- master = aMaster;
- }
-
- public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure {
- if (writerEngine==null) {
- writerEngine = master.makeWriterEngine();
- }
-
- return writerEngine;
- };
-
- public Generator.Library makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
- if (producerGeneratorLibrary==null) {
- producerGeneratorLibrary = master.makeProducerGeneratorLibrary();
- }
-
- return producerGeneratorLibrary;
- };
-
- public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
- if (adminGeneratorLibrary==null) {
- adminGeneratorLibrary = master.makeAdminGeneratorLibrary();
- }
-
- return adminGeneratorLibrary;
- };
-
- public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
- if (openPostingGeneratorLibrary==null) {
- openPostingGeneratorLibrary = master.makeOpenPostingGeneratorLibrary();
- }
-
- return openPostingGeneratorLibrary;
- };
- }
-
-}
\ No newline at end of file
package mircoders.localizer;
+/**
+ * <p>Localizers provide a customization framework that allows
+ * different mir sites to behave differently. This is effectively used
+ * by various indymedia sites to customize things such open posting
+ * mechanisms, open posting validation, data model enhancements, etc.
+ * </p>
+ *
+ * <p>The <code>MirLocalizer</code> interface defines the centralized
+ * localizer, that may be accessed via the global
+ * <function>MirGlobal.localizer()</function> function. The central
+ * localizer provides accessors to domain specific localizers (like
+ * <code>MirBasicOpenPostingLocalizer</code>). </p>
+ *
+ * <p> Default behavior is provided by the
+ * <code>MirBasicLocalizer</code> and it's associated classes. These
+ * classes can be extended to override default behavior.</p>
+ *
+ */
+
public interface MirLocalizer {
- public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc;
- public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc;
- public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc;
- public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc;
- public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc;
- public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc;
- public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc;
+ public MirProducerLocalizer producers() throws MirLocalizerFailure;
+ public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure;
+ public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure;
+ public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure;
+ public MirGeneratorLocalizer generators() throws MirLocalizerFailure;
+ public MirDataModelLocalizer dataModel() throws MirLocalizerFailure;
+ public MirMediaLocalizer media() throws MirLocalizerFailure;
}
\ No newline at end of file
import multex.Failure;
public class MirLocalizerFailure extends Failure {
- public MirLocalizerFailure(String msg, Throwable throwable) {
- super(msg, throwable);
+ public MirLocalizerFailure(String aMessage, Throwable aCause) {
+ super(aMessage, aCause);
}
- public MirLocalizerFailure(Throwable aThrowable) {
- this(aThrowable.getMessage(), aThrowable);
+
+ public MirLocalizerFailure(Throwable aCause) {
+ this(aCause.getMessage(), aCause);
+ }
+
+ public MirLocalizerFailure(String aMessage) {
+ super(aMessage, null);
}
}
/**
* Interface to allow for customization of the way Mir handles media publication,
- * manipulation and storage
+ * manipulation and database
*/
public interface MirMediaLocalizer {
/**
* This method will be called after an article is posted via the open posting interface.
*/
- public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;
+ public void afterArticlePosting(EntityContent anArticle) throws MirLocalizerExc, MirLocalizerFailure;
/**
*
*/
public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * This method should return <code>true</code> if the article should be visible
+ * to "open posting" users. This method is used to determine whether the request
+ * for a pdf, or an email for the article should be allowed. It is however
+ * <emph>not</emph> used by default by the production subsystem
+ */
+ public boolean allowArticlePublication(EntityContent anArticle);
}
*/
package mircoders.localizer;
+import mir.generator.Generator;
+
import java.util.Map;
public interface MirProducerAssistantLocalizer {
public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure;
public String filterHTMLText(String aText) throws MirLocalizerExc, MirLocalizerFailure;
public String filterNonHTMLText(String aText) throws MirLocalizerExc, MirLocalizerFailure;
+ public Generator.Interceptor createGenerationInterceptor() throws MirLocalizerExc, MirLocalizerFailure;
}
public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure;
public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure;
+
+ public void beforeProducerTask(String aFactory, String aVerb);
+ public void afterProducerTask(String aFactory, String aVerb);
}
package mircoders.localizer.basic;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+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 mir.bundle.Bundle;
import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
-import mir.entity.adapter.EntityAdapterExc;
+import mir.entity.adapter.EntityAdapterFailure;
import mir.generator.Generator;
import mir.generator.GeneratorExc;
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.module.ModuleExc;
-import mir.storage.StorageObjectFailure;
-import mir.util.DateTimeFunctions;
+import mir.storage.DatabaseFailure;
+import mir.util.DateTimeRoutines;
import mir.util.EntityUtility;
import mir.util.StringRoutines;
import mir.util.generator.BundleGeneratorFunction;
import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.MirLocalizerFailure;
import mircoders.module.ModuleLanguage;
+import mircoders.module.ModuleContent;
+import mircoders.module.ModuleComment;
import mircoders.storage.DatabaseContent;
-import java.util.*;
-
public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer {
/** preview page name (String) -> generator name (String) */
private Map simpleCommentOperationsMap;
private Map simpleArticleOperationsMap;
- protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");;
+ protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");
protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure {
-
simpleCommentOperations = new ArrayList();
simpleArticleOperations = new ArrayList();
simpleCommentOperationsMap = 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));
+ addSimpleArticleOperation(new DeleteEntityOperation("delete"));
addSimpleCommentOperation(new ModifyCommentFieldOperation("unhide", "is_published", "1"));
addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0"));
+ addSimpleCommentOperation(new DeleteEntityOperation("delete"));
}
/** {@inheritDoc} */
- public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser, String aDefault) throws MirLocalizerExc {
+ public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser,
+ String aDefault) throws MirLocalizerExc {
return aDefault;
}
/** {@inheritDoc} */
- public Generator prepareArticlePreview(String aPreviewPage, EntityAdapter anArticle, Map aContext) throws MirLocalizerExc {
+ public Generator prepareArticlePreview(String aPreviewPage, EntityAdapter anArticle,
+ Map aContext) throws MirLocalizerExc {
MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(aContext);
aContext.put("article", anArticle);
-
try {
aContext.put(
"language",
MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("language",
new ModuleLanguage().languageForCode(configuration.getString("Mir.Localizer.Admin.ArticlePreviewLanguage"))));
}
- catch (EntityAdapterExc e) {
+ catch (EntityAdapterFailure e) {
throw new MirLocalizerFailure("Can't create entity adapter", e);
}
catch (ModuleExc e) {
if (previewPages.containsKey(aPreviewPage)) {
try {
- return MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator((String) previewPages.get(aPreviewPage));
+ return MirGlobal.localizer().generators().makeAdminGeneratorLibrary().
+ makeGenerator((String) previewPages.get(aPreviewPage), null);
}
catch (GeneratorExc e) {
throw new MirLocalizerFailure(e);
}
}
- else {
- throw new MirLocalizerExc("Unknown preview: " + aPreviewPage);
- }
+ throw new MirLocalizerExc("Unknown preview: " + aPreviewPage);
}
/** {@inheritDoc} */
/** {@inheritDoc} */
public String makePasswordDigest(String aPassword) {
+
+
return aPassword;
}
+ /** {@inheritDoc} */
public void initializeArticle(Map anArticle) {
anArticle.put("is_published", "0");
anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
- };
+ }
public List simpleCommentOperations() {
return Collections.unmodifiableList(simpleCommentOperations);
- };
+ }
public List simpleArticleOperations() {
return Collections.unmodifiableList(simpleArticleOperations);
- };
+ }
- public MirSimpleEntityOperation simpleArticleOperationForName(String aName) {
- return (MirSimpleEntityOperation) simpleArticleOperationsMap.get(aName);
- };
+ public EntityOperation simpleArticleOperationForName(String aName) {
+ return (EntityOperation) simpleArticleOperationsMap.get(aName);
+ }
- public MirSimpleEntityOperation simpleCommentOperationForName(String aName) {
- return (MirSimpleEntityOperation) simpleCommentOperationsMap.get(aName);
- };
+ public EntityOperation simpleCommentOperationForName(String aName) {
+ return (EntityOperation) simpleCommentOperationsMap.get(aName);
+ }
public void removeSimpleArticleOperation(String aName) {
simpleArticleOperations.remove(simpleArticleOperationsMap.get(aName));
simpleArticleOperationsMap.remove(aName);
}
- public void addSimpleArticleOperation(MirSimpleEntityOperation anOperation) {
+ public void addSimpleArticleOperation(EntityOperation anOperation) {
removeSimpleArticleOperation(anOperation.getName());
simpleArticleOperationsMap.put(anOperation.getName(), anOperation);
simpleArticleOperations.add(anOperation);
simpleCommentOperationsMap.remove(aName);
}
- public void addSimpleCommentOperation(MirSimpleEntityOperation anOperation) {
+ public void addSimpleCommentOperation(EntityOperation anOperation) {
removeSimpleCommentOperation(anOperation.getName());
simpleCommentOperationsMap.put(anOperation.getName(), anOperation);
simpleCommentOperations.add(anOperation);
}
- protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation {
+ protected abstract static class EntityModifyingOperation implements EntityOperation {
private String name;
private boolean logOperation;
public String getName() {
return name;
- };
+ }
public boolean isAvailable(EntityAdapter anEntity) {
try {
catch (Throwable t) {
return false;
}
- };
+ }
public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
Entity entity = anEntity.getEntity();
try {
StringBuffer line = new StringBuffer();
- line.append(DateTimeFunctions.advancedDateFormat(
+ line.append(DateTimeRoutines.advancedDateFormat(
MirGlobal.config().getString("Mir.DefaultDateTimeFormat"),
(new GregorianCalendar()).getTime(),
MirGlobal.config().getString("Mir.DefaultTimezone")));
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
- };
+ }
- protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ;
+ protected abstract boolean isAvailable(Entity anEntity) throws DatabaseFailure ;
protected abstract void performModification(EntityAdapter aUser, Entity anEntity) throws MirLocalizerExc, MirLocalizerFailure ;
}
this(aName, true);
}
- protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
+ protected boolean isAvailable(Entity anEntity) throws DatabaseFailure {
return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity);
}
- protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, Entity anEntity) throws DatabaseFailure {
performModification(aUser, (EntityComment) anEntity);
DatabaseContent.getInstance().setUnproduced("id="+anEntity.getFieldValue("to_media"));
- };
+ }
- protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ;
- protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ;
+ protected abstract boolean isAvailable(EntityComment aComment) throws DatabaseFailure ;
+ protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure ;
}
public static abstract class ArticleModifyingOperation extends EntityModifyingOperation {
super(aName, aLogOperation);
}
- protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
+ protected boolean isAvailable(Entity anEntity) throws DatabaseFailure {
return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity);
}
- protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, Entity anEntity) throws DatabaseFailure {
performModification(aUser, (EntityContent) anEntity);
anEntity.setFieldValue("is_produced", "0");
- };
+ }
- protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ;
- protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ;
+ protected abstract boolean isAvailable(EntityContent anArticle) throws DatabaseFailure ;
+ protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure ;
}
protected static class SetCommentFieldOperation extends CommentModifyingOperation {
return true;
}
- protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure {
aComment.setFieldValue(field, value);
}
}
return true;
}
- protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure {
Iterator i = values.entrySet().iterator();
while (i.hasNext()) {
return aComment.getFieldValue(field) == null || !aComment.getFieldValue(field).equals(value);
}
- protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure {
aComment.setFieldValue(field, value);
}
}
return true;
}
- protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure {
anArticle.setFieldValue(field, value);
}
}
return anArticle.getFieldValue(field) == null || !anArticle.getFieldValue(field).equals(value);
}
- protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure {
anArticle.setFieldValue(field, value);
}
}
return anArticle.getFieldValue(field) != null && oldValues.contains(anArticle.getFieldValue(field));
}
- protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure {
anArticle.setFieldValue(field, newValue);
}
}
+
+ public static class DeleteEntityOperation implements EntityOperation {
+ private String name;
+ private ModuleContent content;
+ private ModuleComment comment;
+
+ public DeleteEntityOperation(String aName) {
+ name = aName;
+ comment = new ModuleComment();
+ content = new ModuleContent();
+ }
+
+ public String getName() {
+ return "delete";
+ }
+
+ public boolean isAvailable(EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+ return false;
+ }
+
+ public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+ Entity entity = anEntity.getEntity();
+ try {
+ if (entity instanceof EntityContent) {
+ content.deleteById(entity.getId());
+ }
+ else if (entity instanceof EntityComment) {
+ comment.deleteById(entity.getId());
+ }
+ }
+ catch (ModuleExc e) {
+ throw new MirLocalizerFailure(e);
+ }
+ }
+ }
}
+++ /dev/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 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 gnu.regexp.RE;
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.session.Request;
-import mir.util.InternetFunctions;
-import mircoders.localizer.MirAntiAbuseFilterType;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-
-/**
- * Wrapper around a collection of common filter classes for Mir's
- * anti-abuse filtering system.
- */
-public class MirBasicAntiAbuseFilterTypes {
- protected static final LoggerWrapper logger = new LoggerWrapper("Localizer.ProducerAssistant");
-
- private MirBasicAntiAbuseFilterTypes() {
- }
-
- public static abstract class BasicFilterType implements MirAntiAbuseFilterType {
- private String name;
-
- public BasicFilterType(String aName) {
- name = aName;
- }
-
- public String getName() {
- return name;
- }
- }
-
- /**
- * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.
- */
- public static class IPFilter extends BasicFilterType {
- /**
- *
- */
- public IPFilter(String aName) {
- super(aName);
- }
-
- /**
- *
- */
- public boolean validate(String anExpression) {
- try {
- InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);
- return true;
- }
- catch (Throwable t) {
- return false;
- }
- };
-
- /**
- *
- */
- public boolean test(String anExpression, Entity anEntity, Request aRequest) {
- try {
- return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);
- }
- catch (Throwable t) {
- return false;
- }
- };
- }
-
- /**
- * A regular expression filter.
- */
- public static class RegularExpressionFilter extends BasicFilterType {
- private boolean exactMatch;
- private boolean caseSensitive;
- private int fieldKind;
- private List selectedFields;
-
- public static final int ENTITY_FIELDS = 0;
- public static final int REQUEST_HEADERS = 2;
-
- public RegularExpressionFilter(String aName) {
- this(aName, false, false, null);
- }
-
- public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {
- this (aName, aCaseSensitive, anExactMatch, ENTITY_FIELDS, aSelectedFields);
- }
-
- public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, int aFieldKind, String[] aSelectedFields) {
- super(aName);
-
- fieldKind = aFieldKind;
-
- caseSensitive = aCaseSensitive;
- exactMatch = anExactMatch;
- if (aSelectedFields==null)
- selectedFields = null;
- else
- selectedFields = Arrays.asList(aSelectedFields);
- }
-
- public boolean validate(String anExpression) {
- try {
- new RE(anExpression);
- return true;
- }
- catch (Throwable t) {
- return false;
- }
- };
-
- public boolean test(String anExpression, Entity anEntity, Request aRequest) {
- try {
- Iterator j;
- int flags = 0;
-
- if (!caseSensitive) {
- flags |= RE.REG_ICASE;
- }
-
- RE regularExpression = new RE(anExpression, flags);
-
- switch (fieldKind) {
- case REQUEST_HEADERS:
- if (selectedFields != null) {
- j = selectedFields.iterator();
-
- while (j.hasNext()) {
- String fieldName = (String) j.next();
- String field = aRequest.getHeader(fieldName);
-
- if (exactMatch) {
- if (field != null && regularExpression.isMatch(field)) {
- return true;
- }
- }
- else {
- if (field != null && regularExpression.getMatch(field) != null) {
- return true;
- }
- }
- }
- }
- break;
- case ENTITY_FIELDS:
- if (selectedFields != null)
- j = selectedFields.iterator();
- else
- j = anEntity.getFieldNames().iterator();
-
- while (j.hasNext()) {
- String field = anEntity.getFieldValue( (String) j.next());
-
- if (exactMatch) {
- if (field != null && regularExpression.isMatch(field)) {
- return true;
- }
- }
- else {
- if (field != null && regularExpression.getMatch(field) != null) {
- return true;
- }
- }
- }
- }
- }
- catch (Throwable t) {
- }
- return false;
- }
- }
-
-}
\ No newline at end of file
import mir.entity.Entity;
import mir.misc.StringUtil;
-import mir.session.*;
+import mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mir.session.ValidationHelper;
+import mir.util.EntityUtility;
import mircoders.entity.EntityContent;
import mircoders.global.MirGlobal;
import mircoders.media.MediaUploadProcessor;
import mircoders.module.ModuleArticleType;
-import mircoders.module.ModuleContent;
import mircoders.module.ModuleMediafolder;
-import mircoders.storage.*;
+import mircoders.storage.DatabaseContent;
+import mircoders.storage.DatabaseContentToMedia;
+import mircoders.storage.DatabaseContentToTopics;
-import java.util.*;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
/**
* Extensible handler for open article postings
*/
public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {
- protected ModuleContent contentModule = new ModuleContent();
protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();
protected DatabaseContent contentDatabase = DatabaseContent.getInstance();
protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
super.initializeResponseData(aRequest, aSession, aResponse);
- Iterator i = DatabaseContent.getInstance().getFields().iterator();
+ Iterator i = DatabaseContent.getInstance().getFieldNames().iterator();
while (i.hasNext()) {
String field = (String) i.next();
aResponse.setResponseValue(field, aRequest.getParameter(field));
String id;
Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());
- EntityContent article = (EntityContent) contentModule.createNew();
+ EntityContent article = (EntityContent) contentDatabase.createNewEntity();
article.setFieldValues(values);
finalizeArticle(aRequest, aSession, article);
}
}
+ public void processAttachmentError(Request aRequest, Session aSession, Attachment aFile, Throwable anError) {
+ EntityUtility.appendLineToField( ((EntityContent) aSession.getAttribute("content")), "comment",
+ "error with attachment: " + anError.toString());
+ ((EntityContent) aSession.getAttribute("content")).update();
+ }
+
public void processAttachment(Request aRequest, Session aSession, Attachment aFile) throws SessionExc, SessionFailure {
try {
Map values = new HashMap();
MirGlobal.abuse().checkArticle(article, aRequest, null);
try {
- MirGlobal.localizer().openPostings().afterContentPosting(article);
+ MirGlobal.localizer().openPostings().afterArticlePosting(article);
}
catch (Throwable t) {
throw new SessionFailure(t);
}
logger.info("article posted");
- };
+ }
}
throw new SessionExc("initializeSession: parent id not set!");
aSession.setAttribute("to_content", parentId);
- };
+ }
}
\ No newline at end of file
package mircoders.localizer.basic;
import mir.entity.Entity;
-import mir.session.*;
+import mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mir.session.ValidationHelper;
+import mir.util.EntityUtility;
import mircoders.entity.EntityComment;
import mircoders.global.MirGlobal;
import mircoders.media.MediaUploadProcessor;
-import mircoders.module.ModuleComment;
import mircoders.module.ModuleCommentStatus;
import mircoders.module.ModuleMediafolder;
-import mircoders.storage.*;
+import mircoders.storage.DatabaseComment;
+import mircoders.storage.DatabaseCommentToMedia;
+import mircoders.storage.DatabaseContent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
- *
- * <p>Title: Experimental session handler for comment postings </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
+ * Session handler for comment postings
+ *
* @author Zapata
- * @version 1.0
*/
public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler {
- protected ModuleComment commentModule = new ModuleComment();
+ protected DatabaseComment commentDatabase = DatabaseComment.getInstance();
protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance();
protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
super.initializeResponseData(aRequest, aSession, aResponse);
- Iterator i = DatabaseComment.getInstance().getFields().iterator();
+ Iterator i = DatabaseComment.getInstance().getFieldNames().iterator();
while (i.hasNext()) {
String field = (String) i.next();
aResponse.setResponseValue(field, aRequest.getParameter(field));
throw new SessionExc("initializeSession: article id not set!");
aSession.setAttribute("to_media", articleId);
- };
+ }
public void finalizeComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure {
try {
aComment.setFieldValue("is_published", "1");
- ModuleCommentStatus module = new ModuleCommentStatus();
+ ModuleCommentStatus module = new ModuleCommentStatus();
aComment.setFieldValue("to_comment_status", module.commentStatusIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultCommentStatus")));
aComment.setFieldValue("is_html", "0");
aComment.setFieldValue("to_media", (String) aSession.getAttribute("to_media"));
String id;
Map values = getIntersectingValues(aRequest, DatabaseComment.getInstance());
- EntityComment comment = (EntityComment) commentModule.createNew();
+ EntityComment comment = (EntityComment) commentDatabase.createNewEntity();
comment.setFieldValues(values);
finalizeComment(aRequest, aSession, comment);
id = comment.insert();
}
}
+ public void processAttachmentError(Request aRequest, Session aSession, Attachment aFile, Throwable anError) {
+ EntityUtility.appendLineToField( ((EntityComment) aSession.getAttribute("comment")), "comment",
+ "error with attachment: " + anError.toString());
+
+ ((EntityComment) aSession.getAttribute("comment")).update();
+ }
+
public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
EntityComment comment = (EntityComment) aSession.getAttribute("comment");
}
DatabaseContent.getInstance().setUnproduced("id=" + comment.getFieldValue("to_media"));
logger.info("Comment posted");
- };
+ }
protected static class DuplicateCommentExc extends SessionExc {
public DuplicateCommentExc(String aMessage) {
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer.basic;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.Entity;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.entity.adapter.EntityAdapterDefinition;\r
-import mir.entity.adapter.EntityAdapterModel;\r
-import mir.generator.Generator;\r
-import mir.generator.GeneratorExc;\r
-import mir.generator.GeneratorFailure;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaHandler;\r
-import mir.misc.NumberUtils;\r
-import mir.util.JDBCStringRoutines;\r
-import mir.util.ParameterExpander;\r
-import mir.util.RewindableIterator;\r
-import mir.util.StructuredContentParser;\r
-import mircoders.entity.EntityUploadedMedia;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirDataModelLocalizer;\r
-import mircoders.localizer.MirLocalizerExc;\r
-import mircoders.localizer.MirLocalizerFailure;\r
-import mircoders.media.MediaHelper;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.module.ModuleLanguage;\r
-import mircoders.storage.*;\r
-import multex.Failure;\r
-\r
-import java.util.*;\r
-\r
-public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {\r
- protected LoggerWrapper logger = new LoggerWrapper("Localizer.DataModel");\r
- protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
- protected ModuleLanguage languageModule = new ModuleLanguage();\r
-\r
- protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc {\r
- try {\r
- anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange", configuration.getString("Mir.DefaultTimezone"));\r
- anEntityAdapterDefinition.addMirDateField("date", "date", configuration.getString("Mir.DefaultTimezone"));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("lockinguser", new ContentToUserField("to_locking_user"));\r
- anEntityAdapterDefinition.addCalculatedField("is_locked", new ContentToIsLockedField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField());\r
- anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField());\r
- anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'"));\r
- anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField(""));\r
-\r
-\r
- anEntityAdapterDefinition.addCalculatedField("mediacount", new ContentMediaCountField("uploaded_media", true));\r
- anEntityAdapterDefinition.addCalculatedField("fullmediacount", new ContentMediaCountField("uploaded_media", false));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" ));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("firstImage", new ContentToFirstMediaField( "image" ));\r
- anEntityAdapterDefinition.addCalculatedField("firstAudio", new ContentToFirstMediaField( "audio" ));\r
- anEntityAdapterDefinition.addCalculatedField("firstVideo", new ContentToFirstMediaField( "video" ));\r
- anEntityAdapterDefinition.addCalculatedField("firstOther", new ContentToFirstMediaField( "otherMedia" ));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new ContentToMediaField( "image", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new ContentToMediaField( "video", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new ContentToMediaField( "otherMedia", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));\r
- anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data"));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField());\r
- anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Article.PublicUrl")));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("operations",\r
- new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));\r
- \r
- anEntityAdapterDefinition.addCalculatedField("languagename", new ContentToLanguageNameField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("is_original", new ContentIsOriginalField());\r
- anEntityAdapterDefinition.addCalculatedField("to_original", new ContentToOriginalField());\r
- anEntityAdapterDefinition.addCalculatedField("to_translations", new ContentToTranslationsField());\r
- anEntityAdapterDefinition.addCalculatedField("to_translation", new ContentToTranslationField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("previews", new EntityAdapterDefinition.CalculatedField() {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return MirGlobal.localizer().adminInterface().getPreviewPages(anEntityAdapter);\r
- }\r
- catch (MirLocalizerExc e) {\r
- throw new Failure("Cannot get previews for article", e);\r
- }\r
- }\r
- });\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t.getMessage(), t);\r
- }\r
- }\r
-\r
-\r
-\r
- protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure {\r
- try {\r
- anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField());\r
- anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField());\r
-\r
- anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new CommentToMediaField( "uploadedMedia" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_images", new CommentToMediaField( "image" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_audio", new CommentToMediaField( "audio" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_video", new CommentToMediaField( "video" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_media_other", new CommentToMediaField( "otherMedia" ));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new CommentToMediaField( "uploadedMedia", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new CommentToMediaField( "image", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new CommentToMediaField( "audio", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new CommentToMediaField( "video", false));\r
- anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new CommentToMediaField( "otherMedia", false));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Comment.PublicUrl")));\r
-\r
- anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));\r
- anEntityAdapterDefinition.addCalculatedField("operations",\r
- new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations()));\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t.getMessage(), t);\r
- }\r
- }\r
-\r
- public EntityAdapterModel adapterModel() throws MirLocalizerFailure, MirLocalizerExc {\r
- EntityAdapterModel result = new EntityAdapterModel();\r
-\r
- try {\r
- EntityAdapterDefinition definition;\r
-\r
- definition = new EntityAdapterDefinition();\r
- constructContentAdapterDefinition( definition );\r
- result.addMapping( "content", DatabaseContent.getInstance(), definition);\r
-\r
- definition = new EntityAdapterDefinition();\r
- constructCommentAdapterDefinition( definition );\r
- result.addMapping( "comment", DatabaseComment.getInstance(), definition);\r
- result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());\r
-\r
- result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition());\r
-\r
- result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());\r
-\r
-\r
- definition = new EntityAdapterDefinition();\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition);\r
-\r
- definition = new EntityAdapterDefinition();\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- result.addMapping( "internalMessage", DatabaseMessages.getInstance(), definition);\r
-\r
- definition = new EntityAdapterDefinition();\r
- definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
- definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("info", new MediaToMediaInfoField());\r
- result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), definition);\r
- definition = new EntityAdapterDefinition();\r
- definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
- definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("info", new MediaToMediaInfoField());\r
- definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
- result.addMapping( "image", DatabaseImages.getInstance(), definition);\r
- definition = new EntityAdapterDefinition();\r
- definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
- definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("info", new MediaToMediaInfoField());\r
- definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
- result.addMapping( "audio", DatabaseAudio.getInstance(), definition);\r
- definition = new EntityAdapterDefinition();\r
- definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
- definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("info", new MediaToMediaInfoField());\r
- definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
- result.addMapping( "video", DatabaseVideo.getInstance(), definition);\r
-\r
- definition = new EntityAdapterDefinition();\r
- definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
- definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("info", new MediaToMediaInfoField());\r
- definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
- result.addMapping( "otherMedia", DatabaseOther.getInstance(), definition);\r
-\r
-\r
- result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition());\r
-\r
- definition = new EntityAdapterDefinition();\r
- definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addDBDateField("lastlogindate", "lastlogin", configuration.getString("Mir.DefaultTimezone"));\r
- definition.addCalculatedField("structuredProfile", new StructuredContentField("profile"));\r
- result.addMapping( "user", DatabaseUsers.getInstance(), definition);\r
-\r
- result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition());\r
-\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t.getMessage(), t);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_media"),\r
- "id",\r
- "content" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_comment_status"),\r
- "id",\r
- "commentStatus" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField {\r
- private List operations;\r
-\r
- public EntityToSimpleOperationsField(List anOperations) {\r
- operations = anOperations;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- Iterator i = operations.iterator();\r
- List availableOperations = new Vector();\r
-\r
- while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-\r
- if (operation.isAvailable(anEntityAdapter)) {\r
- availableOperations.add(operation.getName());\r
- }\r
- };\r
-\r
- return availableOperations;\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class FilteredField implements EntityAdapterDefinition.CalculatedField {\r
- private String fieldName;\r
-\r
- public FilteredField(String aFieldName) {\r
- fieldName = aFieldName;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) {\r
- return MirGlobal.localizer().producerAssistant().filterHTMLText((String) anEntityAdapter.get(fieldName));\r
- }\r
- else {\r
- return MirGlobal.localizer().producerAssistant().filterNonHTMLText((String) anEntityAdapter.get(fieldName));\r
- }\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class StructuredContentField implements EntityAdapterDefinition.CalculatedField {\r
- private String expression;\r
-\r
- public StructuredContentField(String anExpression) {\r
- expression = anExpression;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return StructuredContentParser.parse(ParameterExpander.evaluateStringExpression(anEntityAdapter, expression));\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ExpandedField implements EntityAdapterDefinition.CalculatedField {\r
- private String expression;\r
-\r
- public ExpandedField(String anExpression) {\r
- expression = anExpression;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return ParameterExpander.expandExpression(anEntityAdapter, expression);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class EvaluatedField implements EntityAdapterDefinition.CalculatedField {\r
- private String expression;\r
-\r
- public EvaluatedField(String anExpression) {\r
- expression = anExpression;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return ParameterExpander.evaluateExpression(anEntityAdapter, expression);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- logger.debug("ContentToParentField.getFieldValue");\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_content"),\r
- "id",\r
- "content" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getRelation(\r
- "to_content="+anEntityAdapter.get("id"),\r
- "id",\r
- "content" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_language"),\r
- "id",\r
- "language" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_article_type"),\r
- "id",\r
- "articleType" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class MediaToMediaFolderField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id="+anEntityAdapter.get("to_media_folder"),\r
- "id",\r
- "mediaFolder" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- public static class MediaInfo {\r
- private MediaHandler mediaHandler;\r
-\r
- public MediaInfo(MediaHandler aHandler) {\r
- mediaHandler = aHandler;\r
- }\r
- public String getBigIcon() {\r
- if (mediaHandler == null)\r
- return "bla";\r
- else\r
- return mediaHandler.getBigIconName();\r
- }\r
-\r
- public String getSmallIcon() {\r
- if (mediaHandler == null)\r
- return "bla";\r
- else\r
- return mediaHandler.getTinyIconName();\r
- }\r
-\r
- public String getMediaType() {\r
- return "";\r
- }\r
- }\r
-\r
- protected class MediaToMediaInfoField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- MediaHandler mediaHandler = MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType());\r
-\r
- return new MediaInfo(mediaHandler);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class MediaToBigIconField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType()).getBigIconName();\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField {\r
- private String extracondition;\r
- private String order;\r
-\r
- public ContentToCommentsField() {\r
- this ( " and is_published='1'", "webdb_create");\r
- }\r
-\r
- public ContentToCommentsField(String anExtraCondition, String anOrder) {\r
- order = anOrder;\r
- extracondition = anExtraCondition;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getRelation(\r
- "to_media="+anEntityAdapter.get("id")+" " + extracondition,\r
- order,\r
- "comment" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField {\r
- private String topicCondition;\r
- private String topicOrder;\r
-\r
- public ContentToTopicsField() {\r
- this(null);\r
- }\r
-\r
- public ContentToTopicsField(String aTopicCondition) {\r
- this(aTopicCondition, "title");\r
- }\r
-\r
- public ContentToTopicsField(String aTopicCondition, String aTopicOrder) {\r
- topicCondition = aTopicCondition;\r
- topicOrder = aTopicOrder;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
-\r
- Vector extraTable = new Vector();\r
- extraTable.add("content_x_topic cxt");\r
- String condition = "cxt.content_id="+anEntityAdapter.get("id")+\r
- " and cxt.topic_id=t.id";\r
-\r
- if (topicCondition!=null && topicCondition.length()>0)\r
- condition = "(" + topicCondition + ") and " + condition;\r
-\r
- return anEntityAdapter.getComplexRelation("t", extraTable,\r
- condition, topicOrder, "topic" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField {\r
- private String definition;\r
- private boolean published;\r
-\r
- public ContentToMediaField(String aDefinition, boolean anOnlyPublished) {\r
- definition = aDefinition;\r
- published = anOnlyPublished;\r
- }\r
-\r
- public ContentToMediaField(String aDefinition) {\r
- this(aDefinition, true);\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- String condition = "cxm.content_id="+ anEntityAdapter.get("id") +\r
- " and cxm.media_id = m.id";\r
- if (published)\r
- condition = "is_published='t' and " + condition;\r
-\r
- List extraTables = new Vector();\r
- extraTables.add("content_x_media cxm");\r
-\r
- return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToFirstMediaField implements EntityAdapterDefinition.CalculatedField {\r
- private String definition;\r
- private boolean published;\r
-\r
- public ContentToFirstMediaField(String aDefinition, boolean anOnlyPublished) {\r
- definition = aDefinition;\r
- published = anOnlyPublished;\r
- }\r
-\r
- public ContentToFirstMediaField(String aDefinition) {\r
- this(aDefinition, true);\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- String condition = "cxm.content_id="+ anEntityAdapter.get("id") +\r
- " and cxm.media_id = m.id";\r
- if (published)\r
- condition = "is_published='t' and " + condition;\r
-\r
- List extraTables = new Vector();\r
- extraTables.add("content_x_media cxm");\r
-\r
- return anEntityAdapter.getComplexToOneRelation("m", extraTables, condition, "id", definition);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class CommentToMediaField implements EntityAdapterDefinition.CalculatedField {\r
- private String definition;\r
- private boolean published;\r
-\r
- public CommentToMediaField(String aDefinition, boolean anOnlyPublished) {\r
- definition = aDefinition;\r
- published = anOnlyPublished;\r
- }\r
-\r
- public CommentToMediaField(String aDefinition) {\r
- this(aDefinition, true);\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
-\r
- String condition = "cxm.comment_id="+ anEntityAdapter.get("id") +\r
- " and cxm.media_id = m.id";\r
- if (published)\r
- condition = "is_published='t' and " + condition;\r
-\r
- List extraTables = new Vector();\r
- extraTables.add("comment_x_media cxm");\r
- return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);\r
-\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- EntityAdapter media;\r
- Entity mediaType;\r
- RewindableIterator iterator;\r
- Map result;\r
- MediaHandler mediaHandler;\r
- String tinyIcon;\r
- String iconAlt;\r
-\r
- try {\r
- iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media"));\r
- iterator.rewind();\r
-\r
- tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText");\r
- iconAlt = "Text";\r
-\r
- if (iterator.hasNext()) {\r
- media = (EntityAdapter) iterator.next();\r
-\r
- mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType();\r
- mediaHandler = MediaHelper.getHandler( mediaType );\r
-\r
- tinyIcon = mediaHandler.getTinyIconName();\r
- iconAlt = mediaHandler.getIconAltName();\r
- }\r
- }\r
- catch (Throwable t) {\r
- logger.error("ContentToIconField: " +t.getMessage());\r
- throw new RuntimeException(t.getMessage());\r
- }\r
-\r
- result = new HashMap();\r
- result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon);\r
- result.put("icon_alt", iconAlt);\r
-\r
- return result;\r
- }\r
- }\r
-\r
- protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField {\r
- private String extraCondition;\r
-\r
- public ContentCommentCountField(String anExtraCondition) {\r
- super();\r
-\r
- extraCondition = anExtraCondition;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return Integer.toString(\r
- DatabaseComment.getInstance().getSize(\r
- "to_media="+anEntityAdapter.get("id")+" " + extraCondition));\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class HumanReadableSizeField implements EntityAdapterDefinition.CalculatedField {\r
- private String fieldName;\r
-\r
- public HumanReadableSizeField(String aFieldName) {\r
- fieldName= aFieldName;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- String size = (String) anEntityAdapter.get(fieldName);\r
- if (size!=null)\r
- return NumberUtils.humanReadableSize(Double.parseDouble(size));\r
- else\r
- return "";\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
-\r
- protected class ContentMediaCountField implements EntityAdapterDefinition.CalculatedField {\r
- private String table;\r
- private boolean published;\r
-\r
- public ContentMediaCountField(String aTable, boolean anOnlyPublished) {\r
- table = aTable;\r
- published = anOnlyPublished;\r
- }\r
-\r
- public ContentMediaCountField(String aTable) {\r
- this(aTable, true);\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- Vector extraTable = new Vector();\r
- extraTable.add(table+" m");\r
- String selectSql = "cxm.media_id=m.id and cxm.content_id="+\r
- anEntityAdapter.get("id");\r
- if (published)\r
- selectSql+= " and m.is_published='t'";\r
-\r
- return Integer.toString(\r
- DatabaseContentToMedia.getInstance().getSize(\r
- "cxm", extraTable, selectSql));\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToUserField implements EntityAdapterDefinition.CalculatedField {\r
- private String fieldName;\r
-\r
- public ContentToUserField(String aFieldName) {\r
- fieldName = aFieldName;\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getToOneRelation(\r
- "id=" + anEntityAdapter.get(fieldName),\r
- "id",\r
- "user");\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToIsLockedField implements EntityAdapterDefinition.CalculatedField {\r
- private ModuleContent contentModule;\r
-\r
- public ContentToIsLockedField() {\r
- contentModule = new ModuleContent();\r
- }\r
-\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return new Boolean(contentModule.queryArticleLock(anEntityAdapter.getEntity().getId())!=null);\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
- protected class ContentIsOriginalField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
- try {\r
-\r
- //ML: add check on article type\r
- boolean result = (anEntityAdapter.get("parent")==null);\r
-\r
- return new Boolean(result);\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t);\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToOriginalField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
- try {\r
- if (anEntityAdapter.get("parent")!=null)\r
- return anEntityAdapter.get("parent");\r
- else\r
- return anEntityAdapter;\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t);\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToTranslationsField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) {\r
- try {\r
- return anEntityAdapter.getRelation(\r
- "is_published='t' and to_content="+anEntityAdapter.get("id"),\r
- "id",\r
- "content" );\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.getMessage());\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToLanguageNameField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
- try {\r
- String result = "";\r
- EntityAdapter language = (EntityAdapter) anEntityAdapter.get("language");\r
- if (language != null) {\r
- if (language.get("code").equals("ot")) {\r
- result = ((String) anEntityAdapter.get("subtitle")).trim();\r
- if (result == null || result.equals(""))\r
- result = (String) language.get("name");\r
- } else {\r
- result = (String) language.get("name");\r
- }\r
- }\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t);\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToTranslationFunction implements Generator.Function {\r
- private EntityAdapter target;\r
- private String targetId;\r
- private String targetLanguageId;\r
-\r
- public ContentToTranslationFunction(EntityAdapter aTarget) {\r
- target = aTarget;\r
- targetId = (String) target.get("id");\r
- targetLanguageId = (String) target.get("to_language");\r
- }\r
-\r
- public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {\r
- if (aParameters.size()!=1 || !(aParameters.get(0) instanceof String))\r
- throw new GeneratorExc("1 string parameter expected");\r
-\r
- try {\r
- String language = (String) aParameters.get(0);\r
- String languageId = languageModule.languageIdForCode(language);\r
- Object result = null;\r
-\r
- if (languageId != null && !targetLanguageId.equals(languageId)) {\r
- result = target.getToOneRelation(\r
- "is_published='t' and to_content=" + targetId + " and to_language='" + JDBCStringRoutines.escapeStringLiteral(languageId) + "'",\r
- "id", "content");\r
- }\r
-\r
- if (result == null)\r
- result = target;\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- t.printStackTrace(System.out);\r
- throw new GeneratorFailure(t);\r
- }\r
- }\r
- }\r
-\r
- protected class ContentToTranslationField implements EntityAdapterDefinition.CalculatedField {\r
- public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
- try {\r
- return new ContentToTranslationFunction((EntityAdapter) anEntityAdapter.get("to_original"));\r
- }\r
- catch (Throwable t) {\r
- throw new MirLocalizerFailure(t);\r
- }\r
- }\r
- }\r
-}\r
-\r
+/*
+ * 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 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 mir.config.MirPropertiesConfiguration;
+import mir.entity.Entity;
+import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityAdapterDefinition;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.ToManyRelationField;
+import mir.entity.adapter.ToOneRelationField;
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.generator.GeneratorFailure;
+import mir.log.LoggerWrapper;
+import mir.media.MediaHandler;
+import mir.misc.NumberUtils;
+import mir.util.JDBCStringRoutines;
+import mir.util.ParameterExpander;
+import mir.util.StructuredContentParser;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUploadedMedia;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.MirDataModelLocalizer;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.media.MediaHelper;
+import mircoders.module.ModuleCommentStatus;
+import mircoders.module.ModuleContent;
+import mircoders.module.ModuleLanguage;
+import mircoders.storage.*;
+import multex.Failure;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {
+ protected LoggerWrapper logger = new LoggerWrapper("Localizer.DataModel");
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+ protected ModuleLanguage languageModule = new ModuleLanguage();
+
+ protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc {
+ try {
+ anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange", configuration.getString("Mir.DefaultTimezone"));
+ anEntityAdapterDefinition.addMirDateField("date", "date", configuration.getString("Mir.DefaultTimezone"));
+
+ anEntityAdapterDefinition.addCalculatedField("lockinguser", new ToOneRelationField("to_locking_user", "id", "user"));
+ anEntityAdapterDefinition.addCalculatedField("is_locked", new ContentToIsLockedField());
+
+ anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField());
+ anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField());
+ anEntityAdapterDefinition.addCalculatedField("language", new ToOneRelationField("to_language", "language", "id"));
+ anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'"));
+ anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField(""));
+ anEntityAdapterDefinition.addCalculatedField("commentstatuscount", new CommentStatusCountField());
+
+ anEntityAdapterDefinition.addCalculatedField("mediacount", new ContentMediaCountField("uploaded_media", true));
+ anEntityAdapterDefinition.addCalculatedField("fullmediacount", new ContentMediaCountField("uploaded_media", false));
+
+ anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" ));
+ anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" ));
+ 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("firstImage", new ContentToFirstMediaField( "image" ));
+ anEntityAdapterDefinition.addCalculatedField("firstAudio", new ContentToFirstMediaField( "audio" ));
+ anEntityAdapterDefinition.addCalculatedField("firstVideo", new ContentToFirstMediaField( "video" ));
+ anEntityAdapterDefinition.addCalculatedField("firstOther", new ContentToFirstMediaField( "otherMedia" ));
+
+ anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new ContentToMediaField( "image", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new ContentToMediaField( "video", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new ContentToMediaField( "otherMedia", false));
+ anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField());
+
+ anEntityAdapterDefinition.addCalculatedField("article_type", new ToOneRelationField("to_article_type", "articleType", "id"));
+
+ 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 ToOneRelationField("to_content", "content", "id"));
+
+ anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Article.PublicUrl")));
+
+ anEntityAdapterDefinition.addCalculatedField("operations",
+ new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));
+
+ anEntityAdapterDefinition.addCalculatedField("languagename", new ContentToLanguageNameField());
+
+ anEntityAdapterDefinition.addCalculatedField("is_original", new ContentIsOriginalField());
+ anEntityAdapterDefinition.addCalculatedField("to_original", new ContentToOriginalField());
+ anEntityAdapterDefinition.addCalculatedField("to_translations", new ContentToTranslationsField());
+ anEntityAdapterDefinition.addCalculatedField("to_translation", new ContentToTranslationField());
+
+ anEntityAdapterDefinition.addCalculatedField("allow_publication",
+ new EntityAdapterDefinition.CalculatedField() {
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return new Boolean(MirGlobal.localizer().openPostings().
+ allowArticlePublication((EntityContent) anEntityAdapter.getEntity()));
+ }
+ catch (Throwable t) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ );
+
+ anEntityAdapterDefinition.addCalculatedField("previews", new EntityAdapterDefinition.CalculatedField() {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return MirGlobal.localizer().adminInterface().getPreviewPages(anEntityAdapter);
+ }
+ catch (MirLocalizerExc e) {
+ throw new Failure("Cannot get previews for article", e);
+ }
+ }
+ });
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t.getMessage(), t);
+ }
+ }
+
+
+
+ protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure {
+ try {
+ anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ anEntityAdapterDefinition.addCalculatedField("to_content", new ToOneRelationField("to_media", "content", "id"));
+ anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField());
+
+ anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new CommentToMediaField( "uploadedMedia" ));
+ anEntityAdapterDefinition.addCalculatedField("to_media_images", new CommentToMediaField( "image" ));
+ anEntityAdapterDefinition.addCalculatedField("to_media_audio", new CommentToMediaField( "audio" ));
+ anEntityAdapterDefinition.addCalculatedField("to_media_video", new CommentToMediaField( "video" ));
+ anEntityAdapterDefinition.addCalculatedField("to_media_other", new CommentToMediaField( "otherMedia" ));
+ anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new CommentToMediaField( "uploadedMedia", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new CommentToMediaField( "image", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new CommentToMediaField( "audio", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new CommentToMediaField( "video", false));
+ anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new CommentToMediaField( "otherMedia", false));
+
+ anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Comment.PublicUrl")));
+
+ 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);
+ }
+ }
+
+ public EntityAdapterModel adapterModel() throws MirLocalizerFailure, MirLocalizerExc {
+ 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( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());
+
+ result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition());
+
+ result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());
+
+
+ definition = new EntityAdapterDefinition();
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition);
+
+ definition = new EntityAdapterDefinition();
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ result.addMapping( "internalMessage", DatabaseMessages.getInstance(), definition);
+
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("mediafolder", new ToOneRelationField("to_media_folder", "mediaFolder", "id"));
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("size"));
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("info", new MediaToMediaInfoField());
+ result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), definition);
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("mediafolder", new ToOneRelationField("to_media_folder", "mediaFolder", "id"));
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("size"));
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("info", new MediaToMediaInfoField());
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());
+ result.addMapping( "image", DatabaseImages.getInstance(), definition);
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("mediafolder", new ToOneRelationField("to_media_folder", "mediaFolder", "id"));
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("size"));
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("info", new MediaToMediaInfoField());
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());
+ result.addMapping( "audio", DatabaseAudio.getInstance(), definition);
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("mediafolder", new ToOneRelationField("to_media_folder", "mediaFolder", "id"));
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("size"));
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("info", new MediaToMediaInfoField());
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());
+ result.addMapping( "video", DatabaseVideo.getInstance(), definition);
+
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("mediafolder", new ToOneRelationField("to_media_folder", "mediaFolder", "id"));
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("size"));
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("info", new MediaToMediaInfoField());
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());
+ result.addMapping( "otherMedia", DatabaseOther.getInstance(), definition);
+
+
+ result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition());
+ result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition());
+ result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition());
+ result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());
+ result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition());
+
+ definition = new EntityAdapterDefinition();
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));
+ definition.addDBDateField("lastlogindate", "lastlogin", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("structuredProfile", new StructuredContentField("profile"));
+ result.addMapping( "user", DatabaseUsers.getInstance(), definition);
+
+ result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition());
+
+ definition = new EntityAdapterDefinition();
+ definition.addCalculatedField("to_filters",
+ new ToManyRelationField("id", "filter", "filter_group_id", "priority asc"));
+ result.addMapping("filterGroup", DatabaseFilterGroup.getInstance(), definition);
+ definition = new EntityAdapterDefinition();
+ definition.addDBDateField("lasthit", "last_hit", configuration.getString("Mir.DefaultTimezone"));
+ definition.addCalculatedField("to_filter_group",
+ new ToOneRelationField("filter_group_id", "filter_group", "id"));
+ result.addMapping("filter", DatabaseFilter.getInstance(), definition);
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t.getMessage(), t);
+ }
+
+ return result;
+ }
+
+ 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 ArrayList();
+
+ while (i.hasNext()) {
+ MirAdminInterfaceLocalizer.EntityOperation operation =
+ (MirAdminInterfaceLocalizer.EntityOperation) 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 {
+ private 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 MirGlobal.localizer().producerAssistant().filterHTMLText((String) anEntityAdapter.get(fieldName));
+ }
+ return MirGlobal.localizer().producerAssistant().filterNonHTMLText((String) anEntityAdapter.get(fieldName));
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected class StructuredContentField implements EntityAdapterDefinition.CalculatedField {
+ private String expression;
+
+ public StructuredContentField(String anExpression) {
+ expression = anExpression;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return StructuredContentParser.parse(ParameterExpander.evaluateStringExpression(anEntityAdapter, expression));
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected class ExpandedField implements EntityAdapterDefinition.CalculatedField {
+ private String expression;
+
+ public ExpandedField(String anExpression) {
+ expression = anExpression;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return ParameterExpander.expandExpression(anEntityAdapter, expression);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected class EvaluatedField implements EntityAdapterDefinition.CalculatedField {
+ private String expression;
+
+ public EvaluatedField(String anExpression) {
+ expression = anExpression;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return ParameterExpander.evaluateExpression(anEntityAdapter, expression);
+ }
+ 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());
+ }
+ }
+ }
+
+ public static class MediaInfo {
+ private MediaHandler mediaHandler;
+ private Entity mediaType;
+
+ public MediaInfo(MediaHandler aHandler, Entity aMediaType) {
+ mediaHandler = aHandler;
+ mediaType = aMediaType;
+ }
+
+ public String getBigIcon() {
+ return mediaHandler.getBigIconName();
+ }
+
+ public String getSmallIcon() {
+ return mediaHandler.getTinyIconName();
+ }
+
+ public String getDescription() {
+ return mediaHandler.getDescr(mediaType);
+ }
+ }
+
+ protected static class MediaToMediaInfoField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ MediaHandler mediaHandler =
+ MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType());
+
+ return new MediaInfo(mediaHandler,
+ ((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType());
+ }
+ catch (Throwable t) {
+ throw new Failure(t.getMessage(), t);
+ }
+ }
+ }
+
+ protected static class MediaToBigIconField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType()).getBigIconName();
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField {
+ private String extracondition;
+ private String order;
+
+ public ContentToCommentsField() {
+ this ( " and is_published='1'", "webdb_create");
+ }
+
+ public ContentToCommentsField(String anExtraCondition, String anOrder) {
+ order = anOrder;
+ extracondition = anExtraCondition;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return anEntityAdapter.getRelation(
+ "to_media="+anEntityAdapter.get("id")+" " + extracondition,
+ order,
+ "comment" );
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField {
+ private String topicCondition;
+ private String topicOrder;
+
+ public ContentToTopicsField() {
+ this(null);
+ }
+
+ public ContentToTopicsField(String aTopicCondition) {
+ this(aTopicCondition, "title");
+ }
+
+ public ContentToTopicsField(String aTopicCondition, String aTopicOrder) {
+ topicCondition = aTopicCondition;
+ topicOrder = aTopicOrder;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ String condition = "cxt.content_id="+anEntityAdapter.get("id")+
+ " and cxt.topic_id=t.id";
+
+ if (topicCondition!=null && topicCondition.length()>0) {
+ condition = "(" + topicCondition + ") and " + condition;
+ }
+
+ return anEntityAdapter.getComplexRelation("t", Collections.singletonList("content_x_topic cxt"),
+ condition, topicOrder, "topic" );
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class ContentToMediaField implements EntityAdapterDefinition.CalculatedField {
+ private String definition;
+ private boolean published;
+
+ public ContentToMediaField(String aDefinition, boolean anOnlyPublished) {
+ definition = aDefinition;
+ published = anOnlyPublished;
+ }
+
+ public ContentToMediaField(String aDefinition) {
+ this(aDefinition, true);
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ String condition = "cxm.content_id="+ anEntityAdapter.get("id") +
+ " and cxm.media_id = m.id";
+
+ if (published) {
+ condition = "is_published='t' and " + condition;
+ }
+
+ List extraTables = new ArrayList();
+ extraTables.add("content_x_media cxm");
+
+ return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class ContentToFirstMediaField implements EntityAdapterDefinition.CalculatedField {
+ private String definition;
+ private boolean published;
+
+ public ContentToFirstMediaField(String aDefinition, boolean anOnlyPublished) {
+ definition = aDefinition;
+ published = anOnlyPublished;
+ }
+
+ public ContentToFirstMediaField(String aDefinition) {
+ this(aDefinition, true);
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ String condition = "cxm.content_id="+ anEntityAdapter.get("id") +
+ " and cxm.media_id = m.id";
+ if (published)
+ condition = "is_published='t' and " + condition;
+
+ List extraTables = new ArrayList();
+ extraTables.add("content_x_media cxm");
+
+ return anEntityAdapter.getComplexToOneRelation("m", extraTables, condition, "id", definition);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class CommentToMediaField implements EntityAdapterDefinition.CalculatedField {
+ private String definition;
+ private boolean published;
+
+ public CommentToMediaField(String aDefinition, boolean anOnlyPublished) {
+ definition = aDefinition;
+ published = anOnlyPublished;
+ }
+
+ public CommentToMediaField(String aDefinition) {
+ this(aDefinition, true);
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+
+ String condition = "cxm.comment_id = " + anEntityAdapter.get("id") + " and cxm.media_id = m.id";
+
+ if (published) {
+ condition = "is_published='t' and " + condition;
+ }
+
+ return anEntityAdapter.getComplexRelation("m", Collections.singletonList("comment_x_media cxm"),
+ condition, "id", definition);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected static class ContentToIconField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ String tinyIcon;
+ String iconAlt;
+
+ try {
+ tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText");
+ iconAlt = "Text";
+
+ Iterator iterator = anEntityAdapter.getIterator("to_media_video");
+ if (!iterator.hasNext()) {
+ iterator = anEntityAdapter.getIterator("to_media_audio");
+ }
+ if (!iterator.hasNext()) {
+ iterator = anEntityAdapter.getIterator("to_media_images");
+ }
+ if (!iterator.hasNext()) {
+ iterator = anEntityAdapter.getIterator("to_media_other");
+ }
+
+ if (iterator.hasNext()) {
+ EntityAdapter media = (EntityAdapter) iterator.next();
+
+ Entity mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType();
+ MediaHandler mediaHandler = MediaHelper.getHandler(mediaType);
+
+ tinyIcon = mediaHandler.getTinyIconName();
+ iconAlt = mediaHandler.getIconAltName();
+ }
+ }
+ catch (Throwable t) {
+ throw new Failure(t.getMessage(), t);
+ }
+
+ Map result = new HashMap();
+ result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon);
+ result.put("icon_alt", iconAlt);
+
+ return result;
+ }
+ }
+
+ protected static class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField {
+ private String extraCondition;
+
+ public ContentCommentCountField(String anExtraCondition) {
+ 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());
+ }
+ }
+ }
+
+ protected static class HumanReadableSizeField implements EntityAdapterDefinition.CalculatedField {
+ private String fieldName;
+
+ public HumanReadableSizeField(String aFieldName) {
+ fieldName= aFieldName;
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ String size = (String) anEntityAdapter.get(fieldName);
+ if (size!=null) {
+ return NumberUtils.humanReadableSize(Double.parseDouble(size));
+ }
+ return "";
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+
+ protected class ContentMediaCountField implements EntityAdapterDefinition.CalculatedField {
+ private String table;
+ private boolean published;
+
+ public ContentMediaCountField(String aTable, boolean anOnlyPublished) {
+ table = aTable;
+ published = anOnlyPublished;
+ }
+
+ public ContentMediaCountField(String aTable) {
+ this(aTable, true);
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ ArrayList extraTable = new ArrayList();
+ extraTable.add(table+" m");
+ String selectSql = "cxm.media_id=m.id and cxm.content_id="+
+ anEntityAdapter.get("id");
+ if (published)
+ selectSql+= " and m.is_published='t'";
+
+ return Integer.toString(
+ DatabaseContentToMedia.getInstance().getSize(
+ "cxm", extraTable, selectSql));
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected class ContentToIsLockedField implements EntityAdapterDefinition.CalculatedField {
+ private ModuleContent contentModule;
+
+ public ContentToIsLockedField() {
+ contentModule = new ModuleContent();
+ }
+
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return new Boolean(contentModule.queryArticleLock(anEntityAdapter.getEntity().getId())!=null);
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+ protected class ContentIsOriginalField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {
+ try {
+
+ //ML: add check on article type
+ boolean result = (anEntityAdapter.get("parent")==null);
+
+ return new Boolean(result);
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t);
+ }
+ }
+ }
+
+ protected class ContentToOriginalField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {
+ try {
+ if (anEntityAdapter.get("parent")!=null)
+ return anEntityAdapter.get("parent");
+ return anEntityAdapter;
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t);
+ }
+ }
+ }
+
+ protected class ContentToTranslationsField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ try {
+ return anEntityAdapter.getRelation(
+ "is_published='t' and to_content="+anEntityAdapter.get("id"),
+ "id",
+ "content" );
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.getMessage());
+ }
+ }
+ }
+
+ protected class ContentToLanguageNameField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {
+ try {
+ String result = "";
+ EntityAdapter language = (EntityAdapter) anEntityAdapter.get("language");
+ if (language != null) {
+ if (language.get("code").equals("ot")) {
+ result = ((String) anEntityAdapter.get("subtitle")).trim();
+ if (result == null || result.equals(""))
+ result = (String) language.get("name");
+ } else {
+ result = (String) language.get("name");
+ }
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t);
+ }
+ }
+ }
+
+ protected class ContentToTranslationFunction implements Generator.Function {
+ private EntityAdapter target;
+ private String targetId;
+ private String targetLanguageId;
+
+ public ContentToTranslationFunction(EntityAdapter aTarget) {
+ target = aTarget;
+ targetId = (String) target.get("id");
+ targetLanguageId = (String) target.get("to_language");
+ }
+
+ public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+ if (aParameters.size()!=1 || !(aParameters.get(0) instanceof String))
+ throw new GeneratorExc("1 string parameter expected");
+
+ try {
+ String language = (String) aParameters.get(0);
+ String languageId = languageModule.languageIdForCode(language);
+ Object result = null;
+
+ if (languageId != null && !targetLanguageId.equals(languageId)) {
+ result = target.getToOneRelation(
+ "is_published='t' and to_content=" + targetId + " and to_language='" + JDBCStringRoutines.escapeStringLiteral(languageId) + "'",
+ "id", "content");
+ }
+
+ if (result == null)
+ result = target;
+
+ return result;
+ }
+ catch (Throwable t) {
+ t.printStackTrace(System.out);
+ throw new GeneratorFailure(t);
+ }
+ }
+ }
+
+ protected class ContentToTranslationField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {
+ try {
+ return new ContentToTranslationFunction((EntityAdapter) anEntityAdapter.get("to_original"));
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t);
+ }
+ }
+ }
+
+ protected static class CommentStatusCountField implements EntityAdapterDefinition.CalculatedField {
+ public Object getValue(EntityAdapter anEntityAdapter) {
+ return new CommentStatusCountField2(anEntityAdapter);
+ }
+ }
+
+ public static class CommentStatusCountField2 {
+ private final EntityAdapter comment;
+ private final ModuleCommentStatus mcs = new ModuleCommentStatus();
+
+ CommentStatusCountField2(EntityAdapter anEntityAdapter) {
+ comment = anEntityAdapter;
+ }
+
+ public String get(String aCommentStatus) {
+ try {
+ return Integer.toString(
+ DatabaseComment.getInstance().getSize(
+ "to_media=" + comment.get("id") + " and is_published='1' and to_comment_status = " +
+ mcs.commentStatusIdForName(aCommentStatus)));
+ }
+ catch (Exception e) {
+ return "0";
+ }
+ }
+ }
+}
+
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Vector;
-import java.util.Collections;
import mir.config.MirPropertiesConfiguration;
import mir.generator.Generator;
import mircoders.global.CacheKey;
import mircoders.global.MirGlobal;
import mircoders.module.ModuleContent;
-import mircoders.storage.DatabaseContent;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
if (articleID == null){
throw new SessionExc("makeInitialResponse: article id not set!");
}
- else {
- aSession.setAttribute("email.aid",articleID);
- aResponse.setResponseValue("errors", null);
-
- String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
- aResponse.setResponseValue("mail_language",mail_language);
- aResponse.setResponseValue("mail_to","");
- aResponse.setResponseValue("mail_from","");
- aResponse.setResponseValue("mail_from_name","");
- aResponse.setResponseValue("mail_comment","");
- aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
+ EntityContent article;
+ try {
+ article = (EntityContent) (new ModuleContent()).getById(articleID);
+ }
+ catch (Throwable t) {
+ throw new SessionExc("Unknown article: " + articleID);
+ }
+ if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
}
+
+
+
+ aSession.setAttribute("email.aid",articleID);
+ aResponse.setResponseValue("errors", null);
+
+ String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
+ aResponse.setResponseValue("mail_language",mail_language);
+ aResponse.setResponseValue("mail_to","");
+ aResponse.setResponseValue("mail_from","");
+ aResponse.setResponseValue("mail_from_name","");
+ aResponse.setResponseValue("mail_comment","");
+
+ aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
}
protected boolean shouldSendMail(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
|| to.indexOf(',') != -1) {
throw new SessionExc("Invalid to address"); // we might want to see this in a log, so it is not a validation error
}
- else return true; // go for it
- }
- else{
- return false; //validation failed, but not in a potentially abusive way
+ return true; // go for it
}
+ return false; //validation failed, but not in a potentially abusive way
}
String emailAnArticleTemplate = configuration.getString("Localizer.OpenSession.email.MailTemplate");
- Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(emailAnArticleTemplate);
+ Generator generator =
+ MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().
+ makeGenerator(emailAnArticleTemplate, null);
StringWriter theEmailStringWriter = new StringWriter();
PrintWriter theEmailPrintWriter = new PrintWriter(theEmailStringWriter);
protected String getExtraEmailHeaders(Request aRequest,String to,String from) throws SessionExc {
- String headers = "To: " + to + "\nReply-To: "+ from+"\n";;
+ String headers = "To: " + to + "\nReply-To: "+ from+"\n";
if (configuration.getString("Localizer.OpenSession.email.includeSenderIP","no").equals("yes"))
headers= headers+"X-Originating-IP: "+ ((HTTPRequestAdapter)aRequest).getRequest().getRemoteAddr() + "\n";
// mission accomplished??
if (! trueIfItWorked)
throw new SessionExc(client.getReplyString());
- else
- return trueIfItWorked;
+ return trueIfItWorked;
}
catch(IOException e) {
if(client.isConnected()) {
protected void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
- List validationErrors = new Vector();
+ List validationErrors = new ArrayList();
if (shouldSendMail(aRequest,aSession,aResponse,validationErrors)){
sendMail(aRequest,aSession,aResponse);
package mircoders.localizer.basic;
import mir.generator.FreemarkerGenerator;
-import mir.generator.VelocityGenerator;
-import mir.generator.TALGenerator;
import mir.generator.Generator;
import mir.generator.GeneratorLibraryRepository;
+import mir.generator.TALGenerator;
+import mir.generator.VelocityGenerator;
import mir.generator.WriterEngine;
import mir.log.LoggerWrapper;
import mircoders.global.MirGlobal;
"freemarker",
new FreemarkerGenerator.FreemarkerGeneratorLibraryFactory(
MirGlobal.config().getHome()));
+
aRepository.registerLibraryFactory(
"velocity",
new VelocityGenerator.VelocityGeneratorLibraryFactory(MirGlobal.config().getHome() ) );
+
aRepository.registerLibraryFactory(
"tal",
new TALGenerator.TALGeneratorLibraryFactory(MirGlobal.config().getHome() ) );
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
- };
+ }
public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
try {
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
- };
+ }
public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
try {
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
- };
+ }
public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure {
return new MirBasicWriterEngine(MirGlobal.config().getString("Mir.DefaultEncoding"));
*/
package mircoders.localizer.basic;
-import mircoders.localizer.MirAdminInterfaceLocalizer;
-import mircoders.localizer.MirDataModelLocalizer;
-import mircoders.localizer.MirGeneratorLocalizer;
-import mircoders.localizer.MirLocalizer;
-import mircoders.localizer.MirLocalizerExc;
-import mircoders.localizer.MirLocalizerFailure;
-import mircoders.localizer.MirOpenPostingLocalizer;
-import mircoders.localizer.MirProducerAssistantLocalizer;
-import mircoders.localizer.MirProducerLocalizer;
-import mircoders.localizer.MirMediaLocalizer;
+import mircoders.localizer.*;
public class MirBasicLocalizer implements MirLocalizer {
- public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirProducerLocalizer producers() throws MirLocalizerFailure {
return new MirBasicProducerLocalizer();
}
- public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirGeneratorLocalizer generators() throws MirLocalizerFailure {
return new MirBasicGeneratorLocalizer();
}
- public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure {
return new MirBasicOpenPostingLocalizer();
}
- public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure {
return new MirBasicProducerAssistantLocalizer();
}
- public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirDataModelLocalizer dataModel() throws MirLocalizerFailure {
return new MirBasicDataModelLocalizer();
- };
+ }
- public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure {
return new MirBasicAdminInterfaceLocalizer();
}
- public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
+ public MirMediaLocalizer media() throws MirLocalizerFailure{
return new MirBasicMediaLocalizer();
}
-}
\ No newline at end of file
+}
*/
package mircoders.localizer.basic;
-import java.util.HashMap;
-import java.util.Map;
-
+import mir.config.MirPropertiesConfiguration;
import mir.media.MediaHandler;
-import mir.config.*;
-import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.MirLocalizerFailure;
import mircoders.localizer.MirMediaLocalizer;
import mircoders.media.*;
-/**
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import java.util.HashMap;
+import java.util.Map;
public class MirBasicMediaLocalizer implements MirMediaLocalizer {
- private Map mediaHandlers;
+ private final Map mediaHandlers = new HashMap();
- /**
- *
- * @throws MirLocalizerExc
- * @throws MirLocalizerFailure
- */
- public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+ public MirBasicMediaLocalizer() throws MirLocalizerFailure {
MirPropertiesConfiguration configuration;
try {
throw new MirLocalizerFailure("Can't get configuration", t);
}
- mediaHandlers = new HashMap();
-
-
registerMediaHandler("Audio", new MediaHandlerAudio());
registerMediaHandler("Generic", new MediaHandlerGeneric());
registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern());
+ registerMediaHandler("ImagesExternScaling", new MediaHandlerImagesExternScaling());
registerMediaHandler("ImagesJpeg", new MediaHandlerImagesJpeg());
registerMediaHandler("ImagesPng", new MediaHandlerImagesPng());
registerMediaHandler("Mp3", new MediaHandlerMp3());
import mir.session.Request;
import mir.session.Session;
import mir.session.SessionHandler;
+import mircoders.abuse.FilterType;
+import mircoders.abuse.IPFilterType;
+import mircoders.abuse.RegularExpressionFilterType;
+import mircoders.abuse.ThrottleFilter;
+import mircoders.abuse.PostingSizeFilterType;
+import mircoders.abuse.URLBlacklistFilterType;
import mircoders.entity.EntityComment;
import mircoders.entity.EntityContent;
import mircoders.global.MirGlobal;
import mircoders.global.ProducerEngine;
-import mircoders.localizer.MirAntiAbuseFilterType;
import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.MirLocalizerFailure;
import mircoders.localizer.MirOpenPostingLocalizer;
-import mircoders.localizer.basic.filters.ThrottleFilter;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Arrays;
public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
private List afterContentProducerTasks;
protected LoggerWrapper logger;
protected MirPropertiesConfiguration configuration;
- public MirBasicOpenPostingLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+ public MirBasicOpenPostingLocalizer() throws MirLocalizerFailure {
logger = new LoggerWrapper("Localizer.Basic.OpenPosting");
try {
throw new MirLocalizerFailure(t);
}
- filterTypes = new Vector();
+ filterTypes = new ArrayList();
filterTypesMap = new HashMap();
- addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("regexp"));
- addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("useragent", false, false,
- MirBasicAntiAbuseFilterTypes.RegularExpressionFilter.REQUEST_HEADERS, new String[] {"User-Agent"}));
- addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.IPFilter("ip"));
- addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("hostname", false, false,
- MirBasicAntiAbuseFilterTypes.RegularExpressionFilter.REQUEST_HEADERS, new String[] {"hostname"}));
- addSimpleAntiAbuseFilterType(new ThrottleFilter("throttle", 60*60*1000));
+ addSimpleAntiAbuseFilterType(new RegularExpressionFilterType("regexp"));
+ addSimpleAntiAbuseFilterType(new RegularExpressionFilterType("useragent", false, false,
+ RegularExpressionFilterType.REQUEST_HEADERS, new String[] {"User-Agent"}));
+ addSimpleAntiAbuseFilterType(new IPFilterType("ip"));
+ addSimpleAntiAbuseFilterType(new RegularExpressionFilterType("hostname", false, false,
+ RegularExpressionFilterType.REQUEST_HEADERS, new String[] {"hostname"}));
+ addSimpleAntiAbuseFilterType(new ThrottleFilter("throttle"));
+ addSimpleAntiAbuseFilterType(new PostingSizeFilterType("size"));
+ addSimpleAntiAbuseFilterType(new URLBlacklistFilterType("urlblacklist",
+ Arrays.asList(MirGlobal.config().getStringArray("Mir.URLBlacklistFilter.WhiteList"))));
}
public SessionHandler getOpenSessionHandler(String aSessionType) throws MirLocalizerExc, MirLocalizerFailure {
- if (aSessionType!=null && aSessionType.equals("email"))
+ if ("email".equals(aSessionType))
return new MirBasicEmailArticleHandler();
- if (aSessionType!=null && aSessionType.equals("comment"))
+ if ("comment".equals(aSessionType))
return new MirBasicCommentPostingHandler(configuration.getBoolean("Localizer.OpenSession.PersistentUploadedFiles"));
+ if ("translation".equals(aSessionType))
+ return new MirBasicTranslationPostingHandler();
+
return new MirBasicArticlePostingHandler(configuration.getBoolean("Localizer.OpenSession.PersistentUploadedFiles"));
}
}
}
- public void afterContentPosting(EntityContent aContent) {
+ public void afterArticlePosting() {
afterContentPosting();
}
+ public void afterArticlePosting(EntityContent anArticle) {
+ afterContentPosting(anArticle);
+ }
+
+ public void afterContentPosting(EntityContent anArticle) {
+ afterArticlePosting();
+ }
+
public void afterCommentPosting(EntityComment aComment) {
afterCommentPosting();
}
long l = System.currentTimeMillis();
l = (l*l*l*l)/random;
- if (l<0)
+ if (l<0) {
l = l * -1;
+ }
String returnString = ""+l;
}
public List getAntiAbuseFilterTypes() {
- return filterTypes;
+ return Collections.unmodifiableList(filterTypes);
+ }
+
+ public boolean allowArticlePublication(EntityContent anArticle){
+ return anArticle != null && "1".equals(anArticle.getFieldValue("is_published"));
}
public void removeSimpleAntiAbuseFilterType(String aName) {
filterTypesMap.remove(aName);
}
- public void addSimpleAntiAbuseFilterType(MirAntiAbuseFilterType aFilterType) {
+ public void addSimpleAntiAbuseFilterType(FilterType aFilterType) {
removeSimpleAntiAbuseFilterType(aFilterType.getName());
filterTypesMap.put(aFilterType.getName(), aFilterType);
filterTypes.add(aFilterType);
import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
import mir.session.*;
-import mir.storage.StorageObject;
-import mir.util.ExceptionFunctions;
-import mir.util.FileFunctions;
+import mir.storage.Database;
+import mir.util.ExceptionRoutines;
+import mir.util.FileRoutines;
+import mir.util.IORoutines;
import mircoders.global.MirGlobal;
-import mircoders.module.ModuleMediaType;
+import mircoders.media.UnsupportedMediaTypeExc;
import java.io.*;
import java.util.*;
*/
public abstract class MirBasicPostingSessionHandler implements SessionHandler {
protected static LoggerWrapper logger = new LoggerWrapper("Localizer.OpenPosting");
- protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();;
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
/** Previously uploaded files */
protected List attachments;
subsequentRequest(aRequest, aSession, aResponse);
}
}
- };
+ }
protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
initializeSession(aRequest, aSession);
makeInitialResponse(aRequest, aSession, aResponse);
}
- protected void processAttachments(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ protected void processAttachments(Request aRequest, Session aSession, Response aResponse) {
Iterator i = attachments.iterator();
while (i.hasNext()) {
- processAttachment(aRequest, aSession, (Attachment) i.next());
+ Attachment attachment = (Attachment) i.next();
+ try{
+ processAttachment(aRequest, aSession, attachment);
+ }
+ catch (Throwable t) {
+ try {
+ processAttachmentError(aRequest, aSession, attachment, t);
+ }
+ catch (Throwable u) {
+ }
+ logger.error("Error while processing attachment", t);
+ }
}
}
preProcessRequest(aRequest, aSession);
processAttachments(aRequest, aSession, aResponse);
-
postProcessRequest(aRequest, aSession);
initializeResponseData(aRequest, aSession, aResponse);
makeFinalResponse(aRequest, aSession, aResponse);
if (configuration.getBoolean("Localizer.OpenSession.AllowFTPUploads", false)) {
aResponse.setResponseValue("ftpfiles",
- FileFunctions.getDirectoryContentsAsList(configuration.getFile("Localizer.OpenSession.FTPDirectory"),
+ FileRoutines.getDirectoryContentsAsList(configuration.getFile("Localizer.OpenSession.FTPDirectory"),
new FilenameFilter() {
public boolean accept(File aDir, String aName) {
return !(new File(aDir, aName).isDirectory());
if (configuration.getBoolean("Localizer.OpenSession.AllowFTPUploads", false)) {
File FTPDirectory = configuration.getFile("Localizer.OpenSession.FTPDirectory");
- List ftpUploads = aRequest.getPrefixedParameterNames("ftpupload");
+ List ftpUploads = new ArrayList(aRequest.getPrefixedParameterNames("ftpupload"));
+ Collections.sort(ftpUploads, new Comparator() {
+ public int compare(Object o1, Object o2) {
+ if (o1 instanceof String && o2 instanceof String) {
+ return ((String) o1).compareTo((String) o2);
+ }
+ else {
+ return 0;
+ }
+ }
+ });
+
i = ftpUploads.iterator();
while (i.hasNext()) {
final String fieldName = (String) i.next();
preprocessNewAttachment(aRequest, aSession, new UploadedFile() {
public void writeToFile(File aFile) throws SessionFailure {
try {
- FileFunctions.move(sourceFile, aFile);
+ FileRoutines.move(sourceFile, aFile);
+ }
+ catch (IOException e) {
+ throw new SessionFailure(e);
+ }
+ }
+
+ public void writeToStream(OutputStream aStream) throws SessionFailure {
+ try {
+ IORoutines.copyStream(getInputStream(), aStream);
}
catch (IOException e) {
throw new SessionFailure(e);
protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
aResponse.setResponseGenerator(normalResponseGenerator);
- };
+ }
protected void makeResponse(Request aRequest, Session aSession, Response aResponse, List anErrors) throws SessionExc, SessionFailure {
aResponse.setResponseValue("errors", anErrors);
aResponse.setResponseGenerator(normalResponseGenerator);
- };
+ }
protected void makeFinalResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
aResponse.setResponseGenerator(finalResponseGenerator);
- };
+ }
protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {
- Throwable rootCause = ExceptionFunctions.traceCauseException(anError);
+ Throwable rootCause = ExceptionRoutines.traceCauseException(anError);
if (rootCause instanceof DuplicatePostingExc)
aResponse.setResponseGenerator(dupeResponseGenerator);
- if (rootCause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
- aResponse.setResponseValue("mimetype", ((ModuleMediaType.UnsupportedMimeTypeExc) rootCause).getMimeType());
+ if (rootCause instanceof UnsupportedMediaTypeExc) {
+ aResponse.setResponseValue("mimetype", ((UnsupportedMediaTypeExc) rootCause).getMimeType());
aResponse.setResponseGenerator(unsupportedMediaTypeResponseGenerator);
}
else {
new Object[] {anError.getMessage()}));
makeResponse(aRequest, aSession, aResponse, errors);
}
- };
+ }
protected void makeOpenPostingDisabledResponse(Request aRequest, Session aSession, Response aResponse) {
aResponse.setResponseGenerator(configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
*
*/
protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
- };
+ }
public void processAttachment(Request aRequest, Session aSession, Attachment aFile) throws SessionExc, SessionFailure {
- };
+ }
+ public void processAttachmentError(Request aRequest, Session aSession, Attachment aFile, Throwable anError) {
+ }
protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
- };
+ }
/**
* Determine whether the request shoudl be processed: that is, the validate,
protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {
if (aRequest.getParameter("post")==null)
return false;
- else {
- validate(aValidationErrors, aRequest, aSession);
- return (aValidationErrors == null || aValidationErrors.size() == 0);
- }
+ validate(aValidationErrors, aRequest, aSession);
+ return (aValidationErrors == null || aValidationErrors.size() == 0);
}
/**
/**
* Method to filter the attributes and their values of a request
- * based on the fields of a storage object.
+ * based on the fields of a database object.
*/
- protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionFailure {
+ protected static final Map getIntersectingValues(Request aRequest, Database aStorage) throws SessionFailure {
Map result = new HashMap();
- Iterator i = aStorage.getFields().iterator();
+ Iterator i = aStorage.getFieldNames().iterator();
while (i.hasNext()) {
String fieldName = (String) i.next();
uploadedFile.writeToFile(aFile);
}
+ public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure {
+ try {
+ IORoutines.copyStream(uploadedFile.getInputStream(), aStream);
+ }
+ catch (IOException e) {
+ throw new SessionFailure(e);
+ }
+ }
+
public InputStream getInputStream() throws SessionExc, SessionFailure {
return uploadedFile.getInputStream();
}
*/
package mircoders.localizer.basic;
+import gnu.regexp.RE;
import mir.config.MirPropertiesConfiguration;
import mir.entity.adapter.EntityAdapter;
import mir.entity.adapter.EntityIteratorAdapter;
import mir.generator.GeneratorExc;
import mir.generator.GeneratorFailure;
import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.util.*;
+import mir.util.GeneratorDateTimeFunctions;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.HTMLStripper;
+import mir.util.StringRoutines;
import mir.util.generator.ReflectionGeneratorFunctionsAdapter;
import mircoders.global.MirGlobal;
import mircoders.localizer.MirLocalizerExc;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.w3c.tidy.Tidy;
import org.w3c.tidy.Configuration;
+import org.w3c.tidy.Tidy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
protected LoggerWrapper logger;
- public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure {
+ private HTMLStripper stripper;
+ private RE regularExpressionLT;
+ private RE regularExpressionGT;
+ private RE regularExpressionWhitespace;
+ private RE regularExpressionLeadingSlashes;
+
+
+ public MirBasicProducerAssistantLocalizer() throws MirLocalizerFailure {
+ try {
+ stripper = new HTMLStripper();
+
+ regularExpressionLT = new RE("<");
+ regularExpressionGT = new RE(">");
+ regularExpressionWhitespace = new RE("\\s+|
|
");
+ regularExpressionLeadingSlashes = new RE("^//+");
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure(t);
+ }
+ }
+
+ public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure {
try {
Iterator i;
aValueSet.put("config", configMap);
- aValueSet.put("utility", new Utility());
+ aValueSet.put("utility", new Utility());
aValueSet.put("languages",
- new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
+ new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
aValueSet.put("topics",
- new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+ new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
Map articleTypeMap = new HashMap();
articleTypeMap.put("openposting", "0");
}
catch (Throwable t) {
logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
- throw new RuntimeException(t.getMessage());
+
+ throw new MirLocalizerFailure(t);
}
- };
+ }
+
public static class getLanguageIdFunction implements Generator.Function {
private Map languageCodeToId;
private String otherLanguageId;
Iterator i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language");
while (i.hasNext()) {
EntityAdapter language = (EntityAdapter) i.next();
- if (language.get("code").equals("ot"))
+ if (language.get("code").equals("ot")) {
otherLanguageId = (String) language.get("id");
+ }
languageCodeToId.put(language.get("code"), language.get("id"));
}
public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
try {
- if (aParameters.size() != 1)
+ if (aParameters.size() != 1) {
throw new GeneratorExc("getLanguageIdFunction: 1 parameter expected: language-code");
+ }
String result = (String) languageCodeToId.get(aParameters.get(0));
- if (result == null)
+ if (result == null) {
result = otherLanguageId;
+ }
return result;
}
catch (Throwable t) {
throw new GeneratorFailure("getLanguageIdFunction: " + t.getMessage(), t);
}
- };
+ }
}
logger.debug("about to filter non HTML Text of length " + aText.length());
try {
String result =
- StringUtil.createHTML(
- StringUtil.removeHTMLTags(aText),
- MirGlobal.config().getString("Producer.ImageRoot"),
- MirGlobal.config().getString("Producer.MailLinkName"),
- MirGlobal.config().getString("Producer.ExtLinkName"),
- MirGlobal.config().getString("Producer.IntLinkName")
- );
+ stripper.createHTML(
+ stripper.removeHTMLTags(aText),
+ MirGlobal.config().getString("Producer.ImageRoot"),
+ MirGlobal.config().getString("Producer.MailLinkName"),
+ MirGlobal.config().getString("Producer.ExtLinkName"),
+ MirGlobal.config().getString("Producer.IntLinkName"));
logger.debug("done filtering non-HTML text ");
return result;
}
throw new RuntimeException(t.toString());
}
}
+
+ public Generator.Interceptor createGenerationInterceptor() throws MirLocalizerExc, MirLocalizerFailure {
+
+ if (MirGlobal.config().getBoolean("Mir.Producer.UseInterceptor", true)) {
+ return new Generator.Interceptor() {
+
+ public Object intercept(Object anObject) {
+ if (anObject instanceof EntityAdapter) {
+ return new InterceptedEntityAdapter((EntityAdapter) anObject);
+ }
+
+ return anObject;
+ }
+ };
+ }
+ else {
+ return null;
+ }
+ }
+
+ public class InterceptedEntityAdapter {
+ private EntityAdapter adapter;
+
+ InterceptedEntityAdapter(EntityAdapter anEntityAdapter) {
+ adapter = anEntityAdapter;
+ }
+
+ public Object get(String aField) {
+ Object result = adapter.get(aField);
+ if (result instanceof String) {
+ return filterHTMLText((String) result);
+ }
+ else {
+ return result;
+ }
+ }
+
+ public Object getRaw() {
+ return new RawEntityAdapter(adapter);
+ }
+ }
+
+ public class RawEntityAdapter {
+ private EntityAdapter adapter;
+
+ RawEntityAdapter(EntityAdapter anEntityAdapter) {
+ adapter = anEntityAdapter;
+ }
+
+ public Object get(String aField) {
+ return adapter.get(aField);
+ }
+ }
+
public String filterHTMLText(String aText) {
try {
StringWriter out = new StringWriter();
ByteArrayInputStream in = new ByteArrayInputStream(aText.getBytes("UTF8"));
tidy.setMakeClean(true);
tidy.setCharEncoding(Configuration.UTF8);
+ tidy.setErrout(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
print(tidy.parseDOM(in, null), out);
+
return out.toString();
- } catch (IOException e) {
+ }
+ catch (IOException e) {
return e.getMessage();
}
}
+
+
+ private boolean isBadAttr(String attrName) {
+ List badAttributes = StringRoutines.splitString(MirGlobal.config().getString("Localizer.HTML.BadAttributes"), ";");
+ Iterator i = badAttributes.iterator();
+ while (i.hasNext()) {
+ if (((String) i.next()).toLowerCase().equals(attrName.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private String stripWhitespace(String aString) {
+ try {
+ return regularExpressionWhitespace.substituteAll(aString, "");
+ }
+ catch (Throwable t) {
+ return "";
+ }
+ }
+
private boolean checkAttr(String attrName) {
- if (attrName.equals("onLoad") || attrName.equals("onClick") || attrName.equals("onFocus") || attrName.equals("onBlur") || attrName.equals("onMouseOver") || attrName.equals("onMouseOut") || attrName.equals("style") || attrName.equals("STYLE") || attrName.equals("height") || attrName.equals("width") || attrName.equals("HEIGHT") || attrName.equals("WIDTH"))
+ if (isBadAttr(attrName)) {
return false;
- else
- return true;
+ }
+ return true;
}
+ private boolean checkAttrValue(String attrValue) {
+ List badPrefixes = StringRoutines.splitString(MirGlobal.config().getString("Localizer.HTML.BadAttributeValuePrefixes"), ";");
+ Iterator i = badPrefixes.iterator();
+ while (i.hasNext()) {
+ if ((stripWhitespace(attrValue.toLowerCase())).startsWith(((String) i.next()).toLowerCase() + ":")) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+
private boolean checkNode(String nodeName) {
- if (nodeName.equals("a") ||
- nodeName.equals("img") ||
- nodeName.equals("h1") ||
- nodeName.equals("h2") ||
- nodeName.equals("h3") ||
- nodeName.equals("h4") ||
- nodeName.equals("h5") ||
- nodeName.equals("h6") ||
- nodeName.equals("br") ||
- nodeName.equals("form") ||
- nodeName.equals("input") ||
- nodeName.equals("hr") ||
- nodeName.equals("strong") ||
- nodeName.equals("font") ||
- nodeName.equals("b") ||
- nodeName.equals("i") ||
- nodeName.equals("em") ||
- nodeName.equals("p") ||
- nodeName.equals("table") ||
- nodeName.equals("tr") ||
- nodeName.equals("td") ||
- nodeName.equals("th") ||
- nodeName.equals("ul") ||
- nodeName.equals("ol") ||
- nodeName.equals("li")
- ) {
- return true;
- } else {
+ List acceptableNodes = StringRoutines.splitString(MirGlobal.config().getString("Localizer.HTML.Whitelist"), ";");
- return false;
+ Iterator i = acceptableNodes.iterator();
+ while (i.hasNext()) {
+ if (nodeName.equals(i.next())) {
+ return true;
+ }
}
+ return false;
}
private void print(Node node, StringWriter out) throws IOException {
for (int i = 0; i < attrs.getLength(); i++) {
String attrName = attrs.item(i).getNodeName();
- if (checkAttr(attrName)) {
+ String attrValue = attrs.item(i).getNodeValue();
+ if (attrValue.startsWith("//")){
+ attrValue=regularExpressionLeadingSlashes.substitute(attrValue, "/");
+ }
+
+ if (checkAttr(attrName) && checkAttrValue(attrValue)) {
out.write(' ');
out.write(attrs.item(i).getNodeName());
out.write("=\"");
}
}
- if (node.getChildNodes()==null || node.getChildNodes().getLength()==0) {
+ if (node.getChildNodes() == null || node.getChildNodes().getLength() == 0) {
out.write("/");
}
out.write('>');
break;
case Node.TEXT_NODE:
- out.write(node.getNodeValue());
+ String value = node.getNodeValue();
+ try {
+ value = regularExpressionLT.substituteAll(value, "<");
+ value = regularExpressionGT.substituteAll(value, ">");
+ }
+ catch (Throwable t) {
+ value = "";
+ }
+ out.write(value);
+
break;
}
- if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes()!=null && node.getChildNodes().getLength()>0) {
+ if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes() != null && node.getChildNodes().getLength() > 0) {
out.write("</");
out.write(node.getNodeName());
out.write('>');
}
public static class Utility extends ReflectionGeneratorFunctionsAdapter {
- public Utility () {
+ public Utility() {
super(new MirBasicUtilityFunctions());
}
+
public Object getDatetime() {
return new GeneratorDateTimeFunctions.DateTimeFunctions(
- MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
+ MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
}
public Object getCompressWhitespace() {
package mircoders.localizer.basic;
import java.io.File;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
import mir.entity.adapter.EntityAdapterModel;
import mir.generator.Generator;
logger = new LoggerWrapper("Localizer.Basic.Producer");
producerRecipes = new HashMap();
- producerRecipeNames = new Vector();
+ producerRecipeNames = new ArrayList();
String[] recipes = MirGlobal.config().getStringArray("Mir.Localizer.Producer.ProducerRecipes");
for (int i = 0; i<recipes.length; i++) {
throw new MirLocalizerExc("Unknown recipe name: " + aName);
}
+ public void beforeProducerTask(String aFactory, String aVerb) {
+ }
+
+ public void afterProducerTask(String aFactory, String aVerb) {
+ }
+
/**
* Loads factories from a file with a {@link ProducerConfigReader}
*/
public List loadFactories() throws MirLocalizerExc {
try {
- List producers = new Vector();
+ List producers = new ArrayList();
ProducerConfigReader reader;
ProducerNodeBuilderLibrary library = new ProducerNodeBuilderLibrary();
setupProducerNodeBuilderLibrary(library);
t.getMessage());
throw new MirLocalizerFailure(t);
}
- };
+ }
/**
* Sets up a {@link ProducerNodeBuilderLibrary} for use by the producer
protected void setupProducerNodeBuilderLibrary(ProducerNodeBuilderLibrary aLibrary) throws MirLocalizerFailure {
try {
DefaultProducerNodeBuilders.registerBuilders(
- aLibrary, model, generatorLibrary, writerEngine,
- MirGlobal.config().getHome(), MirGlobal.config().getFile("Producer.StorageRoot"));
+ aLibrary, model, generatorLibrary,
+ MirGlobal.localizer().producerAssistant().createGenerationInterceptor(),
+ writerEngine,
+ MirGlobal.config().getHome(),
+ MirGlobal.config().getFile("Producer.StorageRoot"));
SupplementalProducerNodeBuilders.registerBuilders(aLibrary, MirGlobal.config().getHome());
}
catch (Throwable t) {
--- /dev/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 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 mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleArticleType;
+import mircoders.storage.DatabaseContent;
+
+public class MirBasicTranslationPostingHandler extends MirBasicChildArticlePostingHandler {
+ public MirBasicTranslationPostingHandler() {
+ super();
+
+ setResponseGenerators(
+ configuration.getString("Localizer.OpenSession.translation.EditTemplate"),
+ configuration.getString("Localizer.OpenSession.translation.DupeTemplate"),
+ configuration.getString("Localizer.OpenSession.translation.UnsupportedMediaTemplate"),
+ configuration.getString("Localizer.OpenSession.translation.DoneTemplate"));
+ }
+
+ protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ initializeSession(aRequest, aSession);
+ initializeResponseData(aRequest, aSession, aResponse);
+
+ if (aRequest.getParameter("title")!=null)
+ subsequentRequest(aRequest, aSession, aResponse);
+ else
+ makeInitialResponse(aRequest, aSession, aResponse);
+ }
+
+ public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
+ String is_html=anArticle.getFieldValue("is_html");
+ super.finalizeArticle(aRequest, aSession, anArticle);
+ anArticle.setFieldValue("is_html", is_html);
+ try {
+ anArticle.setFieldValue("to_article_type", new ModuleArticleType().articleTypeIdForName("translation"));
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+ protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ super.initializeSession(aRequest, aSession);
+
+ try {
+ String parentId = aRequest.getParameter("to_content");
+ aSession.setAttribute("parent",
+ MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", DatabaseContent.getInstance().selectById(parentId))
+ );
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+ protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ try {
+ super.initializeResponseData(aRequest, aSession, aResponse);
+ aResponse.setResponseValue("parent", aSession.getAttribute("parent"));
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer.basic;\r
-\r
-import mir.util.*;\r
-import mir.config.MirPropertiesConfiguration;\r
-\r
-import java.util.Collections;\r
-import java.util.List;\r
-\r
-public class MirBasicUtilityFunctions {\r
- public String encodeXML(Object anObject) throws Exception {\r
- return HTMLRoutines.encodeXML(StringRoutines.interpretAsString(anObject));\r
- }\r
-\r
- public String encodeHTML(Object aString) throws Exception {\r
- return HTMLRoutines.encodeHTML(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public String prettyEncodeHTML(Object aString) throws Exception {\r
- return HTMLRoutines.prettyEncodeHTML(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public String encodeURI(Object aString) throws Exception {\r
- return HTMLRoutines.encodeURL(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public String encodeURI(Object aString, Object anEncoding) throws Exception {\r
- return HTMLRoutines.encodeURL(\r
- StringRoutines.interpretAsString(aString),\r
- StringRoutines.interpretAsString(anEncoding));\r
- }\r
-\r
- public String subString(Object aString, Object aFrom) throws Exception {\r
- return StringRoutines.interpretAsString(aString).substring(StringRoutines.interpretAsInteger(aFrom));\r
- }\r
-\r
- public String subString(Object aString, Object aFrom, Object aLength) throws Exception {\r
- int length = StringRoutines.interpretAsInteger(aLength);\r
- String target = StringRoutines.interpretAsString(aString);\r
- if (length<0 || length>target.length()) {\r
- length=target.length();\r
- }\r
-\r
- return target.substring(StringRoutines.interpretAsInteger(aFrom), length);\r
- }\r
-\r
- public String escapeJDBCString(Object aString) throws Exception {\r
- return JDBCStringRoutines.escapeStringLiteral(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public String constructString(Object aString) throws Exception {\r
- if (aString==null)\r
- return StructuredContentParser.constructStringLiteral("");\r
- else\r
- return StructuredContentParser.constructStringLiteral(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public Object parseStructuredString(Object aString) throws Exception {\r
- if (aString==null)\r
- return null;\r
- else\r
- return StructuredContentParser.parse(StringRoutines.interpretAsString(aString));\r
- }\r
-\r
- public boolean isOdd(Object anInteger) throws Exception {\r
- return (StringRoutines.interpretAsInteger(anInteger) & 1) == 1;\r
- }\r
-\r
- public int increment(Object anInteger) throws Exception {\r
- final Integer ONE = new Integer(1);\r
-\r
- return increment(anInteger, ONE);\r
- }\r
-\r
- public int increment(Object anInteger, Object anIncrement) throws Exception {\r
- return StringRoutines.interpretAsInteger(anInteger) +\r
- StringRoutines.interpretAsInteger(anIncrement);\r
- }\r
-\r
- public Object subList(Object aList, Object aSkip) throws Exception {\r
- return subList(aList, aSkip, new Integer(-1));\r
- }\r
-\r
- public Object subList(Object aList, Object aSkip, Object aMaxSize) throws Exception {\r
- int skip = StringRoutines.interpretAsInteger(aSkip);\r
- int maxSize = StringRoutines.interpretAsInteger(aMaxSize);\r
-\r
- if (aList instanceof RewindableIterator)\r
- return new SubsetIterator((RewindableIterator) aList, skip, maxSize);\r
- else {\r
- List list = (List) aList;\r
-\r
- if (skip>=list.size())\r
- return Collections.EMPTY_LIST;\r
- if (maxSize<0 || (skip+maxSize)>=list.size())\r
- return list.subList(skip, list.size());\r
- else\r
- return list.subList(skip, skip+maxSize);\r
- }\r
- }\r
-\r
- public int listSize(RewindableIterator anIterator) {\r
- anIterator.rewind();\r
- int result=0;\r
-\r
- while (anIterator.hasNext()) {\r
- result++;\r
- anIterator.next();\r
- }\r
-\r
- anIterator.rewind();\r
-\r
- return result;\r
- }\r
-\r
- public int listSize(List aList) {\r
- return aList.size();\r
- }\r
-\r
- public Object evaluate(Object aTarget, String anExpression) throws Exception {\r
- return ParameterExpander.expandExpression(aTarget, anExpression);\r
- }\r
-\r
- public String regexpreplace(String aString, String anExpression, String aReplacement) {\r
- return StringRoutines.performRegularExpressionReplacement(aString, anExpression, aReplacement);\r
- }\r
-\r
- public boolean regexpmatch(String aString, String anExpression) {\r
- return StringRoutines.performRegularExpressionSearch(aString, anExpression);\r
- }\r
-}\r
+/*
+ * 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 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.Collections;
+import java.util.List;
+
+import mir.util.HTMLRoutines;
+import mir.util.JDBCStringRoutines;
+import mir.util.ParameterExpander;
+import mir.util.RewindableIterator;
+import mir.util.StringRoutines;
+import mir.util.StructuredContentParser;
+import mir.util.SubsetIterator;
+
+public class MirBasicUtilityFunctions {
+ public String encodeXML(Object anObject) throws Exception {
+ return HTMLRoutines.encodeXML(StringRoutines.interpretAsString(anObject));
+ }
+
+ public String encodeHTML(Object aString) throws Exception {
+ return HTMLRoutines.encodeHTML(StringRoutines.interpretAsString(aString));
+ }
+
+ public String prettyEncodeHTML(Object aString) throws Exception {
+ return HTMLRoutines.prettyEncodeHTML(StringRoutines.interpretAsString(aString));
+ }
+
+ public String encodeURI(Object aString) throws Exception {
+ return HTMLRoutines.encodeURL(StringRoutines.interpretAsString(aString));
+ }
+
+ public String encodeURI(Object aString, Object anEncoding) throws Exception {
+ return HTMLRoutines.encodeURL(
+ StringRoutines.interpretAsString(aString),
+ StringRoutines.interpretAsString(anEncoding));
+ }
+
+ public String subString(Object aString, Object aFrom) throws Exception {
+ return StringRoutines.interpretAsString(aString).substring(StringRoutines.interpretAsInteger(aFrom));
+ }
+
+ public String subString(Object aString, Object aFrom, Object aLength) throws Exception {
+ int length = StringRoutines.interpretAsInteger(aLength);
+ String target = StringRoutines.interpretAsString(aString);
+ if (length<0 || length>target.length()) {
+ length=target.length();
+ }
+
+ return target.substring(StringRoutines.interpretAsInteger(aFrom), length);
+ }
+
+ public String escapeJDBCString(Object aString) throws Exception {
+ return JDBCStringRoutines.escapeStringLiteral(StringRoutines.interpretAsString(aString));
+ }
+
+ public String constructString(Object aString) throws Exception {
+ if (aString==null)
+ return StructuredContentParser.constructStringLiteral("");
+ return StructuredContentParser.constructStringLiteral(StringRoutines.interpretAsString(aString));
+ }
+
+ public Object parseStructuredString(Object aString) throws Exception {
+ if (aString==null)
+ return null;
+ return StructuredContentParser.parse(StringRoutines.interpretAsString(aString));
+ }
+
+ public boolean isOdd(Object anInteger) throws Exception {
+ return (StringRoutines.interpretAsInteger(anInteger) & 1) == 1;
+ }
+
+ public int increment(Object anInteger) throws Exception {
+ final Integer ONE = new Integer(1);
+
+ return increment(anInteger, ONE);
+ }
+
+ public int increment(Object anInteger, Object anIncrement) throws Exception {
+ return StringRoutines.interpretAsInteger(anInteger) +
+ StringRoutines.interpretAsInteger(anIncrement);
+ }
+
+ public Object subList(Object aList, Object aSkip) throws Exception {
+ return subList(aList, aSkip, new Integer(-1));
+ }
+
+ public Object subList(Object aList, Object aSkip, Object aMaxSize) throws Exception {
+ int skip = StringRoutines.interpretAsInteger(aSkip);
+ int maxSize = StringRoutines.interpretAsInteger(aMaxSize);
+
+ if (aList instanceof RewindableIterator)
+ return new SubsetIterator((RewindableIterator) aList, skip, maxSize);
+
+ List list = (List) aList;
+ if (skip>=list.size())
+ return Collections.EMPTY_LIST;
+ if (maxSize<0 || (skip+maxSize)>=list.size())
+ return list.subList(skip, list.size());
+ return list.subList(skip, skip+maxSize);
+ }
+
+ public int listSize(RewindableIterator anIterator) {
+ anIterator.rewind();
+ int result=0;
+
+ while (anIterator.hasNext()) {
+ result++;
+ anIterator.next();
+ }
+
+ anIterator.rewind();
+
+ return result;
+ }
+
+ public int listSize(List aList) {
+ return aList.size();
+ }
+
+ public Object evaluate(Object aTarget, String anExpression) throws Exception {
+ return ParameterExpander.expandExpression(aTarget, anExpression);
+ }
+
+ public String regexpreplace(String aString, String anExpression, String aReplacement) {
+ return StringRoutines.performRegularExpressionReplacement(aString, anExpression, aReplacement);
+ }
+
+}
*/
package mircoders.localizer.basic;
+import mir.config.MirPropertiesConfiguration;
+import mir.generator.WriterEngine;
+import mir.log.LoggerWrapper;
+import mir.util.FileRoutines;
+import mircoders.localizer.MirLocalizerFailure;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
-
-import mir.generator.WriterEngine;
-import mircoders.localizer.MirLocalizerFailure;
+import java.io.Writer;
public class MirBasicWriterEngine implements WriterEngine {
private String defaultEncoding;
+ protected static LoggerWrapper logger = new LoggerWrapper("Localizer.WriterEngine");
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+
+ /**
+ * Directory to store temp files into
+ */
+ private File tempDirectory;
+
public MirBasicWriterEngine(String aDefaultEncoding) {
defaultEncoding = aDefaultEncoding;
+ tempDirectory = configuration.getFile("TempDir");
}
+ /**
+ * {@inheritDoc}
+ */
public Object openWriter(String anIdentifier, String anEncoding) throws MirLocalizerFailure {
String encoding;
- File file;
- File dir;
- if (anEncoding != null && !anEncoding.equals(""))
+ if (anEncoding != null && !anEncoding.equals("")) {
encoding = anEncoding;
- else
+ }
+ else {
encoding = defaultEncoding;
+ }
- try {
- file = new File(anIdentifier);
+ File destinationFile = new File(anIdentifier);
- dir = file.getParentFile();
+ File destinationDirectory = destinationFile.getParentFile();
- if (dir != null && !dir.exists()) {
- dir.mkdirs();
- }
+ if (destinationDirectory != null && !destinationDirectory.exists()) {
+ destinationDirectory.mkdirs();
+ }
+ try {
return new PrintWriter(
- new BufferedWriter(
- new OutputStreamWriter(
- new FileOutputStream(file), encoding
- ), 8192)
+ new TempWriter(destinationFile, encoding)
);
}
- catch (Throwable t) {
- throw new MirLocalizerFailure("Failure while opening a PrintWriter: " + t.getMessage(), t);
+ catch (IOException t) {
+ throw new MirLocalizerFailure("Failure while opening a writer", t);
}
- };
+ }
public void closeWriter(Object aWriter) {
((PrintWriter) aWriter).close();
- };
-}
+ }
+
+ private class TempWriter extends Writer {
+ TempWriter(File aDestination, String anEncoding) throws IOException {
+ destinationFile = aDestination;
+ slaveFile = File.createTempFile("Mir", ".generated", tempDirectory);
+ slaveFile.deleteOnExit();
+ slaveWriter = new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(slaveFile), anEncoding
+ ), 8192);
+ }
+
+ public void close() throws IOException {
+ slaveWriter.close();
+
+ try {
+ FileRoutines.move(slaveFile, destinationFile);
+
+ slaveFile.delete();
+ }
+ catch (Throwable e) {
+ System.out.println("error: " + e.toString());
+
+ throw new IOException(e.getMessage());
+ }
+ }
+
+ public void flush() throws IOException {
+ slaveWriter.flush();
+ }
+
+ public void write(char cbuf[], int off, int len) throws IOException {
+ slaveWriter.write(cbuf, off, len);
+ }
+
+ private Writer slaveWriter;
+ private File slaveFile;
+ private File destinationFile;
+ }
+
+}
\ No newline at end of file
package mircoders.localizer.basic.actions;
import java.util.ArrayList;
-import java.util.List;
import java.util.Iterator;
+import java.util.List;
import mir.entity.adapter.EntityAdapter;
import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.basic.MirBasicAdminInterfaceLocalizer;
import mircoders.storage.DatabaseContentToTopics;
-public class ArticleTopicAction implements MirBasicAdminInterfaceLocalizer.MirSimpleEntityOperation{
+public class ArticleTopicAction implements MirBasicAdminInterfaceLocalizer.EntityOperation {
private String name;
private List deleteTopics;
private List addTopics;
db.setTopics(anEntity.getEntity().getId(), topicsToSet);
}
+
public void perform2(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
DatabaseContentToTopics db = DatabaseContentToTopics.getInstance();
+++ /dev/null
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer.basic.filters;\r
-\r
-import mircoders.localizer.basic.MirBasicAntiAbuseFilterTypes;\r
-import mircoders.entity.EntityComment;\r
-\r
-import java.util.*;\r
-\r
-import mir.util.StringRoutines;\r
-import mir.entity.Entity;\r
-import mir.session.Request;\r
-\r
-/**\r
- * A ip-based throttling filter.\r
- *\r
- * <p>\r
- * Expressions have the form <time in minutes>:<posting limit>\r
- */\r
-public class ThrottleFilter extends MirBasicAntiAbuseFilterTypes.BasicFilterType {\r
- private long overallHorizon;\r
-\r
- private ThrottleManager throttleManager;\r
-\r
- public ThrottleFilter(String aName, long anOverallHorizon) {\r
- super(aName);\r
-\r
- overallHorizon = anOverallHorizon;\r
- throttleManager = new ThrottleManager(overallHorizon);\r
- }\r
-\r
- /** * {@inheritDoc} */\r
- public boolean validate(String anExpression) {\r
- List parts = StringRoutines.splitString(anExpression.trim(), ":");\r
-\r
- try {\r
- if (parts.size()==2) {\r
- Integer.parseInt((String) parts.get(0));\r
- Integer.parseInt((String) parts.get(1));\r
-\r
- return true;\r
- }\r
- }\r
- catch (Throwable t) {\r
- }\r
-\r
- return false;\r
- }\r
-\r
- /**\r
- *\r
- */\r
- public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
- String ip = aRequest.getHeader("ip");\r
- int limit;\r
- long period;\r
-\r
- List parts = StringRoutines.splitString(anExpression, ":");\r
-\r
- try {\r
- period = Integer.parseInt((String) parts.get(0))*1000*60;\r
- limit = Integer.parseInt((String) parts.get(1));\r
- }\r
- catch (Throwable t) {\r
- return false;\r
- }\r
-\r
- return throttleManager.addMessage(ip, anEntity, limit, period);\r
- };\r
-\r
- private class ThrottleManager {\r
- private Map throttles;\r
- private long overallHorizon;\r
- private Thread cleanUpThread;\r
-\r
- public ThrottleManager(long anOverallHorizon) {\r
- throttles = new HashMap();\r
- overallHorizon = anOverallHorizon;\r
-\r
- cleanUpThread = new Thread() {\r
- public void run() {\r
- while (true) {\r
- synchronized(throttles) {\r
- List toDelete = new ArrayList();\r
- Iterator i = throttles.entrySet().iterator();\r
-\r
- while (i.hasNext()) {\r
- Map.Entry entry = (Map.Entry) i.next();\r
- try {\r
- if (((Throttle) entry.getValue()).flush()) {\r
- toDelete.add(entry.getKey());\r
- }\r
- }\r
- catch (Throwable t) {\r
- toDelete.add(entry.getKey());\r
- }\r
- }\r
-\r
- i = toDelete.iterator();\r
- while (i.hasNext()) {\r
- throttles.remove(i.next());\r
- }\r
- }\r
- try {\r
- Thread.sleep(60*10*1000);\r
- }\r
- catch (InterruptedException e) {\r
- break;\r
- }\r
- }\r
- }\r
- };\r
-\r
- cleanUpThread.setDaemon(true);\r
- cleanUpThread.start();\r
- }\r
-\r
- public boolean addMessage(String anIP, Entity anEntity, int aLimit, long aPeriod) {\r
- synchronized (throttles) {\r
- Throttle throttle = (Throttle) throttles.get(anIP);\r
-\r
- if (throttle==null) {\r
- throttle = new Throttle(overallHorizon);\r
- throttles.put(anIP, throttle);\r
- }\r
- return throttle.addMessage(anEntity, aLimit, aPeriod);\r
- }\r
- }\r
-\r
- private class Throttle {\r
- private List messages;\r
- private long horizon;\r
-\r
- public Throttle(long aHorizon) {\r
- messages = new ArrayList();\r
- horizon = aHorizon;\r
- }\r
-\r
- public boolean flush() {\r
- long limit = System.currentTimeMillis() - horizon;\r
-\r
- while (messages.size()>0 && ((Message) messages.get(0)).getTime()<=limit) {\r
- messages.remove(0);\r
- }\r
-\r
- return messages.size()==0;\r
- }\r
-\r
- public boolean addMessage(Entity anEntity, int aLimit, long aPeriod) {\r
- Message lastMessage=null;\r
- if (messages.size()>0) {\r
- lastMessage = (Message) messages.get(messages.size()-1);\r
- }\r
-\r
- Message newMessage = new Message(anEntity.getId(),\r
- anEntity instanceof EntityComment, System.currentTimeMillis());\r
-\r
- if (!newMessage.equals(lastMessage))\r
- messages.add(newMessage);\r
-\r
- if (messages.size()>=aLimit) {\r
- Message message = (Message) messages.get(messages.size()-aLimit);\r
- return (System.currentTimeMillis()-message.getTime())<aPeriod;\r
- }\r
-\r
- return false;\r
- }\r
-\r
- private class Message {\r
- private String id;\r
- private boolean isComment;\r
- private long time;\r
-\r
- public Message(String anId, boolean anIsComment, long aTime) {\r
- id = anId;\r
- isComment = anIsComment;\r
- time = aTime;\r
- }\r
-\r
- public String getId() {\r
- return id;\r
- }\r
-\r
- public boolean getIsComment() {\r
- return isComment;\r
- }\r
-\r
- public long getTime() {\r
- return time;\r
- }\r
-\r
- public int hashCode() {\r
- return getId().hashCode();\r
- }\r
-\r
- public boolean equals(Object anObject) {\r
- if (anObject instanceof Message) {\r
- Message that = (Message) anObject;\r
-\r
- if (that.getId().equals(getId()) && that.getIsComment() == getIsComment()) {\r
- return true;\r
- }\r
- }\r
-\r
- return false;\r
- }\r
- }\r
- }\r
- }\r
-}\r
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.media;\r
-\r
-import mir.media.MediaHandler;\r
-import mir.media.MediaExc;\r
-import mir.media.MediaFailure;\r
-import mir.entity.Entity;\r
-import mir.misc.StringUtil;\r
-\r
-import java.io.File;\r
-\r
-public abstract class AbstractMediaHandler implements MediaHandler {\r
- public File getStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {\r
- return new File(new File(getStoragePath()), getRelativeStorageFile(aMedia, aMediaType));\r
- }\r
-\r
- public String getRelativeStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {\r
- String publishPath = aMedia.getFieldValue("publish_path");\r
-\r
- if (publishPath==null || publishPath.length()==0) {\r
- String extension = aMediaType.getFieldValue("name");\r
- String mediaFileName = aMedia.getId() + "." + extension;\r
- String date = aMedia.getFieldValue("date");\r
- String datePath = StringUtil.webdbDate2path(date);\r
- return (new File(datePath, mediaFileName)).getPath();\r
- }\r
- else {\r
- return publishPath;\r
- }\r
- }\r
-\r
-}\r
+/*
+ * 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 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.changetracker.ChangeTracker;
+import mir.changetracker.ChangeType;
+import mir.entity.Entity;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MediaHandler;
+import mir.misc.StringUtil;
+import mircoders.global.MirGlobal;
+
+import java.io.*;
+
+public abstract class AbstractMediaHandler implements MediaHandler {
+ protected InputStream getStorageInputStream(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ return new FileInputStream(getMediaStorageFile(aMedia, aMediaType));
+ }
+ catch (Throwable e) {
+ throw new MediaFailure(e);
+ }
+ }
+
+ protected OutputStream getStorageOutputStream(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ return new FileOutputStream(getMediaStoragePath(aMedia, aMediaType));
+ }
+ catch (Throwable e) {
+ throw new MediaFailure(e);
+ }
+ }
+
+ protected String getRelativeMediaStoragePath(Entity aMedia, Entity aMediaType) {
+ String publishPath = aMedia.getFieldValue("publish_path");
+
+ if (publishPath==null || publishPath.length()==0) {
+ String extension = aMediaType.getFieldValue("name");
+ String mediaFileName = aMedia.getId() + "." + extension;
+ String date = aMedia.getFieldValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+
+ return datePath + "/" + mediaFileName;
+ }
+
+ return publishPath;
+ }
+
+ protected String getMediaStoragePath(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ return getBaseStoragePath() + "/" + getRelativeMediaStoragePath(aMedia, aMediaType);
+ }
+
+ protected final File getMediaStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ return new File(getMediaStoragePath(aMedia, aMediaType));
+ }
+
+ /*
+ * Report filesystem changes to the ChangeTracker.
+ */
+ protected void reportChange(String imagePath) {
+ ChangeTracker tracker = MirGlobal.getChangeEngine().getTracker();
+ tracker.addChange(imagePath, ChangeType.MODIFICATION);
+ }
+
+}
+++ /dev/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 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.awt.RenderingHints;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-import java.awt.image.PixelInterleavedSampleModel;
-import java.awt.image.RenderedImage;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import javax.media.jai.ImageLayout;
-import javax.media.jai.InterpolationBilinear;
-import javax.media.jai.JAI;
-import javax.media.jai.ParameterBlockJAI;
-
-import mir.log.LoggerWrapper;
-
-import com.sun.media.jai.codec.ByteArraySeekableStream;
-import com.sun.media.jai.codec.FileSeekableStream;
-import com.sun.media.jai.codec.SeekableStream;
-
-/**
- *
- * <p>Title: Image processor</p>
- * <p>Description: Temporary image processor class. (Made for the immediate needs of CMI brasil.
- * Will become obsolete when mh's media handler rewrite is finished. </p>
- * @author Zapata
- * @version 1.0
- */
-
-public class ImageProcessor {
- static final LoggerWrapper logger = new LoggerWrapper("media");
-
- private RenderedImage image;
- private RenderedImage scaledImage;
-
- public ImageProcessor(RenderedImage anImage) throws IOException {
- image = anImage;
- scaledImage = anImage;
- }
-
- public ImageProcessor(SeekableStream anImageStream) throws IOException {
- RenderedImage tempImage = JAI.create("stream", anImageStream);
- ParameterBlockJAI params = new ParameterBlockJAI("format");
- int bands[];
- int nrComponents;
-
-
- params.addSource(tempImage);
- params.setParameter("dataType", DataBuffer.TYPE_BYTE);
-
- ImageLayout layout = new ImageLayout();
- nrComponents = tempImage.getColorModel().getNumColorComponents();
-
- bands = new int[nrComponents];
- for (int i=0; i<nrComponents; i++)
- bands[i]=i;
-
- layout.setColorModel(ColorModel.getRGBdefault());
- layout.setSampleModel(
- new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
- tempImage.getWidth(),
- tempImage.getHeight(),
- nrComponents,
- nrComponents*tempImage.getWidth(),
- bands));
-
- RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
-
- image = JAI.create("format", params, hints);
-
- scaledImage = image;
- }
-
- public ImageProcessor(File aFile) throws IOException {
- this(new FileSeekableStream(aFile));
- }
-
- public ImageProcessor(byte[] anImageData) throws IOException {
- this(new ByteArraySeekableStream(anImageData));
- }
-
- public void descaleImage(int aMaxSize) throws java.io.IOException {
- descaleImage(aMaxSize, 0);
- }
-
- public void descaleImage(int aMaxSize, float aMinDescale) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, aMinDescale, 0);
- }
-
- public void descaleImage(int aMaxSize, int aMinResize) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, 0, aMinResize);
- }
-
- public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, aMinDescale, aMinResize);
- }
-
- /**
- *
- * Resizes an image to fit inside <code>aMaxWidth</code> and <code>aMaxHeight</code>, provided
- * this requires at least <code>aMinResize</code> pixels will be removed from either the width or
- * the height
- *
- * @param aMaxWidth
- * @param aMaxHeight
- * @param aMinDescale
- * @param aMinResize
- * @throws java.io.IOException
- */
- public void descaleImage(int aMaxWidth, int aMaxHeight, float aMinDescale, int aMinResize) throws java.io.IOException {
- float scale;
- scaledImage = image;
-
- if ((aMaxWidth>0 && image.getWidth()>aMaxWidth+aMinResize-1) || (aMaxHeight>0 && image.getHeight()>aMaxHeight+aMinResize-1))
- {
- logger.info("Scaling image");
-
- scale=1;
-
- if (aMaxWidth>0 && image.getWidth()>aMaxWidth) {
- scale = Math.min(scale, (float) aMaxWidth / (float) image.getWidth());
- }
- if (aMaxHeight>0 && image.getHeight()>aMaxHeight) {
- scale = Math.min(scale, (float) aMaxHeight / (float) image.getHeight());
- }
-
- if (1-scale>aMinDescale) {
- scaleImage(scale);
- }
- }
- }
-
- public void scaleImage(float aScalingFactor) throws java.io.IOException {
- ParameterBlockJAI params = new ParameterBlockJAI("scale");
- params.addSource(image);
-
- params.setParameter("xScale", aScalingFactor);
- params.setParameter("yScale", aScalingFactor);
- params.setParameter("xTrans", 0.0F);
- params.setParameter("yTrans", 0.0F);
- params.setParameter("interpolation", new InterpolationBilinear());
- scaledImage = JAI.create("scale", params);
- }
-
- public int getWidth() {
- return image.getWidth();
- }
-
- public int getHeight() {
- return image.getHeight();
- }
-
- public int getScaledWidth() {
- return scaledImage.getWidth();
- }
-
- public int getScaledHeight() {
- return scaledImage.getHeight();
- }
-
- public void writeScaledData(OutputStream aStream, String anImageType) {
- JAI.create("encode", scaledImage, aStream, anImageType, null);
- }
-
- public byte[] getScaledData(String anImageType) {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- writeScaledData(outputStream, anImageType);
- return outputStream.toByteArray();
- }
-
- public void writeScaledData(File aFile, String anImageType) throws IOException {
- writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType);
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
*
* @see mir.media.MediaHandler
* @author mh <mh@nadir.org>
+ * @version $Id: MediaHandlerAudio.java,v 1.13 2007/04/08 21:46:35 idfx Exp $
*/
public class MediaHandlerAudio extends MediaHandlerGeneric implements MediaHandler
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
-import mir.media.MediaHandler;
import mir.misc.StringUtil;
-import mir.util.FileFunctions;
import mir.session.UploadedFile;
+import mir.util.IORoutines;
import javax.servlet.ServletContext;
-import java.io.BufferedInputStream;
-import java.io.File;
import java.io.FileInputStream;
+import java.io.FileOutputStream;
import java.io.InputStream;
-import java.util.List;
-import java.util.Vector;
/**
*
* @see mir.media.MediaHandler
* @author mh <mh@nadir.org>
+ * @version $Id: MediaHandlerGeneric.java,v 1.24 2007/04/08 21:46:35 idfx Exp $
*/
-public class MediaHandlerGeneric extends AbstractMediaHandler
-{
+public class MediaHandlerGeneric extends AbstractMediaHandler {
protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
protected LoggerWrapper logger = new LoggerWrapper("Media.Generic");
/** {@inheritDoc} */
- public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
- try {
- FileFunctions.move(aFile, getStorageFile(aMedia, aMediaType));
-
- aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
- aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
- aMedia.update();
- }
- catch (Throwable e) {
- logger.error("MediaHandlerGeneric.set: " + e.toString());
- throw new MediaFailure(e);
- }
- }
-
- /** {@inheritDoc} */
public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
try {
- anUploadedFile.writeToFile(getStorageFile(aMedia, aMediaType));
-
- aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
- aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
+ anUploadedFile.writeToFile(getMediaStorageFile(aMedia, aMediaType));
+ aMedia.setFieldValue("publish_path", getRelativeMediaStoragePath(aMedia, aMediaType));
+ aMedia.setFieldValue("size", Long.toString(getMediaStorageFile(aMedia, aMediaType).length()));
aMedia.update();
+ reportChange(getMediaStorageFile(aMedia, aMediaType).getAbsolutePath());
}
catch (Throwable e) {
logger.error("MediaHandlerGeneric.set: " + e.toString());
/** {@inheritDoc} */
public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
try {
- FileFunctions.copy(anInputStream, getStorageFile(aMedia, aMediaType));
+ IORoutines.copyStream(anInputStream, new FileOutputStream(getMediaStorageFile(aMedia, aMediaType)));
- aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
- aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
+ aMedia.setFieldValue("publish_path", getRelativeMediaStoragePath(aMedia, aMediaType));
+ aMedia.setFieldValue("size", Long.toString(getMediaStorageFile(aMedia, aMediaType).length()));
aMedia.update();
+ reportChange(getMediaStorageFile(aMedia, aMediaType).getAbsolutePath());
}
catch (Throwable e) {
logger.error("MediaHandlerGeneric.set: " + e.toString());
}
}
+ /** {@inheritDoc} */
public void produce(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
- if (!getStorageFile(aMedia, aMediaType).exists())
- throw new MediaExc("error in producing media:: " + getStorageFile(aMedia, aMediaType) + " does not exist!");
+ if (!getMediaStorageFile(aMedia, aMediaType).exists()) {
+ throw new MediaExc("error in producing media:: " + getMediaStorageFile(aMedia, aMediaType) + " does not exist!");
+ }
}
- /**
- * Get access to the raw media data by an {@link InputStream}
- */
+ /** {@inheritDoc} */
public InputStream getMedia(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
- File file = getStorageFile(aMedia, aMediaType);
- if (!file.exists())
- throw new MediaExc("error in MirMediaHandler.getMedia(): " + file + " does not exist!");
-
try {
- return new BufferedInputStream(new FileInputStream(file));
+ return new FileInputStream(getMediaStorageFile(aMedia, aMediaType));
}
catch (Throwable e) {
throw new MediaFailure("MediaHandlerGeneric.getMedia(): " + e.toString(), e);
String fileName = aMediaEntity.getId() + "." + aMediaType.getFieldValue("name");
return servletContext.getMimeType(fileName);
- };
+ }
- public String getStoragePath() {
+ public String getBaseStoragePath() {
return configuration.getString("Producer.Media.Path");
}
- public String getIconStoragePath() {
+ public String getBaseIconStoragePath() {
return configuration.getString("Producer.Image.IconPath");
}
return "Generic media";
}
- public List getURL(Entity ent, Entity mediaTypeEnt) {
- List theList = new Vector();
- theList.add(ent);
- return theList;
- }
-
public String getDescr(Entity mediaType) {
return mediaType.getFieldValue("mime_type");
}
*/
package mircoders.media;
+import java.io.ByteArrayInputStream;
import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.InputStream;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.util.List;
-import java.util.Vector;
+import java.io.OutputStream;
+import java.sql.SQLException;
import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
-import mir.misc.FileUtil;
import mir.misc.StringUtil;
-import mir.session.UploadedFile;
import mir.session.SessionExc;
+import mir.session.UploadedFile;
+import mir.util.FileRoutines;
+import mir.util.IORoutines;
import mircoders.entity.EntityImages;
/**
*
* @see mir.media.MediaHandler
* @author mh
+ * @version $Id: MediaHandlerImages.java,v 1.26 2007/04/08 21:46:35 idfx Exp $
*/
}
public InputStream getMedia(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
- InputStream inputStream;
-
try {
- inputStream = ((EntityImages)ent).getImage();
+ return new ByteArrayInputStream(((EntityImages) ent).getImage());
}
catch (Throwable e) {
logger.error("MediaHandlerImages.getImage: " + e.toString());
throw new MediaFailure(e);
}
-
- return inputStream;
}
public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
public void store(InputStream in, Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
try {
- ((EntityImages)ent).setImage(in, getType());
+ ((EntityImages) ent).setImage(in, getType());
}
- catch (Throwable e) {
- logger.error("MediaHandlerImages.store: "+e.toString());
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.ERROR_MESSAGE));
+ catch (IOException e) {
+ logger.error("MediaHandlerImages.store", e);
- throw new MediaExc("A problem has occurred processing the media file: " + e.toString());
+ throw new MediaFailure("A problem has occurred processing the media file", e);
}
- }
+ catch (SQLException e) {
+ logger.error("MediaHandlerImages.store", e);
- public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
- try {
- store(new FileInputStream(aFile), aMedia, aMediaType);
- }
- catch (FileNotFoundException e) {
- throw new MediaFailure(e);
+ throw new MediaFailure("A problem has occurred processing the media file", e);
}
}
String datePath = StringUtil.webdbDate2path(date);
String ext = "."+mediaTypeEnt.getFieldValue("name");
String filepath = datePath+ent.getId()+ext;
- String iconFilePath = configuration.getString("Producer.StorageRoot")
- +getIconStoragePath() + filepath;
- String productionFilePath = getStoragePath() + File.separator + filepath;
+ String iconFilePath = configuration.getString("Producer.StorageRoot") + getBaseIconStoragePath() + filepath;
+ String productionFilePath = getBaseStoragePath() + File.separator + filepath;
if (ent.getFieldValue("icon_data")!= null &&
ent.getFieldValue("image_data")!= null) {
// make icon
try {
- InputStream in = ((EntityImages) ent).getIcon();
- FileUtil.write(iconFilePath, in);
- in = ((EntityImages)ent).getImage();
- FileUtil.write(productionFilePath, in);
- ent.setFieldValue("icon_path",getIconStoragePath()+filepath);
- ent.setFieldValue("publish_path",filepath);
+ OutputStream out;
+ InputStream in = new ByteArrayInputStream(((EntityImages) ent).getIcon());
+ try {
+ File iconFile = new File(iconFilePath);
+
+ FileRoutines.createParentDirectories(iconFile);
+
+ out = new FileOutputStream(iconFile);
+ try {
+ IORoutines.copyStream(in, out);
+ reportChange(iconFile.getAbsolutePath());
+ }
+ finally {
+ out.close();
+ }
+ }
+ finally {
+ in.close();
+ }
+
+ in = new ByteArrayInputStream(((EntityImages) ent).getImage());
+ try {
+ File imageFile = new File(productionFilePath);
+
+ FileRoutines.createParentDirectories(imageFile);
+
+ out = new FileOutputStream(imageFile);
+ try {
+ IORoutines.copyStream(in, out);
+ reportChange(imageFile.getAbsolutePath());
+ }
+ finally {
+ out.close();
+ }
+ }
+ finally {
+ in.close();
+ }
+
+ ent.setFieldValue("icon_path", getBaseIconStoragePath() + filepath);
+ ent.setFieldValue("publish_path", filepath);
ent.update();
}
catch (Throwable e) {
- logger.error("MediaHandlerImages.produce: " + e.toString());
- throw new MediaFailure("MediaHandlerImages.produce: " + e.toString(), e);
+ logger.error("Error producing image", e);
+
+ throw new MediaFailure("Error producing image", e);
+ }
+ finally {
}
}
else {
- logger.error("MediaHandlerImages.produce: missing image or icon OID for: " + ent.getId());
+ logger.error("Can't produce image " + ent.getId() + ": missing image or icon OID");
- throw new MediaExc("MediaHandlerImages.produce: missing image or icon OID for: " + ent.getId());
+ throw new MediaExc("Can't produce image " + ent.getId() + ": missing image or icon OID");
}
}
-
+
public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure {
- InputStream in;
try {
- in = ((EntityImages) ent).getIcon();
+ return new ByteArrayInputStream(((EntityImages) ent).getIcon());
}
catch (Throwable e) {
logger.error("MediaHandlerImages.getIcon: " + e.toString());
throw new MediaFailure(e);
}
-
- return in;
- }
-
- public List getURL(Entity ent, Entity mediaTypeEnt) {
- List theList = new Vector();
- theList.add(ent);
- return theList;
}
- public String getStoragePath() {
+ public String getBaseStoragePath() {
return configuration.getString("Producer.Image.Path");
}
- public String getIconStoragePath() {
+ public String getBaseIconStoragePath() {
return configuration.getString("Producer.Image.IconPath");
}
package mircoders.media;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
+import mir.media.image.ImageMagickImageProcessor;
+import mir.media.image.ImageProcessor;
import mir.misc.StringUtil;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
/**
- * Image handler that stores images outside of the database. Will be replaced by the new
- * media handling system.
+ * Image handler that stores images outside of the database.
+ *
* @author Zapata
* @version 1.0
*/
-public class MediaHandlerImagesExtern extends MediaHandlerGeneric
-{
+public class MediaHandlerImagesExtern extends MediaHandlerGeneric {
private int maxIconSize;
private float minDescaleRatio;
private int minDescaleReduction;
minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");
}
- public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
- try {
+ public void produce(Entity anImageEntity, Entity aMediaTypeEntity) throws MediaExc, MediaFailure {
String date = anImageEntity.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
- String ext = "." + mediaTypeEnt.getFieldValue("name");
+ String ext = "." + aMediaTypeEntity.getFieldValue("name");
String fileBasePath = datePath + anImageEntity.getId();
String filePath = fileBasePath + ext;
- String iconPath = getIconStoragePath() + fileBasePath + ".jpg";
+ String iconPath = getBaseIconStoragePath() + fileBasePath + ".jpg";
String iconStoragePath = configuration.getString("Producer.StorageRoot") + iconPath;
- String imageFilePath = getStoragePath() + File.separator + filePath;
+ String imageFilePath = getBaseStoragePath() + File.separator + filePath;
File imageFile = new File(imageFilePath);
File iconFile = new File(iconStoragePath);
if (!imageFile.exists()) {
- throw new MediaExc("error in MediaHandlerImagesExtern.produce(): " + filePath + " does not exist!");
+ throw new MediaExc("error in MediaHandlerImagesExtern.execute(): " + filePath + " does not exist!");
}
else {
- ImageProcessor processor = new ImageProcessor(imageFile);
+ ImageProcessor processor;
+ try {
+ processor = new ImageMagickImageProcessor(imageFile);
+ }
+ catch (IOException e) {
+ throw new MediaFailure(e);
+ }
processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
File dir = new File(iconFile.getParent());
- if (dir!=null && !dir.exists()){
- dir.mkdirs();
+ if (dir!=null && !dir.exists()){
+ dir.mkdirs();
}
processor.writeScaledData(iconFile, "JPEG");
- anImageEntity.setFieldValue("img_height", new Integer(processor.getHeight()).toString());
- anImageEntity.setFieldValue("img_width", new Integer(processor.getWidth()).toString());
+ anImageEntity.setFieldValue("img_height",
+ Integer.toString(processor.getHeight()));
+ anImageEntity.setFieldValue("img_width",
+ Integer.toString(processor.getWidth()));
- anImageEntity.setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
- anImageEntity.setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
+ anImageEntity.setFieldValue("icon_height",
+ Integer.toString(processor.getScaledHeight()));
+ anImageEntity.setFieldValue("icon_width",
+ Integer.toString(processor.getScaledWidth()));
+ processor.cleanup();
anImageEntity.setFieldValue("icon_path", iconPath);
anImageEntity.setFieldValue("publish_path", filePath);
anImageEntity.update();
-
-
+ reportChange(iconStoragePath);
+ reportChange(imageFilePath);
}
- }
- catch(Throwable t) {
- logger.error("MediaHandlerImagesExtern.produce: " + t.toString());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- throw new MediaFailure(t.getMessage(), t);
- }
}
return "image/jpeg";
}
- public String getStoragePath()
+ public String getBaseStoragePath()
{
return configuration.getString("Producer.Image.Path");
}
- public String getIconStoragePath()
+ public String getBaseIconStoragePath()
{
return configuration.getString("Producer.Image.IconPath");
}
--- /dev/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 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.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.image.ImageMagickImageProcessor;
+import mir.media.image.ImageProcessor;
+import mir.misc.StringUtil;
+import mir.util.FileRoutines;
+
+/**
+ * Image handler that stores images outside of the database.
+ *
+ * @author Zapata
+ * @version 1.0
+ */
+
+public class MediaHandlerImagesExternScaling extends MediaHandlerGeneric
+{
+ private int maxSize;
+ private int maxIconSize;
+ private float minDescaleRatio;
+ private int minDescaleReduction;
+ public MediaHandlerImagesExternScaling() {
+ logger = new LoggerWrapper("Media.Images.Extern");
+ maxSize = configuration.getInt("Producer.Image.MaxSize");
+ maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");
+ minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;
+ minDescaleReduction = configuration.getInt("Producer.Image.MinDescaleReduction");
+ }
+
+
+
+ public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
+ try {
+ String date = anImageEntity.getFieldValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String ext = "." + mediaTypeEnt.getFieldValue("name");
+ String fileBasePath = datePath + anImageEntity.getId();
+ String filePath = fileBasePath + ext;
+
+ String imageFilePath = getBaseStoragePath() + File.separator + filePath;
+ File imageFile = new File(imageFilePath);
+
+ if (!imageFile.exists()) {
+ throw new MediaExc("error in MediaHandlerImagesExtern.execute(): "
+ + filePath + " does not exist!");
+ } else {
+ ImageProcessor processor = new ImageMagickImageProcessor(imageFile);
+ String iconPath = getBaseIconStoragePath() + fileBasePath + ".jpg";
+ String iconStoragePath = doIconScaling(processor, iconPath);
+ anImageEntity.setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
+ anImageEntity.setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
+ anImageEntity.setFieldValue("icon_path", iconPath);
+
+ String imageOriginalRelPath = doImageScaling(filePath, imageFile, processor);
+ anImageEntity.setFieldValue("original_file_path", imageOriginalRelPath);
+ anImageEntity.setFieldValue("img_height", Integer.toString(processor.getScaledHeight()));
+ anImageEntity.setFieldValue("img_width", Integer.toString(processor.getScaledWidth()));
+
+ processor.cleanup();
+ anImageEntity.setFieldValue("publish_path", filePath);
+ anImageEntity.update();
+ reportChange(iconStoragePath);
+ reportChange(imageFilePath);
+ }
+ }
+ catch(Throwable t) {
+ logger.error("MediaHandlerImagesExtern.execute: " + t.getMessage(), t);
+ throw new MediaFailure(t.getMessage(), t);
+ }
+ }
+
+ /**
+ * Scale an icon image and write it to the file system.
+ * @param processor
+ * @param iconPath
+ * @return
+ * @throws MediaExc
+ */
+ private String doIconScaling(ImageProcessor processor, String iconPath) throws MediaExc {
+ String iconStoragePath = configuration.getString("Producer.StorageRoot") + iconPath;
+ File iconFile = new File(iconStoragePath);
+ processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
+ File dir = new File(iconFile.getParent());
+ if (dir != null && !dir.exists()) {
+ dir.mkdirs();
+ }
+ processor.writeScaledData(iconFile, "JPEG");
+ return iconStoragePath;
+ }
+
+ /**
+ * Make the resized file.
+ * @param filePath
+ * @param imageFile
+ * @param processor
+ * @return
+ * @throws MediaExc
+ * @throws IOException
+ */
+ private String doImageScaling(String filePath, File imageFile, ImageProcessor processor) throws MediaExc, IOException {
+ // get a file path where the the original image should be saved if image resizing is turned on
+ String imagesOriginalDir = configuration.getString("Producer.ImagesOriginalDir.Path");
+ String imagesOriginalDirRelPath = configuration.getString("Producer.ImagesOriginalDir.RelPath");
+ String imageOriginalFilePath = imagesOriginalDir + filePath;
+ String imageOriginalRelPath = imagesOriginalDirRelPath + filePath;
+ File originalFile = new File(imageOriginalFilePath);
+ processor.descaleImage(maxSize, minDescaleRatio, minDescaleReduction);
+ File originalDir = new File(originalFile.getParent());
+ if (originalDir != null && !originalDir.exists()) {
+ originalDir.mkdirs();
+ }
+ if (!originalFile.exists()) {
+ FileRoutines.copy(imageFile, originalFile);
+ reportChange(originalFile.getAbsolutePath());
+ }
+ // yoss: don't write the scaled data again if it's the same size as
+ // the file that's there right now. Image producer runs are 4 times
+ // faster this way.
+ if (processor.getScaledFileSize() != imageFile.length()) {
+ processor.writeScaledData(imageFile, "JPEG");
+ }
+ return imageOriginalRelPath;
+ }
+
+/** {@inheritDoc} */
+ public InputStream getThumbnail(Entity anImageEntity) throws MediaExc, MediaFailure {
+ try {
+ File file = new File(configuration.getString("Producer.StorageRoot") + anImageEntity.getFieldValue("icon_path"));
+
+ if (!file.exists()) {
+ // hackish
+ file = new File(configuration.getHome(), "../img/photo_big.gif");
+ }
+
+ return new BufferedInputStream(
+ new FileInputStream(file),8192);
+ }
+ catch (Throwable t) {
+ return null;
+ }
+ }
+
+ public String getIconMimeType(Entity anImageEntity, Entity aMediaType) {
+ return "image/jpeg";
+ }
+
+ public String getBaseStoragePath()
+ {
+ return configuration.getString("Producer.Image.Path");
+ }
+
+ public String getBaseIconStoragePath()
+ {
+ 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 String getDescr(Entity mediaType)
+ {
+ return "image/jpeg";
+ }
+}
* @see mir.media.MediaHandler
* @see mircoders.media.MediaHandlerImages
* @author mh, mir-coders group
+ * @version $Id: MediaHandlerImagesJpeg.java,v 1.8 2007/04/08 21:46:35 idfx Exp $
*/
* @see mir.media.MediaHandler
* @see mircoders.media.MediaHandlerImages
* @author mh ,mir-coders
- * @version $Id: MediaHandlerImagesPng.java,v 1.8 2004/11/06 20:04:00 idfx Exp $
+ * @version $Id: MediaHandlerImagesPng.java,v 1.9 2007/04/08 21:46:35 idfx Exp $
*/
*/
package mircoders.media;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
+import java.io.File;
+import java.io.FileOutputStream;
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
-import mir.misc.FileUtil;
import mir.misc.StringUtil;
+import mir.util.IORoutines;
/**
* Please note: this media handler produces
*
* @see mir.media.MediaHandler
* @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerMp3.java,v 1.17 2004/11/06 20:04:00 idfx Exp $
+ * @version $Id: MediaHandlerMp3.java,v 1.18 2007/04/08 21:46:35 idfx Exp $
*/
-public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler
-{
-
+public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler {
public MediaHandlerMp3() {
logger = new LoggerWrapper("Media.Audio.Mp3");
}
+ /**
+ * {@inheritDoc}
+ */
public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
-
- // first check if the file exists
super.produce(ent, mediaTypeEnt);
String baseName = ent.getId();
String playlistFile = baseName + ".pls";
try {
- //write the "meta" files
- //first the .m3u since it only contains one line
- FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,
- new StringReader(mp3Pointer), "US-ASCII");
- //now the .pls file
- FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,
- new StringReader(mp3Pointer), "US-ASCII");
+ IORoutines.writeStream(mp3Pointer, "us-ascii",
+ new FileOutputStream(new File(getBaseStoragePath() + "/" + datePath + "/" + mpegURLFile)));
+
+ IORoutines.writeStream(mp3Pointer, "us-ascii",
+ new FileOutputStream(new File(getBaseStoragePath() + "/" + datePath + "/" + playlistFile)));
+ reportChange(getBaseStoragePath() + "/" + datePath + "/" + mpegURLFile);
+ reportChange(getBaseStoragePath() + "/" + datePath + "/" + playlistFile);
}
catch (Throwable e) {
- logger.error("MediaHandlerMp3.produce: " + e.toString());
+ logger.error("MediaHandlerMp3.execute: " + e.toString());
throw new MediaFailure(e);
}
}
-
- public List getURL(Entity ent, Entity mediaTypeEnt) {
- List theList = new Vector();
-
- //String stringSize = ent.getFieldValue("size");
- //int size = Integer.parseInt(stringSize, 10)/1024;
- theList.add(ent);
-
- String basePath = StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
- ".mp3$", "");
-
- // @todo the texts ("title") below urgently need to be sanely localizaeble
- // somehow
- Map m3uHash = new HashMap();
- m3uHash.put("publish_path", basePath + ".m3u");
- m3uHash.put("publish_server", ent.getFieldValue("publish_server"));
- m3uHash.put("title", "stream URL");
- theList.add(m3uHash);
-
- Map plsHash = new HashMap();
- plsHash.put("publish_path", basePath + ".pls");
- plsHash.put("publish_server", ent.getFieldValue("publish_server"));
- plsHash.put("title", "playlist URL");
- theList.add(plsHash);
-
- return theList;
-
- }
-
+
public String getDescr(Entity mediaType) {
return "mp3";
}
*/
package mircoders.media;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
-import mir.misc.FileUtil;
import mir.misc.StringUtil;
+import mir.util.IORoutines;
+
+import java.io.File;
+import java.io.FileOutputStream;
/**
* Please note: this media handler produces
public class MediaHandlerOgg extends MediaHandlerAudio implements MediaHandler
{
- protected LoggerWrapper logger;
-
+
public MediaHandlerOgg() {
logger = new LoggerWrapper("Media.Audio.Ogg");
}
String date = ent.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
String oggPointer = getPublishHost() + ent.getFieldValue("publish_path");
- //String mpegURLFile = baseName + ".m3u";
String playlistFile = baseName + ".pls";
try {
- //write the "meta" files
- //first the .m3u since it only contains one line
- //dont write the .m3u it is an ogg vorbis file
- //FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,
- //new StringReader(mp3Pointer), "US-ASCII");
- //now the .pls file
- FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,
- new StringReader(oggPointer), "US-ASCII");
+ IORoutines.writeStream(oggPointer, "us-ascii",
+ new FileOutputStream(getBaseStoragePath() + File.separator + datePath + File.separator + playlistFile));
+ reportChange(getBaseStoragePath() + File.separator + datePath + File.separator + playlistFile);
}
catch (Throwable e) {
- logger.error("MediaHandlerOgg.produce: " + e.toString());
+ logger.error("MediaHandlerOgg.execute: " + e.toString());
throw new MediaFailure(e);
}
}
- public List getURL(Entity ent, Entity mediaTypeEnt) {
- List theList = new Vector();
-
- //String stringSize = ent.getFieldValue("size");
- //int size = Integer.parseInt(stringSize, 10)/1024;
- theList.add(ent);
-
- String basePath = StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
- ".ogg$", "");
-
- // @todo the texts ("title") below urgently need to be sanely localizaeble
- // somehow
- //no .m3u!
- //Map m3uHash = new HashMap();
- //m3uHash.put("publish_path", basePath + ".m3u");
- //m3uHash.put("publish_server", ent.getFieldValue("publish_server"));
- //m3uHash.put("title", "stream URL");
- //theList.add(m3uHash);
-
- Map plsHash = new HashMap();
- plsHash.put("publish_path", basePath + ".pls");
- plsHash.put("publish_server", ent.getFieldValue("publish_server"));
- plsHash.put("title", "playlist URL");
- theList.add(plsHash);
-
- return theList;
-
- }
-
public String getDescr(Entity mediaType) {
return "ogg";
}
*/
package mircoders.media;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
+import java.io.File;
+import java.io.FileOutputStream;
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
-import mir.misc.FileUtil;
import mir.misc.StringUtil;
+import mir.util.IORoutines;
/**
* Handles realAudio .it manages the ram file.
*
- * 03.2002 - reworked Realmedia handling. -mh
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MediaHandler
* @author john <john@manifestor.org>, mh <heckmann@hbe.ca>
- * @version $Id: MediaHandlerRealAudio.java,v 1.21 2004/11/06 20:04:00 idfx Exp $
+ * @version $Id: MediaHandlerRealAudio.java,v 1.22 2007/04/08 21:46:35 idfx Exp $
*/
// first see if the file exists
super.produce(ent, mediaTypeEnt);
- String baseName = ent.getId();
String date = ent.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
- String rtspDir = configuration.getString("Producer.RealMedia.Path");
String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path");
String RealMediaFile = datePath+ent.getId()+".ram";
try {
- //write an rm (ram?. -mh) file
- FileUtil.write(super.getStoragePath()+"/"+RealMediaFile,
- new StringReader(RealMediaPointer), "US-ASCII");
+ //write a ram file
+
+ IORoutines.writeStream(RealMediaPointer, "us-ascii",
+ new FileOutputStream(getBaseStoragePath() + File.separator + datePath + File.separator + RealMediaFile));
+ reportChange(getBaseStoragePath() + File.separator + datePath + File.separator + RealMediaFile);
}
catch (Throwable e) {
- logger.error("MediaHandlerRealAudio.produce: " + e.toString());
+ logger.error("Error while producing realmedia: " + e.toString(), e);
+
throw new MediaFailure(e);
}
}
- public List getURL(Entity ent, Entity mediaTypeEnt)
- {
- List theList = new Vector();
-
- //String stringSize = ent.getFieldValue("size");
- //int size = Integer.parseInt(stringSize, 10)/1024;
- theList.add(ent);
-
- String basePath=StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
- ".ra$","");
-
- // @todo the texts ("title") below urgently need to be sanely localizaeble
- // somehow
- Map ramHash = new HashMap();
- ramHash.put("publish_path", basePath+".ram");
- ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
- ramHash.put("title", "stream URL");
- theList.add(ramHash);
-
- return theList;
- }
-
- public String getStoragePath()
+ public String getBaseStoragePath()
{
return configuration.getString("Producer.RealMedia.Path");
}
*/
package mircoders.media;
-import java.io.File;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
-import mir.misc.FileUtil;
import mir.misc.StringUtil;
+import mir.util.IORoutines;
-
+import java.io.File;
+import java.io.FileOutputStream;
/**
* Handles realVideo .it manages the ram file.
*
* 03.2002 - reworked Realmedia handling. -mh
*
- * @see mir.media.MediaHandlerGeneric
* @see mir.media.MediaHandler
* @author john <john@manifestor.org>, mh <mh@nadir.org>
- * @version $Id: MediaHandlerRealVideo.java,v 1.21 2004/11/06 20:04:00 idfx Exp $
+ * @version $Id: MediaHandlerRealVideo.java,v 1.22 2007/04/08 21:46:35 idfx Exp $
*/
-public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHandler
-{
-
+public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHandler {
public MediaHandlerRealVideo() {
logger = new LoggerWrapper("Media.Video.Real");
}
// first see if the file exists
super.produce(ent, mediaTypeEnt);
- String baseName = ent.getId();
String date = ent.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
- String rtspDir = configuration.getString("Producer.RealMedia.Path");
String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path");
String RealMediaFile = datePath+ent.getId()+".ram";
+
try {
- //write an rm (ram?. -mh) file
- FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile,
- new StringReader(RealMediaPointer), "US-ASCII");
+ // write a ram file
+ IORoutines.writeStream(RealMediaPointer, "us-ascii",
+ new FileOutputStream(new File(super.getBaseStoragePath() + File.separator + RealMediaFile)));
+ reportChange(super.getBaseStoragePath() + File.separator + RealMediaFile);
}
catch (Throwable e) {
- logger.error("MediaHandlerRealVideo.produce: " + e.toString());
+ logger.error("MediaHandlerRealVideo.execute: " + e.toString());
throw new MediaFailure(e);
}
}
- public List getURL(Entity ent, Entity mediaTypeEnt) {
- List theList = new Vector();
-
- //String stringSize = ent.getFieldValue("size");
- //int size = Integer.parseInt(stringSize, 10)/1024;
- theList.add(ent);
-
- String basePath=StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
- ".rm$","");
-
- // @todo the texts ("title") below urgently need to be sanely localizaeble
- // somehow
- Map ramHash = new HashMap();
- ramHash.put("publish_path", basePath+".ram");
- ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
- ramHash.put("title", "stream URL");
- theList.add(ramHash);
-
- return theList;
-
- }
-
- public String getStoragePath() {
+ public String getBaseStoragePath() {
return configuration.getString("Producer.RealMedia.Path");
}
* It is like MediaHandlerAudio with different icons.
* It is MediaHandlerGeneric with different icons.
*
- * @see mir.media.MediaHandlerGeneric
* @see mir.media.MediaHandler
* @author john <john@manifestor.org>
+ * @version $Id: MediaHandlerVideo.java,v 1.11 2007/04/08 21:46:35 idfx Exp $
*/
public class MediaHandlerVideo extends MediaHandlerGeneric implements MediaHandler
package mircoders.media;
import mir.entity.Entity;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MediaHandler;
import mir.storage.Database;
-import java.util.Map;
-import java.util.HashMap;
-import mircoders.global.*;
-import mircoders.storage.*;
-import mir.media.*;
-import mircoders.localizer.MirLocalizerExc;
+import mircoders.global.MirGlobal;
+import mircoders.storage.DatabaseAudio;
+import mircoders.storage.DatabaseImages;
+import mircoders.storage.DatabaseOther;
+import mircoders.storage.DatabaseVideo;
/**
* helper class to resolve media handlers using reflection
*/
public final class MediaHelper {
- private static Map nameToMediaHandler = new HashMap();
- private static String defaultMediaHandler = null;
-
- public static void addHandler(String aName, MediaHandler aHandler) {
- synchronized (nameToMediaHandler) {
- nameToMediaHandler.put(aName, aHandler);
- }
- }
-
public static MediaHandler getHandler(Entity aMediaType) throws MediaExc, MediaFailure {
String handlerName = aMediaType.getFieldValue("classname");
- try {
- return MirGlobal.localizer().media().getHandler(handlerName);
- }
- catch (MirLocalizerExc e) {
- throw new MediaFailure(e);
- }
+ return MirGlobal.localizer().media().getHandler(handlerName);
}
public static Database getStorage(Entity mediaType, String aTable) throws MediaExc, MediaFailure {
if (aTable.equals("Other"))
return DatabaseOther.getInstance();
- throw new MediaExc("Unknown storage specification: " + aTable);
+ throw new MediaExc("Unknown database specification: " + aTable);
}
}
package mircoders.media;
import mir.entity.Entity;
-import mir.media.MediaExc;
+import mir.log.LoggerWrapper;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
+import mir.media.MediaExc;
import mir.misc.StringUtil;
import mir.session.UploadedFile;
import mir.storage.Database;
-import mir.log.LoggerWrapper;
-import mir.util.FileFunctions;
+import mir.storage.DatabaseExc;
+import mir.util.FileRoutines;
import mircoders.module.ModuleMediaType;
import java.util.GregorianCalendar;
* Processes an uploaded media file.
* Will create the media entity and so on.
*/
- public static Entity processMediaUpload(UploadedFile aFile, Map aValues) throws MediaExc, MediaFailure {
+ public static Entity processMediaUpload(UploadedFile aFile, Map aValues)
+ throws UnsupportedMediaTypeExc, MediaExc, DatabaseExc {
MediaHandler mediaHandler;
- Entity mediaType;
+ Entity mediaType = null;
Database mediaStorage;
Map values = new HashMap();
Entity mediaEntity;
logger.debug("processing media upload of " + aFile.getFileName() + " (content type = " + contentType + ")");
if (contentType!=null) {
- if (contentType.equals("text/plain") ||
- contentType.equals("application/octet-stream") ||
- contentType == null) {
- throw new MediaExc("Invalid content-type: " + contentType);
- }
+ mediaType = mediaTypeModule.findMediaTypeForMimeType(contentType);
}
- try {
- if (contentType!=null) {
- mediaType = mediaTypeModule.findMediaTypeForExtension(contentType);
- }
- else {
- String extension = FileFunctions.getExtension(aFile.getFileName());
- mediaType = mediaTypeModule.findMediaTypeForExtension(extension);
- }
+ if (mediaType==null) {
+ String extension = FileRoutines.getExtension(aFile.getFileName());
+ mediaType = mediaTypeModule.findMediaTypeForExtension(extension);
}
- catch (Throwable t) {
- throw new MediaFailure(t);
+
+ if (mediaType==null) {
+ throw new UnsupportedMediaTypeExc("Media " + aFile.getFileName() + " " +
+ (aFile!=null?"("+aFile.getContentType()+") ":"") + " not supported", aFile.getContentType());
}
values.putAll(aValues);
values.put("to_media_type", mediaType.getId());
- try {
- mediaEntity = (Entity) mediaStorage.getEntityClass().newInstance();
- mediaEntity.setStorage(mediaStorage);
- }
- catch (Throwable e) {
- throw new MediaFailure(e);
- }
-
+ mediaEntity = mediaStorage.createNewEntity();
mediaEntity.setFieldValues(values);
+ mediaEntity.insert();
+ mediaHandler.store(aFile, mediaEntity, mediaType);
try {
- mediaEntity.insert();
- mediaHandler.store(aFile, mediaEntity, mediaType);
}
catch (Throwable e) {
throw new MediaFailure(e);
package mircoders.media;
+import java.io.File;
+import java.io.InputStream;
+
import mir.entity.Entity;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.media.MediaHandler;
import mir.session.UploadedFile;
-import java.io.File;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* <p>URLMediaHandler</p>
* <p>Description:
/**
* {@inheritDoc}
- *
- * Since this media handler assumes the media is stored on a wholly different
- * server, this operation is not applicable
- */
- public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
- throw new UnsupportedOperationException();
- }
-
- /**
- * {@inheritDoc}
*/
public void produce(Entity anEntity, Entity aMediaTypeEntity) throws MediaExc, MediaFailure {
// nothing to do here
return "application/octetstream";
}
- public List getURL(Entity aMediaEntity, Entity aMediaTypeEntity) throws MediaExc, MediaFailure {
- List result = new ArrayList();
- result.add(aMediaTypeEntity.getFieldValue("publish_server")+aMediaTypeEntity.getFieldValue("publish_path"));
-
- return result;
- }
-
- public Object getURLs(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
- return null;
- }
-
- public String getStoragePath () throws MediaExc, MediaFailure {
+ public String getBaseStoragePath () throws MediaExc, MediaFailure {
throw new UnsupportedOperationException();
}
- public String getIconStoragePath () throws MediaExc, MediaFailure {
+ public String getBaseIconStoragePath () throws MediaExc, MediaFailure {
throw new UnsupportedOperationException();
}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.media;\r
+\r
+import multex.Exc;\r
+\r
+public class UnsupportedMediaTypeExc extends Exc {\r
+ private String mimeType;\r
+\r
+ public UnsupportedMediaTypeExc(String aMessage, String aMimeType) {\r
+ super(aMessage);\r
+ mimeType = aMimeType;\r
+ }\r
+\r
+ public String getMimeType() {\r
+ return mimeType;\r
+ }\r
+}\r
public String articleTypeIdForName(String aName) throws ModuleExc, ModuleFailure {
try {
- return storage.executeFreeSingleValueSql("select id from article_type where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ return database.executeFreeSingleValueSql("select id from article_type where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
}
catch (Throwable t) {
throw new ModuleFailure(t);
import mir.module.AbstractModule;
import mircoders.storage.DatabaseBreaking;
-
-
-/*
- *
- *
- *
- * @author RK
- */
-
-public class ModuleBreaking extends AbstractModule
-{
+public class ModuleBreaking extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Breaking");
public ModuleBreaking ()
*/
package mircoders.module;
+import java.util.Map;
+
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
import mircoders.storage.DatabaseComment;
import mircoders.storage.DatabaseContent;
-import java.util.Map;
-
/*
* ModuleComment - methods and access for comments
public void deleteById (String anId) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = storage.selectById((String)anId);
+ Entity theEntity = database.selectById(anId);
if (theEntity != null)
DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getFieldValue("to_media"));
}
}
- /**
- *
- * @param theValues
- * @return
- * @throws ModuleExc
- * @throws ModuleFailure
- */
-
public String set(Map theValues) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = storage.selectById((String)theValues.get("id"));
+ Entity theEntity = database.selectById((String)theValues.get("id"));
if (theEntity == null)
throw new ModuleExc("No Object in the database with id " + theValues.get("id"));
DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getFieldValue("to_media"));
public String commentStatusIdForName(String aName) throws ModuleExc, ModuleFailure {
try {
- return storage.executeFreeSingleValueSql("select id from comment_status where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ return database.executeFreeSingleValueSql("select id from comment_status where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
}
catch (Throwable t) {
throw new ModuleFailure(t);
if (!aForce)
query = query + " and to_locking_user is null";
- return storage.executeUpdate(query) > 0;
+ return database.executeUpdate(query) > 0;
}
catch (Throwable t) {
return false;
if (!aForce)
query = query + " and to_locking_user = "+JDBCStringRoutines.escapeStringLiteral(aUserId);
- return storage.executeUpdate(query) > 0;
+ return database.executeUpdate(query) > 0;
}
catch (Throwable t) {
return false;
*/
public String queryArticleLock(String anId) {
try {
- String result = storage.executeFreeSingleValueSql("select to_locking_user from content where id = " + JDBCStringRoutines.escapeStringLiteral(anId));
+ String result = database.executeFreeSingleValueSql("select to_locking_user from content where id = " + JDBCStringRoutines.escapeStringLiteral(anId));
if (result!=null && !MirGlobal.isUserLoggedIn(result)) {
expireArticleLock(anId, result);
*/
package mircoders.module;
+import mir.entity.Entity;
+import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
import mir.util.JDBCStringRoutines;
-import mir.entity.Entity;
-import mir.entity.EntityList;
import mircoders.storage.DatabaseLanguage;
-/**
- * Title: mir - another content management system
- * Description:
- * Copyright: Copyright (c) 2001
- * Company: indymedia
- * @author idefix
- * @version 1.0
- */
-
public class ModuleLanguage extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Language");
public String languageIdForCode(String aCode) throws ModuleExc, ModuleFailure {
try {
- return storage.executeFreeSingleValueSql("select id from language where code = '" + JDBCStringRoutines.escapeStringLiteral(aCode) + "'");
+ return database.executeFreeSingleValueSql("select id from language where code = '" + JDBCStringRoutines.escapeStringLiteral(aCode) + "'");
}
catch (Throwable t) {
throw new ModuleFailure(t);
public Entity languageForCode(String aCode) throws ModuleExc, ModuleFailure {
try {
- EntityList list = storage.selectByFieldValue("code", aCode);
+ EntityList list = database.selectByFieldValue("code", aCode);
+
if (list.size()>0) {
return list.elementAt(0);
}
- else {
- throw new ModuleExc("No language found for code " + aCode);
- }
+ throw new ModuleExc("No language found for code " + aCode);
}
catch (Throwable t) {
throw new ModuleFailure(t);
package mircoders.module;
+import java.util.List;
+
import mir.entity.Entity;
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.module.ModuleFailure;
import mir.util.JDBCStringRoutines;
import mir.util.StringRoutines;
+import mir.storage.DatabaseExc;
import mircoders.storage.DatabaseMediaType;
-import java.util.List;
-
public class ModuleMediaType extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Content");
super(DatabaseMediaType.getInstance());
}
- public Entity findMediaTypeForMimeType(String aMimeType) throws ModuleExc, ModuleFailure {
+ public Entity findMediaTypeForMimeType(String aMimeType) {
List contentTypeParts = StringRoutines.splitString(aMimeType, "/");
if (contentTypeParts.size()!=2) {
- throw new InvalidMimeTypeExc("Invalid mimetype: " + aMimeType, aMimeType);
+ return null;
}
String mimeTypeMajor = (String) contentTypeParts.get(0);
EntityList mediaTypes;
- mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(aMimeType)+"'");
- if (mediaTypes.size() == 0) {
- mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'");
- }
- if (mediaTypes.size() == 0) {
- mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral("*/*")+"'");
- }
- if (mediaTypes.size() == 0) {
- throw new UnsupportedMimeTypeExc("Unsupported mimetype: " + aMimeType, aMimeType);
- }
-
- return (Entity) mediaTypes.elementAt(0);
- }
-
- public Entity findMediaTypeForExtension(String anExtension) throws ModuleExc, ModuleFailure {
- EntityList mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension)+"'");
-
- if (mediaTypes.size() == 0) {
- try {
- return findMediaTypeForMimeType("*/*");
+ try {
+ mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(aMimeType)+"'");
+ if (mediaTypes.size() == 0) {
+ mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'");
}
- catch (UnsupportedMimeTypeExc e) {
- throw new UnsupportedMimeTypeExc("Unsupported media extension: " + anExtension, anExtension);
+ if (mediaTypes.size() == 0) {
+ return null;
}
}
- else {
- return (Entity) mediaTypes.elementAt(0);
+ catch (DatabaseExc e) {
+ return null;
}
- }
- public static class MimeTypeExc extends ModuleExc {
- private String mimeType;
+ return mediaTypes.elementAt(0);
+ }
- public MimeTypeExc(String aMessage, String aMimeType) {
- super (aMessage);
- mimeType = aMimeType;
- }
+ public Entity findMediaTypeForExtension(String anExtension) {
+ EntityList mediaTypes;
- public String getMimeType() {
- return mimeType;
+ try {
+ mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause(
+ "name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension.toLowerCase())+"'");
}
- }
-
- public static class UnsupportedMimeTypeExc extends MimeTypeExc {
- public UnsupportedMimeTypeExc(String aMessage, String aMimeType) {
- super(aMessage, aMimeType);
+ catch (DatabaseExc e) {
+ return null;
}
- }
- public static class InvalidMimeTypeExc extends MimeTypeExc {
- public InvalidMimeTypeExc(String aMessage, String aMimeType) {
- super(aMessage, aMimeType);
+ if (mediaTypes.size() == 0) {
+ return null;
}
+ return mediaTypes.elementAt(0);
}
}
\ No newline at end of file
import mir.module.AbstractModule;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
import mir.util.JDBCStringRoutines;
import mircoders.storage.DatabaseMediafolder;
public String mediaFolderIdForName(String aName) throws ModuleExc, ModuleFailure {
try {
- return storage.executeFreeSingleValueSql("select id from media_folder where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ return database.executeFreeSingleValueSql("select id from media_folder where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
}
catch (Throwable t) {
throw new ModuleFailure(t);
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.storage.StorageObject;
+import mir.storage.Database;
/**
*
{
static LoggerWrapper logger = new LoggerWrapper("Module.UploadedMedia");
- public ModuleUploadedMedia(StorageObject aStorage) {
+ public ModuleUploadedMedia(Database aStorage) {
super(aStorage);
}
}
\ No newline at end of file
package mircoders.module;
+import java.util.HashMap;
+import java.util.Map;
+
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
import mircoders.global.MirGlobal;
import mircoders.storage.DatabaseUsers;
-import java.util.HashMap;
-import java.util.Map;
-
/*
* Users Module -
try {
String whereString =
"login='" + JDBCStringRoutines.escapeStringLiteral(user) + "' " +
- "and password='" + JDBCStringRoutines.escapeStringLiteral(
- MirGlobal.localizer().adminInterface().makePasswordDigest(password)) +
- "' " +
+ "and (" +
+ " password='" + JDBCStringRoutines.escapeStringLiteral(MirGlobal.localizer().adminInterface().makePasswordDigest(password)) + "'" +
+ " or password='" + JDBCStringRoutines.escapeStringLiteral(password) + "'" +
+ " )" +
"and is_admin='1'";
EntityList userList = getByWhereClause(whereString, -1);
- if (userList != null && userList.getCount() == 1) {
+ if (userList != null && userList.size() == 1) {
EntityUsers result = (EntityUsers) userList.elementAt(0);
if (result.getFieldValue("is_disabled") == null ||
}
}
- /**
- *
- * @param theValues
- * @return
- * @throws ModuleExc
- * @throws ModuleFailure
- */
public String set (Map theValues) throws ModuleExc, ModuleFailure {
try {
return super.set(digestPassword(theValues));
try {
String sql = "update webdb_users set lastlogin=now() where id = " + aUser.getId();
- storage.executeUpdate(sql);
+ database.executeUpdate(sql);
}
catch (Throwable t) {
// no propagation of this error for now, to allow mir to still function
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
-import java.util.Iterator;
-import java.util.Vector;
+import java.util.*;
import mir.config.MirPropertiesConfiguration;
import mir.entity.EntityBrowser;
+import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
-import mir.util.DateTimeFunctions;
+import mir.util.DateTimeRoutines;
+import mir.util.HTMLRoutines;
+import mir.util.ParameterExpander;
+import mir.generator.GeneratorHelper;
+import mir.generator.GeneratorExc;
import mircoders.entity.EntityContent;
import mircoders.entity.EntityImages;
import mircoders.storage.DatabaseImages;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirLocalizerExc;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
+import multex.Failure;
-public class PDFGenerator{
-
+public class PDFGenerator {
public Document document;
public PdfWriter writer;
public PdfContentByte cb;
public float rightEdge;
public float leftEdge;
- public int maxImageHeight;
- public int maxImageWidth;
+ public int maxImageHeight;
+ public int maxImageWidth;
protected LoggerWrapper logger;
public int indexFontSize;
protected MirPropertiesConfiguration configuration;
- public PDFGenerator(ByteArrayOutputStream out){
+ public PDFGenerator(ByteArrayOutputStream out) {
logger = new LoggerWrapper("PDFGenerator");
configuration = MirPropertiesConfiguration.instance();
- localImageDir=configuration.getString("Producer.Image.Path");
+ localImageDir = configuration.getString("Producer.Image.Path");
try {
- indexFontSize = Integer.parseInt(configuration.getString("PDF.Index.FontSize"));
+ indexFontSize = Integer.parseInt(configuration.getString("PDF.Index.FontSize"));
indexLineHeight = Integer.parseInt(configuration.getString("PDF.Index.LineHeight"));
indexFontFamily = getFontByName(configuration.getString("PDF.Index.FontFamily"));
footerText = configuration.getString("PDF.Footer.String");
- footerFontSize = Integer.parseInt(configuration.getString("PDF.Footer.FontSize"));
+ footerFontSize = Integer.parseInt(configuration.getString("PDF.Footer.FontSize"));
footerFontFamily = getFontByName(configuration.getString("PDF.Footer.FontFamily"));
- footerHeight = Integer.parseInt(configuration.getString("PDF.Footer.Height"));;
+ footerHeight = Integer.parseInt(configuration.getString("PDF.Footer.Height"));
- metaFontSize = Integer.parseInt(configuration.getString("PDF.Meta.FontSize"));
+ metaFontSize = Integer.parseInt(configuration.getString("PDF.Meta.FontSize"));
metaFontFamily = getFontByName(configuration.getString("PDF.Meta.FontFamily"));
- metaHeight = Integer.parseInt(configuration.getString("PDF.Meta.Height"));;
+ metaHeight = Integer.parseInt(configuration.getString("PDF.Meta.Height"));
- descriptionFontSize = Integer.parseInt(configuration.getString("PDF.Description.FontSize"));
+ descriptionFontSize = Integer.parseInt(configuration.getString("PDF.Description.FontSize"));
descriptionLineHeight = Integer.parseInt(configuration.getString("PDF.Description.LineHeight"));
descriptionFontFamily = getFontByName(configuration.getString("PDF.Description.FontFamily"));
- contentFontSize = Integer.parseInt(configuration.getString("PDF.Content.FontSize"));
+ contentFontSize = Integer.parseInt(configuration.getString("PDF.Content.FontSize"));
contentLineHeight = Integer.parseInt(configuration.getString("PDF.Content.LineHeight"));
contentFontFamily = getFontByName(configuration.getString("PDF.Content.FontFamily"));
- sourceFontSize = Integer.parseInt(configuration.getString("PDF.Source.FontSize"));
+ sourceFontSize = Integer.parseInt(configuration.getString("PDF.Source.FontSize"));
sourceLineHeight = Integer.parseInt(configuration.getString("PDF.Source.LineHeight"));
sourceFontFamily = getFontByName(configuration.getString("PDF.Source.FontFamily"));
- bigImageCaptionFontSize = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize"));
+ bigImageCaptionFontSize = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize"));
bigImageCaptionFontFamily = getFontByName(configuration.getString("PDF.BigImageCaption.FontFamily"));
}
- catch (NumberFormatException e){
- e.printStackTrace();
+ catch (NumberFormatException e) {
+ throw new Failure(e.getMessage(), e);
}
// step 1: make a document
String pageSize = configuration.getString("PDF.Pagesize");
- if (pageSize.equals("LETTER")){
+ if (pageSize.equals("LETTER")) {
document = new Document(PageSize.LETTER);
pageWidth = 612;
pageHeight = 792;
- }
- else {
- document = new Document(PageSize.A4);
- pageWidth=595;
- pageHeight=842;
+ } else {
+ document = new Document(PageSize.A4);
+ pageWidth = 595;
+ pageHeight = 842;
}
- maxImageHeight = 250;
- maxImageWidth = 250;
+ maxImageHeight = 250;
+ maxImageWidth = 250;
verticalMargin = 20;
horizontalMargin = 20;
+ topEdge = pageHeight - verticalMargin;
+ bottomEdge = verticalMargin;
+ rightEdge = pageWidth - horizontalMargin;
+ leftEdge = horizontalMargin;
- topEdge=pageHeight-verticalMargin;
- bottomEdge=verticalMargin;
- rightEdge=pageWidth-horizontalMargin;
- leftEdge=horizontalMargin;
-
- currentYPosition=topEdge;
+ currentYPosition = topEdge;
currentPage = 1;
String headerText = configuration.getString("PDF.Title.String");
- try{
+ try {
writer = PdfWriter.getInstance(document, out);
cb = writer.getDirectContent();
document.open();
addHeader(headerText);
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
}
- public void stop(){
+ public void stop() {
addFooter();
document.close();
}
- public void addHeader(String headerText){
- int titleFontSize=Integer.parseInt(configuration.getString("PDF.Title.FontSize"));
- int titleLineHeight=Integer.parseInt(configuration.getString("PDF.Title.LineHeight"));
- String titleFontFamily=configuration.getString("PDF.Title.FontFamily");
- String headerImage=configuration.getString("PDF.Header.Image");
+ public void addHeader(String headerText) {
+ int titleFontSize = Integer.parseInt(configuration.getString("PDF.Title.FontSize"));
+ int titleLineHeight = Integer.parseInt(configuration.getString("PDF.Title.LineHeight"));
+ String titleFontFamily = configuration.getString("PDF.Title.FontFamily");
+ String headerImage = configuration.getString("PDF.Header.Image");
int headerImageHeight = Integer.parseInt(configuration.getString("PDF.Header.ImageHeight"));
try {
- if ((! headerImage.equals("")) && headerImageHeight != 0){
- PdfTemplate template = cb.createTemplate(rightEdge-horizontalMargin,headerImageHeight);
+ if ((! headerImage.equals("")) && headerImageHeight != 0) {
+ PdfTemplate template = cb.createTemplate(rightEdge - horizontalMargin, headerImageHeight);
- float toYPosition=currentYPosition - headerImageHeight;
- Image theImage = Image.getInstance(headerImage);
- theImage.setAbsolutePosition(0,0);
- // theImage.scaleAbsolute(img_width,img_height);
- template.addImage(theImage);
+ float toYPosition = currentYPosition - headerImageHeight;
+ Image theImage = Image.getInstance(headerImage);
+ theImage.setAbsolutePosition(0, 0);
+ // theImage.scaleAbsolute(img_width,img_height);
+ template.addImage(theImage);
- cb.addTemplate(template,leftEdge,toYPosition);
- currentYPosition = toYPosition;
+ cb.addTemplate(template, leftEdge, toYPosition);
+ currentYPosition = toYPosition;
}
- if (! headerText.equals("")){
- ColumnText ct = new ColumnText(cb);
- //add a basic header
- ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize,Font.BOLD)));
- float[] rightCol = {rightEdge,currentYPosition,rightEdge,currentYPosition-titleLineHeight};
- float[] leftCol = {leftEdge,currentYPosition,leftEdge,currentYPosition-titleLineHeight};
- ct.setColumns(leftCol,rightCol);
- ct.setYLine(currentYPosition);
- ct.setAlignment(Element.ALIGN_CENTER);
- ct.go();
-
- currentYPosition = currentYPosition - titleLineHeight;
+ if (! headerText.equals("")) {
+ ColumnText ct = new ColumnText(cb);
+ //add a basic header
+ ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize, Font.BOLD)));
+ float[] rightCol = {rightEdge, currentYPosition, rightEdge, currentYPosition - titleLineHeight};
+ float[] leftCol = {leftEdge, currentYPosition, leftEdge, currentYPosition - titleLineHeight};
+ ct.setColumns(leftCol, rightCol);
+ ct.setYLine(currentYPosition);
+ ct.setAlignment(Element.ALIGN_CENTER);
+ ct.go();
+
+ currentYPosition = currentYPosition - titleLineHeight;
}
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
- catch(MalformedURLException de) {
+ catch (MalformedURLException de) {
logger.error(de.getMessage());
}
- catch(IOException de) {
+ catch (IOException de) {
logger.error(de.getMessage());
}
}
- public void addIndexItem(EntityContent entityContent){
+
+ public void addIndexItem(EntityContent entityContent) {
try {
ColumnText ict = new ColumnText(cb);
String theTitle = entityContent.getFieldValue("title");
String theCreator = entityContent.getFieldValue("creator");
- Phrase titleP=new Phrase(" - " + theTitle,new Font(indexFontFamily,indexFontSize,Font.BOLD));
- Phrase creatorP=new Phrase( " :: " + theCreator,new Font(indexFontFamily,indexFontSize));
+ Phrase titleP = new Phrase(" - " + theTitle, new Font(indexFontFamily, indexFontSize, Font.BOLD));
+ Phrase creatorP = new Phrase(" :: " + theCreator, new Font(indexFontFamily, indexFontSize));
float toYPosition = currentYPosition - indexLineHeight;
- float[] leftIndexCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
- float[] rightIndexCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
+ float[] leftIndexCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+ float[] rightIndexCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
ict.addText(titleP);
ict.addText(creatorP);
- ict.setColumns(leftIndexCols,rightIndexCols);
+ ict.setColumns(leftIndexCols, rightIndexCols);
ict.setYLine(currentYPosition);
ict.setAlignment(Element.ALIGN_LEFT);
- int status=ict.go();
+ ict.go();
currentYPosition = toYPosition;
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
-
}
- private int addTextLine(ColumnText ct,int lineHeight,int alignment,float left, float right){
+ private int addTextLine(ColumnText ct, int lineHeight, int alignment, float left, float right) {
logger.debug("adding a line of text");
- if (! enoughY(lineHeight)){
+ if (! enoughY(lineHeight)) {
newPage();
}
float toYPosition = currentYPosition - lineHeight;
- float[] leftContentCols = {left,currentYPosition,left,toYPosition};
- float[] rightContentCols = {right,currentYPosition,right,toYPosition};
- ct.setColumns(leftContentCols,rightContentCols);
+ float[] leftContentCols = {left, currentYPosition, left, toYPosition};
+ float[] rightContentCols = {right, currentYPosition, right, toYPosition};
+ ct.setColumns(leftContentCols, rightContentCols);
ct.setYLine(currentYPosition);
ct.setAlignment(alignment);
- try{
- int status=ct.go();
+ try {
+ int status = ct.go();
currentYPosition = toYPosition;
return status;
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
return 0;
}
- public void addLine(){
+ public void addLine() {
cb.setLineWidth(1f);
- cb.moveTo(rightEdge, currentYPosition-5);
- cb.lineTo(leftEdge, currentYPosition-5);
+ cb.moveTo(rightEdge, currentYPosition - 5);
+ cb.lineTo(leftEdge, currentYPosition - 5);
cb.stroke();
currentYPosition = currentYPosition - 10;
}
- public void addFooter(){
- try{
- ColumnText fct = new ColumnText(cb);
- cb.setLineWidth(1f);
- cb.moveTo(rightEdge, bottomEdge+footerHeight-5);
- cb.lineTo(leftEdge, bottomEdge+footerHeight-5);
- cb.stroke();
- float[] leftFooterCols = {leftEdge,bottomEdge+footerHeight-1,leftEdge,bottomEdge};
- float[] rightFooterCols = {rightEdge,bottomEdge+footerHeight-1,rightEdge,bottomEdge};
+ public void addFooter() {
+ try {
+ ColumnText fct = new ColumnText(cb);
+ cb.setLineWidth(1f);
+ cb.moveTo(rightEdge, bottomEdge + footerHeight - 5);
+ cb.lineTo(leftEdge, bottomEdge + footerHeight - 5);
+ cb.stroke();
+ float[] leftFooterCols = {leftEdge, bottomEdge + footerHeight - 1, leftEdge, bottomEdge};
+ float[] rightFooterCols = {rightEdge, bottomEdge + footerHeight - 1, rightEdge, bottomEdge};
- Paragraph footerP=new Paragraph(footerText,new Font(footerFontFamily,footerFontSize));
- fct.addText(footerP);
+ Paragraph footerP = new Paragraph(footerText, new Font(footerFontFamily, footerFontSize));
+ fct.addText(footerP);
- fct.setColumns(leftFooterCols,rightFooterCols);
- fct.setYLine(bottomEdge+footerHeight-1);
- fct.setAlignment(Element.ALIGN_JUSTIFIED);
- int status=fct.go();
+ fct.setColumns(leftFooterCols, rightFooterCols);
+ fct.setYLine(bottomEdge + footerHeight - 1);
+ fct.setAlignment(Element.ALIGN_JUSTIFIED);
+ fct.go();
- Paragraph numberP=new Paragraph((new Integer(currentPage)).toString(),new Font(footerFontFamily,footerFontSize,Font.BOLD));
- fct.addText(numberP);
- fct.setAlignment(Element.ALIGN_RIGHT);
- status=fct.go();
+ Paragraph numberP = new Paragraph((new Integer(currentPage)).toString(), new Font(footerFontFamily, footerFontSize, Font.BOLD));
+ fct.addText(numberP);
+ fct.setAlignment(Element.ALIGN_RIGHT);
+ fct.go();
}
- catch (DocumentException de){
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
}
- public void newPage(){
- try{
+ public void newPage() {
+ try {
//add a footer
addFooter();
document.newPage();
currentPage++;
- currentYPosition=topEdge;
+ currentYPosition = topEdge;
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
}
- public void addArticleSeparator(){
+ public void addArticleSeparator() {
// make a line
- if (! enoughY(10)){
+ if (! enoughY(10)) {
newPage();
}
cb.setLineWidth(1f);
- cb.moveTo(rightEdge, currentYPosition-5);
- cb.lineTo(leftEdge, currentYPosition-5);
+ cb.moveTo(rightEdge, currentYPosition - 5);
+ cb.lineTo(leftEdge, currentYPosition - 5);
cb.stroke();
currentYPosition = currentYPosition - 10;
}
- public void addArticleMetaInfo(ColumnText ct,String theTitle,String theCreator,String theDate){
- //see if we have room for the author and title
+ public void addArticleMetaInfo(ColumnText ct, String theTitle, String theCreator, String theDate) {
+ //see if we have room for the author and title
- if (! enoughY(metaHeight)){
- newPage();
- }
+ if (! enoughY(metaHeight)) {
+ newPage();
+ }
- Paragraph titleP=new Paragraph(theTitle+"\n",new Font(metaFontFamily,metaFontSize,Font.BOLD));
- Paragraph whowhenP=new Paragraph(theCreator + " " + theDate ,new Font(metaFontFamily,metaFontSize));
+ Paragraph titleP = new Paragraph(theTitle + "\n", new Font(metaFontFamily, metaFontSize, Font.BOLD));
+ Paragraph whowhenP = new Paragraph(theCreator + " " + theDate, new Font(metaFontFamily, metaFontSize));
ct.addText(titleP);
ct.addText(whowhenP);
ct.setAlignment(Element.ALIGN_LEFT);
float toYPosition = currentYPosition - metaHeight;
- float[] leftHeadCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
- float[] rightHeadCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
+ float[] leftHeadCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+ float[] rightHeadCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
- ct.setColumns(leftHeadCols,rightHeadCols);
+ ct.setColumns(leftHeadCols, rightHeadCols);
try {
ct.go();
currentYPosition = toYPosition;
}
- catch(DocumentException de) {
+ catch (DocumentException de) {
logger.error(de.getMessage());
}
}
- public void addArticleDescription(ColumnText ct,String theDescription){
+ public void addArticleDescription(ColumnText ct, String theDescription) {
// Now we add the description, one line at a time, the ct should be empty at this point
- Paragraph descP=new Paragraph(theDescription,new Font(descriptionFontFamily,descriptionFontSize,Font.BOLD));
+ Paragraph descP = new Paragraph(theDescription, new Font(descriptionFontFamily, descriptionFontSize, Font.BOLD));
ct.addText(descP);
// every article has a description, so we can assume that:
int status = ColumnText.NO_MORE_COLUMN;
- int brake=1000;
- while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake >0){
+ int brake = 1000;
+ while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0) {
//there is still text left in the description.
- status = addTextLine(ct,descriptionLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+ status = addTextLine(ct, descriptionLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
brake--;
}
if (brake == 0)
logger.error("runaway description...try increasing the line height or decreasing the font size");
}
- public void addArticleContent(ColumnText ct,String theContent,Iterator images){
+ public void addArticleContent(ColumnText ct, String theContent, Iterator images) {
//let's go ahead and add in all the body text
- Paragraph contentP=new Paragraph(theContent,new Font(contentFontFamily,contentFontSize));
+ Paragraph contentP = new Paragraph(theContent, new Font(contentFontFamily, contentFontSize));
ct.addText(contentP);
- int contentLinesBeforeImages=3;
+ int contentLinesBeforeImages = 3;
//and assume we have at least one line of text in the content
int status = ColumnText.NO_MORE_COLUMN;
// let's add a little bit of text, like a couple of lines
int x = 0;
- while (((status & ColumnText.NO_MORE_TEXT) == 0) && x<contentLinesBeforeImages){
- status=addTextLine(ct,contentLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+ while (((status & ColumnText.NO_MORE_TEXT) == 0) && x < contentLinesBeforeImages) {
+ status = addTextLine(ct, contentLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
x++;
}
boolean addImageOnLeft = true; //we will alternate within articles
- while (images.hasNext()){
-
- EntityImages currentImage=(EntityImages) images.next();
- float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue();
- float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue();
- if (img_height>maxImageHeight){
- img_width=(new Float((new Float(img_width*(maxImageHeight/img_height))).intValue())).floatValue();
- img_height=maxImageHeight;
+ while (images.hasNext()) {
+
+ EntityImages currentImage = (EntityImages) images.next();
+ float img_width = (new Float(currentImage.getFieldValue("img_width"))).floatValue();
+ float img_height = (new Float(currentImage.getFieldValue("img_height"))).floatValue();
+ if (img_height > maxImageHeight) {
+ img_width = (new Float((new Float(img_width * (maxImageHeight / img_height))).intValue())).floatValue();
+ img_height = maxImageHeight;
}
- if (img_width>maxImageWidth){
- img_height=(new Float((new Float(img_height*(maxImageWidth/img_width))).intValue())).floatValue();
- img_width=maxImageWidth;
+ if (img_width > maxImageWidth) {
+ img_height = (new Float((new Float(img_height * (maxImageWidth / img_width))).intValue())).floatValue();
+ img_width = maxImageWidth;
}
- String img_title=currentImage.getFieldValue("title");
- String img_path=currentImage.getFieldValue("publish_path");
-
- if ((status & ColumnText.NO_MORE_TEXT) == 0){
- // there is still text, so add an image which will have text wrapped around it, then add the text which
- // will be on the left or the right of the image
-
- float templateMinimumHeight = img_height+20;
- float templateWidth = img_width+10;
- float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
-
- PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
-
-
- //here we need a page check
- if (! enoughY((new Float(templateHeight)).intValue())){
- //ok, well just fill text to the bottom then
- float toYPosition = bottomEdge+footerHeight;
- float[] leftBottomCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
- float[] rightBottomCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
- ct.setColumns(leftBottomCols,rightBottomCols);
- ct.setYLine(currentYPosition);
- ct.setAlignment(Element.ALIGN_JUSTIFIED);
- try{
- status=ct.go();
- }
- catch(DocumentException de) {
- logger.error(de.getMessage());
- }
- newPage();
- }
-
- float toYPosition=currentYPosition - templateHeight;
-
- try {
- Image theImage = Image.getInstance(localImageDir+img_path);
- theImage.scaleAbsolute(img_width,img_height);
- theImage.setAbsolutePosition(5,13);
-
- template.addImage(theImage);
- template.beginText();
- BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
- template.setFontAndSize(bf, 8);
- template.setTextMatrix(5, 3);
- template.showText(img_title);
- template.endText();
- }
- catch(BadElementException de) {
- logger.error(de.getMessage());
- }
- catch(DocumentException de) {
- logger.error(de.getMessage());
- }
- catch (MalformedURLException de){
- logger.error(de.getMessage());
- }
- catch (IOException de){
- logger.error(de.getMessage());
- }
-
-
- float leftImageTextEdge=leftEdge;
- float rightImageTextEdge=rightEdge;
-
-
- if (addImageOnLeft){
- cb.addTemplate(template,leftEdge,toYPosition);
- leftImageTextEdge=leftEdge+templateWidth+5;
- addImageOnLeft = false;
- }
- else {
- cb.addTemplate(template,rightEdge-templateWidth,toYPosition);
- rightImageTextEdge = rightEdge-templateWidth-5;
- addImageOnLeft = true;
- }
-
- logger.debug("adding template at " + leftEdge + "," + toYPosition);
-
- //and fill some text while we are at it
-
- float[] leftBottomCols = {leftImageTextEdge,currentYPosition,leftImageTextEdge,toYPosition};
- float[] rightBottomCols = {rightImageTextEdge,currentYPosition,rightImageTextEdge,toYPosition};
- ct.setColumns(leftBottomCols,rightBottomCols);
- ct.setYLine(currentYPosition);
- ct.setAlignment(Element.ALIGN_JUSTIFIED);
- try{
- status=ct.go();
- currentYPosition=toYPosition;
- }
- catch(DocumentException de) {
- logger.error(de.getMessage());
- }
-
-
- }
- else {
- //add an image on the left with a big caption to the right
- currentYPosition = currentYPosition - 10;
- float templateMinimumHeight = img_height;
- float templateWidth = img_width;
- float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
- PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
- if (! enoughY((new Float(templateHeight)).intValue())){
- newPage();
- }
- float toYPosition=currentYPosition - templateHeight;
- try{
- Image theImage = Image.getInstance(localImageDir+img_path);
- theImage.setAbsolutePosition(0,13);
- theImage.scaleAbsolute(img_width,img_height);
- template.addImage(theImage);
- }
- catch(BadElementException de) {
- logger.error(de.getMessage());
- }
- catch(DocumentException de) {
- logger.error(de.getMessage());
- }
- catch(MalformedURLException de) {
- logger.error(de.getMessage());
- }
- catch(IOException de) {
- logger.error(de.getMessage());
- }
-
- cb.addTemplate(template,leftEdge,toYPosition);
-
- // add a big caption
- ColumnText cct = new ColumnText(cb);
- float[] leftCaptionCols = {leftEdge+templateWidth+5,currentYPosition-5,leftEdge+templateWidth+5,toYPosition};
- float[] rightCaptionCols = {rightEdge,currentYPosition-5,rightEdge,toYPosition};
-
- Paragraph captionP=new Paragraph(img_title,new Font(bigImageCaptionFontFamily,bigImageCaptionFontSize,Font.BOLD));
- cct.addText(captionP);
- cct.setColumns(leftCaptionCols,rightCaptionCols);
- cct.setYLine(currentYPosition-5);
- cct.setAlignment(Element.ALIGN_LEFT);
- try{
- cct.go();
- currentYPosition=toYPosition;
- }
- catch(DocumentException de) {
- logger.error(de.getMessage());
- }
+ String img_title = currentImage.getFieldValue("title");
+ String img_path = currentImage.getFieldValue("publish_path");
+
+ if ((status & ColumnText.NO_MORE_TEXT) == 0) {
+ // there is still text, so add an image which will have text wrapped around it, then add the text which
+ // will be on the left or the right of the image
+
+ float templateMinimumHeight = img_height + 20;
+ float templateWidth = img_width + 10;
+ float templateHeight = templateMinimumHeight + contentLineHeight - (templateMinimumHeight % contentLineHeight);
+
+ PdfTemplate template = cb.createTemplate(templateWidth, templateHeight);
+
+ //here we need a page check
+ if (! enoughY((new Float(templateHeight)).intValue())) {
+ //ok, well just fill text to the bottom then
+ float toYPosition = bottomEdge + footerHeight;
+ float[] leftBottomCols = {leftEdge, currentYPosition, leftEdge, toYPosition};
+ float[] rightBottomCols = {rightEdge, currentYPosition, rightEdge, toYPosition};
+ ct.setColumns(leftBottomCols, rightBottomCols);
+ ct.setYLine(currentYPosition);
+ ct.setAlignment(Element.ALIGN_JUSTIFIED);
+ try {
+ status = ct.go();
+ }
+ catch (DocumentException de) {
+ logger.error(de.getMessage());
+ }
+ newPage();
+ }
+
+ float toYPosition = currentYPosition - templateHeight;
+
+ try {
+ Image theImage = Image.getInstance(localImageDir + img_path);
+ theImage.scaleAbsolute(img_width, img_height);
+ theImage.setAbsolutePosition(5, 13);
+
+ template.addImage(theImage);
+ template.beginText();
+ BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
+ template.setFontAndSize(bf, 8);
+ template.setTextMatrix(5, 3);
+ template.showText(img_title);
+ template.endText();
+ }
+ catch (BadElementException de) {
+ logger.error(de.getMessage());
+ }
+ catch (DocumentException de) {
+ logger.error(de.getMessage());
+ }
+ catch (MalformedURLException de) {
+ logger.error(de.getMessage());
+ }
+ catch (IOException de) {
+ logger.error(de.getMessage());
+ }
+
+
+ float leftImageTextEdge = leftEdge;
+ float rightImageTextEdge = rightEdge;
+
+
+ if (addImageOnLeft) {
+ cb.addTemplate(template, leftEdge, toYPosition);
+ leftImageTextEdge = leftEdge + templateWidth + 5;
+ addImageOnLeft = false;
+ } else {
+ cb.addTemplate(template, rightEdge - templateWidth, toYPosition);
+ rightImageTextEdge = rightEdge - templateWidth - 5;
+ addImageOnLeft = true;
+ }
+
+ logger.debug("adding template at " + leftEdge + "," + toYPosition);
+
+ //and fill some text while we are at it
+
+ float[] leftBottomCols = {leftImageTextEdge, currentYPosition, leftImageTextEdge, toYPosition};
+ float[] rightBottomCols = {rightImageTextEdge, currentYPosition, rightImageTextEdge, toYPosition};
+ ct.setColumns(leftBottomCols, rightBottomCols);
+ ct.setYLine(currentYPosition);
+ ct.setAlignment(Element.ALIGN_JUSTIFIED);
+ try {
+ status = ct.go();
+ currentYPosition = toYPosition;
+ }
+ catch (DocumentException de) {
+ logger.error(de.getMessage());
+ }
+
+
+ } else {
+ //add an image on the left with a big caption to the right
+ currentYPosition = currentYPosition - 10;
+ float templateMinimumHeight = img_height;
+ float templateWidth = img_width;
+ float templateHeight = templateMinimumHeight + contentLineHeight - (templateMinimumHeight % contentLineHeight);
+ PdfTemplate template = cb.createTemplate(templateWidth, templateHeight);
+ if (! enoughY((new Float(templateHeight)).intValue())) {
+ newPage();
+ }
+ float toYPosition = currentYPosition - templateHeight;
+ try {
+ Image theImage = Image.getInstance(localImageDir + img_path);
+ theImage.setAbsolutePosition(0, 13);
+ theImage.scaleAbsolute(img_width, img_height);
+ template.addImage(theImage);
+ }
+ catch (BadElementException de) {
+ logger.error(de.getMessage());
+ }
+ catch (DocumentException de) {
+ logger.error(de.getMessage());
+ }
+ catch (MalformedURLException de) {
+ logger.error(de.getMessage());
+ }
+ catch (IOException de) {
+ logger.error(de.getMessage());
+ }
+
+ cb.addTemplate(template, leftEdge, toYPosition);
+
+ // add a big caption
+ ColumnText cct = new ColumnText(cb);
+ float[] leftCaptionCols = {leftEdge + templateWidth + 5, currentYPosition - 5, leftEdge + templateWidth + 5, toYPosition};
+ float[] rightCaptionCols = {rightEdge, currentYPosition - 5, rightEdge, toYPosition};
+
+ Paragraph captionP = new Paragraph(img_title, new Font(bigImageCaptionFontFamily, bigImageCaptionFontSize, Font.BOLD));
+ cct.addText(captionP);
+ cct.setColumns(leftCaptionCols, rightCaptionCols);
+ cct.setYLine(currentYPosition - 5);
+ cct.setAlignment(Element.ALIGN_LEFT);
+ try {
+ cct.go();
+ currentYPosition = toYPosition;
+ }
+ catch (DocumentException de) {
+ logger.error(de.getMessage());
+ }
}
}
//add the rest of the text which might be left
int brake = 10000;
- while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0){
- status=addTextLine(ct,contentLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
+ while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0) {
+ status = addTextLine(ct, contentLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge);
brake --;
}
if (brake == 0)
logger.error("runaway content....try decreasing font size or increasing line height");
}
- private void addArticleSource(ColumnText ct,String theSource){
- Paragraph sourceP = new Paragraph(theSource,new Font(sourceFontFamily,sourceFontSize,Font.BOLD));
+ private void addArticleSource(ColumnText ct, String theSource) {
+ Paragraph sourceP = new Paragraph(theSource, new Font(sourceFontFamily, sourceFontSize, Font.BOLD));
ct.addText(sourceP);
- addTextLine(ct,sourceLineHeight,Element.ALIGN_RIGHT,leftEdge,rightEdge);
+ addTextLine(ct, sourceLineHeight, Element.ALIGN_RIGHT, leftEdge, rightEdge);
}
- private boolean enoughY(int heightOfBlockToAdd){
- if ((currentYPosition - heightOfBlockToAdd - footerHeight) < bottomEdge )
+ private boolean enoughY(int heightOfBlockToAdd) {
+ if ((currentYPosition - heightOfBlockToAdd - footerHeight) < bottomEdge)
return false;
- else
- return true;
+ return true;
}
- public void add(EntityContent entityContent){
- logger.error("adding a content Entity");
+ public void add(EntityContent anArticle, Locale aLocale) throws GeneratorExc, MirLocalizerExc, Exception {
+ logger.debug("adding a content Entity");
/*
* initialize
* source
*/
- Vector extraTables = new Vector();
+ List extraTables = new ArrayList();
extraTables.add("content_x_media cxm");
Iterator images = new EntityBrowser(
- DatabaseImages.getInstance(), "i", extraTables,
- "cxm.content_id="+entityContent.getId()+"and cxm.media_id=i.id",
+ DatabaseImages.getInstance(), "i", extraTables,
+ "cxm.content_id=" + anArticle.getId() + "and cxm.media_id=i.id",
"i.id desc", 30, -1, 0);
- String isHTML = entityContent.getFieldValue("is_html");
- String theTitle = entityContent.getFieldValue("title");
- String theCreator = entityContent.getFieldValue("creator");
- String theDate = DateTimeFunctions.advancedDateFormat(
+ String isHTML = anArticle.getFieldValue("is_html");
+ String theTitle = anArticle.getFieldValue("title");
+ String theCreator = anArticle.getFieldValue("creator");
+ String theDate = DateTimeRoutines.advancedDateFormat(
configuration.getString("RDF.Meta.DateFormat"),
- StringUtil.convertMirInternalDateToDate(entityContent.getFieldValue("webdb_create")),
+ StringUtil.convertMirInternalDateToDate(anArticle.getFieldValue("webdb_create")),
configuration.getString("Mir.DefaultTimezone"));
- String theDescriptionRaw = entityContent.getFieldValue("description");
- String theContentRaw = entityContent.getFieldValue("content_data");
- String theSource = configuration.getString("Producer.PublicationHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getFieldValue("publish_path") + entityContent.getFieldValue("id") + ".shtml";
-
+ String theDescriptionRaw = anArticle.getFieldValue("description");
+ String theContentRaw = anArticle.getFieldValue("content_data");
+ MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+ Map variables = GeneratorHelper.makeBasicGenerationData(new Locale[] {
+ aLocale ,new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "")},
+ "bundles.open","bundles.open");
+ EntityAdapter article =
+ MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle);
+ variables.put("article", article);
+ String source = ParameterExpander.expandExpression(
+ variables,
+ configuration.getString("PDF.Source")
+ );
String theContent = "";
String theDescription = "";
- if (isHTML.equals("1")){
-
+ if (isHTML.equals("1")) {
try {
- RE nobackslashr = new RE("\r");
- theContent= nobackslashr.substituteAll(theContentRaw,"");
- theDescription= nobackslashr.substituteAll(theDescriptionRaw,"");
-
- RE HxTag = new RE("</?h[1-6][^>]*>",RE.REG_ICASE);
- theContent = HxTag.substituteAll(theContent,"\n\n");
- theDescription = HxTag.substituteAll(theDescription,"\n\n");
-
- RE ListItemTag = new RE("<li[^>]*>",RE.REG_ICASE);
- theContent = ListItemTag.substituteAll(theContent,"\n * ");
- theDescription = ListItemTag.substituteAll(theDescription,"\n * ");
-
- RE ListTag = new RE("<(u|o)l[^>]*>",RE.REG_ICASE);
- theContent = ListTag.substituteAll(theContent,"\n");
- theDescription = ListTag.substituteAll(theDescription,"\n");
-
- RE DivTag = new RE("</?div[^>]*>",RE.REG_ICASE);
- theContent= DivTag.substituteAll(theContent,"\n");
- theDescription= DivTag.substituteAll(theDescription,"\n");
-
- RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
- theContent= PTag.substituteAll(theContent,"\n ");
- theDescription= PTag.substituteAll(theDescription,"\n ");
-
- RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
- theContent= PTagClose.substituteAll(theContent,"\n");
- theDescription= PTagClose.substituteAll(theDescription,"\n");
-
- RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
- theContent= BRTag.substituteAll(theContent,"\n");
- theDescription= BRTag.substituteAll(theDescription,"\n");
-
- RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>",RE.REG_ICASE);
- REMatchEnumeration atags= ATagAll.getMatchEnumeration(theContent);
- String theContentCopy=theContent;
- while (atags.hasMoreMatches()){
- REMatch atag = atags.nextMatch();
- String atagString=atag.toString();
- String atagStringHref=atag.toString(1);
- String atagStringText=atag.toString(2);
- int begin=theContentCopy.indexOf(atagString);
- theContentCopy=theContentCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theContentCopy.substring(begin+atagString.length());
- }
- theContent=theContentCopy;
-
- REMatchEnumeration atags2= ATagAll.getMatchEnumeration(theDescription);
- String theDescriptionCopy=theDescription;
- while (atags2.hasMoreMatches()){
- REMatch atag = atags2.nextMatch();
- String atagString=atag.toString();
- String atagStringHref=atag.toString(1);
- String atagStringText=atag.toString(2);
- int begin=theDescriptionCopy.indexOf(atagString);
- theDescriptionCopy=theDescriptionCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theDescriptionCopy.substring(begin+atagString.length());
- }
- theDescription=theDescriptionCopy;
-
-
- RE noTags = new RE("<[^>]*>");
- theContent= noTags.substituteAll(theContent," ");
- theDescription= noTags.substituteAll(theDescription," ");
-
- theContent=mir.util.Translate.decode(theContent);
- theDescription=mir.util.Translate.decode(theDescription);
-
- RE re1 = new RE("\r?\n\r?\n");
- String theDescription1 = re1.substituteAll(theDescription,"BREAKHERE");
-
- RE re2 = new RE("\r?\n");
- String theDescription2 = re2.substituteAll(theDescription1," ");
-
- RE re3 = new RE("BREAKHERE");
- theDescription = re3.substituteAll(theDescription2,"\n ");
+ RE nobackslashr = new RE("\r");
+ theContent = nobackslashr.substituteAll(theContentRaw, "");
+ theDescription = nobackslashr.substituteAll(theDescriptionRaw, "");
+
+ RE HxTag = new RE("</?h[1-6][^>]*>", RE.REG_ICASE);
+ theContent = HxTag.substituteAll(theContent, "\n\n");
+ theDescription = HxTag.substituteAll(theDescription, "\n\n");
+
+ RE ListItemTag = new RE("<li[^>]*>", RE.REG_ICASE);
+ theContent = ListItemTag.substituteAll(theContent, "\n * ");
+ theDescription = ListItemTag.substituteAll(theDescription, "\n * ");
+
+ RE ListTag = new RE("<(u|o)l[^>]*>", RE.REG_ICASE);
+ theContent = ListTag.substituteAll(theContent, "\n");
+ theDescription = ListTag.substituteAll(theDescription, "\n");
+
+ RE DivTag = new RE("</?div[^>]*>", RE.REG_ICASE);
+ theContent = DivTag.substituteAll(theContent, "\n");
+ theDescription = DivTag.substituteAll(theDescription, "\n");
+
+ RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
+ theContent = PTag.substituteAll(theContent, "\n ");
+ theDescription = PTag.substituteAll(theDescription, "\n ");
+
+ RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
+ theContent = PTagClose.substituteAll(theContent, "\n");
+ theDescription = PTagClose.substituteAll(theDescription, "\n");
+
+ RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
+ theContent = BRTag.substituteAll(theContent, "\n");
+ theDescription = BRTag.substituteAll(theDescription, "\n");
+
+ RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>", RE.REG_ICASE);
+ REMatchEnumeration atags = ATagAll.getMatchEnumeration(theContent);
+ String theContentCopy = theContent;
+ while (atags.hasMoreMatches()) {
+ REMatch atag = atags.nextMatch();
+ String atagString = atag.toString();
+ String atagStringHref = atag.toString(1);
+ String atagStringText = atag.toString(2);
+ int begin = theContentCopy.indexOf(atagString);
+ theContentCopy = theContentCopy.substring(0, begin) + atagStringText + " [" + atagStringHref + "] " + theContentCopy.substring(begin + atagString.length());
+ }
+ theContent = theContentCopy;
+
+ REMatchEnumeration atags2 = ATagAll.getMatchEnumeration(theDescription);
+ String theDescriptionCopy = theDescription;
+ while (atags2.hasMoreMatches()) {
+ REMatch atag = atags2.nextMatch();
+ String atagString = atag.toString();
+ String atagStringHref = atag.toString(1);
+ String atagStringText = atag.toString(2);
+ int begin = theDescriptionCopy.indexOf(atagString);
+ theDescriptionCopy = theDescriptionCopy.substring(0, begin) + atagStringText + " [" + atagStringHref + "] " + theDescriptionCopy.substring(begin + atagString.length());
+ }
+ theDescription = theDescriptionCopy;
+
+
+ RE noTags = new RE("<[^>]*>");
+ theContent = noTags.substituteAll(theContent, " ");
+ theDescription = noTags.substituteAll(theDescription, " ");
+
+ theContent = HTMLRoutines.resolveHTMLEntites(theContent);
+ theDescription = HTMLRoutines.resolveHTMLEntites(theDescription);
+
+ RE re1 = new RE("\r?\n\r?\n");
+ String theDescription1 = re1.substituteAll(theDescription, "BREAKHERE");
+
+ RE re2 = new RE("\r?\n");
+ String theDescription2 = re2.substituteAll(theDescription1, " ");
+
+ RE re3 = new RE("BREAKHERE");
+ theDescription = re3.substituteAll(theDescription2, "\n ");
}
- catch(REException ree){
- logger.error(ree.getMessage());
+ catch (REException ree) {
+ logger.error(ree.getMessage());
}
- }
- else {
+ } else {
try {
- RE re1 = new RE("\r?\n\r?\n");
- String theContent1 = re1.substituteAll(theContentRaw,"BREAKHERE");
- String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
+ RE re1 = new RE("\r?\n\r?\n");
+ String theContent1 = re1.substituteAll(theContentRaw, "BREAKHERE");
+ String theDescription1 = re1.substituteAll(theDescriptionRaw, "BREAKHERE");
- RE re2 = new RE("\r?\n");
- String theContent2 = re2.substituteAll(theContent1," ");
- String theDescription2 = re2.substituteAll(theDescription1," ");
+ RE re2 = new RE("\r?\n");
+ String theContent2 = re2.substituteAll(theContent1, " ");
+ String theDescription2 = re2.substituteAll(theDescription1, " ");
- RE re3 = new RE("BREAKHERE");
- theContent = " " + re3.substituteAll(theContent2,"\n ");
- theDescription = re3.substituteAll(theDescription2,"\n ");
+ RE re3 = new RE("BREAKHERE");
+ theContent = " " + re3.substituteAll(theContent2, "\n ");
+ theDescription = re3.substituteAll(theDescription2, "\n ");
}
- catch(REException ree){
- logger.error(ree.getMessage());
+ catch (REException ree) {
+ logger.error(ree.getMessage());
}
}
ColumnText ct = new ColumnText(cb);
- addArticleMetaInfo(ct,theTitle,theCreator,theDate);
- addArticleDescription(ct,theDescription);
- addArticleContent(ct,theContent,images);
- addArticleSource(ct,theSource);
-
+ addArticleMetaInfo(ct, theTitle, theCreator, theDate);
+ addArticleDescription(ct, theDescription);
+ addArticleContent(ct, theContent, images);
+ addArticleSource(ct, source);
}
public int getFontByName(String fontName) {
int theFont = 0;
- if (fontName.equalsIgnoreCase("helvetica")){
+ if ("helvetica".equalsIgnoreCase(fontName)) {
theFont = Font.HELVETICA;
}
+ else if ("courier".equalsIgnoreCase(fontName)) {
+ theFont = Font.COURIER;
+ }
+ else if ("times".equalsIgnoreCase(fontName)) {
+ theFont = Font.TIMES_ROMAN;
+ }
else {
- if (fontName.equalsIgnoreCase("courier")) {
- theFont = Font.COURIER;
- }
- else {
- if (fontName.equalsIgnoreCase("times")) {
- theFont = Font.TIMES_ROMAN;
- }
- else {
- logger.error("using helvetica because I can't get font for name: "+fontName);
- theFont = Font.HELVETICA;
- }
- }
+ logger.error("using helvetica because I can't get font for name: " + fontName);
+ theFont = Font.HELVETICA;
}
return theFont;
-
}
-}
-
-
+}
\ No newline at end of file
--- /dev/null
+package mircoders.producer;\r
+\r
+import mir.changetracker.ChangeTracker;\r
+import mir.log.LoggerWrapper;\r
+import mir.producer.AbstractProducerNode;\r
+import mir.util.ParameterExpander;\r
+import mir.util.StringRoutines;\r
+import mircoders.global.MirGlobal;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.OutputStream;\r
+import java.io.OutputStreamWriter;\r
+import java.io.PrintWriter;\r
+import java.util.Collection;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+public class ChangeReportingProducerNode extends AbstractProducerNode {\r
+ private String format;\r
+ private String outputFile;\r
+ private String basePath;\r
+ private String exclusionList;\r
+\r
+ public ChangeReportingProducerNode(String anOutputFile, String aFormat, String aBasePath, String anExclusionList) {\r
+ format = aFormat;\r
+ outputFile = anOutputFile;\r
+ basePath = aBasePath;\r
+ exclusionList = anExclusionList;\r
+ }\r
+\r
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) {\r
+ try {\r
+ File file = new File(ParameterExpander.expandExpression(aValueMap, outputFile));\r
+ OutputStream stream = null;\r
+ try {\r
+ stream = new FileOutputStream(file, true);\r
+ }\r
+ catch (FileNotFoundException e) {\r
+ aLogger.error("Can't write open report file", e);\r
+\r
+ return;\r
+ }\r
+\r
+ try {\r
+ PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream));\r
+ try {\r
+ String expandedBasePath = ParameterExpander.expandExpression(aValueMap, basePath);\r
+\r
+ List excludedPaths = null;\r
+ if (exclusionList != null) {\r
+ String expandedExclusionList = ParameterExpander.expandExpression(aValueMap, exclusionList);\r
+ excludedPaths = StringRoutines.separateString(expandedExclusionList, ",");\r
+ }\r
+\r
+ Collection changes = MirGlobal.getChangeEngine().getTracker().flushChanges(expandedBasePath, excludedPaths);\r
+\r
+ Iterator i = changes.iterator();\r
+ while (i.hasNext()) {\r
+ ChangeTracker.Change change = (ChangeTracker.Change) i.next();\r
+\r
+ Map changeMap = new HashMap();\r
+\r
+ // the absolute path of the change needs to be transformed into a path relative\r
+ // to base\r
+ changeMap.put("path", change.getPath().substring(expandedBasePath.length()));\r
+ changeMap.put("type", change.getType().getName());\r
+ changeMap.put("date", change.getDate());\r
+\r
+ aValueMap.put("change", changeMap);\r
+ String line = ParameterExpander.expandExpression(aValueMap, format);\r
+ writer.println(line);\r
+ }\r
+ }\r
+ finally {\r
+ try {\r
+ writer.close();\r
+ }\r
+ catch (Throwable t) {\r
+ aLogger.info("Can't close report file");\r
+ }\r
+ }\r
+ }\r
+ finally {\r
+ try {\r
+ stream.close();\r
+ }\r
+ catch (Throwable t) {\r
+ aLogger.info("Can't close report file");\r
+ }\r
+ }\r
+ }\r
+ catch (Throwable t) {\r
+ aLogger.error("Error while writing change report file", t);\r
+ }\r
+ }\r
+}\r
*/
package mircoders.producer;
-import java.util.Map;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
+import mir.producer.AbstractProducerNode;
import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
import mircoders.entity.EntityContent;
+import java.util.Map;
+
-public class ContentMarkingProducerNode implements ProducerNode {
+public class ContentMarkingProducerNode extends AbstractProducerNode {
private String contentKey;
public ContentMarkingProducerNode(String aContentKey) {
*/
package mircoders.producer;
-import java.util.Map;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
+import mir.producer.AbstractProducerNode;
import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
import mircoders.entity.EntityContent;
-public class ContentModifyingProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class ContentModifyingProducerNode extends AbstractProducerNode {
private String contentKey;
private String fieldNameExpression;
private String valueExpression;
*/
package mircoders.producer;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Map;
-import java.io.File;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
+import mir.producer.AbstractProducerNode;
import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
+import mir.util.FileRoutines;
import mir.util.ParameterExpander;
-import mir.util.FileFunctions;
import mircoders.entity.EntityContent;
-import mircoders.search.AudioSearchTerm;
-import mircoders.search.ContentSearchTerm;
-import mircoders.search.ImagesSearchTerm;
-import mircoders.search.IndexUtil;
-import mircoders.search.KeywordSearchTerm;
-import mircoders.search.TextSearchTerm;
-import mircoders.search.TopicSearchTerm;
-import mircoders.search.UnIndexedSearchTerm;
-import mircoders.search.VideoSearchTerm;
-
+import mircoders.search.*;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Map;
-public class IndexingProducerNode implements ProducerNode {
+
+public class IndexingProducerNode extends AbstractProducerNode {
private String contentKey;
private String indexPath;
private File indexBasePath;
startTime = System.currentTimeMillis();
try {
- indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath));
+ indexFile = FileRoutines.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath));
data = ParameterExpander.findValueForKey(aValueMap, contentKey);
if (!(data instanceof EntityAdapter)) {
entity.getClass().getName() + " adapter", null);
}
- aLogger.info("Indexing " + entity.getFieldValue("id") + " into " + indexFile.getAbsolutePath());
+ aLogger.debug("Indexing " + entity.getFieldValue("id") + " into " + indexFile.getAbsolutePath());
// create an index here if one did not already exist
if (!(IndexReader.indexExists(indexFile))) {
- aLogger.error("Didn't find existing index, so I'm making one in " + indexFile.getAbsolutePath());
+ aLogger.warn("Didn't find existing index, so I'm making one in " + indexFile.getAbsolutePath());
IndexWriter indexCreator = new IndexWriter(indexFile, new StandardAnalyzer(), true);
indexCreator.close();
String textValue = entity.getFieldValue("webdb_create");
Calendar calendar = GregorianCalendar.getInstance();
- int year;
- int month;
+ int year=0;
+ int month=0;
int day;
int hours;
int minutes;
Date date;
String formattedDate="";
+ String pathDate="";
if (textValue!=null) {
try {
date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd hh:mm");
formattedDate = formatter.format(date);
+
+ SimpleDateFormat pathFormatter = new SimpleDateFormat("/yyyy/MM/");
+ pathDate = pathFormatter.format(date);
}
catch (Throwable t) {
- aLogger.error("Error while generating content date to index: " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ aLogger.warn("Error while generating content date to index", t);
}
}
(new KeywordSearchTerm("webdb_create_formatted", "search_date",
(new UnIndexedSearchTerm("", "", "", "where", "where")).indexValue(theDoc,
- StringUtil.webdbDate2path(entity.getFieldValue("date")) +
- entity.getFieldValue("id") + ".shtml");
+ pathDate + entity.getFieldValue("id") + ".shtml");
(new TextSearchTerm("creator", "search_creator", "creator", "creator",
"creator")).index(theDoc, entity);
indexWriter.addDocument(theDoc);
}
catch (Throwable t) {
- aLogger.error("Error while indexing content: " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ aLogger.error("Error while indexing content: " + t.getMessage(), t);
}
finally {
if (indexWriter != null) {
indexWriter.close();
}
catch (Throwable t) {
- aLogger.warn("Error while closing indexWriter: " + t.getMessage());
+ aLogger.warn("Error while closing indexWriter", t);
}
}
}
}
catch (Throwable t) {
- aLogger.warn("Error while unlocking index: " + t.getMessage());
+ aLogger.warn("Error while unlocking index", t);
}
}
}
endTime = System.currentTimeMillis();
- aLogger.info(" IndexTime: " + (endTime - startTime) + " ms<br>");
+ aLogger.debug(" IndexTime: " + (endTime - startTime) + " ms<br>");
}
}
package mircoders.producer;
-import java.util.Map;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
-import mircoders.media.MediaHelper;
import mir.media.MediaHandler;
+import mir.producer.AbstractProducerNode;
import mir.producer.ProducerExc;
-import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
import mircoders.entity.EntityUploadedMedia;
+import mircoders.media.MediaHelper;
import mircoders.storage.DatabaseUploadedMedia;
-public class MediaGeneratingProducerNode implements ProducerNode {
+import java.util.Map;
+
+public class MediaGeneratingProducerNode extends AbstractProducerNode {
private String mediaEntityKey;
public MediaGeneratingProducerNode(String aMediaEntityKey) {
data = ParameterExpander.findValueForKey( aValueMap, mediaEntityKey );
if (!(data instanceof EntityAdapter)) {
- throw new ProducerExc("MediaGeneratingProducerNode: value of '"+mediaEntityKey+"' is not an EntityAdapter, but an " + data.getClass().getName());
+ throw new ProducerExc("MediaGeneratingProducerNode: value of '" +
+ mediaEntityKey + "' is not an EntityAdapter, but an " + data.getClass().getName());
}
entity = ((EntityAdapter) data).getEntity();
- if (! (entity instanceof EntityUploadedMedia)) {
- throw new ProducerExc("MediaGeneratingProducerNode: value of '"+mediaEntityKey+"' is not an uploaded media EntityAdapter, but a " + entity.getClass().getName() + " adapter");
+ if (!(entity instanceof EntityUploadedMedia)) {
+ throw new ProducerExc("MediaGeneratingProducerNode: value of '" +
+ mediaEntityKey + "' is not an uploaded media EntityAdapter, but a " +
+ entity.getClass().getName() + " adapter");
}
uploadedMediaEntity = (EntityUploadedMedia) entity;
entity.setFieldValue("icon_is_produced", "1");
entity.setFieldValue("is_produced", "1");
entity.update();
-
- aLogger.info("media with id "+uploadedMediaEntity.getFieldValue("id") + ", mediaType " + mediaType.getFieldValue("name") + " successfully produced");
+
+ aLogger.info("media with id " + uploadedMediaEntity.getFieldValue("id") +
+ ", mediaType " + mediaType.getFieldValue("name") + " successfully produced");
}
catch (Throwable t) {
String message = "Error while generating media";
+++ /dev/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 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.producer;
-
-import java.util.Map;
-
-import mir.log.LoggerWrapper;
-import mir.misc.PDFUtil;
-import mir.producer.ProducerNode;
-import mir.util.ParameterExpander;
-
-public class PDFGeneratingProducerNode implements ProducerNode {
- private String generatorExpression;
- private String destinationExpression;
- private String stylesheet;
-
- public PDFGeneratingProducerNode(String aGenerator, String aDestination,String aStylesheet) {
- generatorExpression=aGenerator;
- destinationExpression=aDestination;
- stylesheet=aStylesheet;
- }
-
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) {
-
- String generatorIdentifier;
- String destinationIdentifier;
- String stylesheetIdentifier;
-
- long startTime;
- long endTime;
-
- startTime = System.currentTimeMillis();
- try {
-
- destinationIdentifier = ParameterExpander.expandExpression( aValueMap, destinationExpression );
- generatorIdentifier = ParameterExpander.expandExpression( aValueMap, generatorExpression );
- stylesheetIdentifier = ParameterExpander.expandExpression( aValueMap, stylesheet);
-
- aLogger.info("Generating " + generatorIdentifier + " into " + destinationIdentifier + " using "+ stylesheetIdentifier);
-
- PDFUtil.makePDF(generatorIdentifier,destinationIdentifier,stylesheetIdentifier);
-
- }
- catch (Throwable t) {
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- aLogger.error(" error while generating: " + t.getMessage() + t.toString());
- }
- endTime = System.currentTimeMillis();
-
- aLogger.info(" Time: " + (endTime-startTime) + " ms<br>");
- }
-}
-
-
-
+++ /dev/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 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.producer;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Vector;
-
-import mir.entity.Entity;
-import mir.entity.EntityBrowser;
-import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerToWriterAdapter;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
-import mir.util.CachingRewindableIterator;
-import mir.util.HTMLRoutines;
-import mir.util.ParameterExpander;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityImages;
-import mircoders.storage.DatabaseImages;
-
-
-public class PDFPreFormattingProducerNode implements ProducerNode {
- private String contentKey;
- private int numLinesBetweenImages;
- private float contentAreaWidthCM;
- private float characterWidthCM;
- private float pixelWidthCM;
- private float lineHeightCM;
-
- public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {
- contentKey = aContentKey;
- numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();
- contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();
- characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();
- pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();
- lineHeightCM=(new Float(aLineHeightCM)).floatValue();
-
- // float characterWidthCM = 0.17F;
- //float contentAreaWidthCM = 16;
- //float pixelWidthCM = .03F;
- //float lineHeightCM = .5F;
- }
-
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
- Object data;
- Entity entity;
-
- try {
- data = ParameterExpander.findValueForKey( aValueMap, contentKey );
-
- if (! (data instanceof EntityAdapter)) {
- throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);
- }
-
- entity = ((EntityAdapter) data).getEntity();
- if (! (entity instanceof EntityContent)) {
- throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
- }
-
- int currentPosition = 0;
-
- //int numLinesBetweenImages=3;
-
-
-
-
- int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();
-
- boolean outOfText = false;
-
- ArrayList brokenUpContent = new ArrayList();
-
-
- Vector extraTables = new Vector();
- extraTables.add("content_x_media cxm");
- Iterator images = new EntityBrowser(
- DatabaseImages.getInstance(), "i", extraTables,
- "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id",
- "i.id desc", 30, -1, 0);
-
- String theContent = ((EntityContent) entity).getFieldValue("content_data");
- //remove pesky characters
- theContent = HTMLRoutines.encodeXML(theContent);
- //put in the <BR> tags so we can turn them to empty blocks
- theContent = StringUtil.convertNewline2Break(theContent);
-
- if (images == null){
- Map row = new HashMap();
- row.put("text",theContent);
- row.put("hasImage","0");
- brokenUpContent.add(row);
- }
- if (images != null){
- //need to add checks for out of content!
- Map row0 = new HashMap();
- if (numCharsInAnImagelessRow>(theContent).length()){
- row0.put("text",theContent);
- outOfText = true;
- }
- else {
- //break on words so we don't split html entities
- int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);
- row0.put("text",theContent.substring(0,lastSpaceAt));
- currentPosition=lastSpaceAt;
- }
- row0.put("hasImage","0");
- brokenUpContent.add(row0);
- aLogger.debug("CP1 is "+ currentPosition);
- while(images.hasNext()){
- Map row1 = new HashMap();
- Map row2 = new HashMap();
- EntityImages currentImage=(EntityImages) images.next();
- float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue();
- float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue();
-
- //oversize images must be shrunk
- if (img_width>250){
- img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();
- img_width=250.0F;
- }
-
-
- //calculate how much text goes in the column(use 8 pixels to pad the column)
- float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);
- float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int
- //add one line for image description
- int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();
-
- row1.put("text_widthCM",Float.toString(text_widthCM));
-
- row1.put("img_title",currentImage.getFieldValue("title"));
-
- row1.put("img_width",Float.toString(img_width));
- row1.put("img_height",Float.toString(img_height));
-
- aLogger.debug("img_width " +Float.toString(img_width));
- aLogger.debug("img_height "+Float.toString(img_height));
-
- row1.put("img_src",currentImage.getFieldValue("publish_path"));
- row1.put("hasImage","1");
- if (! outOfText){
- try {
- int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);
- row1.put("text",theContent.substring(currentPosition,lastSpaceAt));
- currentPosition=lastSpaceAt;
- }
- catch (IndexOutOfBoundsException e){
- row1.put("text",theContent.substring(currentPosition));
- outOfText = true;
- }
- }
- aLogger.debug("CP2 is "+ currentPosition);
- brokenUpContent.add(row1);
-
- if (! outOfText){
- try {
- int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);
- row2.put("text",theContent.substring(currentPosition,lastSpaceAt));
- currentPosition=lastSpaceAt;
- }
- catch (IndexOutOfBoundsException e){
- row2.put("text",theContent.substring(currentPosition));
- outOfText = true;
- }
- }
- row2.put("hasImage","0");
- brokenUpContent.add(row2);
-
- aLogger.debug("CP3 is "+ currentPosition);
- }
- Map row3 = new HashMap();
- if (! outOfText){
- row3.put("text",theContent.substring(currentPosition));
- row3.put("hasImage","0");
- brokenUpContent.add(row3);
- }
-
- }
-
-
-
-
-
- ParameterExpander.setValueForKey(
- aValueMap,
- "data.formatted_content",
- new CachingRewindableIterator(brokenUpContent.iterator())
- );
-
-
- }
- catch (Throwable t) {
- aLogger.error("Error while formatting content for PDF: " + t.getMessage());
- t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));
- }
- }
-}
-
-
-
-
--- /dev/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 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.producer;
+
+import mir.log.LoggerWrapper;
+import mir.producer.AbstractProducerNode;
+import mir.producer.ProducerFailure;
+import mir.util.ExceptionRoutines;
+import mir.util.ParameterExpander;
+import org.apache.xmlrpc.XmlRpcClient;
+
+import java.util.*;
+
+
+public class RadicalendarProducerNode extends AbstractProducerNode {
+ private String key;
+ private String groupname;
+ private String gmtoffset;
+
+
+ public RadicalendarProducerNode(String aKey, String aGroupName, String aGMTOffset) {
+ key = aKey;
+ groupname = aGroupName;
+ gmtoffset = aGMTOffset;
+
+ }
+
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ try {
+ String expandedGroupName = ParameterExpander.expandExpression( aValueMap, groupname);
+ String expandedGMTOffset = ParameterExpander.expandExpression( aValueMap, gmtoffset);
+
+ XmlRpcClient xmlrpc = new XmlRpcClient ("http://radicalendar.org:80/xmlresponderweek.php");
+ Vector params = new Vector();
+ params.add(expandedGroupName+":"+expandedGMTOffset); //(shortname from calendar.getGroups)+gmtoffset in minutes
+ Hashtable result = (Hashtable) xmlrpc.execute ("calendar.getWeek", params);
+
+
+
+ ArrayList thisWeekEventsList=new ArrayList();
+
+ ArrayList day_keys=new ArrayList();
+
+ for (Enumeration e = result.keys() ; e.hasMoreElements() ; ){
+ day_keys.add((String) e.nextElement());
+ }
+ Collections.sort(day_keys);
+
+ for(Iterator i = day_keys.iterator(); i.hasNext(); ){
+ Hashtable day = (Hashtable) result.get((String) i.next());
+ ArrayList order_keys = new ArrayList();
+
+ for (Enumeration ee = day.keys() ; ee.hasMoreElements() ; ){
+ order_keys.add((String) ee.nextElement());
+ }
+ Collections.sort(order_keys);
+
+ for (Iterator ii = order_keys.iterator(); ii.hasNext();){
+ Hashtable event = (Hashtable) day.get((String) ii.next());
+ thisWeekEventsList.add(event);
+ }
+ }
+
+
+ ParameterExpander.setValueForKey(
+ aValueMap,
+ key,
+ thisWeekEventsList
+ );
+ }
+ catch (Throwable t) {
+ Throwable s = ExceptionRoutines.traceCauseException(t);
+ aLogger.error("Error while accessing radicalendar: " + s.getClass().getName()+","+ s.getMessage());
+ }
+ }
+}
*/
package mircoders.producer;
-import java.util.Map;
-import java.io.File;
-
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerWrapper;
import mir.producer.ProducerFailure;
import mir.producer.ProducerNode;
+import mir.producer.ProductionContext;
+import mir.util.FileRoutines;
import mir.util.ParameterExpander;
-import mir.util.FileFunctions;
import mircoders.entity.EntityContent;
import mircoders.search.IndexUtil;
+import java.io.File;
+
+/**
+ * UnIndexingProducerNode is one of the 2 producer nodes that works on
+ * the search index db. There's IndexingProducerNode and
+ * UnIndexingProducerNode. The first one adds/updates an article to
+ * the search index the second one removes an article
+ */
public class UnIndexingProducerNode implements ProducerNode {
private String contentKey;
private String indexPath;
indexBasePath = anIndexBasePath;
}
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ public void produce(ProductionContext aProductionContext) throws ProducerFailure {
Object data;
Entity entity;
File indexFile;
startTime = System.currentTimeMillis();
try {
- indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath));
+ indexFile = FileRoutines.getAbsoluteOrRelativeFile(indexBasePath,
+ ParameterExpander.expandExpression(aProductionContext.getValueSet(), indexPath));
- data = ParameterExpander.findValueForKey( aValueMap, contentKey );
+ data = ParameterExpander.findValueForKey(aProductionContext.getValueSet(), contentKey);
if (! (data instanceof EntityAdapter)) {
throw new ProducerFailure("UnIndexingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);
if (! (entity instanceof EntityContent)) {
throw new ProducerFailure("UnIndexingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
}
- aLogger.info("UnIndexing " + entity.getFieldValue("id") + " out of " + indexFile.getAbsolutePath());
+ aProductionContext.getLogger().info("UnIndexing " + entity.getFieldValue("id") + " out of " + indexFile.getAbsolutePath());
IndexUtil.unindexEntity((EntityContent) entity, indexFile);
}
catch (Throwable t) {
- aLogger.error("Error while unindexing content: " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ aProductionContext.getLogger().error("Error while unindexing content: " + t.getMessage(), t);
}
endTime = System.currentTimeMillis();
- aLogger.info(" UnIndexTime: " + (endTime-startTime) + " ms<br>");
+ aProductionContext.getLogger().info(" UnIndexTime: " + (endTime-startTime) + " ms<br>");
}
}
*/
package mircoders.producer.reader;
-import java.util.Map;
import java.io.File;
+import java.util.Map;
import mir.producer.ProducerNode;
import mir.producer.reader.DefaultProducerNodeBuilders;
import mir.producer.reader.ProducerConfigExc;
-import mir.producer.reader.ProducerNodeBuilderLibrary;
import mir.producer.reader.ProducerNodeBuilder;
+import mir.producer.reader.ProducerNodeBuilderLibrary;
import mir.util.xml.XMLParserExc;
import mir.util.xml.XMLReaderTool;
import mircoders.producer.ContentMarkingProducerNode;
import mircoders.producer.ContentModifyingProducerNode;
import mircoders.producer.IndexingProducerNode;
import mircoders.producer.MediaGeneratingProducerNode;
-import mircoders.producer.PDFGeneratingProducerNode;
-import mircoders.producer.PDFPreFormattingProducerNode;
+import mircoders.producer.RadicalendarProducerNode;
import mircoders.producer.UnIndexingProducerNode;
+import mircoders.producer.ChangeReportingProducerNode;
public class SupplementalProducerNodeBuilders {
aBuilderLibrary.registerFactory("IndexContent", new ContentIndexingProducerNodeBuilder.factory(aBasePath));
aBuilderLibrary.registerFactory("UnIndexContent", new ContentUnIndexingProducerNodeBuilder.factory(aBasePath));
- aBuilderLibrary.registerBuilder("PDFPreFormat", PDFPreFormattingProducerNodeBuilder.class);
- aBuilderLibrary.registerBuilder("PDFGenerate", PDFGeneratingProducerNodeBuilder.class);
-// aBuilderLibrary.registerBuilder("ReportChangedFiles", );
+ aBuilderLibrary.registerBuilder("Radicalendar", RadicalendarProducerNodeBuilder.class);
+
+ aBuilderLibrary.registerBuilder("ReportChanges", ChangeReportingProducerNodeBuilder.class);
}
- private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String[] MARKER_REQUIRED_ATTRIBUTES = { MARKER_KEY_ATTRIBUTE };
+ private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
+ private final static String[] MARKER_REQUIRED_ATTRIBUTES = {MARKER_KEY_ATTRIBUTE};
private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {};
private final static String[] MARKER_SUBNODES = {};
XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(MARKER_KEY_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new ContentMarkingProducerNode(key);
- };
+ }
}
- private final static String INDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String INDEXER_INDEX_ATTRIBUTE = "pathToIndex";
- private final static String[] INDEXER_REQUIRED_ATTRIBUTES = { INDEXER_KEY_ATTRIBUTE, INDEXER_INDEX_ATTRIBUTE };
+
+ private final static String INDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
+ private final static String INDEXER_INDEX_ATTRIBUTE = "pathToIndex";
+ private final static String[] INDEXER_REQUIRED_ATTRIBUTES = {INDEXER_KEY_ATTRIBUTE, INDEXER_INDEX_ATTRIBUTE};
private final static String[] INDEXER_OPTIONAL_ATTRIBUTES = {};
private final static String[] INDEXER_SUBNODES = {};
key = (String) anAttributes.get(INDEXER_KEY_ATTRIBUTE);
pathToIndex = (String) anAttributes.get(INDEXER_INDEX_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new IndexingProducerNode(indexBasePath, key, pathToIndex);
- };
+ }
}
- private final static String UNINDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String UNINDEXER_INDEX_ATTRIBUTE = "pathToIndex";
- private final static String[] UNINDEXER_REQUIRED_ATTRIBUTES = { UNINDEXER_KEY_ATTRIBUTE, UNINDEXER_INDEX_ATTRIBUTE };
+ private final static String UNINDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
+ private final static String UNINDEXER_INDEX_ATTRIBUTE = "pathToIndex";
+ private final static String[] UNINDEXER_REQUIRED_ATTRIBUTES = {UNINDEXER_KEY_ATTRIBUTE, UNINDEXER_INDEX_ATTRIBUTE};
private final static String[] UNINDEXER_OPTIONAL_ATTRIBUTES = {};
private final static String[] UNINDEXER_SUBNODES = {};
key = (String) anAttributes.get(UNINDEXER_KEY_ATTRIBUTE);
pathToIndex = (String) anAttributes.get(UNINDEXER_INDEX_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
- return new UnIndexingProducerNode(indexBasePath, key,pathToIndex);
- };
+ return new UnIndexingProducerNode(indexBasePath, key, pathToIndex);
+ }
}
- private final static String CONTENT_MODIFIER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String CONTENT_MODIFIER_FIELD_ATTRIBUTE = "field";
- private final static String CONTENT_MODIFIER_VALUE_ATTRIBUTE = "value";
- private final static String[] CONTENT_MODIFIER_REQUIRED_ATTRIBUTES = { CONTENT_MODIFIER_KEY_ATTRIBUTE, CONTENT_MODIFIER_FIELD_ATTRIBUTE, CONTENT_MODIFIER_VALUE_ATTRIBUTE };
+ private final static String CONTENT_MODIFIER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
+ private final static String CONTENT_MODIFIER_FIELD_ATTRIBUTE = "field";
+ private final static String CONTENT_MODIFIER_VALUE_ATTRIBUTE = "value";
+ private final static String[] CONTENT_MODIFIER_REQUIRED_ATTRIBUTES = {CONTENT_MODIFIER_KEY_ATTRIBUTE, CONTENT_MODIFIER_FIELD_ATTRIBUTE, CONTENT_MODIFIER_VALUE_ATTRIBUTE};
private final static String[] CONTENT_MODIFIER_OPTIONAL_ATTRIBUTES = {};
private final static String[] CONTENT_MODIFIER_SUBNODES = {};
key = (String) anAttributes.get(CONTENT_MODIFIER_KEY_ATTRIBUTE);
field = (String) anAttributes.get(CONTENT_MODIFIER_FIELD_ATTRIBUTE);
value = (String) anAttributes.get(CONTENT_MODIFIER_VALUE_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new ContentModifyingProducerNode(key, field, value);
- };
+ }
}
- private final static String MEDIA_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String[] MEDIA_REQUIRED_ATTRIBUTES = { MEDIA_KEY_ATTRIBUTE };
+ private final static String MEDIA_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
+ private final static String[] MEDIA_REQUIRED_ATTRIBUTES = {MEDIA_KEY_ATTRIBUTE};
private final static String[] MEDIA_OPTIONAL_ATTRIBUTES = {};
private final static String[] MEDIA_SUBNODES = {};
XMLReaderTool.checkAttributes(anAttributes, MEDIA_REQUIRED_ATTRIBUTES, MEDIA_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(MEDIA_KEY_ATTRIBUTE);
- };
+ }
public ProducerNode constructNode() {
return new MediaGeneratingProducerNode(key);
- };
+ }
}
- public static class PDFPreFormattingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
- private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
- private final static String PDF_NUM_LINES_ATTRIBUTE = "numLinesBetweenImages";
- private final static String PDF_CONTENT_WIDTH_ATTRIBUTE = "contentAreaWidthCM";
- private final static String PDF_CHAR_WIDTH_ATTRIBUTE = "charWidthCM";
- private final static String PDF_PIXEL_WIDTH_ATTRIBUTE = "pixelWidthCM";
- private final static String PDF_LINE_HEIGHT_ATTRIBUTE = "lineHeightCM";
- private final static String[] MARKER_REQUIRED_ATTRIBUTES = { MARKER_KEY_ATTRIBUTE, PDF_NUM_LINES_ATTRIBUTE, PDF_CONTENT_WIDTH_ATTRIBUTE,PDF_CHAR_WIDTH_ATTRIBUTE,PDF_PIXEL_WIDTH_ATTRIBUTE,PDF_LINE_HEIGHT_ATTRIBUTE };
- private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {};
- private final static String[] MARKER_SUBNODES = {};
-
+ public static class RadicalendarProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
+ private final static String RC_KEY_ATTRIBUTE = "key";
+ private final static String RC_GROUPNAME_ATTRIBUTE = "groupname";
+ private final static String RC_GMTOFFSET_ATTRIBUTE = "gmtoffset";
+ private final static String[] RC_REQUIRED_ATTRIBUTES = {RC_KEY_ATTRIBUTE, RC_GROUPNAME_ATTRIBUTE, RC_GMTOFFSET_ATTRIBUTE};
+ private final static String[] RC_OPTIONAL_ATTRIBUTES = {};
+ private final static String[] RC_SUBNODES = {};
private String key;
- private String numLinesBetweenImages;
- private String contentAreaWidthCM;
- private String characterWidthCM;
- private String pixelWidthCM;
- private String lineHeightCM;
+ private String groupname;
+ private String gmtoffset;
- public PDFPreFormattingProducerNodeBuilder() {
- super(MARKER_SUBNODES);
+ public RadicalendarProducerNodeBuilder() {
+ super(RC_SUBNODES);
}
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
- XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
+ XMLReaderTool.checkAttributes(anAttributes, RC_REQUIRED_ATTRIBUTES, RC_OPTIONAL_ATTRIBUTES);
- key = (String) anAttributes.get(MARKER_KEY_ATTRIBUTE);
- numLinesBetweenImages = (String) anAttributes.get(PDF_NUM_LINES_ATTRIBUTE);
- contentAreaWidthCM = (String) anAttributes.get(PDF_CONTENT_WIDTH_ATTRIBUTE);
- characterWidthCM = (String) anAttributes.get(PDF_CHAR_WIDTH_ATTRIBUTE);
- pixelWidthCM = (String) anAttributes.get(PDF_PIXEL_WIDTH_ATTRIBUTE);
- lineHeightCM = (String) anAttributes.get(PDF_LINE_HEIGHT_ATTRIBUTE);
-
-
- };
-
- public ProducerNode constructNode() {
- return new PDFPreFormattingProducerNode(key,numLinesBetweenImages,contentAreaWidthCM,characterWidthCM,pixelWidthCM,lineHeightCM);
- };
- }
-
- public static class PDFGeneratingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
- private final static String PDF_GENERATOR_ATTRIBUTE = "generator";
- private final static String PDF_DESTINATION_ATTRIBUTE = "destination";
- private final static String PDF_STYLESHEET_ATTRIBUTE = "stylesheet";
- private final static String[] MARKER_REQUIRED_ATTRIBUTES = {PDF_GENERATOR_ATTRIBUTE,PDF_DESTINATION_ATTRIBUTE,PDF_STYLESHEET_ATTRIBUTE };
- private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {};
- private final static String[] MARKER_SUBNODES = {};
-
- private String generator;
- private String destination;
- private String stylesheet;
-
-
- public PDFGeneratingProducerNodeBuilder() {
- super(MARKER_SUBNODES);
+ key = (String) anAttributes.get(RC_KEY_ATTRIBUTE);
+ groupname = (String) anAttributes.get(RC_GROUPNAME_ATTRIBUTE);
+ gmtoffset = (String) anAttributes.get(RC_GMTOFFSET_ATTRIBUTE);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
- XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
-
- generator = (String) anAttributes.get(PDF_GENERATOR_ATTRIBUTE);
- destination = (String) anAttributes.get(PDF_DESTINATION_ATTRIBUTE);
- stylesheet = (String) anAttributes.get(PDF_STYLESHEET_ATTRIBUTE);
- };
-
public ProducerNode constructNode() {
- return new PDFGeneratingProducerNode(generator,destination,stylesheet);
- };
+ return new RadicalendarProducerNode(key, groupname, gmtoffset);
+ }
}
+ public static class ChangeReportingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
+ private final static String CHANGEREPORTING_FILE_ATTRIBUTE = "file";
+ private final static String CHANGEREPORTING_FORMAT_ATTRIBUTE = "format";
+ private final static String CHANGEREPORTING_BASEPATH_ATTRIBUTE = "basepath";
+ private final static String CHANGEREPORTING_EXCLUDEDPATHS_ATTRIBUTE = "excludedpaths";
+ private final static String[] CHANGEREPORTING_REQUIRED_ATTRIBUTES = {CHANGEREPORTING_FILE_ATTRIBUTE,
+ CHANGEREPORTING_FORMAT_ATTRIBUTE, CHANGEREPORTING_BASEPATH_ATTRIBUTE};
+ private static final String[] CHANGEREPORTING_OPTIONAL_ATTRIBUTES = {CHANGEREPORTING_EXCLUDEDPATHS_ATTRIBUTE};
- /**
- * Builder for {@link mircoders.producer.ChangedFilesReportingProducerNode}
- * nodes.
- */
-/*
- private static class ChangeReportingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
- private final static String DESTINATION_FILE_ATTRIBUTE = "reportFile";
- private final static String LOCK_FILE_ATTRIBUTE = "lockfile";
- private final static String BASE_PATH_ATTRIBUTE = "basepath";
- private final static String EXCLUDED_PATHS_ATTRIBUTE = "excludedpaths";
- private final static String FLUSH_ATTRIBUTE = "flush";
- private final static String[] REQUIRED_ATTRIBUTES = {DESTINATION_FILE_ATTRIBUTE};
- private final static String[] OPTIONAL_ATTRIBUTES = {LOCK_FILE_ATTRIBUTE, BASE_PATH_ATTRIBUTE, EXCLUDED_PATHS_ATTRIBUTE, FLUSH_ATTRIBUTE};
- private final static String[] SUBNODES = {};
-
- private String reportFile;
- private String lockFile;
- private String basePath;
- private String excludedPaths;
- private String flush;
+ private String file;
+ private String format;
+ private String basepath;
+ private String excludedpaths;
public ChangeReportingProducerNodeBuilder() {
- super(SUBNODES);
+ super(new String[0]);
}
public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
- XMLReaderTool.checkAttributes(anAttributes, REQUIRED_ATTRIBUTES, OPTIONAL_ATTRIBUTES);
+ XMLReaderTool.checkAttributes(anAttributes, CHANGEREPORTING_REQUIRED_ATTRIBUTES, CHANGEREPORTING_OPTIONAL_ATTRIBUTES);
- reportFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, DESTINATION_FILE_ATTRIBUTE, null);
- lockFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, LOCK_FILE_ATTRIBUTE, null);
- basePath = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BASE_PATH_ATTRIBUTE, "");
- excludedPaths = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXCLUDED_PATHS_ATTRIBUTE, "");
- flush = XMLReaderTool.getStringAttributeWithDefault(anAttributes, FLUSH_ATTRIBUTE, "1");
- };
+ file = (String) anAttributes.get(CHANGEREPORTING_FILE_ATTRIBUTE);
+ format = (String) anAttributes.get(CHANGEREPORTING_FORMAT_ATTRIBUTE);
+ basepath = (String) anAttributes.get(CHANGEREPORTING_BASEPATH_ATTRIBUTE);
+ excludedpaths = (String) anAttributes.get(CHANGEREPORTING_EXCLUDEDPATHS_ATTRIBUTE);
+ }
public ProducerNode constructNode() {
- return new ChangedFilesReportingProducerNode(reportFile, lockFile, basePath, excludedPaths, flush);
- };
+ return new ChangeReportingProducerNode(file, format, basepath, excludedpaths);
+ }
}
-*/
}
package mircoders.search;
+import java.util.ArrayList;
import java.util.Iterator;
-import java.util.Map;
-import java.util.Vector;
+import java.util.List;
+import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
-import mircoders.storage.DatabaseContentToMedia;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseAudio;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
+/**
+ * indexes whether an Enity has audio
+ */
public class AudioSearchTerm extends SearchTerm{
public AudioSearchTerm() {
super(null, "search_hasAudio", "hasAudio", null, "hasAudio");
}
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
+ public void index(Document doc, Entity entity) throws DatabaseFailure{
// EntityList audio = DatabaseContentToMedia.getInstance().getAudio((EntityContent) entity);
- Vector extraTables = new Vector();
+ List extraTables = new ArrayList();
extraTables.add("content_x_media cxm");
Iterator audios = new EntityBrowser(
DatabaseAudio.getInstance(), "i", extraTables,
if (wanted != null && wanted.equals("y")){
return matchField + ":" + "\"" + wanted + "\"";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-
+/**
+ * Tokenizes a string field in an Entity and indexes
+ * it, but does not store it for retrieval (used for content_data)
+ */
public class ContentSearchTerm extends SearchTerm{
protected ContentSearchTerm() {
}
}
}
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
-import java.util.Vector;
+
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityImages;
import mircoders.storage.DatabaseImages;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-
+/**
+ * Indexes whether or not an Entity has associated
+ * images, and also stores urls of those images for
+ * retrieval in the search results
+ */
public class ImagesSearchTerm extends SearchTerm{
public ImagesSearchTerm() {
super (null, "search_hasImages", "hasImages", "images", "images");
}
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
- Vector extraTables = new Vector();
+ public void index(Document doc, Entity entity) throws DatabaseFailure{
+ List extraTables = new ArrayList();
extraTables.add("content_x_media cxm");
Iterator images = new EntityBrowser(
if (wanted != null && wanted.equals("y")){
return matchField + ":y";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
package mircoders.search;
-import java.io.IOException;
import java.io.File;
+import java.io.IOException;
+
+import mircoders.entity.EntityContent;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
-import mircoders.entity.EntityContent;
/**
* Some utility functions for article (un)indexing
import org.apache.lucene.document.Field;
-
+/**
+ * indexes a field and stores it for retrieval, but
+ * does not tokenize it. useful for things
+ * like strings representing
+ */
public class KeywordSearchTerm extends SearchTerm{
if (wanted != null && !(wanted.equals(""))){
return matchField + ":" + "\"" + wanted + "\"";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
result.put(templateVariable,doc.get(dataField));
+++ /dev/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 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.search;
-
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import mir.entity.Entity;
-import mir.storage.StorageObjectFailure;
-
-import org.apache.lucene.document.Document;
-
-
-public class MediaSearchTerm extends SearchTerm{
- public MediaSearchTerm() {
- super(null, "search_hasMedia", "", null, "");
- }
-
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
- // only use this term for doing alternate queries on media
- return;
- }
-
- public String makeTerm(HttpServletRequest req){
- String wanted = req.getParameter(paramName);
- if (wanted != null && (wanted.equals("hasImages") || wanted.equals("hasAudio") || wanted.equals("hasVideo") )){
- return wanted + ":\"y\"";
- }
- else {
- return null;
- }
- }
-
- public void returnMeta(Map result,Document doc){
- return;
- }
-
-
-}
-
-
package mircoders.search;
import java.util.Map;
+
import javax.servlet.http.HttpServletRequest;
+
import mir.entity.Entity;
+
import org.apache.lucene.document.Document;
+/**
+ * The SearchTerm class attempts to encapsulate the relationships
+ * between:
+ * <ul>
+ * <li>A fields or property of Content Entities</li>
+ * <li>A field of Lucene Documents</li>
+ * <li>An HTTP Query Parameter</li>
+ * <li>And a bit of HTML on a Search Results Page</li>
+ * </ul>
+ * The basic idea is that how you index, query, and display a
+ * particular field in a resource are all intimately related, possibly
+ * more so than how you index two different fields of the same
+ * resource.
+ *
+ * <p>Instances of classes implementing SearchTerm are created when a Mir
+ * content entity is indexed by the IndexingProducerNode Class. The
+ * index method of each class is called in turn to add a bit of
+ * information to the Lucene documents which will be added to the
+ * index after it is created and all its fields specified. Instances
+ * of the same classes are created by ServletModuleOpenIndy so that it
+ * can construct a query to match against the lucene index, here the
+ * makeTerm methods are called in turn to pick out the parameter they
+ * want from the request and then construct the appropriate fragment
+ * of lucene query, which are ultimately concatenated together. These
+ * classes are also used to return appropriate template models
+ * representing any hits to be displayed as a result of processing the
+ * query.</p>
+ */
abstract public class SearchTerm {
protected String partOfEntity;
protected String paramName;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-
+/**
+ * tokenizes a string field in an Entity and indexes
+ * it, and stores it for retrieval (used for description)
+ */
public class TextSearchTerm extends SearchTerm{
public TextSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
if (wanted != null && !(wanted.equals(""))){
return matchField + ":" + "\"" + wanted + "\"";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
result.put(templateVariable, doc.get(dataField));
import mir.entity.Entity;
import mir.entity.EntityList;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityContent;
import mircoders.storage.DatabaseContentToTopics;
super(null, "search_topicmatrix", "topic", null, null);
}
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
+ public void index(Document doc, Entity entity) throws DatabaseFailure{
EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity);
if (topics != null && topics.size()>0){
for(int k=0;k<topics.size();k++){
if (queryTerm.equals("")){
return null;
}
- else {
- return "( "+queryTerm+ " )";
- }
+ return "( "+queryTerm+ " )";
}
import mir.entity.Entity;
import mir.entity.EntityList;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityContent;
import mircoders.storage.DatabaseContentToTopics;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-
+/**
+ * used by indexing and querying
+ * documents based on Topic
+ */
public class TopicSearchTerm extends SearchTerm{
public TopicSearchTerm() {
super(null, "search_topic", "topic", null, null);
}
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
+ public void index(Document doc, Entity entity) throws DatabaseFailure{
EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity);
if (topics != null && topics.size()>0){
for(int k=0;k<topics.size();k++){
if (wanted != null && !(wanted.equals(""))){
return matchField + ":" + "\"" + wanted + "\"";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
import org.apache.lucene.document.Field;
-
+/**
+ * Stores some metatdata for retrieval with a
+ * hit (for example a URL)
+ */
public class UnIndexedSearchTerm extends SearchTerm{
public UnIndexedSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-
+/**
+ * not currently used
+ */
public class UnStoredSearchTerm extends SearchTerm{
public UnStoredSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
if (wanted != null && !(wanted.equals(""))){
return matchField + ":" + "\"" + wanted + "\"";
}
- else {
- return null;
- }
+ return null;
}
public void returnMeta(Map result,Document doc){
return;
*/
package mircoders.search;
+import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
-import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseVideo;
import org.apache.lucene.document.Document;
-
+/**
+ * indexes whether an Enity has video
+ */
public class VideoSearchTerm extends SearchTerm {
public VideoSearchTerm() {
super(null, "search_hasVideo", "hasVideo", null, "hasVideo");
}
- public void index(Document doc, Entity entity) throws StorageObjectFailure {
- Vector extraTables = new Vector();
+ public void index(Document doc, Entity entity) throws DatabaseFailure {
+ List extraTables = new ArrayList();
extraTables.add("content_x_media cxm");
Iterator videos = new EntityBrowser(
if ((wanted != null) && wanted.equals("y")) {
return matchField + ":" + "\"" + wanted + "\"";
- } else {
- return null;
}
+ return null;
}
public void returnMeta(Map result, Document doc) {
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.servlet;\r
-\r
-import java.io.PrintWriter;\r
-import java.io.IOException;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.generator.Generator;\r
-import mir.generator.GeneratorHelper;\r
-import mir.log.LoggerWrapper;\r
-import mir.servlet.ServletModuleExc;\r
-import mir.servlet.ServletModuleFailure;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.global.MirGlobal;\r
-\r
-\r
-public class ServletHelper {\r
- private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");\r
-\r
- public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {\r
- return makeGenerationData(aRequest, aResponse, aLocales, "etc/bundles/adminlocal", "bundles/admin");\r
- }\r
-\r
- public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {\r
- return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);\r
- }\r
-\r
- public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {\r
- try {\r
- MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
- Map result = GeneratorHelper.makeBasicGenerationData(aLocales, aBundle, aDefaultBundle);\r
- if (configuration.getString("Mir.Admin.ShowLoggedinUsers").equals("1")) {\r
- result.put("loggedinusers", MirGlobal.getLoggedInUsers());\r
- }\r
- else {\r
- result.put("loggedinusers", null);\r
- }\r
- result.put("systemstatus", MirGlobal.getStatus());\r
-\r
- // ML: hackish\r
- ((Map) result.get("config")).put("actionRoot",\r
- aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));\r
-\r
- result.put("returnurl", null);\r
- result.put("login_user", getUserAdapter(aRequest));\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new ServletModuleFailure(t);\r
- }\r
- }\r
-\r
- public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
- logger.debug("generator used: " + aGenerator);\r
-\r
- Generator generator;\r
-\r
- try {\r
- generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);\r
-\r
- generator.generate(aWriter, aGenerationData, logger);\r
- }\r
- catch (Throwable t) {\r
- throw new ServletModuleFailure(t);\r
- }\r
- }\r
-\r
- public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
- Generator generator;\r
-\r
- try {\r
- generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);\r
-\r
- generator.generate(aWriter, aGenerationData, logger);\r
- }\r
- catch (Throwable t) {\r
- throw new ServletModuleFailure(t);\r
- }\r
- }\r
-\r
- public static void generateInfoMessage(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
- Locale[] aLocales, String aBundle, String aDefaultBundle, String aMessage, String anArgument1, String anArgument2) throws ServletModuleExc {\r
- Map responseData = makeGenerationData(aRequest, aResponse, aLocales, aBundle, aDefaultBundle);\r
- responseData.put("message", aMessage);\r
- responseData.put("argument1", anArgument1);\r
- responseData.put("argument2", anArgument2);\r
-\r
- try {\r
- generateResponse(aResponse.getWriter(), responseData, "infomessage.template");\r
- }\r
- catch (IOException e) {\r
- throw new ServletModuleFailure(e);\r
- }\r
- }\r
-\r
- public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
- try {\r
- aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));\r
- }\r
- catch (IOException t) {\r
- throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);\r
- }\r
- }\r
-\r
- public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure {\r
- redirect(aResponse, "module="+aModule+"&do="+aMethod);\r
- }\r
-\r
- public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {\r
- if (aUser!=null)\r
- aRequest.getSession().setAttribute("login.uid", aUser);\r
- else\r
- aRequest.getSession().removeAttribute("login.uid");\r
- }\r
-\r
- public static EntityUsers getUser(HttpServletRequest aRequest) {\r
- return (EntityUsers) aRequest.getSession().getAttribute("login.uid");\r
- }\r
-\r
- public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {\r
- try {\r
- return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid"));\r
- }\r
- catch (Throwable t) {\r
- throw new ServletModuleFailure (t);\r
- }\r
- }\r
-\r
- public static String getUserName(HttpServletRequest aRequest) {\r
- EntityUsers user = getUser(aRequest);\r
-\r
- if (user!=null)\r
- return user.getFieldValue("login");\r
- else\r
- return "nobody";\r
- }\r
-}\r
+/*
+ * 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 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.IOException;
+import java.io.PrintWriter;
+import java.util.Locale;
+import java.util.Map;
+import java.util.HashMap;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityAdapter;
+import mir.entity.Entity;
+import mir.generator.Generator;
+import mir.generator.GeneratorHelper;
+import mir.log.LoggerWrapper;
+import mir.servlet.ServletModuleExc;
+import mir.servlet.ServletModuleFailure;
+import mir.servlet.AdminServletModule;
+import mircoders.entity.EntityUsers;
+import mircoders.global.MirGlobal;
+
+
+public class ServletHelper {
+ private static final LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");
+
+ private ServletHelper() {
+ }
+
+ public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) {
+ return makeGenerationData(aRequest, aResponse, aLocales, "etc/bundles/adminlocal", "bundles/admin");
+ }
+
+ public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) {
+ return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);
+ }
+
+ public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) {
+ try {
+ MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+ Map result = GeneratorHelper.makeBasicGenerationData(aLocales, aBundle, aDefaultBundle);
+ if (configuration.getBoolean("Mir.Admin.ShowLoggedinUsers")) {
+ result.put("loggedinusers", MirGlobal.getLoggedInUsers());
+ }
+ else {
+ result.put("loggedinusers", null);
+ }
+ result.put("systemstatus", MirGlobal.getStatus());
+
+ // ML: hackish
+ ((Map) result.get("config")).put("actionRoot",
+ aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));
+
+ result.put("returnurl", null);
+ result.put("login_user", getUserAdapter(aRequest));
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) {
+ logger.debug("generator used: " + aGenerator);
+
+ try {
+ Generator generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator, null);
+
+ generator.generate(aWriter, aGenerationData, logger);
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) {
+ try {
+ Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator, null);
+
+ generator.generate(aWriter, aGenerationData, logger);
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure(t);
+ }
+ }
+
+ public static void generateInfoMessage(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ Locale[] aLocales, String aBundle, String aDefaultBundle, String aMessage, String anArgument1, String anArgument2) {
+ Map responseData = makeGenerationData(aRequest, aResponse, aLocales, aBundle, aDefaultBundle);
+ responseData.put("message", aMessage);
+ responseData.put("argument1", anArgument1);
+ responseData.put("argument2", anArgument2);
+
+ try {
+ generateResponse(aResponse.getWriter(), responseData, "infomessage.template");
+ }
+ catch (IOException e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
+ public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleFailure {
+ try {
+ aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));
+ }
+ catch (IOException t) {
+ throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);
+ }
+ }
+
+ public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleFailure {
+ redirect(aResponse, "module="+aModule+"&do="+aMethod);
+ }
+
+ public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {
+ if (aUser!=null) {
+ aRequest.getSession().setAttribute("login.uid", aUser);
+ }
+ else {
+ aRequest.getSession().removeAttribute("login.uid");
+ }
+ }
+
+ public static EntityUsers getUser(HttpServletRequest aRequest) {
+ return (EntityUsers) aRequest.getSession().getAttribute("login.uid");
+ }
+
+ public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {
+ try {
+ return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("user",
+ (Entity) aRequest.getSession().getAttribute("login.uid"));
+ }
+ catch (Throwable t) {
+ throw new ServletModuleFailure (t);
+ }
+ }
+
+ public static String getUserName(HttpServletRequest aRequest) {
+ EntityUsers user = getUser(aRequest);
+
+ if (user!=null) {
+ return user.getFieldValue("login");
+ }
+
+ return "nobody";
+ }
+
+ private static final Map servletModules = new HashMap();
+
+ public static AdminServletModule getServletModule(String aName) throws ServletModuleExc {
+ synchronized (servletModules) {
+ if (!servletModules.containsKey(aName)) {
+ // was not found in the cache...
+ try {
+ Class servletModuleClass =
+ Class.forName("mircoders.servlet.ServletModule" + aName);
+
+ AdminServletModule module = (AdminServletModule)
+ servletModuleClass.newInstance();
+
+ // we put it into our cache for future calls
+ servletModules.put(aName, module);
+
+ return module;
+ }
+ catch (Exception e) {
+ throw new ServletModuleExc("*** error resolving classname for " + aName + " -- " + e.getMessage());
+ }
+ }
+
+ return (AdminServletModule) servletModules.get(aName);
+ }
+ }
+
+ public static ServletModuleFileEdit getServletModuleFileEdit() throws ServletModuleExc {
+ return (ServletModuleFileEdit) getServletModule("FileEdit");
+ }
+
+ public static ServletModuleLocalizer getServletModuleLocalizer() throws ServletModuleExc {
+ return (ServletModuleLocalizer) getServletModule("Localizer");
+ }
+
+ public static ServletModuleAdmin getServletModuleAdmin() throws ServletModuleExc {
+ return (ServletModuleAdmin) getServletModule("Admin");
+ }
+
+ public static ServletModuleContent getServletModuleContent() throws ServletModuleExc {
+ return (ServletModuleContent) getServletModule("Content");
+ }
+
+ public static ServletModuleComment getServletModuleComment() throws ServletModuleExc {
+ return (ServletModuleComment) getServletModule("Comment");
+ }
+
+}
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.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
+import mir.storage.DatabaseExc;
import mir.util.HTTPRequestParser;
import mir.util.URLBuilder;
-import mircoders.global.Abuse;
+import mircoders.abuse.FilterEngine;
import mircoders.global.MirGlobal;
-public class ServletModuleAbuse extends ServletModule {
- private static ServletModuleAbuse instance = new ServletModuleAbuse();
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Map;
+
+public class ServletModuleAbuse extends AdminServletModule {
private String editFilterTemplate;
private String listFiltersTemplate;
+ private String editFilterGroupTemplate;
+ private String listFilterGroupsTemplate;
private String mainTemplate;
private String viewLogTemplate;
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleAbuse() {
- logger = new LoggerWrapper("ServletModule.Abuse");
- defaultAction = "showsettings";
+ public ServletModuleAbuse() {
+ editFilterTemplate = getConfiguration().getString("ServletModule.Abuse.EditFilter.Template");
+ listFiltersTemplate = getConfiguration().getString("ServletModule.Abuse.ListFilters.Template");
+ editFilterGroupTemplate = getConfiguration().getString("ServletModule.Abuse.EditFilterGroup.Template");
+ listFilterGroupsTemplate = getConfiguration().getString("ServletModule.Abuse.ListFilterGroups.Template");
+ viewLogTemplate = getConfiguration().getString("ServletModule.Abuse.ViewLog.Template");
+ mainTemplate = getConfiguration().getString("ServletModule.Abuse.Main.Template");
+ }
- editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template");
- listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template");
- viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template");
- mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template");
+ public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ showsettings(aRequest, aResponse);
}
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String id=requestParser.getParameterWithDefault("id", "");
+ String groupid=requestParser.getParameterWithDefault("groupid", "");
- if (id.equals("")) {
- editfilter(aRequest, aResponse, "", "", "", "", "", "", "");
- }
- else {
- Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id);
- if (filter==null)
- throw new ServletModuleExc("Filter not found");
+ FilterEngine.Filter filter = MirGlobal.abuse().getFilterEngine().getFilterForId(groupid, id);
- editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), "");
- }
+ editfilter(aRequest, aResponse,
+ groupid,
+ id, filter.getType(), filter.getExpression(),
+ filter.getComment(), filter.getTag(), filter.getCommentAction(), filter.getArticleAction(), "");
+ }
+
+ public void addfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ String groupid=requestParser.getParameterWithDefault("groupid", "");
+
+ editfilter(aRequest, aResponse, groupid, "", "", "", "", "", "", "", "");
}
public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse,
- String anId, String aType, String anExpression, String aComments,
+ String aGroupId, String anId, String aType, String anExpression, String aComments,
+ String aTag,
String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc {
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
responseData.put("id", anId);
+ responseData.put("groupid", aGroupId);
responseData.put("type", aType);
responseData.put("expression", anExpression);
responseData.put("comments", aComments);
+ responseData.put("tag", aTag);
responseData.put("articleaction", anArticleAction);
responseData.put("commentaction", aCommentAction);
responseData.put("errormessage", anErrorMessage);
responseData.put("articleactions", MirGlobal.abuse().getArticleActions());
responseData.put("commentactions", MirGlobal.abuse().getCommentActions());
- responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());
+ responseData.put("filtertypes", MirGlobal.abuse().getFilterEngine().getFilterTypes());
ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate);
}
String type=requestParser.getParameterWithDefault("type", "");
String id=requestParser.getParameterWithDefault("id", "");
+ String groupid=requestParser.getParameter("groupid");
String expression=requestParser.getParameterWithDefault("expression", "");
String commentaction=requestParser.getParameterWithDefault("commentaction", "");
String articleaction=requestParser.getParameterWithDefault("articleaction", "");
String comments=requestParser.getParameterWithDefault("comments", "");
+ String tag=requestParser.getParameterWithDefault("tag", "");
String errorMessage;
- if (id.equals("")) {
- errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction);
- logAdminUsage(aRequest, "?", "object added");
+ try {
+ if (id.equals("")) {
+ errorMessage = MirGlobal.abuse().getFilterEngine().addFilter(
+ groupid, type, expression, comments, tag,
+ articleaction, commentaction);
+ logAdminUsage(aRequest, id, "filter added");
+ }
+ else {
+ errorMessage = MirGlobal.abuse().getFilterEngine().updateFilter(
+ groupid, id, type, expression, comments, tag,
+ articleaction, commentaction);
+ logAdminUsage(aRequest, id, "filter modified");
+ }
}
- else {
- errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction);
- logAdminUsage(aRequest, id, "object modified");
+ catch (DatabaseExc e) {
+ throw new ServletModuleFailure(e);
}
if (errorMessage!=null) {
- editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage);
+ editfilter(aRequest, aResponse, groupid, id, type,
+ expression, comments, tag, commentaction, articleaction, errorMessage);
}
else {
MirGlobal.abuse().save();
- showfilters(aRequest, aResponse);
+ listfilters(aRequest, aResponse);
}
}
- public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void movefilterup(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- String id=requestParser.getParameterWithDefault("id", "");
- MirGlobal.abuse().deleteFilter(id);
- logAdminUsage(aRequest, id, "object deleted");
+ String id=requestParser.getParameter("id");
+ String groupid=requestParser.getParameter("groupid");
+
+ MirGlobal.abuse().getFilterEngine().moveFilterUp(groupid, id);
+ listfilters(aRequest, aResponse);
+ }
+
- MirGlobal.abuse().save();
+ public void movefilterdown(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- showfilters(aRequest, aResponse);
+ String id=requestParser.getParameter("id");
+ String groupid=requestParser.getParameter("groupid");
+
+ MirGlobal.abuse().getFilterEngine().moveFilterDown(groupid, id);
+ listfilters(aRequest, aResponse);
}
- public void moveup(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void movefiltertop(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- String id=requestParser.getParameterWithDefault("id", "");
- MirGlobal.abuse().moveFilterUp(id);
+ String id=requestParser.getParameter("id");
+ String groupid=requestParser.getParameter("groupid");
- MirGlobal.abuse().save();
- logAdminUsage(aRequest, id, "object moved upwards");
+ MirGlobal.abuse().getFilterEngine().moveFilterToTop(groupid, id);
+ listfilters(aRequest, aResponse);
+ }
+
+ public void movefilterbottom(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- showfilters(aRequest, aResponse);
+ String id=requestParser.getParameter("id");
+ String groupid=requestParser.getParameter("groupid");
+
+ MirGlobal.abuse().getFilterEngine().moveFilterToBottom(groupid, id);
+ listfilters(aRequest, aResponse);
}
- public void movedown(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- String id=requestParser.getParameterWithDefault("id", "");
- MirGlobal.abuse().moveFilterDown(id);
- logAdminUsage(aRequest, id, "object moved downwards");
+ String id=requestParser.getParameter("id");
+ String groupid=requestParser.getParameter("groupid");
+ MirGlobal.abuse().getFilterEngine().deleteFilter(groupid, id);
+ MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filter:"+groupid+":"+id, "filter deleted");
+
+ listfilters(aRequest, aResponse);
+ }
+
+ public void deletefiltergroup(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+ String groupid=requestParser.getParameter("groupid");
+ MirGlobal.abuse().getFilterEngine().deleteFilterGroup(groupid);
- MirGlobal.abuse().save();
+ MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filtergroup:"+groupid, "filter group deleted");
- showfilters(aRequest, aResponse);
+ showfiltergroups(aRequest, aResponse);
}
- public void movetop(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void movefiltergroupup(HttpServletRequest aRequest, HttpServletResponse aResponse) {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- String id=requestParser.getParameterWithDefault("id", "");
- MirGlobal.abuse().moveFilterToTop(id);
+ String groupid=requestParser.getParameter("groupid");
+ MirGlobal.abuse().getFilterEngine().moveFilterGroupUp(groupid);
- MirGlobal.abuse().save();
- logAdminUsage(aRequest, id, "object moved to the top");
+ MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filtergroup:"+groupid, "filter group moved upwards");
- showfilters(aRequest, aResponse);
+ showfiltergroups(aRequest, aResponse);
}
- public void movebottom(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void movefiltergroupdown(HttpServletRequest aRequest, HttpServletResponse aResponse) {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ String groupid=requestParser.getParameter("groupid");
+ MirGlobal.abuse().getFilterEngine().moveFilterGroupDown(groupid);
+
+ MirGlobal.logAdminUsage(ServletHelper.getUser(aRequest), getName() + ":" + "filtergroup:"+groupid, "filter group moved downwards");
+
+ showfiltergroups(aRequest, aResponse);
+ }
+
+ public void showfilterconfiguration(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ showfiltergroups(aRequest, aResponse);
+ }
+
+ public void addfiltergroup(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ editfiltergroup(aRequest, aResponse, "", "");
+ }
+
+ public void editgroup(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String id=requestParser.getParameterWithDefault("id", "");
- MirGlobal.abuse().moveFilterToBottom(id);
- MirGlobal.abuse().save();
- logAdminUsage(aRequest, id, "object moved to the bottom");
+ FilterEngine.FilterGroup group = MirGlobal.abuse().getFilterEngine().getFilterGroupForId(id);
- showfilters(aRequest, aResponse);
+ editfiltergroup(aRequest, aResponse, id, group.getName());
}
- public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
- editfilter(aRequest, aResponse, "", "", "", "", "", "", "");
+ public void editfiltergroup(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String anId, String aName) throws ServletModuleExc {
+ try {
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+ responseData.put("id", anId);
+ responseData.put("name", aName);
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterGroupTemplate);
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
}
- public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ public void listfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {
URLBuilder urlBuilder = new URLBuilder();
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ String groupid=requestParser.getParameterWithDefault("groupid", "");
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
urlBuilder.setValue("module", "Abuse");
- urlBuilder.setValue("do", "showfilters");
+ urlBuilder.setValue("do", "listfilters");
+ urlBuilder.setValue("groupid", groupid);
responseData.put("thisurl", urlBuilder.getQuery());
+ responseData.put("groupid", groupid);
- responseData.put("filters", MirGlobal.abuse().getFilters());
+ responseData.put("filters", MirGlobal.abuse().getFilterEngine().getFilters(groupid));
ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate);
}
}
}
+ public void updatefiltergroup(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+
+ String name = requestParser.getParameterWithDefault("name", "");
+ String id = requestParser.getParameterWithDefault("id", "");
+
+ try {
+ if (id.equals("")) {
+ MirGlobal.abuse().getFilterEngine().addFilterGroup(name);
+ }
+ else {
+ MirGlobal.abuse().getFilterEngine().updateFilterGroup(id, name);
+ }
+ }
+ catch (DatabaseExc e) {
+ throw new ServletModuleFailure(e);
+ }
+
+ showfiltergroups(aRequest, aResponse);
+ }
+
+ public void showfiltergroups(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ URLBuilder urlBuilder = new URLBuilder();
+
+ try {
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest));
+
+ urlBuilder.setValue("module", "Abuse");
+ urlBuilder.setValue("do", "showfiltergroups");
+ responseData.put("thisurl", urlBuilder.getQuery());
+
+ responseData.put("filtergroups", MirGlobal.abuse().getFilterEngine().getFilterGroups());
+
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFilterGroupsTemplate);
+ }
+ catch (Throwable e) {
+ throw new ServletModuleFailure(e);
+ }
+ }
+
public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
URLBuilder urlBuilder = new URLBuilder();
*/
package mircoders.servlet;
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Map;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
-import mir.util.CachingRewindableIterator;
import mir.util.URLBuilder;
import mircoders.global.MirGlobal;
-public class ServletModuleAdmin extends ServletModule
-{
- private static ServletModuleAdmin instance = new ServletModuleAdmin();
- public static ServletModule getInstance() { return instance; }
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.List;
+import java.util.Map;
- private ServletModuleAdmin() {
- logger = new LoggerWrapper("ServletModule.Admin");
- defaultAction = "start";
+public class ServletModuleAdmin extends AdminServletModule {
+ public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ start(aRequest, aResponse);
}
public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {
}
public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) {
- String defaultStartTemplate = configuration.getString("Mir.StartTemplate");
+ String defaultStartTemplate = getConfiguration().getString("Mir.StartTemplate");
try {
- Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest),
+ Map templateData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest),
"bundles/admin", "etc/bundles/adminlocal");
- mergeData.put("messages",
- new CachingRewindableIterator(
- new EntityIteratorAdapter("", "webdb_create desc", 10,
- MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
-
- mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
- mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
-
- mergeData.put("searchvalue", null);
- mergeData.put("searchfield", null);
- mergeData.put("searchispublished", null);
- mergeData.put("searcharticletype", null);
- mergeData.put("searchorder", null);
- mergeData.put("selectarticleurl", null);
- mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());
+
+ List messages = EntityAdapterEngine.retrieveAdapterList(getModel(),
+ "internalMessage", "", "webdb_create desc", 10, 0);
+
+ templateData.put("messages", messages);
+
+ templateData.put("fileeditentries",
+ ServletHelper.getServletModuleFileEdit().getEntries());
+ templateData.put("administeroperations",
+ ServletHelper.getServletModuleLocalizer().getAdministerOperations());
+
+ templateData.put("searchvalue", null);
+ templateData.put("searchfield", null);
+ templateData.put("searchispublished", null);
+ templateData.put("searcharticletype", null);
+ templateData.put("searchorder", null);
+ templateData.put("searchtopic", null);
+ templateData.put("selectarticleurl", null);
+ templateData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());
String startTemplate = MirGlobal.localizer().adminInterface().getAdminPageGenerator(
- "admin.start", mergeData,
+ "admin.start", templateData,
ServletHelper.getUserAdapter(aRequest), defaultStartTemplate);
- ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate);
+ ServletHelper.generateResponse(aResponse.getWriter(), templateData, startTemplate);
}
catch (Exception e) {
throw new ServletModuleFailure(e);
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleArticleType;
/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * ServletModule for managing article types
*/
-public class ServletModuleArticleType extends ServletModule
-{
- private static ServletModuleArticleType instance = new ServletModuleArticleType();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleArticleType() {
- logger = new LoggerWrapper("ServletModule.ArticleType");
-
- try {
- definition = "articleType";
- mainModule = new ModuleArticleType();
- }
- catch (Exception e) {
- logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
- }
+public class ServletModuleArticleType extends AdminServletModule {
+ public ServletModuleArticleType() {
+ definition = "articleType";
+ mainModule = new ModuleArticleType();
}
}
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mircoders.global.MirGlobal;
import mircoders.module.ModuleUploadedMedia;
import mircoders.storage.DatabaseAudio;
-/*
- *
- *
- * @author br1
+/**
+ * ServletModule for managing Audio uploads
*/
-
public class ServletModuleAudio extends ServletModuleUploadedMedia {
- private static ServletModuleAudio instance = new ServletModuleAudio();
-
- public static ServletModule getInstance() {
- return instance;
- }
-
- private ServletModuleAudio() {
- logger = new LoggerWrapper("ServletModule.Audio");
-
- moduleName = "Audio";
-
- try {
- definition = "audio";
- mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance());
- }
- catch (Throwable e) {
- logger.error("servletmodule audio could not be initialized: " + e.getMessage());
- }
+ public ServletModuleAudio() {
+ super("Audio");
+ definition = "audio";
+ mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance());
}
}
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mircoders.global.MirGlobal;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleBreaking;
-import mircoders.storage.DatabaseBreaking;
/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * ServletModule for managing breaking news
*/
-public class ServletModuleBreaking extends ServletModule
-{
- private static ServletModuleBreaking instance = new ServletModuleBreaking();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleBreaking() {
- logger = new LoggerWrapper("ServletModule.Breaking");
-
- try {
- definition = "breakingNews";
- mainModule = new ModuleBreaking();
- }
- catch (Exception e) {
- logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage());
- }
+public class ServletModuleBreaking extends AdminServletModule {
+ public ServletModuleBreaking() {
+ definition = "breakingNews";
+ mainModule = new ModuleBreaking();
}
}
package mircoders.servlet;
+import mir.entity.adapter.EntityAdapterEngine;
import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.servlet.ServletModuleUserExc;
-import mir.util.*;
+import mir.util.HTTPRequestParser;
+import mir.util.JDBCStringRoutines;
+import mir.util.SQLQueryBuilder;
+import mir.util.URLBuilder;
import mircoders.entity.EntityComment;
import mircoders.global.MirGlobal;
import mircoders.module.ModuleComment;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.util.*;
-
-/*
- * ServletModuleComment - controls navigation for Comments
- *
- *
- * @author the mir-coders
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * ServletModule for managing Comments
*/
-public class ServletModuleComment extends ServletModule
-{
- private static ServletModuleComment instance = new ServletModuleComment();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleComment() {
- logger = new LoggerWrapper("ServletModule.Comment");
- try {
- mainModule = new ModuleComment();
- }
- catch (Exception e) {
- logger.error("servletmodule comment could not be initialized:" + e.getMessage());
- }
+public class ServletModuleComment extends AdminServletModule {
+ public ServletModuleComment() {
+ mainModule = new ModuleComment();
+ definition = "comment";
}
public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
}
}
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String idParam = aRequest.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("Invalid call: id not supplied ");
+ }
editObject(aRequest, aResponse, idParam);
}
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
- Map comment;
+ Object comment;
URLBuilder urlBuilder = new URLBuilder();
urlBuilder.setValue("module", "Comment");
comment = model.makeEntityAdapter("comment", mainModule.getById(anId));
}
else {
- List fields = DatabaseComment.getInstance().getFields();
+ List fields = DatabaseComment.getInstance().getFieldNames();
responseData.put("new", Boolean.TRUE);
- comment = new HashMap();
+ Map emptyComment = new HashMap();
Iterator i = fields.iterator();
while (i.hasNext()) {
- comment.put(i.next(), null);
+ emptyComment.put(i.next(), null);
}
+
+ comment = emptyComment;
}
responseData.put("comment", comment);
}
}
- public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String mediaIdParam = aRequest.getParameter("mid");
String commentId = aRequest.getParameter("commentid");
- if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
+ if (commentId == null || mediaIdParam==null) {
+ throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
+ }
try {
EntityComment comment = (EntityComment) mainModule.getById(commentId);
editObject(aRequest, aResponse, commentId);
}
- public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String commentId = aRequest.getParameter("commentid");
String midParam = aRequest.getParameter("mid");
- if (commentId == null)
+ if (commentId == null) {
throw new ServletModuleExc("smod comment :: dettach :: commentid missing");
- if (midParam == null)
+ }
+ if (midParam == null) {
throw new ServletModuleExc("smod comment :: dettach :: mid missing");
+ }
try {
EntityComment comment = (EntityComment)mainModule.getById(commentId);
String searchStatus = requestParser.getParameter("searchstatus");
String searchOrder = requestParser.getParameter("searchorder");
- if (searchIsPublished.equals("0")) {
+ if ("0".equals(searchIsPublished)) {
queryBuilder.appendAndCondition("is_published='f'");
}
- else if (searchIsPublished.equals("1")) {
+ else if ("1".equals(searchIsPublished)) {
queryBuilder.appendAndCondition("is_published='t'");
}
}
if (searchOrder.length()>0) {
- if (searchOrder.equals("datedesc"))
+ if ("datedesc".equals(searchOrder)) {
queryBuilder.appendDescendingOrder("webdb_create");
- else if (searchOrder.equals("dateasc"))
+ }
+ else if ("dateasc".equals(searchOrder)) {
queryBuilder.appendAscendingOrder("webdb_create");
- else if (searchOrder.equals("articletitle"))
+ }
+ else if ("articletitle".equals(searchOrder)) {
queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");
- else if (searchOrder.equals("creator"))
+ }
+ else if ("creator".equals(searchOrder)) {
queryBuilder.appendDescendingOrder("creator");
+ }
}
returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
}
- public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String articleIdString = aRequest.getParameter("articleid");
- int articleId;
-
try {
- articleId = Integer.parseInt(articleIdString);
+ int articleId = Integer.parseInt(articleIdString);
returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0);
}
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
URLBuilder urlBuilder = new URLBuilder();
- int count;
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- Object commentList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,
- MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset)
- );
+ List commentList =
+ EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause,
+ anOrderByClause, nrEntitiesPerListPage, anOffset);
responseData.put("nexturl", null);
responseData.put("prevurl", null);
- count=mainModule.getSize(aWhereClause);
-
urlBuilder.setValue("module", "Comment");
urlBuilder.setValue("do", "list");
urlBuilder.setValue("where", aWhereClause);
responseData.put("searchorder", requestParser.getParameter("searchorder"));
urlBuilder.setValue("offset", anOffset);
- responseData.put("offset" , new Integer(anOffset).toString());
+ responseData.put("offset" , Integer.toString(anOffset));
responseData.put("thisurl" , urlBuilder.getQuery());
- if (count>=anOffset+nrEntitiesPerListPage) {
+ if (commentList.size()>=nrEntitiesPerListPage) {
urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
responseData.put("nexturl" , urlBuilder.getQuery());
}
responseData.put("comments", commentList);
responseData.put("from" , Integer.toString(anOffset+1));
- responseData.put("count", Integer.toString(count));
- responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+ responseData.put("to", Integer.toString(anOffset+commentList.size()-1));
ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
}
String returnUrl = requestParser.getParameter("returnurl");
String idParam = aRequest.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("Wrong call: (id) is missing");
+ }
Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance());
- if (!withValues.containsKey("is_published"))
+ if (!withValues.containsKey("is_published")) {
withValues.put("is_published","0");
- if (!withValues.containsKey("is_html"))
+ }
+ if (!withValues.containsKey("is_html")) {
withValues.put("is_html","0");
+ }
String webdbCreate = (String) withValues.get("webdb_create");
- if (webdbCreate==null || webdbCreate.trim().length()==0)
+ if (webdbCreate==null || webdbCreate.trim().length()==0) {
withValues.remove("webdb_create");
+ }
String id = mainModule.set(withValues);
if (returnUrl!=null){
ServletHelper.redirect(aResponse, returnUrl);
}
- else
+ else {
editObject(aRequest, aResponse, idParam);
+ }
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleCommentStatus;
-public class ServletModuleCommentStatus extends ServletModule
-{
- private static ServletModuleCommentStatus instance = new ServletModuleCommentStatus();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleCommentStatus() {
- logger = new LoggerWrapper("ServletModule.CommentStatus");
-
- try {
- definition = "commentStatus";
- mainModule = new ModuleCommentStatus();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleCommentStatus failed!: " + e.getMessage());
- }
+public class ServletModuleCommentStatus extends AdminServletModule {
+ public ServletModuleCommentStatus() {
+ definition = "commentStatus";
+ mainModule = new ModuleCommentStatus();
}
}
package mircoders.servlet;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerWrapper;
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.generator.Generator;
import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
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.StringRoutines;
import mir.util.URLBuilder;
-import mir.generator.Generator;
-import mircoders.entity.*;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityUsers;
import mircoders.global.MirGlobal;
import mircoders.module.ModuleContent;
import mircoders.storage.DatabaseContent;
import mircoders.storage.DatabaseContentToTopics;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
/**
* Article admin interface code
*/
-public class ServletModuleContent extends ServletModule
-{
- private static ServletModuleContent instance = new ServletModuleContent();
- public static ServletModule getInstance() { return instance; }
- private static ModuleContent contentModule;
-
- private ServletModuleContent() {
- super();
+public class ServletModuleContent extends AdminServletModule {
+ private ModuleContent contentModule = new ModuleContent();
- logger = new LoggerWrapper("ServletModule.Content");
+ public ServletModuleContent() {
+ addPropagatedParameter("selectarticleurl");
+ addPropagatedParameter("searchtopic");
+ addPropagatedParameter("searchvalue");
+ addPropagatedParameter("searcharticletype");
- try {
- contentModule = new ModuleContent();
- mainModule = contentModule;
- }
- 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");
-
- returnList(aRequest, aResponse, where, order, offset, selectArticleUrl);
+ definition = "content";
+ mainModule = contentModule;
}
public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
try {
+ String extraTables = "";
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
String searchField = requestParser.getParameterWithDefault("searchfield", "");
String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
- String selectArticleUrl = requestParser.getParameter("selectarticleurl");
+ String searchTopic = requestParser.getParameterWithDefault("searchtopic", "");
if (searchValue.length()>0) {
- if (searchField.equals("id"))
+ if ("id".equals(searchField)) {
queryBuilder.appendAndCondition(
"id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
- else if (searchField.equals("contents"))
+ }
+ else if ("contents".equals(searchField)) {
queryBuilder.appendAndCondition(
"(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
" or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
- else
+ }
+ else {
queryBuilder.appendAndCondition(
"lower("+ searchField + ") like " +
"'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
+ }
}
if (searchispublished.length()>0) {
- if (searchispublished.equals("0"))
+ if ("0".equals(searchispublished)) {
queryBuilder.appendAndCondition("is_published='f'");
- else
+ }
+ else {
queryBuilder.appendAndCondition("is_published='t'");
+ }
}
if (searchArticleType.length()>0) {
}
if (searchOrder.length()>0) {
- if (searchOrder.equals("datedesc"))
+ if ("datedesc".equals(searchOrder)) {
queryBuilder.appendDescendingOrder("webdb_create");
- else if (searchOrder.equals("dateasc"))
+ }
+ else if ("dateasc".equals(searchOrder)) {
queryBuilder.appendAscendingOrder("webdb_create");
- else if (searchOrder.equals("title"))
+ }
+ else if ("title".equals(searchOrder)) {
queryBuilder.appendAscendingOrder("title");
- else if (searchOrder.equals("creator"))
+ }
+ else if ("creator".equals(searchOrder)) {
queryBuilder.appendAscendingOrder("creator");
+ }
}
- returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
+ if (searchTopic.length() > 0) {
+ queryBuilder.appendAndCondition("cxt.content_id = id");
+ queryBuilder.appendAndCondition("cxt.topic_id = " + JDBCStringRoutines.escapeStringLiteral(searchTopic));
+
+ extraTables = "content_x_topic cxt";
+ }
+
+ returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0,
+ Collections.EMPTY_MAP, null, extraTables);
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
withValues.put("publish_path", StringUtil.webdbDate2path(now));
withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
withValues.put("is_produced", "0");
- if (!withValues.containsKey("is_published"))
+ if (!withValues.containsKey("is_published")) {
withValues.put("is_published","0");
- if (!withValues.containsKey("is_html"))
+ }
+ if (!withValues.containsKey("is_html")) {
withValues.put("is_html","0");
+ }
String webdbCreate = (String) withValues.get("webdb_create");
- if (webdbCreate==null || webdbCreate.trim().length()==0)
+ if (webdbCreate==null || webdbCreate.trim().length()==0) {
withValues.remove("webdb_create");
+ }
String id = mainModule.add(withValues);
logAdminUsage(aRequest, id, "object added");
/**
* Attaches media to an article
- *
*/
public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String mediaIdParam = aRequest.getParameter("mid");
String articleId = aRequest.getParameter("articleid");
-
- if (articleId == null || mediaIdParam==null)
+ if (articleId == null || mediaIdParam==null) {
throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
+ }
- if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId))
+ // check if mediaIdParam and articleid are correct integers
+ try {
+ Integer.parseInt(mediaIdParam);
+ Integer.parseInt(articleId);
+ }
+ catch (NumberFormatException e) {
+ throw new ServletModuleExc("smod content :: attach :: invalid articleid/mid", e);
+ }
+
+ if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) {
throw new ServletModuleExc("Article has been locked");
+ }
try {
EntityContent entContent = (EntityContent) mainModule.getById(articleId);
/**
* Deattaches media from an article
*/
- public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String articleId = aRequest.getParameter("articleid");
String midParam = aRequest.getParameter("mid");
if (articleId == null)
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String idParam = requestParser.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("Wrong call: (id) is missing");
+ }
EntityUsers user = ServletHelper.getUser(aRequest);
- if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam))
+ if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) {
throw new ServletModuleExc("Unable to lock");
+ }
contentModule.lockArticle(idParam, user.getId(), false);
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String idParam = requestParser.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("Wrong call: (id) is missing");
+ }
EntityUsers user = ServletHelper.getUser(aRequest);
- if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam))
+ if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) {
throw new ServletModuleExc("Unable to unlock");
+ }
contentModule.unlockArticle(idParam, user.getId(), false);
/**
* Forcelocks an article
*/
- public void forcelock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void forcelock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String idParam = requestParser.getParameter("id");
/**
* Stores an article
*/
- public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String idParam = requestParser.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("Wrong call: (id) is missing");
+ }
- if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam))
+ if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) {
throw new ServletModuleExc("Article has been locked");
+ }
Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
withValues.put("is_produced", "0");
- if (!withValues.containsKey("is_published"))
+ if (!withValues.containsKey("is_published")) {
withValues.put("is_published","0");
- if (!withValues.containsKey("is_html"))
+ }
+ if (!withValues.containsKey("is_html")) {
withValues.put("is_html","0");
+ }
String webdbCreate = (String) withValues.get("webdb_create");
- if (webdbCreate==null || webdbCreate.trim().length()==0)
+ if (webdbCreate==null || webdbCreate.trim().length()==0) {
withValues.remove("webdb_create");
+ }
String id = mainModule.set(withValues);
DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) &&
- (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) {
+ requestParser.getParameterWithDefault("unlock", "0").equals("1")) {
contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false);
}
/**
* Returns the basic article editing form.
*
- * @param id identifier of the article. <code>null</code>, means show an
+ * @param anId identifier of the article. <code>null</code>, means show an
* empty form to add a new article.
*/
- public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)
- throws ServletModuleExc {
+ public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String anId) throws ServletModuleExc {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
- Map article;
+ Object article;
URLBuilder urlBuilder = new URLBuilder();
urlBuilder.setValue("module", "Content");
urlBuilder.setValue("do", "edit");
- urlBuilder.setValue("id", id);
+ urlBuilder.setValue("id", anId);
urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
- if (id!=null) {
+ if (anId !=null) {
responseData.put("new", Boolean.FALSE);
- article = model.makeEntityAdapter("content", mainModule.getById(id));
+ article = model.makeEntityAdapter("content", mainModule.getById(anId));
EntityUsers user = ServletHelper.getUser(aRequest);
- responseData.put("mayEdit", new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, id)));
- responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, id)));
- responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, id)));
- responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, id)));
+ responseData.put("mayEdit",
+ new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, anId)));
+ responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, anId)));
+ responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, anId)));
+ responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, anId)));
}
else {
- List fields = DatabaseContent.getInstance().getFields();
+ List fields = DatabaseContent.getInstance().getFieldNames();
responseData.put("new", Boolean.TRUE);
- article = new HashMap();
+ Map emptyArticle = new HashMap();
Iterator i = fields.iterator();
while (i.hasNext()) {
- article.put(i.next(), null);
+ emptyArticle.put(i.next(), null);
}
- article.put("to_topics", null);
+ emptyArticle.put("to_topics", null);
- MirGlobal.localizer().adminInterface().initializeArticle(article);
+ MirGlobal.localizer().adminInterface().initializeArticle(emptyArticle);
+ article = emptyArticle;
responseData.put("mayEdit", Boolean.TRUE);
responseData.put("mayLock", Boolean.FALSE);
responseData.put("mayForceLock", Boolean.FALSE);
responseData.put("mayUnlock", Boolean.FALSE);
+
}
responseData.put("article", article);
- List topicsList = new Vector();
+ List topicsList = new ArrayList();
- String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");
+ String[] topicCategories = getConfiguration().getStringArray("Mir.Localizer.Admin.TopicLists");
if (topicCategories.length==0 ) {
Map categoryMap = new HashMap();
categoryMap.put("key", "topic");
categoryMap.put("listtype", "0");
categoryMap.put("listparameter", "3");
- categoryMap.put("items",
- new EntityIteratorAdapter("", "title",
- 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+ categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", "", "title", -1, 0));
topicsList.add(categoryMap);
}
- else
- {
-
+ else {
for (int i = 0; i < topicCategories.length; i++) {
- try {
- Map categoryMap = new HashMap();
- List parts = StringRoutines.splitString(topicCategories[i], ":");
- String key = null;
- String listtype = "0";
- String listparameter = "5";
- String where = "";
- String order = "";
-
- if (parts.size() > 0)
- key = (String) parts.get(0);
- if (parts.size() > 1)
- listtype = (String) parts.get(1);
- if (parts.size() > 2)
- listparameter = (String) parts.get(2);
- if (parts.size() > 3)
- where = (String) parts.get(3);
- if (parts.size() > 4)
- order = (String) parts.get(4);
-
- if (key != null) {
- categoryMap.put("key", key);
- categoryMap.put("listtype", listtype);
- categoryMap.put("listparameter", listparameter);
- categoryMap.put("items",
- new EntityIteratorAdapter(where, order,
- 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
- topicsList.add(categoryMap);
- }
+ Map categoryMap = new HashMap();
+ List parts = StringRoutines.splitString(topicCategories[i], ":");
+
+ String key = null;
+
+ if (parts.size() > 0) {
+ key = (String) parts.get(0);
+ }
+ String listtype = "0";
+ if (parts.size() > 1) {
+ listtype = (String) parts.get(1);
+ }
+ String listparameter = "5";
+ if (parts.size() > 2) {
+ listparameter = (String) parts.get(2);
}
- catch (Throwable t) {
- logger.error("error while preparing topics: " + t.toString());
+ String where = "";
+ if (parts.size() > 3) {
+ where = (String) parts.get(3);
+ }
+ String order = "";
+ if (parts.size() > 4) {
+ order = (String) parts.get(4);
+ }
+
+ if (key != null) {
+ categoryMap.put("key", key);
+ categoryMap.put("listtype", listtype);
+ categoryMap.put("listparameter", listparameter);
+ categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
+ topicsList.add(categoryMap);
}
}
}
}
}
- public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,
- String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
- this.returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, null);
- }
-
- public void returnList(
- HttpServletRequest aRequest,
- HttpServletResponse aResponse,
- String aWhereClause,
- String anOrderByClause,
- int anOffset,
- String aSelectArticleUrl) throws ServletModuleExc {
-
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- URLBuilder urlBuilder = new URLBuilder();
- int count;
-
- try {
- Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- Object articleList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,
- MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, 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+nrEntitiesPerListPage) {
- urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));
- responseData.put("nexturl" , urlBuilder.getQuery());
- }
-
- if (anOffset>0) {
- urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 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+nrEntitiesPerListPage, count)));
- responseData.put("offset" , Integer.toString(anOffset));
- responseData.put("order", anOrderByClause);
- responseData.put("where" , aWhereClause);
-
- ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
-
- public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
URLBuilder urlBuilder = new URLBuilder();
urlBuilder.setValue("childid", requestParser.getParameter("id"));
urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
- returnList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
+ returnList(aRequest, aResponse, "", "", 0,
+ Collections.singletonMap("selectarticleurl", 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");
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ String articleId = requestParser.getParameter("article_id");
- if (articleId == null)
- throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+ if (articleId == null) {
+ throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+ }
- returnList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
+ try {
+ returnList(aRequest, aResponse, "to_content = " + articleId, "webdb_create desc", 0);
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
}
}
- public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String articleId = requestParser.getParameter("childid");
String parentId = requestParser.getParameter("id");
logAdminUsage(aRequest, articleId, "parent set to " + parentId);
}
catch(Throwable e) {
- logger.error("ServletModuleContent.setparent: " + e.getMessage());
+ getLogger().error("ServletModuleContent.setparent: " + e.getMessage());
+
throw new ServletModuleFailure(e);
}
ServletHelper.redirect(aResponse, returnUrl);
}
- public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ 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.setFieldValue("to_content", "");
+ article.setFieldValue("to_content", null);
article.setProduced(false);
article.update();
logAdminUsage(aRequest, articleId, "parent cleared");
}
catch(Throwable e) {
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- logger.error("ServletModuleContent.clearparent: " + e.getMessage());
+ getLogger().error("ServletModuleContent.clearparent: " + e.getMessage(), e);
throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
}
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String articleId = requestParser.getParameter("id");
- EntityAdapter article = model.makeEntityAdapter("content", mainModule.getById(articleId));
+ EntityAdapter article = getModel().makeEntityAdapter("content", mainModule.getById(articleId));
String preview = requestParser.getParameterWithDefault("preview", "default");
Map generationValues = new HashMap();
Generator generator =
MirGlobal.localizer().adminInterface().prepareArticlePreview(preview, article, generationValues);
- generator.generate(aResponse.getWriter(), generationValues, logger);
+ generator.generate(aResponse.getWriter(), generationValues, getLogger());
}
catch (Exception e) {
throw new ServletModuleFailure(e);
package mircoders.servlet;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.FilenameFilter;
-import java.io.StringWriter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-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.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
-import mir.util.FileFunctions;
+import mir.util.FileRoutines;
import mir.util.HTTPRequestParser;
import mir.util.StringRoutines;
import mir.util.URLBuilder;
+import mir.changetracker.ChangeType;
+import mircoders.global.MirGlobal;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.util.*;
/*
* ServletModuleFileEdit -
* in the config file.
*
* @author $Author: idfx $
- * @version $Revision: 1.15 $ $Date: 2004/11/06 20:09:12 $
+ * @version $Revision: 1.16 $ $Date: 2007/04/08 21:46:43 $
*
*/
-public class ServletModuleFileEdit extends ServletModule
-{
- private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
- public static ServletModule getInstance() { return instance; }
-
+public class ServletModuleFileEdit extends AdminServletModule {
private Map directories;
private List directoryNames;
private FilenameFilter dirFilter;
- private class FileEditDirectory {
- private String name;
- private FileFunctions.RegExpFileFilter filter;
- private File rootDirectory;
- private boolean recursive;
-
- public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
- name = aName;
- rootDirectory = new File(aRootDirectory);
- filter = new FileFunctions.RegExpFileFilter(aFilter);
- recursive = aRecursive;
- }
-
- public String getName() {
- return name;
- }
-
- public FileFunctions.RegExpFileFilter getFilter() {
- return filter;
- }
-
- public File getRootDirectory() {
- return rootDirectory;
- }
-
- public boolean getRecursive() {
- return recursive;
- }
- }
-
- private ServletModuleFileEdit() {
- super();
-
- logger = new LoggerWrapper("ServletModule.FileEdit");
-
+ public ServletModuleFileEdit() {
directories = new HashMap();
- directoryNames = new Vector();
+ directoryNames = new ArrayList();
- String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
+ String settings[] =
+ getConfiguration().getStringArray("ServletModule.FileEdit.Configuration");
if (settings!=null) {
for (int i = 0; i < settings.length; i++) {
if (setting.length() > 0) {
List parts = StringRoutines.splitStringWithEscape(setting, ':', '\\');
if (parts.size() != 4) {
- logger.error("config error: " + settings[i] + ", 4 parts expected");
+ getLogger().error("config error: " + settings[i] + ", 4 parts expected");
}
else {
String name = (String) parts.get(0);
String recursive = (String) parts.get(3);
directories.put(name, new FileEditDirectory(name, directory, filter,
- recursive.equals("1") || recursive.toLowerCase().equals("y")));
+ "1".equals(recursive) || "y".equals(recursive.toLowerCase())));
directoryNames.add(name);
}
}
}
}
- dirFilter = new FileFunctions.DirectoryFilter();
+ dirFilter = new FileRoutines.DirectoryFilter();
}
public List getEntries() {
return result;
}
- public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
}
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
/**
* Called when an edited file is saved by the user
*/
- public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String filename = requestParser.getParameter("filename");
String subDirectory = requestParser.getParameter("subdirectory");
try {
File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
- if (validateDirectory(directory, f)) {
+ if (isDirectoryValid(directory, f)) {
FileWriter out = new FileWriter(f);
try {
out.write(text.toCharArray());
}
logAdminUsage(aRequest, f.getAbsolutePath(), "object modified");
-/*
- MirGlobal.getChangeEngine().getTracker().addChange(f.getCanonicalPath());
-*/
+
+ MirGlobal.getChangeEngine().getTracker().addChange(f.getCanonicalPath(), ChangeType.MODIFICATION);
+
editFile(directory, filename, subDirectory, aRequest, aResponse);
}
}
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
- if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
+ if (!isDirectoryValid(aDirectory, dir) || !dir.isDirectory()) {
dir = aDirectory.getRootDirectory();
aSubDirectory = "";
}
- responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
+ responseData.put("filelist", FileRoutines.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
if (aDirectory.getRecursive()) {
- List dirs = new Vector();
+ List dirs = new ArrayList();
if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
responseData.put("updir", new File(aSubDirectory).getParent());
- dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter));
+ dirs.addAll(FileRoutines.getDirectoryContentsAsList(dir, dirFilter));
responseData.put("dirlist", dirs);
}
}
}
- public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
try {
File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
- if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
+ if (!isDirectoryValid(aDirectory, f) || f.isDirectory() || !isFileValid(aDirectory, f)) {
listSubDirectory(aDirectory, "", aRequest, aResponse);
}
else {
// TODO read array
char[] c = new char[4096];
- int read;;
- while ( (read=in.read(c)) != -1)
+ int read;
+ while ((read=in.read(c)) != -1) {
out.write(c, 0, read);
+ }
in.close();
out.close();
}
}
- protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
+ private boolean isDirectoryValid(FileEditDirectory aDirectory, File aFile) {
try {
- return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
+ return aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath());
}
catch (Throwable t) {
return false;
}
}
- protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
+ private boolean isFileValid(FileEditDirectory aDirectory, File aFile) {
try {
return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
}
return false;
}
}
+
+ private class FileEditDirectory {
+ private String name;
+ private FileRoutines.RegExpFileFilter filter;
+ private File rootDirectory;
+ private boolean recursive;
+
+ public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
+ name = aName;
+ rootDirectory = new File(aRootDirectory);
+ filter = new FileRoutines.RegExpFileFilter(aFilter);
+ recursive = aRecursive;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public FileRoutines.RegExpFileFilter getFilter() {
+ return filter;
+ }
+
+ public File getRootDirectory() {
+ return rootDirectory;
+ }
+
+ public boolean getRecursive() {
+ return recursive;
+ }
+ }
+
}
*/
package mircoders.servlet;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.entity.adapter.EntityAdapterEngine;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
-import mir.storage.StorageObjectFailure;
-import mir.util.CachingRewindableIterator;
import mir.util.HTTPRequestParser;
import mir.util.JDBCStringRoutines;
-import mircoders.global.MirGlobal;
import mircoders.module.ModuleContent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.util.Iterator;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
* ServletModuleHidden - output of so called "censored" articles
* @author mh
* @version $Id
- *
*/
-public class ServletModuleHidden extends ServletModule
-{
- private static ServletModuleHidden instance = new ServletModuleHidden();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleHidden() {
- super();
-
- logger = new LoggerWrapper("ServletModule.Hidden");
-
- try {
- mainModule = new ModuleContent();
- }
- catch (StorageObjectFailure e) {
- logger.error("initialization of servletmoduleHidden failed: " + e.getMessage());
- }
+public class ServletModuleHidden extends AdminServletModule {
+ public ServletModuleHidden() {
+ definition = "content";
+ mainModule = new ModuleContent();
}
- public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
- {
-// determine parameter
- HTTPRequestParser requestParser = new HTTPRequestParser(req);
- Map responseData = ServletHelper.makeGenerationData(req, res, new Locale[] { getLocale(req), getFallbackLocale(req)});
+ public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- String query_year = requestParser.getParameter("year");
- String query_month = requestParser.getParameter("month");
+ String queryYear = requestParser.getParameter("year");
+ String queryMonth = requestParser.getParameter("month");
try {
- if ((query_year!=null && !query_year.equals("")) && (query_month!=null && !query_month.equals(""))) {
+ if ((queryYear !=null && !queryYear.equals("")) &&
+ (queryMonth !=null && !queryMonth.equals(""))) {
String whereClause = "is_published=false AND webdb_create LIKE "+
- "'"+JDBCStringRoutines.escapeStringLiteral(query_year)+"-"+JDBCStringRoutines.escapeStringLiteral(query_month)+"%'";
+ "'"+JDBCStringRoutines.escapeStringLiteral(queryYear)+"-"+
+ JDBCStringRoutines.escapeStringLiteral(queryMonth)+"%'";
+
- Iterator articleList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter( whereClause, "webdb_create", 100,
- MirGlobal.localizer().dataModel().adapterModel(), "content", -1, 0)
- );
+ List articleList = EntityAdapterEngine.retrieveAdapterList(getModel(), definition, whereClause, "webdb_create", -1, 0);
- responseData.put("year", query_year);
- responseData.put("month", query_month);
+ responseData.put("year", queryYear);
+ responseData.put("month", queryMonth);
responseData.put("articles", articleList);
}
- ServletHelper.generateResponse(res.getWriter(), responseData, listGenerator);
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
import mircoders.module.ModuleImages;
/*
* ServletModuleImages -
*
+ * @version $Id: ServletModuleImages.java,v 1.29 2007/04/08 21:46:43 idfx Exp $
* @author RK, the mir-coders group
*/
-public class ServletModuleImages extends ServletModuleUploadedMedia
-{
- // Singelton / Kontruktor
- private static ServletModuleImages instance = new ServletModuleImages();
- public static ServletModule getInstance() { return instance; }
-
-
- private ServletModuleImages() {
- super();
- logger = new LoggerWrapper("ServletModule.Images");
- moduleName = "Images";
-
- try {
- definition = "image";
- mainModule = new ModuleImages();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleImages failed!: " + e.getMessage());
- }
+public class ServletModuleImages extends ServletModuleUploadedMedia {
+ public ServletModuleImages() {
+ super("Images");
+
+ definition = "image";
+ mainModule = new ModuleImages();
}
-
}
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleLanguage;
-/*
- * ServletModuleLanguage -
- * Servlet-Interface to Language
- *
- *
- * @author idefix
+/**
+ * ServletModule for managing languages
*/
-public class ServletModuleLanguage extends ServletModule
-{
- private static ServletModuleLanguage instance = new ServletModuleLanguage();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleLanguage() {
- super();
- logger = new LoggerWrapper("ServletModule.Language");
-
- try {
- definition = "language";
- mainModule = new ModuleLanguage();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage());
- }
+public class ServletModuleLanguage extends AdminServletModule {
+ public ServletModuleLanguage() {
+ definition = "language";
+ mainModule = new ModuleLanguage();
}
}
\ No newline at end of file
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.util.StringRoutines;
import mircoders.entity.EntityComment;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
-public class ServletModuleLocalizer extends ServletModule {
- private static ServletModuleLocalizer instance = new ServletModuleLocalizer();
- public static ServletModule getInstance() { return instance; }
+public class ServletModuleLocalizer extends AdminServletModule {
+ private final ModuleContent contentModule = new ModuleContent();
+ private final ModuleComment commentModule = new ModuleComment();
+ private final List administerOperations = new ArrayList();
- private ModuleContent contentModule;
- private ModuleComment commentModule;
- private List administerOperations;
-
- private ServletModuleLocalizer() {
+ public ServletModuleLocalizer() {
try {
- logger = new LoggerWrapper("ServletModule.Localizer");
-
- contentModule = new ModuleContent();
- commentModule = new ModuleComment();
-
- administerOperations = new Vector();
-
- String settings[] = configuration.getStringArray("Mir.Localizer.Admin.AdministerOperations");
+ String settings[] =
+ getConfiguration().getStringArray("Mir.Localizer.Admin.AdministerOperations");
if (settings!=null) {
for (int i = 0; i < settings.length; i++) {
if (setting.length() > 0) {
List parts = StringRoutines.splitString(setting, ":");
if (parts.size() != 2) {
- logger.error("config error: " + settings[i] + ", 2 parts expected");
+ getLogger().error("config error: " + settings[i] + ", 2 parts expected");
}
else {
Map entry = new HashMap();
}
}
catch (Exception e) {
- logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage());
+ getLogger().error("ServletModuleLocalizer could not be initialized" + e.getMessage(), e);
}
}
* @param anOperation The identifier of the operation to perform
*/
public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) {
- EntityComment entity;
-
try {
- entity = (EntityComment) commentModule.getById(anId);
+ EntityComment entity = (EntityComment) commentModule.getById(anId);
if (entity != null) {
MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation);
- logger.info("Operation " + anOperation + " successfully performed on comment " + anId);
+ getLogger().debug("Operation " + anOperation + " successfully performed on comment " + anId);
logAdminUsage(aRequest, "comment."+anId, "operation " + anOperation + " performed");
}
else {
- logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");
+ getLogger().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());
+ getLogger().error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage(), e);
}
}
ServletHelper.redirect(aResponse, returnUrlString);
}
+ public void operation(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ String type = aRequest.getParameter("objecttype");
+ String id = aRequest.getParameter("id");
+ String operation = aRequest.getParameter("operation");
+ String returnUrl = aRequest.getParameter("returnurl");
+
+
+ if ("comment".equals(type)) {
+ performCommentOperation(aRequest, id, operation);
+ }
+ else {
+ performArticleOperation(aRequest, id, operation);
+ }
+
+ ServletHelper.redirect(aResponse, returnUrl);
+ }
+
public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String returnUrlString = aRequest.getParameter("returnurl");
List parts = StringRoutines.splitString(operations[i], ";");
if (parts.size() != 2) {
- logger.error("commentoperationbatch: operation string invalid: " +
+ getLogger().error("commentoperationbatch: operation string invalid: " +
operations[i]);
}
else {
ServletHelper.redirect(aResponse, returnUrlString);
}
+ public void operationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ String returnUrlString = aRequest.getParameter("returnurl");
+
+ String[] operations = aRequest.getParameterValues("operation");
+
+ if (operations!=null) {
+ for (int i = 0; i < operations.length; i++) {
+ if (operations[i].length() > 0) {
+ List parts = StringRoutines.splitString(operations[i], ";");
+
+ if (parts.size() != 3) {
+ getLogger().error("commentoperationbatch: operation string invalid: " +
+ operations[i]);
+ }
+ else {
+ String type = (String) parts.get(0);
+ String id = (String) parts.get(1);
+ String operationString = (String) parts.get(2);
+
+ if ("comment".equals(type)) {
+ performCommentOperation(aRequest, id, operationString);
+ }
+ else {
+ performArticleOperation(aRequest, id, operationString);
+ }
+ }
+ }
+ }
+ }
+
+ ServletHelper.redirect(aResponse, returnUrlString);
+ }
public void performArticleOperation(HttpServletRequest aRequest, String anId, String anOperation) {
EntityContent entity;
if (entity != null) {
MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation);
- logger.info("Operation " + anOperation + " successfully performed on article " + anId);
+ getLogger().info("Operation " + anOperation + " successfully performed on article " + anId);
logAdminUsage(aRequest, "article." + anId, "operation " + anOperation + " performed");
}
else {
- logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null");
+ getLogger().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());
+ getLogger().error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
}
}
List parts = StringRoutines.splitString(operations[i], ";");
if (parts.size() != 2) {
- logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
+ getLogger().error("articleoperationbatch: operation string invalid: " + operations[i]);
}
else {
String articleIdString = (String) parts.get(0);
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleMediaType;
-import mircoders.storage.DatabaseMediaType;
-public class ServletModuleMediaType extends ServletModule
-{
- private static ServletModuleMediaType instance = new ServletModuleMediaType();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleMediaType() {
- logger = new LoggerWrapper("ServletModule.MediaType");
-
- try {
- definition = "mediaType";
- mainModule = new ModuleMediaType();
- }
- catch (Exception e) {
- logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
- }
+public class ServletModuleMediaType extends AdminServletModule {
+ public ServletModuleMediaType() {
+ definition = "mediaType";
+ mainModule = new ModuleMediaType();
}
}
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
-import mircoders.module.ModuleMediafolder;
-import mircoders.storage.DatabaseMediafolder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import java.util.GregorianCalendar;
import java.util.Map;
-/**
- *
- */
-public class ServletModuleMediafolder extends ServletModule
-{
- public static ServletModule getInstance() { return instance; }
- private static ServletModuleMediafolder instance = new ServletModuleMediafolder();
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
- private ServletModuleMediafolder() {
- super();
- logger = new LoggerWrapper("ServletModule.Mediafolder");
+import mir.misc.StringUtil;
+import mir.servlet.AdminServletModule;
+import mircoders.module.ModuleMediafolder;
- try {
- definition = "mediaFolder";
- mainModule = new ModuleMediafolder();
- }
- catch (Throwable t) {
- logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString());
- }
+public class ServletModuleMediafolder extends AdminServletModule {
+ public ServletModuleMediafolder() {
+ definition = "mediaFolder";
+ mainModule = new ModuleMediafolder();
}
protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleMessage;
-import mircoders.storage.DatabaseMessages;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
-/**
- * Title: ServletModuleMessage
- * Description:
- * Copyright: Copyright (c) 2001-2002
- * Company: mir-coders
- * @author
- * @version 1.0
- */
-
-
-public class ServletModuleMessage extends ServletModule
-{
- private static ServletModuleMessage instance = new ServletModuleMessage();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleMessage() {
- super();
- logger = new LoggerWrapper("ServletModule.Messages");
-
- try {
- definition = "internalMessage";
- mainModule = new ModuleMessage();
- }
- catch (Throwable e) {
- logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());
-
- throw new ServletModuleFailure(e);
- }
+public class ServletModuleMessage extends AdminServletModule {
+ public ServletModuleMessage() {
+ definition = "internalMessage";
+ mainModule = new ModuleMessage();
}
protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
import gnu.regexp.RE;
import gnu.regexp.REMatch;
import mir.bundle.Bundle;
-import mir.entity.Entity;
import mir.generator.Generator;
-import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.servlet.ServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.servlet.ServletModuleUserExc;
-import mir.session.*;
-import mir.storage.StorageObjectFailure;
-import mir.util.*;
-import mircoders.entity.EntityComment;
+import mir.session.HTTPAdapters;
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionHandler;
+import mir.session.SimpleResponse;
+import mir.util.FileRoutines;
+import mir.util.HTTPParsedRequest;
+import mir.util.HTTPRequestParser;
+import mir.util.StringRoutines;
+import mir.module.ModuleExc;
import mircoders.entity.EntityContent;
import mircoders.global.CacheKey;
import mircoders.global.MirGlobal;
-import mircoders.media.MediaUploadProcessor;
-import mircoders.module.ModuleComment;
import mircoders.module.ModuleContent;
-import mircoders.module.ModuleMediaType;
import mircoders.pdf.PDFGenerator;
-import mircoders.search.*;
-import mircoders.storage.*;
-import org.apache.commons.fileupload.FileItem;
+import mircoders.search.AudioSearchTerm;
+import mircoders.search.ContentSearchTerm;
+import mircoders.search.ImagesSearchTerm;
+import mircoders.search.KeywordSearchTerm;
+import mircoders.search.TextSearchTerm;
+import mircoders.search.TopicMatrixSearchTerm;
+import mircoders.search.TopicSearchTerm;
+import mircoders.search.UnIndexedSearchTerm;
+import mircoders.search.VideoSearchTerm;
+import mircoders.storage.DatabaseTopics;
+import mircoders.localizer.MirLocalizerExc;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
-import org.apache.lucene.index.IndexReader;
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.lucene.store.FSDirectory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
-import java.io.*;
-import java.util.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+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.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
/*
- * ServletModuleOpenIndy -
- * is the open-access-servlet, which is responsible for
- * adding comments to articles &
- * open-postings to the newswire
- *
- * @author mir-coders group
- *
*/
-public class ServletModuleOpenIndy extends ServletModule
-{
-
- private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
- private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
+public class ServletModuleOpenIndy extends ServletModule {
private String searchResultsTemplate;
private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
private ModuleContent contentModule;
- private ModuleComment commentModule;
- private String directOp ="yes";
- private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
- public static ServletModule getInstance() {
- return instance;
- }
+ public ServletModuleOpenIndy() {
+ searchResultsTemplate = getConfiguration().getString("ServletModule.OpenIndy.SearchResultsTemplate");
+ prepareMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.PrepareMailTemplate");
+ emailAnArticleTemplate = getConfiguration().getString("ServletModule.OpenIndy.MailableArticleTemplate");
+ sentMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.SentMailTemplate");
- 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");
- emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
- sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
- directOp = configuration.getString("DirectOpenposting").toLowerCase();
- commentModule = new ModuleComment();
- mainModule = commentModule;
- contentModule = new ModuleContent();
- defaultAction = "defaultAction";
- }
- catch (StorageObjectFailure e) {
- logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
- }
+ contentModule = new ModuleContent();
}
/**
* @throws ServletModuleFailure
*/
public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- deliver(aRequest, aResponse, 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
-
- if (aid != null && !aid.equals("")) {
- try {
- Map mergeData = new HashMap();
-
- // onetimepasswd
- if (MirGlobal.abuse().getOpenPostingPassword()) {
- String passwd = generateOnetimePassword();
- HttpSession session = req.getSession(false);
- session.setAttribute("passwd", passwd);
- mergeData.put("passwd", passwd);
- }
- else {
- mergeData.put("passwd", null);
- }
- 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");
- withValues.put("is_html", "0");
-
- //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);
-
- SimpleResponse response = new SimpleResponse();
- response.setResponseGenerator(commentFormDoneTemplate);
-
- if (id == null) {
- deliver(req, res, null, null, commentFormDupeTemplate);
- }
- else {
- DatabaseContent.getInstance().setUnproduced("id=" + aid);
-
- try {
- EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
- MirGlobal.localizer().openPostings().afterCommentPosting(comment);
- MirGlobal.abuse().checkComment(
- comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
- }
- catch (Throwable t) {
- throw new ServletModuleExc(t.getMessage());
- }
- }
-
- // redirecting to url
- // should implement back to article
- deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
- }
- 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 = generateOnetimePassword();
- HttpSession session = req.getSession(false);
- session.setAttribute("passwd", passwd);
- mergeData.put("passwd", passwd);
- }
- else {
- mergeData.put("passwd", 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", DatabaseTopics.getInstance().getPopupData());
-
- 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 aRequest, HttpServletResponse aResponse) throws
- ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- if (MirGlobal.abuse().getOpenPostingDisabled()) {
- openPostingDisabled(aRequest, aResponse);
-
- return;
- }
-
- try {
- HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
- aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir"));
-
- Map mergeData = new HashMap();
-
- HttpSession session = aRequest.getSession(false);
- String sessionPasswd = (String) session.getAttribute("passwd");
- if (sessionPasswd != null) {
- String passwd = parsedRequest.getParameter("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 (((parsedRequest.getParameter("title")).length() == 0) ||
- ((parsedRequest.getParameter("description")).length() == 0) ||
- ((parsedRequest.getParameter("content_data")).length() == 0))
- throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
-
- List mediaList = new Vector();
- Iterator i = parsedRequest.getFiles().iterator();
-
- while (i.hasNext()) {
- UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
- Map mediaValues = new HashMap();
-
- String suffix = file.getFieldName().substring(5); // media${m}
- logger.debug("media_title" + suffix);
- String title = parsedRequest.getParameter("media_title" + suffix);
-
- mediaValues.put("title", StringUtil.removeHTMLTags(title));
- mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
- mediaValues.put("to_publisher", "0");
- mediaValues.put("is_published", "1");
- mediaValues.put("to_media_folder", "7");
-
- mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
- }
-
- Map withValues = new HashMap();
- i = DatabaseContent.getInstance().getFields().iterator();
- while (i.hasNext()) {
- String field = (String) i.next();
- String value = parsedRequest.getParameter(field);
- if (value!=null)
- withValues.put(field, value);
- }
-
-
- for (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) {
- deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
- return;
- }
-
- List topics = parsedRequest.getParameterList("to_topic");
- if (topics.size() > 0) {
- try {
- DatabaseContentToTopics.getInstance().setTopics(cid, topics);
- }
- 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);
- }
- }
-
- i = mediaList.iterator();
- while (i.hasNext()) {
- Entity mediaEnt = (Entity) i.next();
- DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
- }
-
- EntityContent article = (EntityContent) contentModule.getById(cid);
- try {
- MirGlobal.abuse().checkArticle(
- article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
- MirGlobal.localizer().openPostings().afterContentPosting(article);
- }
- catch (Throwable t) {
- logger.error("Error while post-processing article: " + t.getMessage());
- }
- deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
- }
- catch (Throwable e) {
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- Throwable cause = ExceptionFunctions.traceCauseException(e);
-
- if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
- throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
- }
- throw new ServletModuleFailure(e);
- }
+ deliver(aRequest, aResponse, null, null, getConfiguration().getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
}
/**
String requestLanguage = aRequest.getParameter("language");
String sessionLanguage = (String) aSession.getAttribute("language");
String acceptLanguage = aRequest.getLocale().getLanguage();
- String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
+ String defaultLanguage = getConfiguration().getString("Mir.Login.DefaultLanguage", "en");
String language = requestLanguage;
try {
Request request =
new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir")));
+ getConfiguration().getString("Mir.DefaultEncoding"),
+ getConfiguration().getInt("MaxMediaUploadSize")*1024,
+ getConfiguration().getString("TempDir")));
if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
- !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
+ !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY))) {
aRequest.getSession().invalidate();
+ }
Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
SimpleResponse response = new SimpleResponse(
- ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
+ ServletHelper.makeGenerationData(aRequest, aResponse,
+ new Locale[] {
+ getResponseLocale(aRequest.getSession(), aRequest),
+ getFallbackLocale(aRequest)
+ },
"etc/bundles/open"));
response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
}
catch (Throwable t) {
- logger.error(t.toString());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ getLogger().error(t.toString(), t);
throw new ServletModuleFailure(t);
}
/**
* Method for preparing and sending a content as an email message
*/
- public void mail(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
- {
- String aid = req.getParameter("mail_aid");
+ public void mail(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ String aid = aRequest.getParameter("mail_aid");
if (aid == null){
- throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
+ throw new ServletModuleExc("An article id must be specified in requests " +
+ "to email an article. Something therefore went badly wrong....");
}
- String to = req.getParameter("mail_to");
- String from = req.getParameter("mail_from");
- String from_name = req.getParameter("mail_from_name");
- String from_ip = req.getRemoteAddr();
- String comment = req.getParameter("mail_comment");
- String mail_language = req.getParameter("mail_language");
+ String to = aRequest.getParameter("mail_to");
+ String from = aRequest.getParameter("mail_from");
+ String from_name = aRequest.getParameter("mail_from_name");
+ String from_ip = aRequest.getRemoteAddr();
+ String comment = aRequest.getParameter("mail_comment");
+ String mail_language = aRequest.getParameter("mail_language");
Map mergeData = new HashMap();
mergeData.put("mail_to",to);
if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
- deliver(req, res, mergeData, null, prepareMailTemplate);
+ deliver(aRequest, aResponse, mergeData, null, prepareMailTemplate);
}
else {
//run checks on to and from and mail_language to make sure no monkey business occurring
CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
String theEmailText;
+ EntityContent article;
+ try {
+ article = (EntityContent) contentModule.getById(aid);
+ }
+ catch (ModuleExc e) {
+ throw new ServletModuleExc("Couldn't retrieve article " + aid);
+ }
+
+ if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+ throw new ServletModuleExc("Illegal article");
+ }
+
if (MirGlobal.mruCache().hasObject(theCacheKey)){
- logger.info("fetching email text for article "+aid+" from cache");
+ getLogger().info("fetching email text for article "+aid+" from cache");
theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
}
else {
- EntityContent contentEnt;
+ StringWriter theEMailTextWriter = new StringWriter();
+ PrintWriter dest = new PrintWriter(theEMailTextWriter);
try {
- contentEnt = (EntityContent) contentModule.getById(aid);
- StringWriter theEMailTextWriter = new StringWriter();
- PrintWriter dest = new PrintWriter(theEMailTextWriter);
Map articleData = new HashMap();
- articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
+ try {
+ articleData.put("article",
+ MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", article));
+ }
+ catch (MirLocalizerExc e) {
+ throw new ServletModuleExc("Can't retrieve article " + aid, e);
+ }
articleData.put("languagecode", mail_language);
- deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
- theEmailText = theEMailTextWriter.toString();
- MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
+ deliver(dest, aRequest, aResponse, articleData, null, emailAnArticleTemplate, mail_language);
}
- catch (Throwable e) {
- throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
+ finally {
+ dest.close();
}
+ theEmailText = theEMailTextWriter.toString();
+ MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
}
String content = theEmailText;
-
// add some headers
content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
// put in the comment where it should go
SMTPClient client=new SMTPClient();
try {
int reply;
- client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
+ client.connect(getConfiguration().getString("ServletModule.OpenIndy.SMTPServer"));
reply = client.getReplyCode();
throw new ServletModuleExc("SMTP server refused connection.");
}
- client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
+ client.sendSimpleMessage(getConfiguration().getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
client.disconnect();
//mission accomplished
- deliver(req, res, mergeData, null, sentMailTemplate);
+ deliver(aRequest, aResponse, mergeData, null, sentMailTemplate);
}
catch(IOException e) {
if(client.isConnected()) {
mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
}
catch (Throwable e) {
- logger.debug("Can't get topics: " + e.toString());
+ getLogger().debug("Can't get topics: " + e.toString());
}
String searchBackValue = req.getParameter("search_back");
session.setAttribute("positionInResults", new Integer(newPosition));
}
else {
- File indexFile = FileFunctions.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
+ File indexFile = FileRoutines.getAbsoluteOrRelativeFile(getConfiguration().getHome(), getConfiguration().getString("IndexPath"));
String creatorFragment = creatorTerm.makeTerm(req);
if (creatorFragment != null) {
// the contentTerm uses param "search_boolean" to combine its terms
String contentFragment = contentTerm.makeTerm(req);
if (contentFragment != null) {
- logger.debug("contentFragment: " + contentFragment);
+ getLogger().debug("contentFragment: " + contentFragment);
queryString = queryString + " +" + contentFragment;
}
else {
try {
Searcher searcher = null;
+
try {
- searcher = new IndexSearcher(IndexReader.open(indexFile));
+ searcher = new IndexSearcher(FSDirectory.getDirectory(indexFile,false));
}
catch (IOException e) {
- logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
+ getLogger().debug("Can't open indexPath: " + indexFile.getAbsolutePath());
throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
}
- Query query = null;
+ Query query;
try {
query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
}
catch (Exception e) {
searcher.close();
- logger.debug("Query don't parse: " + queryString);
+ getLogger().debug("Query don't parse: " + queryString);
throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
}
}
catch (IOException e) {
searcher.close();
- logger.debug("Can't get hits: " + e.toString());
+ getLogger().debug("Can't get hits: " + e.toString());
throw new ServletModuleExc("Problem getting hits!");
}
throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
}
- // here is where the documents will go for storage across sessions
+ // here is where the documents will go for database across sessions
ArrayList theDocumentsSorted = new ArrayList();
if (sortBy.equals("score")) {
searcher.close();
}
catch (IOException e) {
- logger.debug("Can't close searcher: " + e.toString());
+ getLogger().debug("Can't close searcher: " + e.toString());
throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
}
}
catch (IOException e) {
- logger.debug("Can't close searcher: " + e.toString());
+ getLogger().debug("Can't close searcher: " + e.toString());
throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
}
}
if (theDocs != null) {
mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString());
- List theHits = new Vector();
+ List theHits = new ArrayList();
int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
int terminus;
int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
}
}
catch (Throwable e) {
- logger.error("Can't iterate over hits: " + e.toString());
+ getLogger().error("Can't iterate over hits: " + e.toString());
throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
}
* Method for dynamically generating a pdf using iText
*/
- public void getpdf(HttpServletRequest req, HttpServletResponse res)
+ public void getpdf(HttpServletRequest aRequest, HttpServletResponse aResponse)
throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+
long starttime = System.currentTimeMillis();
+
String ID_REQUEST_PARAM = "id";
int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
try {
- String idParam = req.getParameter(ID_REQUEST_PARAM);
+ String idParam = aRequest.getParameter(ID_REQUEST_PARAM);
if (idParam != null) {
-
RE re = new RE("[0-9]+");
REMatch[] idMatches = re.getAllMatches(idParam);
-
String cacheSelector = "";
for (int i = 0; i < idMatches.length; i++) {
byte[] thePDF;
if (MirGlobal.mruCache().hasObject(theCacheKey)) {
- logger.info("fetching pdf from cache");
+ getLogger().debug("fetching pdf from cache");
thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
}
else {
- logger.info("generating pdf and caching it");
+ getLogger().debug("generating pdf and caching it");
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDFGenerator pdfMaker = new PDFGenerator(out);
REMatch aMatch = idMatches[i];
String id = aMatch.toString();
EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+
+
pdfMaker.addIndexItem(contentEnt);
}
}
for (int i = 0; i < idMatches.length; i++) {
REMatch aMatch = idMatches[i];
String id = aMatch.toString();
- EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+ EntityContent article = (EntityContent) contentModule.getById(id);
+
+ if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+ throw new ServletModuleExc("Illegal article");
+ }
- pdfMaker.add(contentEnt);
+ pdfMaker.add(article, getLocale(aRequest));
}
pdfMaker.stop();
MirGlobal.mruCache().storeObject(theCacheKey, thePDF);
}
- res.setContentType("application/pdf");
- res.setContentLength(thePDF.length);
- res.getOutputStream().write(thePDF);
- res.getOutputStream().flush();
+ aResponse.setContentType("application/pdf");
+ aResponse.setContentLength(thePDF.length);
+ aResponse.getOutputStream().write(thePDF);
+ aResponse.getOutputStream().flush();
String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
- logger.info("pdf retireval took " + elapsedtime + " milliseconds");
+ getLogger().info("pdf retireval took " + elapsedtime + " milliseconds");
}
else {
}
}
catch (Throwable t) {
- logger.error(t.toString());
+ getLogger().error(t.toString());
+
throw new ServletModuleFailure(t);
}
}
responseData.put("extra", anExtra);
- Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
- generator.generate(anOutputWriter, responseData, logger);
+ Generator generator =
+ MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator, null);
+ generator.generate(anOutputWriter, responseData, getLogger());
anOutputWriter.close();
}
catch (Throwable e) {
- logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+ getLogger().error("Error while generating " + aGenerator + ": " + e.getMessage());
throw new ServletModuleFailure(e);
}
responseData.put("extra", anExtra);
- Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
- generator.generate(anOutputWriter, responseData, logger);
+ Generator generator =
+ MirGlobal.localizer().generators().
+ makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator, null);
+ generator.generate(anOutputWriter, responseData, getLogger());
anOutputWriter.close();
}
catch (Throwable e) {
- logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+ getLogger().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);
+ getLogger().error("Error during open action", 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"));
+ deliver(out, aRequest, aResponse, data, null, getConfiguration().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());
+ getLogger().warn("user error: " + anException.getMessage());
Map data = new HashMap();
Bundle bundle =
data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
- deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
+ deliver(out, aRequest, aResponse, data, null, getConfiguration().getString("ServletModule.OpenIndy.UserErrorTemplate"));
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
import mircoders.module.ModuleUploadedMedia;
import mircoders.storage.DatabaseOther;
/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author the mir coders
- * @version 1.0
+ * Admin ServletModule to manage "other" (i.e. non-audio, video or image) media uploads
*/
public class ServletModuleOtherMedia extends ServletModuleUploadedMedia {
- private static ServletModuleOtherMedia instance = new ServletModuleOtherMedia();
-
- public static ServletModule getInstance() {
- return instance;
- }
-
- private ServletModuleOtherMedia() {
- super();
- logger = new LoggerWrapper("ServletModule.OtherMedia");
- moduleName = "OtherMedia";
+ public ServletModuleOtherMedia() {
+ super("OtherMedia");
- try {
- definition = "otherMedia";
- mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance());
- }
- catch (Throwable e) {
- logger.error("servletmodule otherMedia could not be initialized: " + e.getMessage());
- }
+ definition = "otherMedia";
+ mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance());
}
}
*/
package mircoders.servlet;
+import mir.generator.Generator;
+import mir.producer.ProducerFactory;
+import mir.servlet.AdminServletModule;
+import mir.servlet.ServletModuleFailure;
+import mir.util.HTTPRequestParser;
+import mircoders.global.MirGlobal;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Vector;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.generator.Generator;
-import mir.log.LoggerWrapper;
-import mir.producer.ProducerFactory;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mir.util.HTTPRequestParser;
-import mircoders.global.MirGlobal;
-
-public class ServletModuleProducer extends ServletModule
-{
- private static ServletModuleProducer instance = new ServletModuleProducer();
- public static ServletModule getInstance() { return instance; }
-
- Object comments;
- int totalNrComments;
-
- private ServletModuleProducer() {
- super();
- logger = new LoggerWrapper("ServletModule.Producer");
- defaultAction="showProducerQueueStatus";
+public class ServletModuleProducer extends AdminServletModule {
+ public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ showProducerQueueStatus(aRequest, aResponse);
}
/**
* @param aResponse
*/
public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) {
- Map generationData;
- Generator generator;
- List producersData;
-
try {
// TODO: use ServletHelper
- generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");
+ Generator generator = MirGlobal.localizer().generators().
+ makeAdminGeneratorLibrary().makeGenerator("producerqueue.template", null);
- generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+ Map generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus");
- producersData = new Vector();
+ List producersData = new ArrayList();
Iterator i = MirGlobal.getProducerEngine().getFactories().iterator();
while (i.hasNext()) {
ProducerFactory factory = (ProducerFactory) i.next();
- List producerVerbs = new Vector();
+ List producerVerbs = new ArrayList();
Iterator j = factory.verbs().iterator();
while (j.hasNext()) {
Map verbData = new HashMap();
generationData.put("producers", producersData);
generationData.put("queue", MirGlobal.getProducerEngine().getQueueStatus());
- generator.generate(aResponse.getWriter(), generationData, logger);
+ generator.generate(aResponse.getWriter(), generationData, getLogger());
}
catch (Throwable t) {
throw new ServletModuleFailure(t);
* The output therefore is very simple.
*/
public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) {
+ PrintWriter out;
try {
- PrintWriter out = aResponse.getWriter();
-
- if (aRequest.getParameter("producer")!=null) {
- String producerParam = aRequest.getParameter("producer");
- String verbParam = aRequest.getParameter("verb");
-
- try {
- MirGlobal.getProducerEngine().addJob(producerParam, verbParam);
- out.println("job added");
- }
- catch (Throwable t) {
- out.println("Can't add job: " + t.getMessage());
- }
- }
+ out = aResponse.getWriter();
}
catch (IOException e) {
throw new ServletModuleFailure(e);
}
+
+ if (aRequest.getParameter("producer")!=null) {
+ String producerParam = aRequest.getParameter("producer");
+ String verbParam = aRequest.getParameter("verb");
+
+ try {
+ MirGlobal.getProducerEngine().addJob(producerParam, verbParam);
+
+ out.println("job added");
+ }
+ catch (Throwable t) {
+
+ out.println("Can't add job: " + t.getMessage());
+ }
+ }
}
/**
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleTopics;
/**
- *
+ * Admin ServletModule for managing topics
*/
-
-public class ServletModuleTopics extends ServletModule
-{
- private static ServletModuleTopics instance = new ServletModuleTopics();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleTopics() {
- super();
- logger = new LoggerWrapper("ServletModule.Topics");
-
- try {
- definition = "topic";
- mainModule = new ModuleTopics();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleTopics failed!: " + e.getMessage());
- }
+public class ServletModuleTopics extends AdminServletModule {
+ public ServletModuleTopics() {
+ definition = "topic";
+ mainModule = new ModuleTopics();
}
}
\ No newline at end of file
package mircoders.servlet;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ArrayList;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mircoders.media.MediaHelper;
+import mir.entity.adapter.EntityAdapterEngine;
import mir.media.MediaHandler;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.servlet.ServletModuleUserExc;
import mir.session.UploadedFile;
-import mir.util.CachingRewindableIterator;
-import mir.util.ExceptionFunctions;
+import mir.session.CommonsUploadedFileAdapter;
+import mir.util.ExceptionRoutines;
import mir.util.HTTPParsedRequest;
import mir.util.HTTPRequestParser;
import mir.util.JDBCStringRoutines;
import mircoders.entity.EntityComment;
import mircoders.entity.EntityContent;
import mircoders.entity.EntityUploadedMedia;
-import mircoders.global.MirGlobal;
+import mircoders.media.MediaHelper;
import mircoders.media.MediaUploadProcessor;
-import mircoders.module.ModuleMediaType;
+import mircoders.media.UnsupportedMediaTypeExc;
import mircoders.storage.DatabaseComment;
import mircoders.storage.DatabaseContent;
-
import org.apache.commons.fileupload.FileItem;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author the mir coders
- * @version 1.0
- */
-
-public abstract class ServletModuleUploadedMedia extends ServletModule {
- protected String moduleName = "UploadedMedia";
-
- public static ServletModule getInstance() {
- return null;
- }
+import javax.servlet.ServletContext;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
- public ServletModuleUploadedMedia() {
- super();
+public abstract class ServletModuleUploadedMedia extends AdminServletModule {
+ private String moduleName;
+ protected ServletModuleUploadedMedia(String aModuleName) {
+ moduleName = aModuleName;
definition = "uploadedMedia";
- logger = new LoggerWrapper("ServletModule.UploadedMedia");
}
public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
throws ServletModuleExc, ServletModuleUserExc {
+
try {
HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir"));
+ getConfiguration().getString("Mir.DefaultEncoding"),
+ getConfiguration().getInt("MaxMediaUploadSize")*1024,
+ getConfiguration().getString("TempDir"));
Map mediaValues = new HashMap();
mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
- Iterator i = mainModule.getStorageObject().getFields().iterator();
+ Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
while (i.hasNext()) {
String field = (String) i.next();
String value = parsedRequest.getParameter(field);
i = parsedRequest.getFiles().iterator();
while (i.hasNext()) {
- UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
+ UploadedFile file = new CommonsUploadedFileAdapter((FileItem) i.next());
String suffix = file.getFieldName().substring(5);
mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
String commentid = parsedRequest.getParameter("commentid");
if (articleid!=null) {
- EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
+ EntityContent entContent = (EntityContent)
+ DatabaseContent.getInstance().selectById(articleid);
- i=mediaList.iterator();
+ i = mediaList.iterator();
while (i.hasNext()) {
- String id = ((EntityUploadedMedia) i.next()).getId();
+ String id = ((Entity) i.next()).getId();
entContent.attach(id);
logAdminUsage(aRequest, id, "object attached to article " + articleid);
}
- (ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid);
-
+ ServletHelper.redirect(aResponse, "module=Content&do=edit&id=" + articleid);
return;
}
logAdminUsage(aRequest, id, "object attached to comment " + commentid);
}
- (ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid);
+ ServletHelper.redirect(aResponse, "module=Comment&do=edit&id=" + commentid);
return;
}
logAdminUsage(aRequest, "", mediaList.size() + " objects added");
- returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null);
+ returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), "", null, null);
}
catch (Throwable t) {
- Throwable cause = ExceptionFunctions.traceCauseException(t);
+ Throwable cause = ExceptionRoutines.traceCauseException(t);
- if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
+ if (cause instanceof UnsupportedMediaTypeExc) {
throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});
}
throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);
try {
HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir"));
+ getConfiguration().getString("Mir.DefaultEncoding"),
+ getConfiguration().getInt("MaxMediaUploadSize")*1024,
+ getConfiguration().getString("TempDir"));
+
Map mediaValues = new HashMap();
- Iterator i = mainModule.getStorageObject().getFields().iterator();
+ Iterator i = mainModule.getStorageObject().getFieldNames().iterator();
while (i.hasNext()) {
String field = (String) i.next();
String value = parsedRequest.getParameter(field);
- if (value!=null)
+ if (value!=null) {
mediaValues.put(field, value);
+ }
}
mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
mediaValues.put("is_produced", "0");
- if (!mediaValues.containsKey("is_published"))
+ if (!mediaValues.containsKey("is_published")) {
mediaValues.put("is_published", "0");
+ }
String id = mainModule.set(mediaValues);
- logger.debug("update: media ID = " + id);
+ getLogger().debug("update: media ID = " + id);
logAdminUsage(aRequest, id, "object modified");
editUploadedMediaObject(id, aRequest, aResponse);
}
public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,
- Object aList, int aFrom, int aTo, int aCount,
+ Object aList, int aFrom, int aTo,
String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc {
try {
responseData.put("from", Integer.toString(aFrom));
- responseData.put("count", Integer.toString(aCount));
responseData.put("to", Integer.toString(aTo));
responseData.put("medialist", aList);
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
URLBuilder urlBuilder = new URLBuilder();
- EntityAdapterModel model;
String nextPageUrl = null;
String previousPageUrl = null;
String thisUrl = null;
- int count;
-
try {
- model = MirGlobal.localizer().dataModel().adapterModel();
-
- Object mediaList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage,
- model, definition, nrEntitiesPerListPage, anOffset)
- );
-
- count = mainModule.getSize(aWhereClause);
+ List list =
+ EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
urlBuilder.setValue("module", moduleName);
urlBuilder.setValue("do", "list");
urlBuilder.setValue("offset", anOffset);
thisUrl = urlBuilder.getQuery();
- if (count >= anOffset + nrEntitiesPerListPage) {
+ if (list.size() >= nrEntitiesPerListPage) {
urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
nextPageUrl = urlBuilder.getQuery();
}
previousPageUrl = urlBuilder.getQuery();
}
- returnUploadedMediaList(aRequest, aResponse, mediaList,
- anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl,
+ returnUploadedMediaList(aRequest, aResponse, list,
+ anOffset+1, anOffset+nrEntitiesPerListPage, thisUrl,
nextPageUrl, previousPageUrl);
}
catch (Throwable e) {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1);
- int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);
+ int maxNrMedia = getConfiguration().getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);
- List fields = mainModule.getStorageObject().getFields();
+ List fields = mainModule.getStorageObject().getFieldNames();
Map media = new HashMap();
Iterator i = fields.iterator();
while (i.hasNext()) {
}
private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
- if (idParam != null && !idParam.equals("")) {
+ if (idParam != null && !"".equals(idParam)) {
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
EntityAdapter object =
- model.makeEntityAdapter(definition, mainModule.getById(idParam));
+ getModel().makeEntityAdapter(definition, mainModule.getById(idParam));
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
responseData.put("uploadedmedia", object);
responseData.put("new", Boolean.FALSE);
if (idParam!=null && !idParam.equals("")) {
try {
- EntityUploadedMedia entity = (EntityUploadedMedia)mainModule.getById(idParam);
+ EntityUploadedMedia entity = (EntityUploadedMedia) mainModule.getById(idParam);
Entity mediaType = entity.getMediaType();
MediaHandler mediaHandler;
throw new ServletModuleFailure(e);
}
}
- else logger.error("id not specified.");
+ else {
+ getLogger().error("id not specified.");
+ }
// no exception allowed
}
getThumbnail(aRequest, aResponse);
}
- /**
- *
- * @param aRequest
- * @param aResponse
- * @throws ServletModuleExc
- */
public void getThumbnail(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String id = aRequest.getParameter("id");
}
}
catch (Throwable e) {
- logger.error("getIcon: " + e.toString());
+ getLogger().error("getIcon: " + e.toString());
}
}
- else logger.error("getIcon: id not specified.");
+ else {
+ getLogger().error("getIcon: id not specified.");
+ }
}
protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure {
try {
aTarget.put("mediafolders",
- new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "mediaFolder"));
+ EntityAdapterEngine.retrieveAdapterList(getModel(), "mediaFolder", "", "", -1, 0));
}
catch (Throwable t) {
throw new ServletModuleFailure(t);
}
}
- public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String idParam = aRequest.getParameter("id");
if (idParam!=null && !idParam.equals("")) {
try {
// TODO rewrite as relational sql
- ServletModuleContent.getInstance().returnList(
+ ServletHelper.getServletModuleContent().returnList(
aRequest,
aResponse,
- "exists (select * from content_x_media where content_id=content.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);
+ "exists (select * from content_x_media where content_id=content.id and media_id='" +
+ JDBCStringRoutines.escapeStringLiteral( idParam ) + "')", "", 0);
}
catch (Throwable t) {
throw new ServletModuleFailure(t);
}
}
- else logger.error("showarticles: id not specified.");
+ else {
+ getLogger().error("showarticles: id not specified.");
+ }
}
public void showcomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
if (idParam!=null && !idParam.equals("")) {
try {
// TODO rewrite as relational sql
- ServletModuleComment.getInstance().returnList(
+ ServletHelper.getServletModuleComment().returnList(
aRequest,
aResponse,
- "exists (select * from comment_x_media where comment_id=comment.id and media_id=" + JDBCStringRoutines.escapeStringLiteral( idParam ) + ")", "", 0);
+ "exists (select * from comment_x_media where comment_id=comment.id and media_id='" + JDBCStringRoutines.escapeStringLiteral( idParam ) + "')", "", 0);
}
catch (Throwable t) {
throw new ServletModuleFailure(t);
}
}
- else logger.error("showcomments: id not specified.");
+ else {
+ getLogger().error("showcomments: id not specified.");
+ }
}
}
\ No newline at end of file
package mircoders.servlet;
+import mir.entity.adapter.EntityAdapterEngine;
import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.servlet.ServletModuleUserExc;
-import mir.util.CachingRewindableIterator;
import mir.util.HTTPRequestParser;
import mir.util.URLBuilder;
import mircoders.entity.EntityUsers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.util.*;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
/**
*
*
*/
-public class ServletModuleUsers extends ServletModule
-{
- private static ServletModuleUsers instance = new ServletModuleUsers();
- public static ServletModule getInstance() { return instance; }
- protected ModuleUsers usersModule;
+public class ServletModuleUsers extends AdminServletModule {
+ protected ModuleUsers usersModule = new ModuleUsers();
- private ServletModuleUsers() {
- super();
- logger = new LoggerWrapper("ServletModule.Users");
-
- try {
- definition = "user";
- usersModule = new ModuleUsers();
- mainModule = usersModule;
- }
- catch (Throwable e) {
- logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());
- }
+ public ServletModuleUsers() {
+ definition = "user";
+ mainModule = usersModule;
}
- public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
- {
+ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String idParam = aRequest.getParameter("id");
- if (idParam == null)
+ if (idParam == null) {
throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
+ }
try {
EntityUsers user = (EntityUsers) mainModule.getById(idParam);
return newPassword;
}
- else
- return null;
+ return null;
}
public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
HttpServletResponse aResponse,
int anOffset) throws ServletModuleExc {
-// ML: to be deleted, support for 3 extra vars to be added
URLBuilder urlBuilder = new URLBuilder();
- int count;
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- model = MirGlobal.localizer().dataModel().adapterModel();
- Object userList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage,
- MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset)
- );
+ List list =
+ EntityAdapterEngine.retrieveAdapterList(getModel(), definition,
+ "", "login", nrEntitiesPerListPage, anOffset);
responseData.put("nexturl", null);
responseData.put("prevurl", null);
- count=mainModule.getSize("");
-
urlBuilder.setValue("module", "Users");
urlBuilder.setValue("do", "list");
urlBuilder.setValue("offset", anOffset);
- responseData.put("offset" , new Integer(anOffset).toString());
+ responseData.put("offset" , Integer.toString(anOffset));
responseData.put("thisurl" , urlBuilder.getQuery());
- if (count>=anOffset+nrEntitiesPerListPage) {
- urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));
+ if (list.size()>=nrEntitiesPerListPage) {
+ urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
responseData.put("nexturl" , urlBuilder.getQuery());
}
responseData.put("prevurl" , urlBuilder.getQuery());
}
- responseData.put("users", userList);
+ responseData.put("users", list);
responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest))));
responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest))));
responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest))));
responseData.put("from" , Integer.toString(anOffset+1));
- responseData.put("count", Integer.toString(count));
- responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));
+ responseData.put("to", Integer.toString(anOffset+list.size()));
responseData.put("offset" , Integer.toString(anOffset));
ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
- Map user;
+ Object user;
URLBuilder urlBuilder = new URLBuilder();
urlBuilder.setValue("module", "Users");
user = model.makeEntityAdapter("user", mainModule.getById(anId));
}
else {
- List fields = DatabaseUsers.getInstance().getFields();
+ List fields = DatabaseUsers.getInstance().getFieldNames();
responseData.put("new", Boolean.TRUE);
- user = new HashMap();
+ Map emptyUser = new HashMap();
Iterator i = fields.iterator();
while (i.hasNext()) {
- user.put(i.next(), null);
+ emptyUser.put(i.next(), null);
}
- MirGlobal.localizer().adminInterface().initializeArticle(user);
+ user = emptyUser;
}
responseData.put("user", user);
responseData.put("passwordonly", new Boolean(anOnlyPassword));
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
import mircoders.module.ModuleUploadedMedia;
import mircoders.storage.DatabaseVideo;
/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * Admin ServletModule for managing video uploads
*/
public class ServletModuleVideo extends ServletModuleUploadedMedia {
- private static ServletModuleVideo instance = new ServletModuleVideo();
-
- public static ServletModule getInstance() {
- return instance;
- }
-
- private ServletModuleVideo() {
- super();
- logger = new LoggerWrapper("ServletModule.Video");
-
- moduleName = "Video";
+ public ServletModuleVideo() {
+ super("Video");
- try {
- definition = "video";
- mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance());
- }
- catch (Throwable e) {
- logger.error("servletmodule video could not be initialized: " + e.getMessage());
- }
+ definition = "video";
+ mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance());
}
-}
\ No newline at end of file
+}
package mircoders.storage;
-/**
- * Title:
- * 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;
-
-public class DatabaseArticleType extends Database implements StorageObject{
+import mir.storage.DatabaseFailure;
+public class DatabaseArticleType extends Database {
private static DatabaseArticleType instance;
- public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure {
- if (instance == null) {
- instance = new DatabaseArticleType();
- }
- return instance;
+ private DatabaseArticleType() throws DatabaseFailure {
+ logger = new LoggerWrapper("Database.ArticleType");
+ mainTable = "article_type";
}
- private DatabaseArticleType() throws StorageObjectFailure {
- super();
+ public static DatabaseArticleType getInstance() throws DatabaseFailure {
+ synchronized (DatabaseArticleType.class) {
+ if (instance == null) {
+ instance = new DatabaseArticleType();
+ }
+ }
- logger = new LoggerWrapper("Database.ArticleType");
- this.hasTimestamp = false;
- this.mainTable = "article_type";
+ return instance;
}
-
}
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-public class DatabaseAudio extends Database implements StorageObject{
+public class DatabaseAudio extends Database {
private static DatabaseAudio instance;
return instance;
}
- private DatabaseAudio() throws StorageObjectFailure {
+ private DatabaseAudio() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Audio");
- hasTimestamp = true;
mainTable = "audio";
- primaryKeySequence = "media_id_seq";
- theEntityClass = mircoders.entity.EntityAudio.class;
+
+ entityClass = mircoders.entity.EntityAudio.class;
}
- public void update(Entity theEntity) throws StorageObjectFailure {
+ public void update(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
super.update(theEntity);
}
- public String insert(Entity theEntity) throws StorageObjectFailure {
+ public String insert(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
return super.insert(theEntity);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseBreaking extends Database implements StorageObject{
+import mir.storage.DatabaseFailure;
+public class DatabaseBreaking extends Database {
private static DatabaseBreaking 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 DatabaseBreaking getInstance() throws StorageObjectFailure {
+ public synchronized static DatabaseBreaking getInstance() throws DatabaseFailure {
if (instance == null) {
instance = new DatabaseBreaking();
}
return instance;
}
- private DatabaseBreaking() throws StorageObjectFailure
- {
+ private DatabaseBreaking() throws DatabaseFailure {
super();
+
logger = new LoggerWrapper("Database.Breaking");
- this.mainTable="breaking";
+ mainTable="breaking";
}
-
-
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- * <b>This class implements the access to the comment-table for the
- * media table.
- *
- *
- */
-
-public class DatabaseComment extends Database implements StorageObject{
+public class DatabaseComment extends Database {
private static DatabaseComment instance;
private DatabaseComment() {
super();
- hasTimestamp = false;
mainTable = "comment";
logger = new LoggerWrapper("Database.Comment");
- this.theEntityClass = mircoders.entity.EntityComment.class;
+ entityClass = mircoders.entity.EntityComment.class;
}
- public boolean deleteByContentId(String id) throws StorageObjectFailure {
+ public boolean deleteByContentId(String id) throws DatabaseFailure {
Statement stmt = null;
Connection con = null;
String sql;
stmt.executeUpdate(sql);
}
catch (SQLException sqe) {
- new StorageObjectFailure(sqe);
+ new DatabaseFailure(sqe);
return false;
}
finally {
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 mir.storage.DatabaseFailure;
-
-public class DatabaseCommentStatus extends Database implements StorageObject{
+public class DatabaseCommentStatus extends Database {
private static DatabaseCommentStatus instance;
- public synchronized static DatabaseCommentStatus getInstance() throws StorageObjectFailure {
+ public synchronized static DatabaseCommentStatus getInstance() throws DatabaseFailure {
if (instance == null) {
instance = new DatabaseCommentStatus();
}
return instance;
}
- private DatabaseCommentStatus() throws StorageObjectFailure {
+ private DatabaseCommentStatus() throws DatabaseFailure {
super();
- hasTimestamp = false;
+
mainTable = "comment_status";
logger = new LoggerWrapper("Database.CommentStatus");
}
package mircoders.storage;
import java.sql.Connection;
-import java.sql.ResultSet;
import java.sql.Statement;
-import java.util.Vector;
+import java.util.ArrayList;
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.EntityComment;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityUploadedMedia;
-/**
- * <b>implements abstract DB connection to the comment_x_media SQL table
- *
- * @author RK, mir-coders group
- * @version $Id: DatabaseCommentToMedia.java,v 1.5 2004/11/06 20:10:37 idfx Exp $
- *
- */
-
-public class DatabaseCommentToMedia extends Database implements StorageObject{
+public class DatabaseCommentToMedia extends Database {
private static DatabaseCommentToMedia instance;
private DatabaseCommentToMedia() {
super();
+
logger = new LoggerWrapper("Database.CommentToMedia");
- hasTimestamp = false;
mainTable = "comment_x_media";
- theEntityClass = mir.entity.GenericEntity.class;
- }
-
- public boolean hasMedia(EntityComment comment) throws StorageObjectFailure,
- StorageObjectExc {
- if (comment != null) {
- try {
- return (getSize("comment_id=" + comment.getId()) == 0) ? false:true;
- }
- catch (Exception e) {
- logger.error("DatabaseCommentToMedia.hasMedia: " + e.toString());
- throw new StorageObjectFailure("DatabaseCommentToMedia.hasMedia: " +
- e.toString(), e);
- }
- }
- else {
- logger.error("DatabaseCommentToMedia.hasMedia: comment == null");
- throw new StorageObjectExc(
- "DatabaseCommentToMedia.hasMedia: comment == null");
- }
- }
-
- private EntityList getMultiMediaForComment(StorageObject store, EntityComment comment)
- throws StorageObjectFailure {
-
- EntityList returnList = null;
- if (comment != null) {
- String id = comment.getId();
- try {
- Vector extraTable = new Vector();
- extraTable.add(mainTable+" cxm");
- // 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"
- store.selectByWhereClause("m", extraTable,
- "m.id=cxm.media_id and cxm.comment_id="+id, "id", -1, -1);
-
- } catch (Exception e) {
- logger.error("DatabaseCommenttToMedia.getMultiMediaForComment: " + e.toString());
- throw new StorageObjectFailure("DatabaseContentToMedia.etMultiMediaForComment: " +
- e.toString(), e);
- }
- }
- return returnList;
- }
-
- /**
- * get all the audio belonging to a comment entity
- */
- public EntityList getAudio(EntityComment comment) throws StorageObjectFailure {
- return getMultiMediaForComment(DatabaseAudio.getInstance(), comment);
- }
-
- /**
- * get all the video belonging to a comment entity
- *
- */
- public EntityList getVideo(EntityComment comment) throws StorageObjectFailure {
- return getMultiMediaForComment(DatabaseVideo.getInstance(), comment);
- }
-
- /**
- * get all the images belonging to a comment entity
- */
- public EntityList getImages(EntityComment comment) throws StorageObjectFailure {
- return getMultiMediaForComment(DatabaseImages.getInstance(), comment);
- }
-
- /**
- * get all the uploaded/other Media belonging to a comment entity
- */
- public EntityList getOther(EntityComment comment) throws StorageObjectFailure {
- return getMultiMediaForComment(DatabaseOther.getInstance(), comment);
- }
-
- /**
- * get all the uploaded/other Media belonging to a comment entity
- */
- public EntityList getUploadedMedia(EntityComment comment) throws StorageObjectFailure {
- return getMultiMediaForComment(DatabaseUploadedMedia.getInstance(), comment);
- }
-
- public void setMedia(String commentId, String[] mediaId) throws
- StorageObjectFailure {
- if (commentId == null) {
- return;
- }
- if (mediaId == null || mediaId[0] == null) {
- return;
- }
- //first delete all row with comment_id=commentId
- String sql = "delete from " + mainTable + " where comment_id=" + commentId;
-
- Connection con = null;
- Statement stmt = null;
- try {
- con = obtainConnection();
- // 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 comment_id=commentId
- for (int i = 0; i < mediaId.length; i++) {
- sql = "insert into " + mainTable + " (comment_id,media_id) values ("
- + commentId + "," + mediaId[i] + ")";
- try {
- con = obtainConnection();
- // 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);
- }
- }
+ entityClass = mir.entity.GenericEntity.class;
}
public void addMedia(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (commentId == null && mediaId == null) {
return;
}
}
catch (Exception e) {
logger.error("-- add media failed -- insert");
- throw new StorageObjectFailure("-- add media failed -- insert ", e);
+ throw new DatabaseFailure("-- add media failed -- insert ", e);
}
finally {
freeConnection(con, stmt);
}
public void setMedia(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (commentId == null && mediaId == null) {
return;
}
}
catch (Exception e) {
logger.error("-- set media failed -- delete");
- throw new StorageObjectFailure("-- set media failed -- delete ", e);
+ throw new DatabaseFailure("-- set media failed -- delete ", e);
}
finally {
freeConnection(con, stmt);
}
catch (Exception e) {
logger.error("-- set media failed -- insert");
- throw new StorageObjectFailure("-- set media failed -- insert ", e);
+ throw new DatabaseFailure("-- set media failed -- insert ", e);
}
finally {
freeConnection(con, stmt);
}
}
- public void deleteByCommentId(String commentId) throws StorageObjectFailure {
+ public void deleteByCommentId(String commentId) throws DatabaseFailure {
if (commentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no comment id");
return;
}
catch (Exception e) {
logger.error("-- delete by commentId failed ");
- throw new StorageObjectFailure(
+ throw new DatabaseFailure(
"-- delete by comment id failed -- delete ", e);
}
finally {
}
}
- public void deleteByMediaId(String mediaId) throws StorageObjectFailure {
+ public void deleteByMediaId(String mediaId) throws DatabaseFailure {
if (mediaId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
return;
}
catch (Exception e) {
logger.error("-- delete media failed ");
- throw new StorageObjectFailure("-- delete by media id failed -- ", e);
+ throw new DatabaseFailure("-- delete by media id failed -- ", e);
}
finally {
freeConnection(con, stmt);
}
public void delete(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (mediaId == null || commentId == null) {
logger.debug("-- delete media failed -- missing parameter");
return;
}
catch (Exception e) {
logger.error("-- delete comment_x_media failed ");
- throw new StorageObjectFailure("-- delete comment_x_media failed -- ", e);
+ throw new DatabaseFailure("-- delete comment_x_media failed -- ", e);
}
finally {
freeConnection(con, stmt);
}
public EntityList getComment(EntityUploadedMedia media) throws
- StorageObjectFailure {
+ DatabaseFailure {
EntityList returnList = null;
if (media != null) {
String id = media.getId();
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable + " cxm");
String mediaSelect = "cxm.comment_id=c.id and cxm.media_id="+id;
}
catch (Exception e) {
logger.error("-- get comment failed");
- throw new StorageObjectFailure("-- get comment failed -- ", e);
+ throw new DatabaseFailure("-- get comment failed -- ", e);
}
}
return returnList;
* a relation to a media
*/
- public EntityList getComment() throws StorageObjectFailure {
+ public EntityList getComment() throws DatabaseFailure {
EntityList returnList = null;
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable + " cxm");
String mediaSelect = "cxm.comment_id=c.id";
}
catch (Exception e) {
logger.error("-- get comment failed");
- throw new StorageObjectFailure("-- get comment failed -- ", e);
+ throw new DatabaseFailure("-- get comment failed -- ", e);
}
return returnList;
package mircoders.storage;
-import java.sql.Connection;
-import java.sql.Statement;
-
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- * <b>this class implements the access to the content-table</b>
- *
- *
- */
+import java.sql.Connection;
+import java.sql.Statement;
-public class DatabaseContent extends Database implements StorageObject {
+public class DatabaseContent extends Database {
private static DatabaseContent instance;
- // Contructors / Singleton
-
- // 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 DatabaseContent getInstance() {
if (instance == null ) {
return instance;
}
- private DatabaseContent() throws StorageObjectFailure {
+ private DatabaseContent() throws DatabaseFailure {
super();
mainTable="content";
- primaryKeySequence="media_id_seq";
logger = new LoggerWrapper("Database.Content");
- theEntityClass = mircoders.entity.EntityContent.class;
+ entityClass = mircoders.entity.EntityContent.class;
}
// methods
* sets the database flag is_produced to unproduced
*/
- public void setUnproduced(String where) throws StorageObjectFailure
+ public void setUnproduced(String where) throws DatabaseFailure
{
Connection con=null;Statement stmt=null;
String sql = "update content set is_produced='0' where " + where;
finally { freeConnection(con,stmt);}
}
- /**
- *
- * @param id
- * @return
- * @throws StorageObjectFailure
- */
-
- public boolean delete(String id) throws StorageObjectFailure
- {
+ public boolean delete(String id) throws DatabaseFailure {
DatabaseComment.getInstance().deleteByContentId(id);
DatabaseContentToTopics.getInstance().deleteByContentId(id);
DatabaseContentToMedia.getInstance().deleteByContentId(id);
return super.delete(id);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
package mircoders.storage;
import java.sql.Connection;
-import java.sql.ResultSet;
import java.sql.Statement;
-import java.util.Vector;
+import java.util.ArrayList;
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 mir.storage.DatabaseFailure;
import mircoders.entity.EntityUploadedMedia;
/**
* <b>implements abstract DB connection to the content_x_media SQL table
*
* @author RK, mir-coders group
- * @version $Id: DatabaseContentToMedia.java,v 1.21 2004/11/06 20:10:37 idfx Exp $
+ * @version $Id: DatabaseContentToMedia.java,v 1.22 2007/04/08 21:46:36 idfx Exp $
*
*/
-public class DatabaseContentToMedia extends Database implements StorageObject{
+public class DatabaseContentToMedia extends Database {
private static DatabaseContentToMedia instance;
super();
logger = new LoggerWrapper("Database.ContentToMedia");
- hasTimestamp = false;
mainTable = "content_x_media";
- theEntityClass = mir.entity.GenericEntity.class;
- }
-
- public boolean hasMedia(EntityContent content) throws StorageObjectFailure,
- StorageObjectExc {
- if (content != null) {
- try {
- return (getSize("content_id=" + content.getId()) == 0) ? false: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");
- }
- }
-
- private EntityList getMultiMediaForContent(StorageObject store, EntityContent content)
- throws StorageObjectFailure {
-
- EntityList returnList = null;
- if (content != null) {
- String id = content.getId();
- try {
- Vector extraTable = new Vector();
- extraTable.add(mainTable+" cxm");
- // 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"
- store.selectByWhereClause("m", extraTable,
- "m.id=cxm.media_id and cxm.content_id="+id, "id", -1, -1);
-
- } catch (Exception e) {
- logger.error("DatabaseContentToMedia.getMultiMediaForContent: " + e.toString());
- throw new StorageObjectFailure("DatabaseContentToMedia.etMultiMediaForContent: " +
- e.toString(), e);
- }
- }
- return returnList;
- }
-
- /**
- * get all the audio belonging to a content entity
- */
- public EntityList getAudio(EntityContent content) throws StorageObjectFailure {
- return getMultiMediaForContent(DatabaseAudio.getInstance(), content);
- }
-
- /**
- * get all the video belonging to a content entity
- */
- public EntityList getVideo(EntityContent content) throws StorageObjectFailure {
- return getMultiMediaForContent(DatabaseVideo.getInstance(), content);
- }
-
- /**
- * get all the images belonging to a content entity
- */
- public EntityList getImages(EntityContent content) throws StorageObjectFailure {
- return getMultiMediaForContent(DatabaseImages.getInstance(), content);
- }
-
- /**
- * get all the uploaded/other Media belonging to a content entity
- */
- public EntityList getOther(EntityContent content) throws StorageObjectFailure {
- return getMultiMediaForContent(DatabaseOther.getInstance(), content);
- }
-
- /**
- * get all the uploaded/other Media belonging to a content entity
- */
- public EntityList getUploadedMedia(EntityContent content) throws StorageObjectFailure {
- return getMultiMediaForContent(DatabaseUploadedMedia.getInstance(), content);
- }
-
-
- public void setMedia(String contentId, String[] mediaId) throws StorageObjectFailure {
- if (contentId == null || mediaId == null || mediaId[0] == null) {
- return;
- }
- //first delete all row with content_id=contentId
- String sql = "delete from " + mainTable + " where content_id=" + contentId;
-
- Connection con = null;
- Statement stmt = null;
- try {
- con = obtainConnection();
- // 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 " + mainTable + " (content_id,media_id) values ("
- + contentId + "," + mediaId[i] + ")";
- try {
- con = obtainConnection();
- // 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);
- }
- }
+ entityClass = mir.entity.GenericEntity.class;
}
public void addMedia(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (contentId == null && mediaId == null) {
return;
}
}
catch (Exception e) {
logger.error("-- add media failed -- insert");
- throw new StorageObjectFailure("-- add media failed -- insert ", e);
+ throw new DatabaseFailure("-- add media failed -- insert ", e);
}
finally {
freeConnection(con, stmt);
}
public void setMedia(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (contentId == null && mediaId == null) {
return;
}
}
catch (Exception e) {
logger.error("-- set media failed -- delete");
- throw new StorageObjectFailure("-- set media failed -- delete ", e);
+ throw new DatabaseFailure("-- set media failed -- delete ", e);
}
finally {
freeConnection(con, stmt);
}
catch (Exception e) {
logger.error("-- set media failed -- insert");
- throw new StorageObjectFailure("-- set media failed -- insert ", e);
+ throw new DatabaseFailure("-- set media failed -- insert ", e);
}
finally {
freeConnection(con, stmt);
}
}
- public void deleteByContentId(String contentId) throws StorageObjectFailure {
+ public void deleteByContentId(String contentId) throws DatabaseFailure {
if (contentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no content id");
return;
}
catch (Exception e) {
logger.error("-- delete by contentId failed ");
- throw new StorageObjectFailure(
+ throw new DatabaseFailure(
"-- delete by content id failed -- delete ", e);
}
finally {
}
}
- public void deleteByMediaId(String mediaId) throws StorageObjectFailure {
+ public void deleteByMediaId(String mediaId) throws DatabaseFailure {
if (mediaId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
}
catch (Exception e) {
logger.error("-- delete media failed ");
- throw new StorageObjectFailure("-- delete by media id failed -- ", e);
+ throw new DatabaseFailure("-- delete by media id failed -- ", e);
}
finally {
freeConnection(con, stmt);
}
public void delete(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (mediaId == null || contentId == null) {
logger.debug("-- delete media failed -- missing parameter");
return;
}
catch (Exception e) {
logger.error("-- delete content_x_media failed ");
- throw new StorageObjectFailure("-- delete content_x_media failed -- ", e);
+ throw new DatabaseFailure("-- delete content_x_media failed -- ", e);
}
finally {
freeConnection(con, stmt);
}
public EntityList getContent(EntityUploadedMedia media) throws
- StorageObjectFailure {
+ DatabaseFailure {
EntityList returnList = null;
if (media != null) {
String id = media.getId();
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable + " cxm");
String mediaSelect = "cxm.content_id=c.id and cxm.media_id="+id;
}
catch (Exception e) {
logger.error("-- get content failed");
- throw new StorageObjectFailure("-- get content failed -- ", e);
+ throw new DatabaseFailure("-- get content failed -- ", e);
}
}
return returnList;
* Returns a EntityList with all content-objects having a relation to a media
*/
- public EntityList getContent() throws StorageObjectFailure {
+ public EntityList getContent() throws DatabaseFailure {
EntityList returnList = null;
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable + " cxm");
String mediaSelect = "cxm.content_id=c.id";
}
catch (Exception e) {
logger.error("-- get content failed");
- throw new StorageObjectFailure("-- get content failed -- ", e);
+ throw new DatabaseFailure("-- get content failed -- ", e);
}
return returnList;
}
package mircoders.storage;
+import mir.entity.EntityList;
+import mir.log.LoggerWrapper;
+import mir.storage.Database;
+import mir.storage.DatabaseFailure;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityTopics;
+
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
-import java.util.Vector;
-
-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;
/**
* <b>This class implements the 1-n-relation between
*
*/
-public class DatabaseContentToTopics extends Database implements StorageObject{
+public class DatabaseContentToTopics extends Database {
private static DatabaseContentToTopics instance;
super();
logger = new LoggerWrapper("Database.ContentToTopics");
-
- hasTimestamp = false;
mainTable="content_x_topic";
- theEntityClass = mir.entity.GenericEntity.class;
+ entityClass = mir.entity.GenericEntity.class;
}
/**
String id = content.getId();
try {
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable+" cxt");
returnList = DatabaseTopics.getInstance()
.selectByWhereClauseWithExtraTables("t",extraTables,
* Returns a List of String-Objects from a content-id.
*/
public List getTopicsOfContent(String contentId)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
ArrayList returnList = new ArrayList();
if (contentId != null) {
return result;
}
- public void setTopics(String anArticleId, String [] aTopics) throws StorageObjectFailure {
+ public void setTopics(String anArticleId, String [] aTopics) throws DatabaseFailure {
if (aTopics==null)
setTopics(anArticleId, (List) null);
else
setTopics(anArticleId, Arrays.asList(aTopics));
}
- public void setTopics(String anArticleId, List aTopics) throws StorageObjectFailure {
- List newTopics = new Vector();
+ public void setTopics(String anArticleId, List aTopics) throws DatabaseFailure {
+ List newTopics = new ArrayList();
if (aTopics!=null) {
Iterator i = aTopics.iterator();
}
public void deleteByContentId(String contentId)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
if (contentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no content id");
return;
}
public void deleteByTopicId(String topicId)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
if (topicId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
return;
* Returns list of Content for a specific topic
* @param topic
* @return EntityList
- * @throws StorageObjectFailure
+ * @throws DatabaseFailure
*/
public EntityList getContent(EntityTopics topic)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
EntityList returnList=null;
if (topic != null) {
String id = topic.getId();
try {
- Vector extraTables = new Vector();
+ ArrayList extraTables = new ArrayList();
extraTables.add(mainTable+" cxt");
returnList = DatabaseContent.getInstance()
.selectByWhereClauseWithExtraTables("c",extraTables,
--- /dev/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 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;
+
+public class DatabaseFilter extends Database {
+ private static DatabaseFilter instance;
+
+ public synchronized static DatabaseFilter getInstance() {
+ if (instance == null) {
+ instance = new DatabaseFilter();
+ }
+
+ return instance;
+ }
+
+ private DatabaseFilter() {
+ super();
+
+ logger = new LoggerWrapper("Database.Filter");
+ mainTable = "filter";
+ }
+}
--- /dev/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 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;
+
+public class DatabaseFilterGroup extends Database {
+ private static DatabaseFilterGroup instance;
+
+ public synchronized static DatabaseFilterGroup getInstance() {
+ if (instance == null) {
+ instance = new DatabaseFilterGroup();
+ }
+ return instance;
+ }
+
+ private DatabaseFilterGroup() {
+ super();
+
+ logger = new LoggerWrapper("Database.FilterGroup");
+ mainTable="filter_group";
+ }
+}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImageColor extends Database implements StorageObject{
+public class DatabaseImageColor extends Database {
private static DatabaseImageColor instance;
private DatabaseImageColor() {
super();
+
logger = new LoggerWrapper("Database.ImageColor");
- hasTimestamp = false;
mainTable = "img_color";
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImageFormat extends Database implements StorageObject{
+public class DatabaseImageFormat extends Database {
private static DatabaseImageFormat instance;
private DatabaseImageFormat() {
super();
+
logger = new LoggerWrapper("Database.ImageFormat");
- hasTimestamp = false;
mainTable = "img_format";
}
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImageLayout extends Database implements StorageObject{
+public class DatabaseImageLayout extends Database {
private static DatabaseImageLayout instance;
super();
logger = new LoggerWrapper("Database.ImageLayout");
- hasTimestamp = false;
mainTable = "img_layout";
}
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseImageType extends Database implements StorageObject{
+public class DatabaseImageType extends Database {
private static DatabaseImageType instance;
public synchronized static DatabaseImageType getInstance() {
private DatabaseImageType() {
super();
- logger = new LoggerWrapper("Database.ImageType");
- hasTimestamp = false;
+ logger = new LoggerWrapper("Database.ImageType");
mainTable = "img_type";
}
}
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImages extends Database implements StorageObject{
+public class DatabaseImages extends Database {
private static DatabaseImages instance;
logger = new LoggerWrapper("Database.Images");
- hasTimestamp = true;
mainTable = "images";
- primaryKeySequence = "media_id_seq";
- theEntityClass = mircoders.entity.EntityImages.class;
+ entityClass = mircoders.entity.EntityImages.class;
+ markBinaryField("image_data");
+ markBinaryField("icon_data");
}
- public void update(Entity theEntity) throws StorageObjectFailure {
+ public void update(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
super.update(theEntity);
}
- public String insert(Entity theEntity) throws StorageObjectFailure {
+ public String insert(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
return super.insert(theEntity);
}
+
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
* @version 1.0
*/
+import java.util.ArrayList;
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.EntityBrowser;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-public class DatabaseLanguage extends Database implements StorageObject{
+public class DatabaseLanguage extends Database {
private static DatabaseLanguage 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 DatabaseLanguage getInstance() throws
- StorageObjectFailure {
+ DatabaseFailure {
if (instance == null) {
instance = new DatabaseLanguage();
}
return instance;
}
- private DatabaseLanguage() throws StorageObjectFailure {
+ private DatabaseLanguage() throws DatabaseFailure {
super();
- logger = new LoggerWrapper("Database.Language");
- this.hasTimestamp = false;
- this.mainTable = "language";
+ logger = new LoggerWrapper("Database.Language");
+ mainTable = "language";
}
- public List getPopupData() throws StorageObjectFailure {
- List result = new Vector();
+ public List getPopupData() throws DatabaseFailure {
+ List result = new ArrayList();
Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0);
while (i.hasNext()) {
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- * <b>This class implements the access to the media_type-table for the
- * media table.
- *
- *
- */
-
-public class DatabaseMediaType extends Database implements StorageObject{
+public class DatabaseMediaType extends Database {
private static DatabaseMediaType instance;
public synchronized static DatabaseMediaType getInstance() {
return instance;
}
- private DatabaseMediaType() throws StorageObjectFailure
+ private DatabaseMediaType() throws DatabaseFailure
{
super();
logger = new LoggerWrapper("Database.MediaType");
-
- hasTimestamp = false;
mainTable="media_type";
- theEntityClass = mir.entity.GenericEntity.class;
+ entityClass = mir.entity.GenericEntity.class;
}
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-public class DatabaseMediafolder extends Database implements StorageObject{
+public class DatabaseMediafolder extends Database {
private static DatabaseMediafolder instance;
public synchronized static DatabaseMediafolder getInstance() {
if (instance == null) {
instance = new DatabaseMediafolder();
}
+
return instance;
}
super();
logger = new LoggerWrapper("Database.Mediafolder");
-
- hasTimestamp = false;
mainTable="media_folder";
}
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-
-/**
- * Title:
- * Description:
- * Copyright: Copyright (c) 2001
- * Company: Indymedia
- * @author
- * @version 1.0
- */
-
-
-public class DatabaseMessages extends Database implements StorageObject{
+public class DatabaseMessages extends Database {
private static DatabaseMessages instance;
public synchronized static DatabaseMessages getInstance() {
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseOther extends Database implements StorageObject{
+public class DatabaseOther extends Database {
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();
super();
logger = new LoggerWrapper("Database.OtherMedia");
-
- hasTimestamp = true;
mainTable = "other_media";
- primaryKeySequence = "media_id_seq";
- theEntityClass = mircoders.entity.EntityOther.class;
+ entityClass = mircoders.entity.EntityOther.class;
}
- public void update(Entity theEntity) throws StorageObjectFailure {
+ public void update(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
super.update(theEntity);
}
- public String insert(Entity theEntity) throws StorageObjectFailure {
+ public String insert(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
return super.insert(theEntity);
}
- // initialisierungen aus den statischen Tabellen
-
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseRights extends Database implements StorageObject{
+public class DatabaseRights extends Database {
private static DatabaseRights instance;
public synchronized static DatabaseRights getInstance() {
return instance;
}
- private DatabaseRights() throws StorageObjectFailure {
+ private DatabaseRights() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Rights");
-
- hasTimestamp = false;
mainTable = "rights";
}
}
package mircoders.storage;
+import java.util.ArrayList;
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.EntityBrowser;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseTopics extends Database implements StorageObject{
+public class DatabaseTopics extends Database {
private static DatabaseTopics instance;
public synchronized static DatabaseTopics getInstance() {
return instance;
}
- private DatabaseTopics() throws StorageObjectFailure {
+ private DatabaseTopics() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Topics");
- hasTimestamp = false;
mainTable = "topic";
- theEntityClass = mircoders.entity.EntityTopics.class;
+ entityClass = mircoders.entity.EntityTopics.class;
}
- public List getPopupData() throws StorageObjectFailure {
- List result = new Vector();
+ public List getPopupData() throws DatabaseFailure {
+ List result = new ArrayList();
Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0);
while (i.hasNext()) {
import mir.entity.EntityBrowser;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
+import mircoders.entity.EntityUploadedMedia;
-public class DatabaseUploadedMedia extends Database implements StorageObject {
- private static DatabaseUploadedMedia instance;
+public class DatabaseUploadedMedia extends Database {
+ private static DatabaseUploadedMedia instance;
- public synchronized static DatabaseUploadedMedia getInstance() {
+ public static synchronized DatabaseUploadedMedia getInstance() {
if (instance == null ) {
instance = new DatabaseUploadedMedia();
}
}
private DatabaseUploadedMedia() {
- super();
-
logger = new LoggerWrapper("Database.UploadedMedia");
mainTable="uploaded_media";
- primaryKeySequence="media_id_seq";
- theEntityClass = mircoders.entity.EntityUploadedMedia.class;
+ entityClass = 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 {
+ public Entity getMediaType(Entity aMedia) throws DatabaseFailure {
Entity type=null;
try {
- Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getFieldValue("to_media_type") + " = id" , "id", 1);
- if (i.hasNext())
+ Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), aMedia.getFieldValue("to_media_type") + " = id" , "id", 1);
+
+ if (i.hasNext()) {
type = (Entity) i.next();
+ }
}
catch (Throwable t) {
logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage());
- throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", t);
+ throw new DatabaseFailure("DatabaseUploadedMedia :: failed to get media_type", t);
}
return type;
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseUsers extends Database implements StorageObject{
+public class DatabaseUsers extends Database {
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() {
if (instance == null) {
instance = new DatabaseUsers();
return instance;
}
- private DatabaseUsers() throws StorageObjectFailure {
+ private DatabaseUsers() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Users");
-
- hasTimestamp = false;
mainTable = "webdb_users";
- theEntityClass = mircoders.entity.EntityUsers.class;
+ entityClass = mircoders.entity.EntityUsers.class;
}
}
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
-public class DatabaseVideo extends Database implements StorageObject{
+public class DatabaseVideo extends Database {
private static DatabaseVideo instance;
super();
logger = new LoggerWrapper("Database.Video");
-
- hasTimestamp = true;
mainTable = "video";
- primaryKeySequence = "media_id_seq";
- theEntityClass = mircoders.entity.EntityVideo.class;
+ entityClass = mircoders.entity.EntityVideo.class;
}
- public void update(Entity theEntity) throws StorageObjectFailure {
+ public void update(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
super.update(theEntity);
}
- public String insert(Entity theEntity) throws StorageObjectFailure {
+ public String insert(Entity theEntity) throws DatabaseFailure {
String date = theEntity.getFieldValue("date");
if (date == null) {
date = StringUtil.date2webdbDate(new GregorianCalendar());
return super.insert(theEntity);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-import org.apache.commons.lang.exception.NestableException;
-
-/**
- * DatabaseExc
- * @author idefix
- * @version $Id: DatabaseFailure.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class DatabaseFailure extends NestableException {
- /**
- *
- * @param e
- */
- public DatabaseFailure(Throwable e) {
- super("A DatabaseFailure occured", e);
- }
-
- /**
- * @param string
- */
- public DatabaseFailure(String msg) {
- super(msg);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-import org.codecoop.mir.core.model.Article;
-
-/**
- * IArticleDAO
- * @author idefix
- * @version $Id: IArticleDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public interface IArticleDAO extends IDAO {
- public abstract Article findArticleById(Integer id) throws DatabaseFailure;
-}
+++ /dev/null
-/*
- * $Id: IArticleStatusDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * ICommentStatusDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IArticleStatusDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IArticleTypeDAO
- * @author idefix
- * @version $Id: IArticleTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public interface IArticleTypeDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IBreakingDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IBreakingDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IBreakingDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: ICategoryDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * ICategoryDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface ICategoryDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: ICategoryTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * ICategoryTypeDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface ICategoryTypeDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-import java.io.Serializable;
-import java.util.List;
-
-
-
-/**
- * IDAO
- * @author idefix
- * @version $Id: IDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public interface IDAO {
- public abstract List findAll() throws DatabaseFailure;
- public abstract List find(int limit, int offset) throws DatabaseFailure;
- public abstract List find(int limit, int offset, Object example) throws DatabaseFailure;
- public abstract List find(IQueryCriteria criteria) throws DatabaseFailure;
- public abstract List find(String query) throws DatabaseFailure;
- public abstract void update(Object o) throws DatabaseFailure;
- public abstract void saveOrUpdate(Object o) throws DatabaseFailure;
- public abstract Serializable save(Object o) throws DatabaseFailure;
- public abstract void delete(Object o) throws DatabaseFailure;
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IDAOFactory
- * @author idefix
- * @version $Id: IDAOFactory.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public interface IDAOFactory {
- public abstract ITransactionManager createTransactionManager();
- public abstract IArticleDAO createArticleDAO();
- public abstract IArticleTypeDAO createArticleTypeDAO();
- public abstract IArticleStatusDAO createArticleStatusDAO();
- public abstract IBreakingDAO createBreakingDAO();
- public abstract ICategoryDAO createCategoryDAO();
- public abstract ICategoryTypeDAO createCategoryTypeDAO();
- public abstract IArticleStatusDAO createCommentStatusDAO();
- public abstract ILanguageDAO createLanugaeDAO();
- public abstract IMediaDAO createMediaDAO();
- public abstract IMediaFolderDAO createMediaFolderDAO();
- public abstract IMediaRelationTypeDAO createMediaRelationTypeDAO();
- public abstract IMessageDAO createMessageDAO();
- public abstract IUploadedMediaDAO createUploadedMediaDAO();
- public abstract IUserDAO createUserDAO();
-}
+++ /dev/null
-/*
- * $Id: ILanguageDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * ILanguageDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface ILanguageDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IMediaDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IMediaDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IMediaDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IMediaFolderDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IMediaFolderDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IMediaFolderDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IMediaRelationTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-
-/**
- * IMediaRelationTypeDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IMediaRelationTypeDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IMessageDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IMessageDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IMessageDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: IQueryCriteria.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-
-
-/**
- * IQueryCriteria
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IQueryCriteria {
- public abstract IQueryCriteria add(IQueryExpression expression);
- public abstract IQueryCriteria addOrder(IQueryOrder order);
- public abstract IQueryCriteria createCriteria(String property) throws DatabaseFailure;
- public abstract IQueryCriteria setLimit(int limit);
- public abstract IQueryCriteria setOffset(int offset);
-}
+++ /dev/null
-/*
- * $Id: IQueryExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-
-/**
- * IExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IQueryExpression {
-}
+++ /dev/null
-/*
- * $Id: IQueryFactory.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-import java.util.Map;
-
-/**
- * IQueryFactory
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IQueryFactory {
- public abstract IQueryCriteria createCriteria(Class persistentClass)
- throws QueryFailure;
- public abstract IQueryOrder descOrder(String property);
- public abstract IQueryOrder ascOrder(String property);
- public abstract IQueryExpression allEq(Map propertyNameValue);
- public abstract IQueryExpression eq(String property, Object value, boolean ignoreCase);
- public abstract IQueryExpression eq(String property, Object value);
- public abstract IQueryExpression not(IQueryExpression expression);
- public abstract IQueryExpression gt(String property, Object value);
- public abstract IQueryExpression ge(String property, Object value);
- public abstract IQueryExpression lt(String property, Object value);
- public abstract IQueryExpression le(String property, Object value);
- public abstract IQueryExpression like(String property, Object value);
-
-
-
-}
+++ /dev/null
-/*
- * $Id: IQueryOrder.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IQueryOrder
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IQueryOrder {
-}
+++ /dev/null
-/*
- * $Id: ITransaction.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-
-/**
- * ITransactionManager
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface ITransaction {
-
- /**
- * commits the transaction
- * @throws DatabaseFailure
- */
- public abstract void commit() throws DatabaseFailure;
-
- /**
- * rolls back the transaction
- */
- public abstract void rollback() throws DatabaseFailure;
-}
+++ /dev/null
-/*
- * $Id: ITransactionManager.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-
-/**
- * ITransactionManager
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface ITransactionManager {
-
- /**
- * Builds a Transaction object and begins the transaction
- * @return the Transaction object
- * @throws DatabaseFailure
- */
- public abstract ITransaction beginTransaction() throws DatabaseFailure;
-}
+++ /dev/null
-/*
- * $Id: IUploadedMediaDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IUploadedMediaDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public interface IUploadedMediaDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-/**
- * IUserDAO
- * @author idefix
- * @version $Id: IUserDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public interface IUserDAO extends IDAO {
-
-}
+++ /dev/null
-/*
- * $Id: QueryFailure.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao;
-
-import org.apache.commons.lang.exception.NestableException;
-
-/**
- * QueryFailure
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class QueryFailure extends NestableException {
-
- /**
- * @param arg0
- */
- public QueryFailure(Throwable e) {
- super("An Exception occured", e);
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import java.io.Serializable;
-import java.math.BigDecimal;
-import java.sql.Timestamp;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import net.sf.hibernate.Criteria;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Query;
-import net.sf.hibernate.Session;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.Transaction;
-import net.sf.hibernate.expression.Criterion;
-import net.sf.hibernate.expression.Example;
-import net.sf.hibernate.expression.Expression;
-import net.sf.hibernate.expression.Order;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IDAO;
-import org.codecoop.mir.core.dao.IQueryCriteria;
-
-/**
- * AbstractDAO
- * @author idefix
- * @version $Id: AbstractDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public abstract class AbstractDAO implements IDAO {
-
- private static SessionFactory sessionFactory;
-
- /**
- * Return the specific Object class that will be used for class-specific
- * implementation of this DAO.
- * @return the reference Class
- *
- */
- protected abstract Class getReferenceClass();
-
- /**
- * Execute a query.
- * @param query a query expressed in Hibernate's query language
- * @return a distinct list of instances (or arrays of instances)
- */
- public List find(String query) throws DatabaseFailure {
- System.out.println(query);
- try {
- List list = find(query, HibernateSessionManager.getSession());
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- initializeCollections(iter.next());
- }
- return list;
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- protected List find(Criteria c) throws DatabaseFailure {
- try {
- List returnList;
- returnList = c.list();
- for (Iterator iter = returnList.iterator(); iter.hasNext();) {
- initializeCollections(iter.next());
- }
- return returnList;
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- public List find(int limit, int offset) throws DatabaseFailure {
- return find(limit, offset, null, null);
- }
-
- public List find(int limit, int offset, Object example) throws DatabaseFailure {
- Example ex = Example.create(example);
- ex.excludeZeroes();
- ex.excludeNone();
- ex.ignoreCase();
- return find(limit, offset, ex, null);
- }
-
- protected List find(int limit, int offset, Criterion crit, Order order)
- throws DatabaseFailure {
- try {
- Session s = HibernateSessionManager.getSession();
- Criteria c = s.createCriteria(getReferenceClass());
- if(crit != null){
- c.add(crit);
- }
- if(order != null){
- c.addOrder(order);
- }
- c.setFirstResult(offset);
- c.setMaxResults(limit);
- return find(c);
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IArticleDAO#findById(java.lang.Integer)
- */
- protected Object findById(Integer id) throws DatabaseFailure{
- try {
- Session s = HibernateSessionManager.getSession();
- Criteria c = s.createCriteria(getReferenceClass());
- c.add(Expression.eq("id", id));
- return find(c).get(0);
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Perform a find but use the session given instead of creating a new one.
- * @param query a query expressed in Hibernate's query language
- * @s the Session to use
- */
- protected List find(String query, Session s) throws HibernateException {
- return s.find(query);
- }
-
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- */
- public List findAll() throws DatabaseFailure {
- try {
- return findAll(HibernateSessionManager.getSession());
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- * Use the session given.
- * @param s the Session
- */
- protected List findAll(Session s) throws DatabaseFailure {
- try {
- Criteria crit = s.createCriteria(getReferenceClass());
- return find(crit);
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
-
-
- public List find(IQueryCriteria criteria) throws DatabaseFailure {
- if(criteria instanceof QueryCriteria){
- QueryCriteria c = (QueryCriteria)criteria;
- return find(c.criteria());
- }
- throw new DatabaseFailure("No applicable implementation of IQueryCriteria");
- }
-
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * @param name the name of a query defined externally
- * @return Query
- */
- protected List getNamedQuery(String name) throws DatabaseFailure {
- try {
- return getNamedQuery(name, HibernateSessionManager.getSession());
- } catch (Exception e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the session given.
- * @param name the name of a query defined externally
- * @param s the Session
- * @return Query
- */
- protected List getNamedQuery(String name, Session s) throws HibernateException {
- Query q = s.getNamedQuery(name);
- return q.list();
- }
-
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given.
- * @param name the name of a query defined externally
- * @param params the parameter array
- * @return Query
- */
- protected List getNamedQuery(String name, Serializable[] params)
- throws DatabaseFailure {
- try {
- return getNamedQuery(name, params, HibernateSessionManager.getSession());
- } catch (Exception e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given and the Session given.
- * @param name the name of a query defined externally
- * @param params the parameter array
- * @s the Session
- * @return Query
- */
- protected List getNamedQuery(String name, Serializable[] params, Session s)
- throws HibernateException {
- Query q = s.getNamedQuery(name);
- for (int i = 0; i < params.length; i++) {
- setParameterValue(q, i, params[i]);
- }
- return q.list();
- }
-
- /**
- * Convenience method to set paramers in the query given based on the actual object type in passed in as the value.
- * You may need to add more functionaly to this as desired (or not use this at all).
- * @param query the Query to set
- * @param position the ordinal position of the current parameter within the query
- * @param value the object to set as the parameter
- */
- protected void setParameterValue(Query query, int position, Object value) {
- if (null == value) {
- return;
- } else if (value instanceof Boolean) {
- query.setBoolean(position, ((Boolean) value).booleanValue());
- } else if (value instanceof String) {
- query.setString(position, (String) value);
- } else if (value instanceof Integer) {
- query.setInteger(position, ((Integer) value).intValue());
- } else if (value instanceof Long) {
- query.setLong(position, ((Long) value).longValue());
- } else if (value instanceof Float) {
- query.setFloat(position, ((Float) value).floatValue());
- } else if (value instanceof Double) {
- query.setDouble(position, ((Double) value).doubleValue());
- } else if (value instanceof BigDecimal) {
- query.setBigDecimal(position, (BigDecimal) value);
- } else if (value instanceof Byte) {
- query.setByte(position, ((Byte) value).byteValue());
- } else if (value instanceof Calendar) {
- query.setCalendar(position, (Calendar) value);
- } else if (value instanceof Character) {
- query.setCharacter(position, ((Character) value).charValue());
- } else if (value instanceof Timestamp) {
- query.setTimestamp(position, (Timestamp) value);
- } else if (value instanceof Date) {
- query.setDate(position, (Date) value);
- } else if (value instanceof Short) {
- query.setShort(position, ((Short) value).shortValue());
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Load object matching the given key and return it.
- */
- protected Object load(Class refClass, Serializable key) throws DatabaseFailure {
- try {
- return load(refClass, key, HibernateSessionManager.getSession());
- } catch (Exception e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Load object matching the given key and return it.
- */
- protected Object load(Class refClass, Serializable key, Session s)
- throws DatabaseFailure {
- try {
- return s.load(refClass, key);
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Persist the given transient instance, first assigning a generated identifier.
- * (Or using the current value of the identifier property if the assigned generator is used.)
- */
- public Serializable save(Object obj) throws DatabaseFailure {
- try {
- return save(obj, HibernateSessionManager.getSession());
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Persist the given transient instance, first assigning a generated identifier.
- * (Or using the current value of the identifier property if the assigned generator is used.)
- */
- protected Serializable save(Object obj, Session s) throws HibernateException {
- Serializable key = null;
- Transaction transaction = s.beginTransaction();
- try {
- key = s.save(obj);
- transaction.commit();
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- }
- return key;
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Either save() or update() the given instance, depending upon the value of its
- * identifier property.
- */
- public void saveOrUpdate(Object obj) throws DatabaseFailure {
- saveOrUpdate(obj, HibernateSessionManager.getSession());
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Either save() or update() the given instance, depending upon the value of its
- * identifier property.
- */
- protected void saveOrUpdate(Object obj, Session s) throws DatabaseFailure {
- try {
- s.saveOrUpdate(obj);
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param obj a transient instance containing updated state
- * @throws
- */
- public void update(Object obj) throws DatabaseFailure {
- try {
- update(obj, HibernateSessionManager.getSession());
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param obj a transient instance containing updated state
- * @param s the Session
- */
- protected void update(Object obj, Session s) throws DatabaseFailure {
- try {
- s.update(obj);
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- */
- public void delete(Object obj) throws DatabaseFailure {
- delete(obj, HibernateSessionManager.getSession());
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- */
- protected void delete(Object obj, Session s) throws DatabaseFailure {
- try {
- s.delete(obj);
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * Used by the base DAO classes but here for your modification
- * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
- * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
- */
- protected void refresh(Object obj, Session s) throws DatabaseFailure {
- try {
- s.refresh(obj);
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- protected abstract void initializeCollections(Object o) throws DatabaseFailure;
-}
+++ /dev/null
-/*
- * $Id: AllEqExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import java.util.Map;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * AllEqExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class AllEqExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param propertyNameValue
- */
- public AllEqExpression(Map propertyNameValue) {
- _expression = Expression.allEq(propertyNameValue);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IArticleDAO;
-import org.codecoop.mir.core.model.Article;
-
-/**
- * ArticleDAO
- * @author idefix
- * @version $Id: ArticleDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class ArticleDAO extends MediaDAO implements IArticleDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return Article.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- super.initializeCollections(o);
- if (o instanceof Article) {
- Article article = (Article) o;
- try {
- Hibernate.initialize(article.getTypedCategories());
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IArticleDAO#findById(java.lang.Integer)
- */
- public Article findArticleById(Integer id) throws DatabaseFailure{
- return (Article) findById(id);
- }
-}
+++ /dev/null
-/*
- * $Id: ArticleStatusDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IArticleStatusDAO;
-import org.codecoop.mir.core.model.ArticleStatus;
-
-/**
- * CommentStatusDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class ArticleStatusDAO extends AbstractDAO implements IArticleStatusDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return ArticleStatus.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.IArticleTypeDAO;
-import org.codecoop.mir.core.model.ArticleType;
-
-/**
- * ArticleTypeDAO
- * @author idefix
- * @version $Id: ArticleTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class ArticleTypeDAO extends AbstractDAO implements IArticleTypeDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return ArticleType.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * $Id: BreakingDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IBreakingDAO;
-import org.codecoop.mir.core.model.BreakingNewsItem;
-
-/**
- * BreakingDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class BreakingDAO extends AbstractDAO implements IBreakingDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return BreakingNewsItem.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * Created on 28.08.2004
- *
- * TODO To change the template for this generated file go to
- * Window - Preferences - Java - Code Generation - Code and Comments
- */
-package org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.Hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.ICategoryDAO;
-import org.codecoop.mir.core.model.Category;
-
-/**
- * CategoryDAO
- * @author idefix
- * $Id: CategoryDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class CategoryDAO extends AbstractDAO implements ICategoryDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return Category.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- if(o instanceof Category){
- Category c = (Category)o;
- try {
- Hibernate.initialize(c.getArticles());
- Hibernate.initialize(c.getChildCategories());
- } catch (Throwable e) {
- throw new DatabaseFailure(e);
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * $Id: CategoryTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.ICategoryTypeDAO;
-import org.codecoop.mir.core.model.CategoryType;
-
-/**
- * CategoryTypeDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class CategoryTypeDAO extends AbstractDAO implements ICategoryTypeDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return CategoryType.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * $Id: EqExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * EqExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class EqExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- * @param ignoreCase
- */
- public EqExpression(String property, Object value, boolean ignoreCase) {
- _expression =
- new net.sf.hibernate.expression.EqExpression(property, value, ignoreCase);
- }
-
- /**
- * @param property
- * @param value
- */
- public EqExpression(String property, Object value) {
- _expression = Expression.eq(property, value);
- }
-}
+++ /dev/null
-/*
- * $Id: GeExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * GeExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class GeExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- */
- public GeExpression(String property, Object value) {
- _expression = Expression.ge(property, value);
- }
-
-}
+++ /dev/null
-/*
- * $Id: GtExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * GtExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class GtExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- */
- public GtExpression(String property, Object value) {
- _expression = Expression.gt(property, value);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.IArticleDAO;
-import org.codecoop.mir.core.dao.IArticleTypeDAO;
-import org.codecoop.mir.core.dao.IBreakingDAO;
-import org.codecoop.mir.core.dao.ICategoryDAO;
-import org.codecoop.mir.core.dao.ICategoryTypeDAO;
-import org.codecoop.mir.core.dao.IArticleStatusDAO;
-import org.codecoop.mir.core.dao.IDAOFactory;
-import org.codecoop.mir.core.dao.ILanguageDAO;
-import org.codecoop.mir.core.dao.IMediaDAO;
-import org.codecoop.mir.core.dao.IMediaFolderDAO;
-import org.codecoop.mir.core.dao.IMediaRelationTypeDAO;
-import org.codecoop.mir.core.dao.IMessageDAO;
-import org.codecoop.mir.core.dao.ITransactionManager;
-import org.codecoop.mir.core.dao.IUploadedMediaDAO;
-import org.codecoop.mir.core.dao.IUserDAO;
-
-/**
- * DAOFactory
- * @author idefix
- * @version $Id: HibernateDAOFactory.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class HibernateDAOFactory implements IDAOFactory {
- private static IDAOFactory factory;
-
- public static synchronized IDAOFactory instance(){
- if(null == factory){
- factory = new HibernateDAOFactory();
- }
- return factory;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createArticleDAO()
- */
- public IArticleDAO createArticleDAO() {
- return new ArticleDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createUserDAO()
- */
- public IUserDAO createUserDAO() {
- return new UserDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createArticleTypeDAO()
- */
- public IArticleTypeDAO createArticleTypeDAO() {
- return new ArticleTypeDAO();
- }
-
- public ICategoryDAO createCategoryDAO(){
- return new CategoryDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createBreakingDAO()
- */
- public IBreakingDAO createBreakingDAO() {
- return new BreakingDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createCategoryTypeDAO()
- */
- public ICategoryTypeDAO createCategoryTypeDAO() {
- return new CategoryTypeDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createCommentStatusDAO()
- */
- public IArticleStatusDAO createCommentStatusDAO() {
- return new ArticleStatusDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createLanugaeDAO()
- */
- public ILanguageDAO createLanugaeDAO() {
- return new LanguageDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createMediaDAO()
- */
- public IMediaDAO createMediaDAO() {
- return new MediaDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createMediaFolderDAO()
- */
- public IMediaFolderDAO createMediaFolderDAO() {
- return new MediaFolderDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createMessageDAO()
- */
- public IMessageDAO createMessageDAO() {
- return new MessageDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createUploadedMediaDAO()
- */
- public IUploadedMediaDAO createUploadedMediaDAO() {
- return new UploadedMediaDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createArticleStatusDAO()
- */
- public IArticleStatusDAO createArticleStatusDAO() {
- return new ArticleStatusDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createMediaRelationTypeDAO()
- */
- public IMediaRelationTypeDAO createMediaRelationTypeDAO() {
- return new MediaRelationTypeDAO();
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.IDAOFactory#createTransactionManager()
- */
- public ITransactionManager createTransactionManager() {
- return new TransactionManager();
- }
-}
+++ /dev/null
-/*
- * $Id: HibernateQueryFactory.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import java.util.Map;
-
-import org.codecoop.mir.core.dao.IQueryCriteria;
-import org.codecoop.mir.core.dao.IQueryExpression;
-import org.codecoop.mir.core.dao.IQueryFactory;
-import org.codecoop.mir.core.dao.IQueryOrder;
-import org.codecoop.mir.core.dao.QueryFailure;
-
-/**
- * HibernateQueryFactory
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class HibernateQueryFactory implements IQueryFactory {
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#createCriteria(java.lang.Class)
- */
- public IQueryCriteria createCriteria(Class persistentClass) throws QueryFailure {
- return new QueryCriteria(persistentClass);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#descOrder(java.lang.String)
- */
- public IQueryOrder descOrder(String property) {
- return new QueryOrder(property, QueryOrder.DESC);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#ascOrder(java.lang.String)
- */
- public IQueryOrder ascOrder(String property) {
- return new QueryOrder(property, QueryOrder.ASC);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#allEq(java.util.Map)
- */
- public IQueryExpression allEq(Map propertyNameValue) {
- return new AllEqExpression(propertyNameValue);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#eq(java.lang.String, java.lang.Object, boolean)
- */
- public IQueryExpression eq(String property, Object value, boolean ignoreCase) {
- return new EqExpression(property, value, ignoreCase);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#eq(java.lang.String, java.lang.Object, boolean)
- */
- public IQueryExpression eq(String property, Object value) {
- return new EqExpression(property, value);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#not(org.codecoop.mir.core.query.IQueryExpression)
- */
- public IQueryExpression not(IQueryExpression expression) {
- return new NotExpression(expression);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#gt(java.lang.String, java.lang.Object)
- */
- public IQueryExpression gt(String property, Object value) {
- return new GtExpression(property, value);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#ge(java.lang.String, java.lang.Object)
- */
- public IQueryExpression ge(String property, Object value) {
- return new GeExpression(property, value);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#lt(java.lang.String, java.lang.Object)
- */
- public IQueryExpression lt(String property, Object value) {
- return new LtExpression(property, value);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#le(java.lang.String, java.lang.Object)
- */
- public IQueryExpression le(String property, Object value) {
- return new LeExpression(property, value);
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryFactory#like(java.lang.String, java.lang.Object)
- */
- public IQueryExpression like(String property, Object value) {
- return new LikeExpression(property, value);
- }
-
-}
+++ /dev/null
-/*
- * $Id: HibernateSessionManager.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Interceptor;
-import net.sf.hibernate.Session;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.cfg.Configuration;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codecoop.mir.core.dao.DatabaseFailure;
-
-/**
- * HibernateUtil
- *
- * @author idefix
- * @version $Revision: 1.1 $
- */
-class HibernateSessionManager {
-
- private static Log log = LogFactory.getLog(HibernateSessionManager.class);
-
- private static Configuration configuration;
- private static SessionFactory sessionFactory;
- private static final ThreadLocal threadSession = new ThreadLocal();
- private static final ThreadLocal threadInterceptor = new ThreadLocal();
-
- // Create the initial SessionFactory from the default configuration files
- static {
- try {
- configuration = new Configuration();
- sessionFactory = configuration.configure().buildSessionFactory();
- log.debug("SessionFactory built.");
- } catch (Throwable ex) {
- log.error("Building SessionFactory failed.", ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- /**
- * Returns the SessionFactory used for this static class.
- *
- * @return SessionFactory
- */
- static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
-
- /**
- * Returns the original Hibernate configuration.
- *
- * @return Configuration
- */
- static Configuration getConfiguration() {
- return configuration;
- }
-
- /**
- * Rebuild the SessionFactory with the static Configuration.
- *
- */
- static void rebuildSessionFactory() throws DatabaseFailure {
- synchronized (sessionFactory) {
- try {
- sessionFactory = getConfiguration().buildSessionFactory();
- } catch (Exception ex) {
- throw new DatabaseFailure(ex);
- }
- }
- }
-
- /**
- * Rebuild the SessionFactory with the given Hibernate Configuration.
- *
- * @param cfg
- */
- static void rebuildSessionFactory(Configuration cfg) throws DatabaseFailure {
- synchronized (sessionFactory) {
- try {
- sessionFactory = cfg.buildSessionFactory();
- configuration = cfg;
- } catch (Exception ex) {
- throw new DatabaseFailure(ex);
- }
- }
- }
-
- /**
- * Retrieves the current Session local to the thread. <p/>If no Session is
- * open, opens a new Session for the running thread.
- *
- * @return Session
- */
- static Session getSession() throws DatabaseFailure {
- Session s = (Session) threadSession.get();
- try {
- if (s == null) {
- log.debug("Opening new Session for this thread.");
- if (getInterceptor() != null) {
- log.debug("Using interceptor: " + getInterceptor().getClass());
- s = getSessionFactory().openSession(getInterceptor());
- } else {
- s = getSessionFactory().openSession();
- }
- threadSession.set(s);
- }
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- }
- return s;
- }
-
- /**
- * Closes the Session local to the thread.
- */
- static void closeSession() throws DatabaseFailure {
- try {
- Session s = (Session) threadSession.get();
- threadSession.set(null);
- if (s != null && s.isOpen()) {
- log.debug("Closing Session of this thread.");
- s.close();
- }
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- }
- }
-
- /**
- * Reconnects a Hibernate Session to the current Thread.
- *
- * @param session
- * The Hibernate Session to be reconnected.
- */
- static void reconnect(Session session) throws DatabaseFailure {
- try {
- session.reconnect();
- threadSession.set(session);
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- }
- }
-
- /**
- * Disconnect and return Session from current Thread.
- *
- * @return Session the disconnected Session
- */
- static Session disconnectSession() throws DatabaseFailure {
-
- Session session = getSession();
- try {
- threadSession.set(null);
- if (session.isConnected() && session.isOpen())
- session.disconnect();
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- }
- return session;
- }
-
- /**
- * Register a Hibernate interceptor with the current thread.
- * <p>
- * Every Session opened is opened with this interceptor after registration.
- * Has no effect if the current Session of the thread is already open,
- * effective on next close()/getSession().
- */
- static void registerInterceptor(Interceptor interceptor) {
- threadInterceptor.set(interceptor);
- }
-
- private static Interceptor getInterceptor() {
- Interceptor interceptor = (Interceptor) threadInterceptor.get();
- return interceptor;
- }
-
-}
-
+++ /dev/null
-/*
- * $Id: LanguageDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.ILanguageDAO;
-import org.codecoop.mir.core.model.Language;
-
-/**
- * LanguageDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class LanguageDAO extends AbstractDAO implements ILanguageDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return Language.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * $Id: LeExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * LeExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class LeExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- */
- public LeExpression(String property, Object value) {
- _expression = Expression.le(property, value);
- }
-
-}
+++ /dev/null
-/*
- * $Id: LikeExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * LikeExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class LikeExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- */
- public LikeExpression(String property, Object value) {
- _expression = Expression.like(property, value);
- }
-
-}
+++ /dev/null
-/*
- * $Id: LtExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * LtExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class LtExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param property
- * @param value
- */
- public LtExpression(String property, Object value) {
- _expression = Expression.lt(property, value);
- }
-
-}
+++ /dev/null
-/*
- * $Id: MediaDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import java.util.Iterator;
-
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IMediaDAO;
-import org.codecoop.mir.core.model.Media;
-
-/**
- * MediaDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class MediaDAO extends AbstractDAO implements IMediaDAO {
-
- /**
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return Media.class;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- if (o instanceof Media) {
- Media media = (Media) o;
- try {
- Hibernate.initialize(media.getRelatedMedias());
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IDAO#delete(java.lang.Object)
- */
- public void delete(Object obj) throws DatabaseFailure {
- if (obj instanceof Media) {
- Media media = (Media) obj;
- //TODO perhaps there could be a smarter way
- //delete all media relations which have the media to be deleted as target
- for (Iterator iter = media.getRelatedMedias().keySet().iterator();
- iter.hasNext();) {
- Media target = (Media) iter.next();
- for (Iterator iterator = target.getRelatedMedias().keySet().iterator();
- iterator.hasNext();) {
- Media m = (Media) iterator.next();
- if(m.equals(media)){
- target.getRelatedMedias().remove(m);
- saveOrUpdate(target);
- }
- }
- }
- }
- super.delete(obj);
- }
-}
+++ /dev/null
-/*
- * $Id: MediaFolderDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IMediaFolderDAO;
-import org.codecoop.mir.core.model.MediaFolder;
-
-/**
- * MediaFolderDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class MediaFolderDAO extends AbstractDAO implements IMediaFolderDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return MediaFolder.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * $Id: MediaRelationTypeDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IMediaRelationTypeDAO;
-import org.codecoop.mir.core.model.MediaRelationType;
-
-/**
- * MediaRelationDAO
- *
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class MediaRelationTypeDAO extends AbstractDAO implements IMediaRelationTypeDAO {
-
- /**
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return MediaRelationType.class;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * $Id: MessageDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IMessageDAO;
-
-/**
- * MessageDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class MessageDAO extends AbstractDAO implements IMessageDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- // TODO Auto-generated method stub
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*
- * $Id: NotExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Expression;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * NotExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class NotExpression extends QueryExpression implements IQueryExpression {
-
- /**
- * @param expression
- */
- public NotExpression(IQueryExpression expression) {
- if(expression instanceof QueryExpression){
- _expression = Expression.not(((QueryExpression)expression).expression());
- }
- }
-
-}
+++ /dev/null
-/*
- * $Id: QueryCriteria.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.Criteria;
-import net.sf.hibernate.HibernateException;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IQueryCriteria;
-import org.codecoop.mir.core.dao.IQueryExpression;
-import org.codecoop.mir.core.dao.IQueryOrder;
-import org.codecoop.mir.core.dao.QueryFailure;
-
-/**
- * QueryCriteria
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class QueryCriteria implements IQueryCriteria {
- private Criteria _criteria;
-
- /**
- * @param persistentClass
- * @throws QueryFailure
- */
- public QueryCriteria(Class persistentClass) throws QueryFailure {
- try {
- _criteria = HibernateSessionManager.getSession().createCriteria(persistentClass);
- } catch (DatabaseFailure e) {
- throw new QueryFailure(e);
- }
- }
-
- /**
- * @param criteria
- */
- private QueryCriteria(Criteria criteria) {
- _criteria = criteria;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryCriteria#add(org.codecoop.mir.core.query.IQueryExpression)
- */
- public IQueryCriteria add(IQueryExpression expression) {
- if(expression instanceof QueryExpression){
- _criteria.add(((QueryExpression)expression).expression());
- }
- return this;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryCriteria#addOrder(org.codecoop.mir.core.query.IQueryOrder)
- */
- public IQueryCriteria addOrder(IQueryOrder order) {
- if(order instanceof QueryOrder){
- _criteria.addOrder(((QueryOrder)order).order());
- }
- return this;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryCriteria#setLimit(int)
- */
- public IQueryCriteria setLimit(int limit) {
- _criteria.setMaxResults(limit);
- return this;
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryCriteria#setOffset(int)
- */
- public IQueryCriteria setOffset(int offset) {
- _criteria.setFirstResult(offset);
- return this;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.query.IQueryCriteria#createCriteria(java.lang.String)
- */
- public IQueryCriteria createCriteria(String property) throws DatabaseFailure {
- try {
- Criteria c = _criteria.createCriteria(property);
- QueryCriteria queryCriteria = new QueryCriteria(c);
- return queryCriteria;
- } catch (HibernateException e) {
- throw new DatabaseFailure(e);
- }
- }
-
- /**
- * @return
- */
- public Criteria criteria() {
- return _criteria;
- }
-
-
-
-}
+++ /dev/null
-/*
- * $Id: QueryExpression.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Criterion;
-
-import org.codecoop.mir.core.dao.IQueryExpression;
-
-/**
- * QueryExpression
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public abstract class QueryExpression implements IQueryExpression {
- protected Criterion _expression;
-
- /**
- * @return
- */
- public Criterion expression() {
- return _expression;
- }
-
-}
+++ /dev/null
-/*
- * $Id: QueryOrder.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.expression.Order;
-
-import org.codecoop.mir.core.dao.IQueryOrder;
-
-/**
- * QueryOrder
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class QueryOrder implements IQueryOrder {
- public static boolean ASC = true;
- public static boolean DESC = false;
- private Order _order;
-
- public QueryOrder(String property, boolean asc){
- if(asc == ASC){
- _order = Order.asc(property);
- } else {
- _order = Order.desc(property);
- }
- }
-
- /**
- * @see org.codecoop.mir.core.dao.IQueryOrder#order()
- */
- public Order order() {
- return _order;
- }
-}
+++ /dev/null
-/*
- * $Id: Transaction.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import net.sf.hibernate.HibernateException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.ITransaction;
-
-/**
- * Transaction
- *
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class Transaction implements ITransaction {
-
- private static Log log = LogFactory.getLog(Transaction.class);
- private static final ThreadLocal threadTransaction = new ThreadLocal();
-
- public Transaction() throws DatabaseFailure {
- net.sf.hibernate.Transaction tx =
- (net.sf.hibernate.Transaction) threadTransaction.get();
- try {
- if (tx == null) {
- log.debug("Starting new database transaction in this thread.");
- tx = HibernateSessionManager.getSession().beginTransaction();
- threadTransaction.set(tx);
- }
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- }
- }
-
- /**
- * @throws DatabaseFailure
- * @see org.codecoop.mir.core.dao.ITransaction#commit()
- */
- public void commit() throws DatabaseFailure {
- net.sf.hibernate.Transaction tx =
- (net.sf.hibernate.Transaction) threadTransaction.get();
- try {
- threadTransaction.set(null);
- if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
- log.debug("Committing database transaction of this thread.");
- tx.commit();
- } else {
- throw new DatabaseFailure("Commiting the transaction was not possible");
- }
- } catch (HibernateException ex) {
- rollback();
- throw new DatabaseFailure(ex);
- }
- }
-
- /**
- * @throws DatabaseFailure
- * @see org.codecoop.mir.core.dao.ITransaction#rollback()
- */
- public void rollback() throws DatabaseFailure {
- net.sf.hibernate.Transaction tx =
- (net.sf.hibernate.Transaction) threadTransaction.get();
- try {
- threadTransaction.set(null);
- if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
- log.debug("Tyring to rollback database transaction of this thread.");
- tx.rollback();
- } else {
- throw new DatabaseFailure("Commiting the transaction was not possible");
- }
- } catch (HibernateException ex) {
- throw new DatabaseFailure(ex);
- } finally {
- HibernateSessionManager.closeSession();
- }
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * $Id: TransactionManager.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.ITransaction;
-import org.codecoop.mir.core.dao.ITransactionManager;
-
-
-/**
- * TransactionManager
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class TransactionManager implements ITransactionManager {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.ITransactionManager#beginTransaction()
- */
- public ITransaction beginTransaction() throws DatabaseFailure {
- return new Transaction();
- }
-
-}
+++ /dev/null
-/*
- * $Id: UploadedMediaDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.DatabaseFailure;
-import org.codecoop.mir.core.dao.IUploadedMediaDAO;
-
-/**
- * UploadedMediaDAO
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class UploadedMediaDAO extends MediaDAO implements IUploadedMediaDAO {
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return IUploadedMediaDAO.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) throws DatabaseFailure {
- super.initializeCollections(o);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.dao.hibernate;
-
-import org.codecoop.mir.core.dao.IUserDAO;
-import org.codecoop.mir.core.model.User;
-
-/**
- * UserDAO
- * @author idefix
- * @version $Id: UserDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- */
-public class UserDAO extends AbstractDAO implements IUserDAO {
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#getReferenceClass()
- */
- protected Class getReferenceClass() {
- return User.class;
- }
-
- /* (non-Javadoc)
- * @see org.codecoop.mir.core.dao.hibernate.AbstractDAO#initializeCollections(java.lang.Object)
- */
- protected void initializeCollections(Object o) {
- // TODO Auto-generated method stub
-
- }
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" > \r
-
-<hibernate-mapping>
- <joined-subclass extends="org.codecoop.mir.core.model.Media"
- name="org.codecoop.mir.core.model.Article"
- table="article">
-
- <key column="media_id" foreign-key="fk_article_media"/>
-
- <property
- column="date"
- length="8"
- name="date"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="subtitle"
- length="255"
- name="subtitle"
- type="java.lang.String"
- />
- <property
- column="edittitle"
- length="255"
- name="edittitle"
- type="java.lang.String"
- />
- <property
- name="content"
- type="java.lang.String">
- <column name="content"
- sql-type="text"
- not-null="true"/>
- </property>
- <property
- column="is_html"
- length="1"
- name="html"
- not-null="true"
- type="boolean"
- />
- <!-- Associations -->
- <many-to-one
- class="org.codecoop.mir.core.model.ArticleStatus"
- column="to_article_status"
- name="status"
- foreign-key="fk_article_articlestatus"
- />
- <many-to-one
- class="org.codecoop.mir.core.model.User"
- column="to_locking_user"
- name="lockingUser"
- foreign-key="fk_article_lockinguser"
- />
- <many-to-one
- class="org.codecoop.mir.core.model.Language"
- column="to_language"
- name="language"
- foreign-key="fk_article_language"
- />
- <set name="typedCategories" table="article_x_category" inverse="false" cascade="save-update">
- <key column="article_id"
- foreign-key="fk_article_category"/>
- <!--
- <composite-element class="org.codecoop.mir.core.model.TypedCategory">
- <many-to-one
- class="org.codecoop.mir.core.model.ArticleType"
- column="article_type_id"
- name="articleType"
- foreign-key="fk_articlexcategory_article_type"
- />
- <many-to-one
- class="org.codecoop.mir.core.model.Category"
- column="category_id"
- name="category"
- foreign-key="fk_articlexcategory_category"
- />
- </composite-element>
- -->
- <many-to-many class="org.codecoop.mir.core.model.TypedCategory"
- foreign-key="fk_articlexcategory">
- <column name="article_type_id"/>
- <column name="category_id"/>
- </many-to-many>
- </set>
- </joined-subclass>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Article.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-/**
- * An Article object is used to save the main content objects.
- * It has references to Media objects and Comment objects. An Article can be in
- * different Categories and has one ArticleType.
- *
- * @author idefix
- */
-public class Article extends Media implements Serializable {
-
- /** persistent field */
- private String date;
-
- /** nullable persistent field */
- private String subtitle;
-
- /** nullable persistent field */
- private String edittitle;
-
- /** nullable persistent field */
- private String content;
-
- /** persistent field */
- private boolean html;
-
- /** nullable persistent field */
- private User lockingUser;
-
- /** nullable persistent field */
- private Language language;
-
- /** nullable persistent field */
- private ArticleStatus status;
-
- /** persistent field */
- private Set typedCategories;
-
- /** persistent field */
- private Set medias;
-
- private int hashCode;
-
- /** default constructor */
- public Article() {
- super();
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
- date = simpleDateFormat.format(new Date());
- }
-
- public String getDate() {
- return this.date;
- }
-
- public void setDate(String date) {
- this.date = date;
- }
-
- public String getSubtitle() {
- return this.subtitle;
- }
-
- public void setSubtitle(String subtitle) {
- this.subtitle = subtitle;
- }
-
- public String getEdittitle() {
- return this.edittitle;
- }
-
- public void setEdittitle(String edittitle) {
- this.edittitle = edittitle;
- }
-
- public String getContent() {
- return this.content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public boolean isHtml() {
- return this.html;
- }
-
- public void setHtml(boolean html) {
- this.html = html;
- }
-
- public User getLockingUser() {
- return this.lockingUser;
- }
-
- public void setLockingUser(User lockingUser) {
- this.lockingUser = lockingUser;
- }
-
- public Language getLanguage() {
- return this.language;
- }
-
- public void setLanguage(Language language) {
- this.language = language;
- }
-
- public ArticleStatus getStatus() {
- return status;
- }
-
- public void setStatus(ArticleStatus status) {
- this.status = status;
- }
-
- public Set getTypedCategories() {
- return this.typedCategories;
- }
-
- public void setTypedCategories(Set topics) {
- this.typedCategories = topics;
- }
-
- public void addTypedCategory(TypedCategory typedCategory){
- if(null == typedCategories){
- typedCategories = new HashSet();
- }
- typedCategories.add(typedCategory);
- }
-
- public Set getMedias() {
- return this.medias;
- }
-
- public void setMedias(Set medias) {
- this.medias = medias;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Article)) {
- return false;
- } else {
- Article mObj = (Article) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
- .append("id", this.getId())
- .toString();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
- \r
-<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.ArticleStatus" \r table="comment_status">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">comment_status_id_seq</param>
- </generator>
- </id>
- <property
- column="name"
- length="40"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: ArticleStatus.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * CommentStatus
- *
- * @author idefix
- */
-public class ArticleStatus implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- private int hashCode;
-
- /** full constructor */
- public ArticleStatus(String name) {
- this.name = name;
- }
-
- /** default constructor */
- public ArticleStatus() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof ArticleStatus)) {
- return false;
- } else {
- ArticleStatus mObj = (ArticleStatus) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-<hibernate-mapping>
- <class name="org.codecoop.mir.core.model.ArticleType" table="article_type">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">article_type_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="40"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: ArticleType.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * An ArticleType object describes the type of an Article. Possible ArticleTypes
- * could be e.g. "feature" or "newswire".
- *
- * @author idefix
- */
-public class ArticleType implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- private int hashCode;
-
- /** full constructor */
- public ArticleType(String name) {
- this.name = name;
- }
-
- /** default constructor */
- public ArticleType() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof ArticleType)) {
- return false;
- } else {
- ArticleType mObj = (ArticleType) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>
- <class name="org.codecoop.mir.core.model.BreakingNewsItem" table="breaking_news_items">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">breaking_id_seq</param>
- </generator>
- </id>
- <property
- column="text"
- length="255"
- name="text"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="creationDate"
- length="8"
- name="creationDate"
- not-null="true"
- type="java.sql.Timestamp"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: BreakingNewsItem.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Breaking
- *
- * @author idefix
- */
-public class BreakingNewsItem implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String text;
-
- /** persistent field */
- private Date creationDate;
-
- private int hashCode;
-
- /** default constructor */
- public BreakingNewsItem() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getText() {
- return this.text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- public Date getCreationDate() {
- return this.creationDate;
- }
-
- public void setCreationDate(Date creationDate) {
- this.creationDate = creationDate;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof BreakingNewsItem)) {
- return false;
- } else {
- BreakingNewsItem mObj = (BreakingNewsItem) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.Category" \r table="category">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">category_id_seq</param>\r </generator>
- </id>
- <property
- column="title"
- length="80"
- name="title"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="description"
- name="description"
- type="java.lang.String"
- />
- <property
- column="filename"
- length="20"
- name="filename"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->\r <many-to-one \r class="org.codecoop.mir.core.model.CategoryType"\r column="category_type"\r name="categoryType"\r foreign-key="fk_category_categorytype"\r />
- <many-to-one
- class="org.codecoop.mir.core.model.Category"
- column="parent_id"
- name="parentCategory"\r foreign-key="fk_category_parentcategory"
- />
- <set name="childCategories">
- <key column="parent_id" \r foreign-key="fk_topic_childcategories"/>
- <one-to-many class="org.codecoop.mir.core.model.Category" />
- </set>
- <set name="articles" table="article_x_category" lazy="true">
- <key column="category_id" \r foreign-key="fk_category_article"/>
- <many-to-many \r class="org.codecoop.mir.core.model.Article"\r foreign-key="fk_article_category_2" \r column="article_id" />
- </set>
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Category.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Category
- *
- * @author idefix
- */
-public class Category implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String title;
-
- /** nullable persistent field */
- private String description;
-
- /** persistent field */
- private String filename;
-
- /** nullable persistent field */
- private CategoryType categoryType;
-
- /** nullable persistent field */
- private Category parentCategory;
-
- /** persistent field */
- private Set childCategories;
-
- /** persistent field */
- private Set articles;
-
- private int hashCode;
-
- /** default constructor */
- public Category() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getTitle() {
- return this.title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getFilename() {
- return this.filename;
- }
-
- public void setFilename(String filename) {
- this.filename = filename;
- }
-
- public org.codecoop.mir.core.model.CategoryType getCategoryType() {
- return this.categoryType;
- }
-
- public void setCategoryType(
- org.codecoop.mir.core.model.CategoryType categoryType) {
- this.categoryType = categoryType;
- }
-
- public Category getParentCategory() {
- return this.parentCategory;
- }
-
- public void setParentCategory(Category parentCategory) {
- this.parentCategory = parentCategory;
- }
-
- public void addChildCategory(Category category){
- if(childCategories == null){
- childCategories = new HashSet();
- }
- childCategories.add(category);
- }
-
- public Set getChildCategories() {
- return this.childCategories;
- }
-
- public void setChildCategories(Set childTopics) {
- this.childCategories = childTopics;
- }
-
- public Set getArticles() {
- return this.articles;
- }
-
- public void setArticles(Set articles) {
- this.articles = articles;
- }
-
- public void addArticle(Article article){
- if(articles == null){
- articles = new HashSet();
- }
- articles.add(article);
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Category)) {
- return false;
- } else {
- Category mObj = (Category) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-\r<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.CategoryType" \r table="category_type">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">category_type_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="40"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: CategoryType.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * CategoryType
- *
- * @author idefix
- */
-public class CategoryType implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- private int hashCode;
-
- /** full constructor */
- public CategoryType(String name) {
- this.name = name;
- }
-
- /** default constructor */
- public CategoryType() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof CategoryType)) {
- return false;
- } else {
- CategoryType mObj = (CategoryType) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
-
-<hibernate-mapping>
- <class name="org.codecoop.mir.core.model.Group" table="Group">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">group_id_seq</param>
- </generator>
- </id>
-
- <many-to-one
- name="role"
- column="to_role"
- foreign-key="fk_group_role"
- class="org.codecoop.mir.core.model.Role"/>
-
- <set
- lazy="true"
- name="users"
- table="users_x_group"
- >
- <key column="group_id" />
- <many-to-many class="org.codecoop.mir.core.model.User"
- foreign-key="fk_group_user"
- column="user_id"/>
- </set>
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Group.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Group
- *
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class Group {
-
- private Integer _id;
- private Set _users;
- private Role _role;
-
- private transient int hashCode;
-
- /**
- * @return Returns the id.
- */
- public Integer getId() {
- return _id;
- }
-
- /**
- * @param id
- * The id to set.
- */
- public void setId(Integer id) {
- _id = id;
- }
-
- /**
- * @return Returns the role.
- */
- public Role getRole() {
- return _role;
- }
-
- /**
- * @param role
- * The role to set.
- */
- public void setRole(Role role) {
- _role = role;
- }
-
- /**
- * @return Returns the users.
- */
- public Set getUsers() {
- return _users;
- }
-
- /**
- * @param users
- * The users to set.
- */
- public void setUsers(Set users) {
- _users = users;
- }
-
- public void addUser(User user){
- if(_users == null){
- _users = new HashSet();
- }
- _users.add(user);
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Group)) {
- return false;
- } else {
- Group mObj = (Group) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.Language" \r table="language">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">language_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="40"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="code"
- length="2"
- name="code"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Language.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Language
- *
- * @author idefix
- */
-public class Language implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String code;
-
- private int hashCode;
-
- /** full constructor */
- public Language(String name, String code) {
- this.name = name;
- this.code = code;
- }
-
- /** default constructor */
- public Language() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getCode() {
- return this.code;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Language)) {
- return false;
- } else {
- Language mObj = (Language) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
- <class
- name="org.codecoop.mir.core.model.Media"
- table="media">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- column="title"
- length="255"
- name="title"
- type="java.lang.String"
- />
- <property
- name="description"
- type="java.lang.String">
- <column name="description" sql-type="text"/>
- </property>
- <property
- column="creator"
- length="80"
- name="creator"
- type="java.lang.String"
- />
- <property
- column="creator_main_url"
- length="255"
- name="creatorMainUrl"
- type="java.lang.String"
- />
- <property
- column="creator_email"
- length="80"
- name="creatorEmail"
- type="java.lang.String"
- />
- <property
- column="creator_address"
- length="80"
- name="creatorAddress"
- type="java.lang.String"
- />
- <property
- column="creator_phone"
- length="80"
- name="creatorPhone"
- type="java.lang.String"
- />
- <property
- column="internal_comment"
- length="255"
- name="internalComment"
- type="java.lang.String"
- />
- <property
- column="is_produced"
- length="1"
- name="produced"
- not-null="true"
- type="boolean"
- />
- <property
- column="creation_date"
- length="8"
- name="creationDate"
- not-null="true"
- type="java.sql.Timestamp"
- />
- <property
- column="last_change"
- length="8"
- name="lastChange"
- type="java.sql.Timestamp"
- />
- <many-to-one
- class="org.codecoop.mir.core.model.User"
- column="to_publisher"
- name="publisher"
- foreign-key="fk_media_user"
- />
- <map
- name="relatedMedias"
- table="media_x_media"
- lazy="true"
- inverse="false"
- cascade="save-update">
- <key
- column="source_media_id"
- foreign-key="fk_mediaxmedia_sourcemedia"/>
- <index-many-to-many
- column="related_media_id"
- class="org.codecoop.mir.core.model.Media"
- foreign-key="fk_mediaxmedia_relatedmedia"/>
- <many-to-many
- column="media_relation_type_id"
- class="org.codecoop.mir.core.model.MediaRelationType"
- foreign-key="fk_mediaxmedia_mediarelationtype"/>
- </map>
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Media.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-/**
- * Media
- *
- * @author idefix
- */
-public class Media implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** nullable persistent field */
- private String title;
-
- /** nullable persistent field */
- private String description;
-
- /** nullable persistent field */
- private String creator;
-
- /** nullable persistent field */
- private String creatorMainUrl;
-
- /** nullable persistent field */
- private String creatorEmail;
-
- /** nullable persistent field */
- private String creatorAddress;
-
- /** nullable persistent field */
- private String creatorPhone;
-
- /** nullable persistent field */
- private String internalComment;
-
- /** persistent field */
- private boolean produced;
-
- /** persistent field */
- private Date creationDate;
-
- /** nullable persistent field */
- private Date lastChange;
-
- /** nullable persistent field */
- private User publisher;
-
- private Map relatedMedias;
-
- /** holds hashCode for hashCode() */
- private transient int hashCode = Integer.MIN_VALUE;
-
- /** default constructor */
- public Media() {
- creationDate = new Date();
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getTitle() {
- return this.title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getCreator() {
- return this.creator;
- }
-
- public void setCreator(String creator) {
- this.creator = creator;
- }
-
- public String getCreatorMainUrl() {
- return this.creatorMainUrl;
- }
-
- public void setCreatorMainUrl(String creatorMainUrl) {
- this.creatorMainUrl = creatorMainUrl;
- }
-
- public String getCreatorEmail() {
- return this.creatorEmail;
- }
-
- public void setCreatorEmail(String creatorEmail) {
- this.creatorEmail = creatorEmail;
- }
-
- public String getCreatorAddress() {
- return this.creatorAddress;
- }
-
- public void setCreatorAddress(String creatorAddress) {
- this.creatorAddress = creatorAddress;
- }
-
- public String getCreatorPhone() {
- return this.creatorPhone;
- }
-
- public void setCreatorPhone(String creatorPhone) {
- this.creatorPhone = creatorPhone;
- }
-
- public String getInternalComment() {
- return this.internalComment;
- }
-
- public void setInternalComment(String internalComment) {
- this.internalComment = internalComment;
- }
-
- public boolean isProduced() {
- return this.produced;
- }
-
- public void setProduced(boolean produced) {
- this.produced = produced;
- }
-
- public Date getCreationDate() {
- return this.creationDate;
- }
-
- public void setCreationDate(Date creationDate) {
- this.creationDate = creationDate;
- }
-
- public Date getLastChange() {
- return this.lastChange;
- }
-
- public void setLastChange(Date lastChange) {
- this.lastChange = lastChange;
- }
-
- public User getPublisher() {
- return this.publisher;
- }
-
- public void setPublisher(User publisher) {
- this.publisher = publisher;
- }
-
- /**
- * @return Returns the relatedMedias.
- */
- public Map getRelatedMedias() {
- return relatedMedias;
- }
-
- /**
- * @param relatedMedias The relatedMedias to set.
- */
- public void setRelatedMedias(Map relatedMedias) {
- this.relatedMedias = relatedMedias;
- }
-
- /**
- * @param mediaRelation
- */
- public void addRelatedMedia(Media target, MediaRelationType relationType) {
- if(relatedMedias == null){
- relatedMedias = new HashMap();
- }
- relatedMedias.put(target, relationType);
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
- .append("id", this.getId()).toString();
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Media)) {
- return false;
- } else {
- Media mObj = (Media) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId())
- return super.hashCode();
- else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.MediaFolder" \r table="media_folder">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">media_folder_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="255"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="date"
- length="8"
- name="date"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="place"
- length="80"
- name="place"
- type="java.lang.String"
- />
- <property
- column="keywords"
- length="255"
- name="keywords"
- type="java.lang.String"
- />
- <property
- column="internal_comment"
- length="255"
- name="internalComment"
- type="java.lang.String"
- />
- <property
- column="creationDate"
- length="8"
- name="creationDate"
- not-null="true"
- type="java.sql.Timestamp"
- />
- <property
- column="last_change"
- length="8"
- name="lastChange"
- type="java.sql.Timestamp"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: MediaFolder.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * MediaFolder
- *
- * @author idefix
- */
-public class MediaFolder implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String date;
-
- /** nullable persistent field */
- private String place;
-
- /** nullable persistent field */
- private String keywords;
-
- /** nullable persistent field */
- private String internalComment;
-
- /** persistent field */
- private Date creationDate;
-
- /** nullable persistent field */
- private Date lastChange;
-
- private int hashCode;
-
- /** default constructor */
- public MediaFolder() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDate() {
- return this.date;
- }
-
- public void setDate(String date) {
- this.date = date;
- }
-
- public String getPlace() {
- return this.place;
- }
-
- public void setPlace(String place) {
- this.place = place;
- }
-
- public String getKeywords() {
- return this.keywords;
- }
-
- public void setKeywords(String keywords) {
- this.keywords = keywords;
- }
-
- public String getInternalComment() {
- return this.internalComment;
- }
-
- public void setInternalComment(String internalComment) {
- this.internalComment = internalComment;
- }
-
- public Date getCreationDate() {
- return this.creationDate;
- }
-
- public void setCreationDate(Date creationDate) {
- this.creationDate = creationDate;
- }
-
- public Date getLastChange() {
- return this.lastChange;
- }
-
- public void setLastChange(Date lastChange) {
- this.lastChange = lastChange;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof MediaFolder)) {
- return false;
- } else {
- MediaFolder mObj = (MediaFolder) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
-
-<hibernate-mapping>
- <class
- name="org.codecoop.mir.core.model.MediaRelationType"
- table="media_relation_type">
-
- <id name="id"
- type="java.lang.Integer"
- column="id">
- <generator class="native">
- <param name="sequence">media_relation_type_id_seq</param>
- </generator>
- </id>
-
- <property name="name" column="name" type="java.lang.String"/>
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: MediaRelationType.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * MediaRelationType
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class MediaRelationType {
- private Integer _id;
- private String _name;
-
- private transient int hashCode;
-
-
- public Integer getId() {
- return _id;
- }
-
- public void setId(Integer id) {
- _id = id;
- }
-
- public String getName() {
- return _name;
- }
-
- public void setName(String name) {
- _name = name;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof MediaRelationType)) {
- return false;
- } else {
- MediaRelationType mObj = (MediaRelationType) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
-<hibernate-mapping>\r <class \r name="org.codecoop.mir.core.model.MediaType" \r table="media_type">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">media_type_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="80"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="mime_type"
- length="40"
- name="mimeType"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="classname"
- length="80"
- name="classname"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="tablename"
- length="80"
- name="tablename"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="dcname"
- length="20"
- name="dcname"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: MediaType.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * MediaType
- *
- * @author idefix
- */
-public class MediaType implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String mimeType;
-
- /** persistent field */
- private String classname;
-
- /** persistent field */
- private String tablename;
-
- /** nullable persistent field */
- private String dcname;
-
- private int hashCode;
-
- /** default constructor */
- public MediaType() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getMimeType() {
- return this.mimeType;
- }
-
- public void setMimeType(String mimeType) {
- this.mimeType = mimeType;
- }
-
- public String getClassname() {
- return this.classname;
- }
-
- public void setClassname(String classname) {
- this.classname = classname;
- }
-
- public String getTablename() {
- return this.tablename;
- }
-
- public void setTablename(String tablename) {
- this.tablename = tablename;
- }
-
- public String getDcname() {
- return this.dcname;
- }
-
- public void setDcname(String dcname) {
- this.dcname = dcname;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof MediaType)) {
- return false;
- } else {
- MediaType mObj = (MediaType) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()) {
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>\r <class \r name="org.codecoop.mir.core.model.Message" \r table="messages">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">breaking_id_seq</param>\r </generator>
- </id>
- <property
- column="title"
- length="30"
- name="title"
- type="java.lang.String"
- />
- <property
- column="description"
- length="255"
- name="description"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="creator"
- length="30"
- name="creator"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="creation_date"
- length="8"
- name="creationDate"
- not-null="true"
- type="java.sql.Timestamp"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Message.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Message
- *
- * @author idefix
- */
-public class Message implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** nullable persistent field */
- private String title;
-
- /** persistent field */
- private String description;
-
- /** persistent field */
- private String creator;
-
- /** persistent field */
- private Date creationDate;
-
- private int hashCode;
-
- /** default constructor */
- public Message() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getTitle() {
- return this.title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getCreator() {
- return this.creator;
- }
-
- public void setCreator(String creator) {
- this.creator = creator;
- }
-
- public Date getCreationDate() {
- return this.creationDate;
- }
-
- public void setCreationDate(Date creationDate) {
- this.creationDate = creationDate;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Message)) {
- return false;
- } else {
- Message mObj = (Message) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
-<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.Right" \r table="rights">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">\r <param name="sequence">right_id_seq</param>\r </generator>
- </id>
- <property
- column="name"
- length="80"
- name="name"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="description"
- length="255"
- name="description"
- type="java.lang.String"
- />
- <!-- Associations -->
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Right.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Right
- *
- * @author idefix
- */
-public class Right implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** nullable persistent field */
- private String description;
-
- private int hashCode;
-
- /** default constructor */
- public Right() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Right)) {
- return false;
- } else {
- Right mObj = (Right) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.Role" \r table="roles">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">role_id_seq</param>
- </generator>
- </id>
- <property
- column="name"
- length="16"
- name="name"
- not-null="true"
- type="java.lang.String"
- unique="true"
- />
- <property
- column="description"
- length="255"
- name="description"
- not-null="true"
- type="java.lang.String"
- />
- <!-- Associations -->\r <set name="users">\r <key column="to_role" foreign-key="fk_role_user"/>\r <one-to-many class="org.codecoop.mir.core.model.User"/>\r </set>\r
- <set name="rights" table="role_x_rights">\r
- <key column="role_id" foreign-key="fk_role_right"/>\r
- <many-to-many class="org.codecoop.mir.core.model.Right"\r
- foreign-key="fk_right_role"\r
- column="right_id"/>\r
- </set>
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: Role.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * Role
- *
- * @author idefix
- */
-public class Role implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String description;
-
- /** persistent field */
- private Set _users;
-
- /** persistent field */
- private Set _rights;
-
- private transient int hashCode;
-
- /** default constructor */
- public Role() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- /**
- * @return Returns the rights.
- */
- public Set getRights() {
- return _rights;
- }
-
- /**
- * @param rights The rights to set.
- */
- public void setRights(Set rights) {
- _rights = rights;
- }
-
- public void addRight(Right right){
- if(null == _rights){
- _rights = new HashSet();
- }
- _rights.add(right);
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Set getUsers() {
- return _users;
- }
-
- public void setUsers(Set users) {
- _users = users;
- }
-
- public void addUser(User user){
- if(_users == null){
- _users = new HashSet();
- }
- _users.add(user);
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof Role)) {
- return false;
- } else {
- Role mObj = (Role) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
-
-<hibernate-mapping>
- <class
- name="org.codecoop.mir.core.model.TypedCategory"
- table="article_x_category">
-
- <composite-id>
- <key-many-to-one
- class="org.codecoop.mir.core.model.ArticleType"
- column="article_type_id"
- name="articleType"
- foreign-key="fk_articlexcategory_article_type"
- />
- <key-many-to-one
- class="org.codecoop.mir.core.model.Category"
- column="category_id"
- name="category"
- foreign-key="fk_articlexcategory_category"
- />
- </composite-id>
-
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: TypedCategory.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-/**
- * TypedCategory
- * @author idefix
- * @version $Revision: 1.1 $
- */
-public class TypedCategory implements Serializable {
- private ArticleType _articleType;
- private Category _category;
-
- private transient int hashCode;
-
- /**
- * @return Returns the articleType.
- */
- public ArticleType getArticleType() {
- return _articleType;
- }
-
- /**
- * @param articleType The articleType to set.
- */
- public void setArticleType(ArticleType articleType) {
- _articleType = articleType;
- }
-
- /**
- * @return Returns the category.
- */
- public Category getCategory() {
- return _category;
- }
-
- /**
- * @param category The category to set.
- */
- public void setCategory(Category category) {
- _category = category;
- }
-
- /**
- *
- */
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof TypedCategory)) {
- return false;
- } else {
- TypedCategory mObj = (TypedCategory) obj;
- if ((null == this.getArticleType() || null == mObj.getArticleType())
- && (null == this.getCategory() || null == mObj.getCategory())) {
- return false;
- } else {
- return
- (this.getArticleType().equals(mObj.getArticleType())
- & this.getCategory().equals(mObj.getCategory()));
- }
- }
- }
-
- /**
- *
- */
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getArticleType() || null == this.getCategory()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getArticleType().hashCode()
- + this.getCategory().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- /**
- *
- */
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
- .append("articleType", this.getArticleType())
- .append("category", this.getCategory())
- .toString();
- }
-}
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>\r <joined-subclass \r name="org.codecoop.mir.core.model.UploadedMedia" \r extends="org.codecoop.mir.core.model.Media" \r table="uploaded_media">\r\r <key \r column="media_id" \r foreign-key="fk_uploadedmedia_media"\r />\r
- <property
- column="publish_server"
- length="255"
- name="publishServer"
- type="java.lang.String"
- />
- <property
- column="publish_path"
- length="255"
- name="publishPath"
- type="java.lang.String"
- />\r <property\r column="storage_path"\r length="255"\r name="storagePath"\r type="java.lang.String"\r />
- <property
- column="icon_produced"
- length="1"
- name="iconProduced"
- not-null="true"
- type="boolean"
- />
- <property
- column="icon_path"
- length="255"
- name="iconPath"
- type="java.lang.String"
- />
- <property
- column="size"
- length="4"
- name="size"
- type="java.lang.Integer"
- />
- <!-- Associations -->\r <many-to-one \r column="to_media_folder"\r name="mediaFolder"\r class="org.codecoop.mir.core.model.MediaFolder"\r foreign-key="fk_uploadedmedia_mediafolder"\r />\r <many-to-one \r column="to_media_type"\r name="mediaType"\r class="org.codecoop.mir.core.model.MediaType"\r foreign-key="fk_uploadedmedia_mediatype" \r />
- </joined-subclass>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: UploadedMedia.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * UploadedMedia
- *
- * @author idefix
- */
-public class UploadedMedia extends Media implements Serializable {
-
- /** nullable persistent field */
- private String publishServer;
-
- /** nullable persistent field */
- private String publishPath;
-
- /** nullable persistent field */
- private String storagePath;
-
- private MediaFolder mediaFolder;
-
- private MediaType mediaType;
-
- /** persistent field */
- private boolean iconProduced;
-
- /** nullable persistent field */
- private String iconPath;
-
- /** nullable persistent field */
- private Integer size;
-
- private int hashCode;
-
- /** default constructor */
- public UploadedMedia() {
- }
-
- public String getPublishServer() {
- return this.publishServer;
- }
-
- public void setPublishServer(String publishServer) {
- this.publishServer = publishServer;
- }
-
- public String getPublishPath() {
- return this.publishPath;
- }
-
- public void setPublishPath(String publishPath) {
- this.publishPath = publishPath;
- }
-
- public String getStoragePath() {
- return this.storagePath;
- }
-
- public void setStoragePath(String storagePath) {
- this.storagePath = storagePath;
- }
-
- public boolean isIconProduced() {
- return this.iconProduced;
- }
-
- public void setIconProduced(boolean iconProduced) {
- this.iconProduced = iconProduced;
- }
-
- public String getIconPath() {
- return this.iconPath;
- }
-
- public void setIconPath(String iconPath) {
- this.iconPath = iconPath;
- }
-
- public Integer getSize() {
- return this.size;
- }
-
- public void setSize(Integer size) {
- this.size = size;
- }
-
- /**
- * @return Returns the mediaFolder.
- */
- public MediaFolder getMediaFolder() {
- return mediaFolder;
- }
-
- /**
- * @param mediaFolder
- * The mediaFolder to set.
- */
- public void setMediaFolder(MediaFolder mediaFolder) {
- this.mediaFolder = mediaFolder;
- }
-
- /**
- * @return Returns the mediaType.
- */
- public MediaType getMediaType() {
- return mediaType;
- }
-
- /**
- * @param mediaType
- * The mediaType to set.
- */
- public void setMediaType(MediaType mediaType) {
- this.mediaType = mediaType;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof UploadedMedia)) {
- return false;
- } else {
- UploadedMedia mObj = (UploadedMedia) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()){
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r "-//Hibernate/Hibernate Mapping DTD 2.0//EN"\r "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r\r<hibernate-mapping>
- <class \r name="org.codecoop.mir.core.model.User" \r table="users">
- <id
- column="id"
- name="id"
- type="java.lang.Integer"
- >
- <generator class="native">
- <param name="sequence">users_id_seq</param>
- </generator>
- </id>
- <property
- column="login"
- length="16"
- name="login"
- not-null="true"
- type="java.lang.String"
- unique="true"
- />
- <property
- column="password"
- length="255"
- name="password"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="internal_comment"
- length="255"
- name="internalComment"
- type="java.lang.String"
- />
- <property
- column="is_disabled"
- length="1"
- name="disabled"
- not-null="true"
- type="boolean"
- />
- <property
- column="email"
- length="255"
- name="email"
- not-null="true"
- type="java.lang.String"
- />
- <property
- column="profile"
- length="255"
- name="profile"
- type="java.lang.String"
- />
- <property
- column="creationDate"
- length="8"
- name="creationDate"
- not-null="true"
- type="java.sql.Timestamp"
- />
- <property
- column="lastlogin"
- length="8"
- name="lastlogin"
- type="java.sql.Timestamp"
- />
- <!-- Associations -->\r <many-to-one \r class="org.codecoop.mir.core.model.Role" \r name="role" \r column="to_role"\r foreign-key="fk_user_role"\r />
- </class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * $Id: User.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
- *
- * Copyright (C) 2001, 2002, 2003, 2004 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 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 org.codecoop.mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * User
- *
- * @author idefix
- */
-public class User implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String login;
-
- /** persistent field */
- private String password;
-
- /** nullable persistent field */
- private String internalComment;
-
- /** persistent field */
- private boolean disabled;
-
- /** persistent field */
- private String email;
-
- /** nullable persistent field */
- private String profile;
-
- /** persistent field */
- private Date creationDate;
-
- /** nullable persistent field */
- private Date lastlogin;
-
- /** nullable persistent field */
- private Role role;
-
- private int hashCode;
-
- /** default constructor */
- public User() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getLogin() {
- return this.login;
- }
-
- public void setLogin(String login) {
- this.login = login;
- }
-
- public String getPassword() {
- return this.password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public String getInternalComment() {
- return this.internalComment;
- }
-
- public void setInternalComment(String internalComment) {
- this.internalComment = internalComment;
- }
-
- public boolean isDisabled() {
- return this.disabled;
- }
-
- public void setDisabled(boolean disabled) {
- this.disabled = disabled;
- }
-
- public String getEmail() {
- return this.email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getProfile() {
- return this.profile;
- }
-
- public void setProfile(String profile) {
- this.profile = profile;
- }
-
- public Date getCreationDate() {
- return this.creationDate;
- }
-
- public void setCreationDate(Date creationDate) {
- this.creationDate = creationDate;
- }
-
- public Date getLastlogin() {
- return this.lastlogin;
- }
-
- public void setLastlogin(Date lastlogin) {
- this.lastlogin = lastlogin;
- }
-
- public Role getRole() {
- return this.role;
- }
-
- public void setRole(Role role) {
- this.role = role;
- }
-
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
- if (!(obj instanceof User)) {
- return false;
- } else {
- User mObj = (User) obj;
- if (null == this.getId() || null == mObj.getId()) {
- return false;
- } else {
- return (this.getId().equals(mObj.getId()));
- }
- }
- }
-
- public int hashCode() {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()) {
- return super.hashCode();
- } else {
- String hashStr = this.getClass().getName() + ":"
- + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
-}
\ No newline at end of file
import java.util.Iterator;
import java.util.List;
-import mir.util.ExceptionFunctions;
+import mir.util.ExceptionRoutines;
import mir.util.PropertiesManipulator;
public class BundleTool {
public static void compare(String aMaster, String aSlave) {
PropertiesManipulator master;
PropertiesManipulator slave;
- PropertiesManipulator result;
try {
master = PropertiesManipulator.readProperties(
new FileInputStream(new File(aSourceFile)),8192), anEncoding);
}
catch (Throwable t) {
- Throwable s = ExceptionFunctions.traceCauseException(t);
+ Throwable s = ExceptionRoutines.traceCauseException(t);
System.out.println("Unable to read sourcefile: " + s.toString());
return;
+++ /dev/null
-package tool;
-
-import java.awt.Transparency;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-import java.awt.image.SampleModel;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-
-import javax.media.jai.JAI;
-import javax.media.jai.PlanarImage;
-
-
-/**
- * This class displays basic information about the image.
- */
-public class ImageTool {
- /**
- * The application entry point.
- * @param args the command line arguments.
- */
- public static void main(String[] args) throws FileNotFoundException {
- // We need one argument: the image filename.
- if (args.length != 1) {
- System.err.println("Usage: java tool.ImageTool image");
- System.exit(0);
- }
- FileInputStream fi = new FileInputStream(args[0]);
- // Open the image (using the name passed as a command line parameter)
- PlanarImage pi = JAI.create("ImageRead", fi);
-
- // Display image data. First, the image size (non-JAI related).
- File image = new File(args[0]);
- System.out.println("Image file size:" + image.length() + " bytes.");
-
- // Now let's display the image dimensions and coordinates.
- System.out.print("Dimensions: ");
- System.out.print(pi.getWidth() + "x" + pi.getHeight() + " pixels");
- System.out.println(" (from " + pi.getMinX() + "," + pi.getMinY() + " to " +
- pi.getMaxX() + "," + pi.getMaxY() + ")");
-
- // Tiles number, dimensions and coordinates.
- System.out.print("Tiles:");
- System.out.print(pi.getTileWidth() + "x" + pi.getTileHeight() + " pixels" +
- " (" + pi.getNumXTiles() + "x" + pi.getNumYTiles() +
- " tiles)");
- System.out.print(" (from " + pi.getMinTileX() + "," + pi.getMinTileY() +
- " to " + pi.getMaxTileX() + "," + pi.getMaxTileY() + ")");
- System.out.println(" offset: " + pi.getTileGridXOffset() + "," +
- pi.getTileGridXOffset());
-
- // Display info about the SampleModel of the image.
- SampleModel sm = pi.getSampleModel();
- System.out.println("Number of bands: " + sm.getNumBands());
- System.out.print("Data type: ");
-
- switch (sm.getDataType()) {
- case DataBuffer.TYPE_BYTE:
- System.out.println("byte");
-
- break;
-
- case DataBuffer.TYPE_SHORT:
- System.out.println("short");
-
- break;
-
- case DataBuffer.TYPE_USHORT:
- System.out.println("unsigned short");
-
- break;
-
- case DataBuffer.TYPE_INT:
- System.out.println("int");
-
- break;
-
- case DataBuffer.TYPE_FLOAT:
- System.out.println("float");
-
- break;
-
- case DataBuffer.TYPE_DOUBLE:
- System.out.println("double");
-
- break;
-
- case DataBuffer.TYPE_UNDEFINED:
- System.out.println("undefined");
-
- break;
- }
-
- // Display info about the ColorModel of the image.
- ColorModel cm = pi.getColorModel();
- System.out.println("Number of color components: " + cm.getNumComponents());
- System.out.println("Bits per pixel: " + cm.getPixelSize());
- System.out.print("Transparency: ");
-
- switch (cm.getTransparency()) {
- case Transparency.OPAQUE:
- System.out.println("opaque");
-
- break;
-
- case Transparency.BITMASK:
- System.out.println("bitmask");
-
- break;
-
- case Transparency.TRANSLUCENT:
- System.out.println("translucent");
-
- break;
- }
- }
-}
<call showGETButton(anUrl, aLabel)>
<comment>
<form method="POST" action="${utility.encodeHTML(config.actionRoot+"?"+anUrl)}"><input type="submit" class="majorbutton" value="${aLabel}"></form>
-</comment>
+</comment>
</function>
<tr>
<list aHeaders as i>
<td class="${TABLE_HEAD_CLASS}">
- <b>${i}</b>
+ <b>${i}</b>
</td>
</list>
<if aShowDelete == "1" || aShowEdit == "1">
<td class="${TABLE_HEAD_CLASS}">
- </td>
+ </td>
</if>
</tr>
<assign alternative="0">
-
+
<list anEntityList as entry>
<if alternative=="0">
<assign alternative="1">
<assign alternative="0">
<tr class="${LIST_ROW_CLASS_ALTERNATIVE}">
</if>
-
- <list aDataKeys as i>
+
+ <list aDataKeys as i>
<td>
${utility.prettyEncodeHTML(entry[i])}
</td>
<a class="listcommand" href="${config.actionRoot}?module=${aModuleName}&do=delete&id=${entry.id}&okurl=${utility.encodeURI(thisurl)}&cancelurl=${utility.encodeURI(thisurl)}">${lang("delete")}</a>
</if>
<if aShowDelete == "1" && aShowEdit == "1">
- |
+ |
</if>
<if aShowEdit == "1">
<a class="listcommand" href="${config.actionRoot}?module=${aModuleName}&do=edit&id=${entry.id}">${lang("edit")}</a>
</if>
</tr>
</list>
-
-
- <tr>
+
+
+ <tr>
<td colspan="${nrColumns}" class="${TABLE_FOOT_CLASS}">
${aCount} ${lang("records")} / ${lang("show_from_to", aFrom, aTo)}
</td>
</tr>
-
+
</table>
</function>
</list>
</td>
</tr>
-</function>
+</function>
<function PulldownTableRow (label, fieldname, entrieslist, keyfield, valuefield, value, langprefix)>
<tr>
</select>
</td>
</tr>
-</function>
+</function>
<function ReadonlyTextTableRowNormal (label, fieldcontent)>
<call ReadonlyTextTableRow(label, fieldcontent, "listrow2")>
-</function>
+</function>
<function _TextInputTableRow(label, size, maxlength, fieldname, fieldcontent, aCanEdit)>
<td align="right" class="table-left">
<b>${label}:</b>
</td>
-
+
<td class="listrow2">
<input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
</td>
<td align="right" class="table-left">
<b>${label}:</b>
</td>
-
+
<td class="${class}">
${utility.encodeHTML(fieldcontent)}
</td>
<td align="right" class="table-left">
<b>${label}:</b>
</td>
-
+
<td class="listrow2">
<input type="password" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
</td>
<td align="right" class="table-left-light">
<b>${label}:</b>
</td>
-
+
<td class="listrow1">
<input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
</td>
<function CheckboxTableRow (label, fieldname, fieldcontent )>
<call EditCheckboxNormal(label, fieldname, fieldcontent)>
-</function>
+</function>
<function _CheckboxTableRow (label, fieldname, fieldcontent, aCanEdit)>
<if aCanEdit=="1">
<else>
<call ReadOnlyCheckboxNormal(label, fieldcontent)>
</if>
-</function>
+</function>
<function _TextAreaTableRow (label, hint, cols, rows, fieldname, fieldcontent, aCanEdit)>
<if aCanEdit=="1">
<b>${label}:</b>
<if hint>
<br>
- <span class="small">${hint}</span>
+ <span class="small">${hint}</span>
</if>
</td>
-
+
<td class="listrow2">
${utility.prettyEncodeHTML(fieldcontent)}
</td>
<b>${label}:</b>
<if hint>
<br>
- <span class="small">${hint}</span>
+ <span class="small">${hint}</span>
</if>
</td>
-
+
<td class="listrow2">
<textarea cols="${cols}" rows="${rows}" name="${fieldname}" wrap="virtual">${utility.encodeHTML(fieldcontent)}</textarea>
</td>
<b>${label}:</b>
<if hint>
<br>
- <span class="small">${hint}</span>
+ <span class="small">${hint}</span>
</if>
</td>
-
+
<td class="listrow1">
<textarea cols="${cols}" rows="${rows}" name="${fieldname}" wrap="virtual">${utility.encodeHTML(fieldcontent)}</textarea>
</td>
<if selectarticleurl>
<input type="hidden" name="selectarticleurl" value="${utility.encodeHTML(selectarticleurl)}">
</if>
-
+
<table border="0" cellpadding="2" cellspacing="3">
<tr <if !aLayout>class="bg-neutral"</if>>
<td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.value")}</td>
<td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.field")}</td>
<td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.publishedstate")}</td>
<td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.articletype")}</td>
+ <td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.topic")}</td>
<td <if aLayout>class="table-head"<else>class="small bg-neutral"</if> valign="bottom"> ${lang("contentsearch.order")}</td>
<td <if aLayout>class="table_head"<else>class="small bg_neutral"</if> valign="bottom"> </td>
</tr>
</select>
</td>
<td <if aLayout>class="listrow2"</if>>
+ <select name="searchtopic">
+ <option value="">--</option>
+ <list topics as t>
+ <option value="${t.id}" <if searchtopic && searchtopic==t.id> selected</if>>${t.title}</option>
+ </list>
+ </select>
+ </td>
+ <td <if aLayout>class="listrow2"</if>>
<select name="searchorder">
<option value="datedesc" <if searchorder && searchorder=="datedesc"> selected</if>>${lang("contentsearch.order.datedesc")}</option>
<option value="dateasc" <if searchorder && searchorder=="dateasc"> selected</if>>${lang("contentsearch.order.dateasc")}</option>
<comment>browse function, only called if necessary</comment>
<function PrevNext (align)>
- <if prevurl || nexturl>
+ <if prevurl || nexturl>
<p align="${align}">
<if prevurl>
- <a class="link-box" href="${config.actionRoot}?${prevurl}"> [ < ] ${lang("list.previous")}</a>
+ <a class="link-box" href="${config.actionRoot}?${prevurl}"> [ < ] ${lang("list.previous")}</a>
</if>
<if nexturl>
<a class="link-box" href="${config.actionRoot}?${nexturl}"> ${lang("list.next")} [ > ]</a>
<comment>previous next links</comment>
<function showPrevNextLinks (aPreviousUrl, aNextUrl, anAlignment)>
- <if aPreviousUrl || aNextUrl>
+ <if aPreviousUrl || aNextUrl>
<p align="${anAlignment}">
<if aPreviousUrl>
<a class="link-box" href="${config.actionRoot}?${aPreviousUrl}"> [ < ] ${lang("list.previous")}</a>
</if>
- <if aPreviousUrl && aNextUrl>
-
+ <if aPreviousUrl && aNextUrl>
+
</if>
<if aNextUrl>
<a class="link-box" href="${config.actionRoot}?${aNextUrl}"> ${lang("list.next")} [ > ]</a>
<comment>multifunctional help - popup or not - big or small designs</comment>
<function Help (HelpUrl, popup, big )>
<if popup>
-
+
<Script Language="JavaScript">
- <!--
+ <!--
function openwindowlink() {
newwin = window.open("${HelpUrl}","windowname","height=320,width=320,top=200,left=300, scrollbars,resizable")
}
// end hiding -->
</Script>
-
+
<a href="JavaScript: openwindowlink()">
<if big><span class="link-help"><else><span class="link-help-small"></if>
<if big> [ ? ] ${lang("help")}<else>[?]</if>
</span>
- </a>
-
+ </a>
+
<else>
-
+
<if big>
<a href="${HelpUrl}" target="_blank"><span class="link-help"> [ ? ] ${lang("help")}</span></a>
<else>
- <a href="${HelpUrl}" target="_blank"><span class="link-help-small">[?]</span></a>
+ <a href="${HelpUrl}" target="_blank"><span class="link-help-small">[?]</span></a>
</if>
</if>
</function>
<tr>
<td align=right valign=top class="table-left">
- ${lang("content.images")}:
+ ${lang("content.images")}:
</td>
<if aCanEdit=="1">
<td align="left" valign="top" class="listrow2">
<a href="${config.actionRoot}?module=Images&do=list&${objectKey}=${anObject.id}&returnurl=${utility.encodeURI(aReturnUrl)}">[+] ${lang("content.addimage")}</a> |
- <a href="${config.actionRoot}?module=Images&do=add&${objectKey}=${anObject.id}&returnurl=${utility.encodeURI(aReturnUrl)}">${lang("content.uploadimage")}</a>
+ <a href="${config.actionRoot}?module=Images&do=add&${objectKey}=${anObject.id}&returnurl=${utility.encodeURI(aReturnUrl)}">${lang("content.uploadimage")}</a> |
+ <form method="post" action="${config.actionRoot}">
+ id:
+ <input type="hidden" name="module" value="${objectModule}">
+ <input type="hidden" name="do" value="attach">
+ <input type="text" size="5" maxlength="10" name="mid" value="">
+ <input type="hidden" name="${objectKey}" value="${anObject.id}">
+ <input type="submit" class="minorbutton" value="${lang("content.addimage")}">
+ </form>
</td>
</if>
</tr>
</if>
</tr>
</list>
-
+
<tr>
<td align=right valign=top class="table-left">
<list anObject.to_all_media_video as m>
<tr>
<td align=right valign=top>
- <a href="${config.actionRoot}?module=Video&do=getMedia&id=${m["id"]}&returnurl=${utility.encodeURI(aReturnUrl)}"><img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0"></a>
+ <a href="${config.actionRoot}?module=Video&do=getMedia&id=${m["id"]}&returnurl=${utility.encodeURI(aReturnUrl)}"><img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0"></a>
</td>
<if aCanEdit=="1">
<td align="left" valign="top">
</tr>
</list>
-
+
<tr>
<td align=right valign=top class="table-left">
${lang("content.other")}:
<list anObject.to_all_media_other as m>
<tr>
<td align=right valign=top">
- <a href="${config.actionRoot}?module=OtherMedia&do=getMedia&id=${m["id"]}&returnurl=${utility.encodeURI(aReturnUrl)}"><img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0"></a>
+ <a href="${config.actionRoot}?module=OtherMedia&do=getMedia&id=${m["id"]}&returnurl=${utility.encodeURI(aReturnUrl)}"><img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0"></a>
</td>
<if aCanEdit=="1">
<td align="left" valign="top">
</tr>
</list>
</table>
-</function>
+</function>
+
+<function showCommentAttachment(aComment, aReturnUrl)>
+ <call showAttachment(0, aComment, "1", aReturnUrl)>
+</function>
+
+<function showAttachment(anIsArticle, anObject, aCanEdit, aReturnUrl)>
+ <assign objectKey="commentid">
+ <assign objectModule="Comment">
+ <list anObject.to_all_media_images as m>
+ <a href="${config.actionRoot}?module=Images&do=getMedia&id=${m["id"]}">
+ <img src="${config.actionRoot}?module=Images&do=getIcon&id=${m["id"]}"
+ alt="edit" border="0">
+ </a>
+ </list>
+ <list anObject.to_all_media_audio as m>
+ <img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0">
+ </list>
+ <list anObject.to_all_media_video as m>
+ <img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0">
+ </list>
+ <list anObject.to_all_media_other as m>
+ <img src="${config.docRoot}/img/${m["big_icon"]}" alt="edit" border="0">
+ </list>
+</function>
+++ /dev/null
-<html>
-<head>
- <title>${lang("abuse.filter.htmltitle")}</title>
- <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css"
-</head>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "FUNCTIONS.template">
-<include "EDITFUNCTIONS.template">
-
-<include "head.template">
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
- <if errormessage>
- <p class="text-alert"> ${lang("abuse.filtererror."+errormessage)}
- </p>
- </if>
-
-
- <call EditStart(
- ["module", "id", "do"],
- ["Abuse", id, "updatefilter"])>
-
- <call EditPullDownNormal(lang("abuse.filter.type"), "type", filtertypes, "identifier", "resource", type, "abuse.filtertype.")>\r
- <call EditTextNormal (lang("abuse.filter.expression"), 40, 255, "expression", expression)>
- <call EditPullDownNormal(lang("abuse.filter.articleaction"), "articleaction", articleactions, "identifier", "resource", articleaction, "content.operation.")>\r
- <call EditPullDownNormal(lang("abuse.filter.commentaction"), "commentaction", commentactions, "identifier", "resource", commentaction, "comment.operation.")>\r
- <call EditTextAreaNormal (lang("abuse.filter.comments"), "", 40, 3, "comments", comments)>
-
- <tr>
- <td class="table-foot" colspan="2" align="right">
- <if id>
- <input type="submit" class="majorbutton" name="save" value="${lang("save")}">
- <else>
- <input type="submit" class="majorbutton" name="save" value="${lang("insert")}">
- </if>
- </td>
- </tr>
-
- <call EditEnd()>
- <p><a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilters">[<] ${lang("back")} </a> </p>
- <include "foot.template">
- </body>
-</html>
+++ /dev/null
-<html>
-<head>
- <title>${config["Mir.Name"]} | ${lang("abuse.filters.htmltitle")}</title>
- <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-</head>
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<include "LISTFUNCTIONS.template">
-<include "FUNCTIONS.template">
-<include "head.template">
-
- <p>
- <a class="link-box" href="${config.actionRoot}?module=Abuse">[ < ] ${lang("back")}</a>
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=add">[+] ${lang("add")}</a>
- <if config["Abuse.DisallowIPLogging"]!="1">
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
- </if>
- <br><br>
- </p>
- <call ListStart()>\r
- <call SpannedListHead([
- lang("abuse.filter.type"),
- lang("abuse.filter.expression")], ["1","3"])>
- <call ListHead([
- lang("abuse.filter.articleaction"),
- lang("abuse.filter.commentaction"),
- lang("abuse.filter.comments"),
- lang("abuse.filter.lasthit")])>
- <list filters as f>
- <call SpannedListEntry([
- lang("abuse.filtertype."+f.type),
- utility.encodeHTML(f.expression)],
- ["1","3"],
- "module=Abuse&id="+f.id,
- ["&do=edit", "&do=delete"],
- [lang("edit"), lang("delete")])>
- <if f.lastHit>\r
- <call ListEntry([
- lang("content.operation."+f.articleAction),
- lang("comment.operation."+f.commentAction),
- utility.prettyEncodeHTML(f.comments),
- f.lastHit.format(config["Mir.DefaultDateTimeFormat"], config["Mir.DefaultTimezone"])
- ],
- "module=Abuse&id="+f.id,
- ["&do=moveup", "&do=movedown", "&do=movetop", "&do=movebottom"],
- [lang("abuse.filters.moveup"), lang("abuse.filters.movedown"),
- lang("abuse.filters.movetop"), lang("abuse.filters.movebottom")])
- >
- <else>
- <call ListEntry([
- lang("content.operation."+f.articleAction),
- lang("comment.operation."+f.commentAction),
- utility.prettyEncodeHTML(f.comments),
- "-"
- ],
- "module=Abuse&id="+f.id,
- ["&do=moveup", "&do=movedown", "&do=movetop", "&do=movebottom"],
- [lang("abuse.filters.moveup"), lang("abuse.filters.movedown"),
- lang("abuse.filters.movetop"), lang("abuse.filters.movebottom")])
- >
- </if>
- <tr height="2" class="${TABLE_HEAD_CLASS}"><td colspan="6"> </td></tr>
- </list>\r
- <call ListEnd()>\r
-
- <p>
- <a class="link-box" href="${config.actionRoot}?module=Abuse">[ < ] ${lang("back")}</a>
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=add">[+] ${lang("add")}</a>
- <if config["Abuse.DisallowIPLogging"]!="1">
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
- </if>
- <br><br>
- </p>
-
- <include "foot.template">
-</body>
-</html>
-
-
-
-
<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
<include "head.template">
-
+
<p>
<a class="link-box" href="${config.actionRoot}?module=Abuse"> [ < ] ${lang("back")}</a>
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilters">${lang("abuse.showfilters")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilterconfiguration">${lang("abuse.showfilterconfiguration")}</a>
<br>
</p>
+ <if config["Mir.Localizer.Admin.ListOperationsFlavor"]!="0">
+ <form method="post" action="${config.actionRoot}">
+ <input type="hidden" name="module" value="Localizer">
+ <input type="hidden" name="do" value="operationbatch">
+ <input type="hidden" name="returnurl" value="${utility.encodeHTML(thisurl)}">
+ <p class="box">
+ <input type="submit" class="majorbutton" name="save" value="${lang("save")}">
+ </p>
+ </if>
+
+
<table border="0" cellpadding="2" cellspacing="3">
<tr class="darkgrey">
<td class="table-head">${lang("abuse.log.time")}</td>
<td class="table-head">${lang("abuse.log.address")}</td>
<td class="table-head">${lang("abuse.log.object")}</td>
+ <td class="table-head"></td>
<td class="table-head">${lang("abuse.log.browser")}</td>
- <td class="table-head">${lang("abuse.log.filtertype")}</td>
- <td class="table-head">${lang("abuse.log.filterexpression")}</td>
+ <td class="table-head">${lang("abuse.log.filtertag")}</td>
</tr>
-
- <assign grey="0">
+
+ <assign grey="0">
<list log as l>
<if grey=="1"><assign grey="0"><tr class="listrow1"><else><tr class="listrow2"><assign grey="1"> </if>
<td>${l.timestamp.format(config["Mir.DefaultDateTimeFormat"])}</td>
<td>${l.ip}</td>
<td>
<if l.type=="content">
- <a href="${config.actionRoot}?module=Content&do=edit&id=${l.id}&returnurl=${utility.encodeURI(thisurl)}">Article</a>
+ <if l.object>
+ <a href="${config.actionRoot}?module=Content&do=edit&id=${l.id}&returnurl=${utility.encodeURI(thisurl)}">Article</a>
+ <else>
+ Article ${l.id} (no longer available)
+ </if>
<else>
- <a href="${config.actionRoot}?module=Comment&do=edit&id=${l.id}&returnurl=${utility.encodeURI(thisurl)}">Comment</a>
+ <if l.object>
+ <a href="${config.actionRoot}?module=Comment&do=edit&id=${l.id}&returnurl=${utility.encodeURI(thisurl)}">Comment</a>
+ <else>
+ Comment ${l.id} (no longer available)
+ </if>
+ </if>
+ </td>
+ <td>
+ <if l.object>
+ <if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="0">
+ <list l.object.operations as op>
+ [ <a href="${config.actionRoot}?module=Localizer&do=operation&objectype=${l.type}&operation=${op}&id=${l.object.id}&returnurl=${utility.encodeURI(thisurl + "#" + l.object.id)}">${lang(l.type+".operation."+op)}</a> ]
+ </list>
+ </if>
+ <if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="1">
+ <list l.object.operations as op>
+ <input type="checkbox" name="operation" value="${l.type};${l.object.id};${op}">${lang(l.type+".operation."+op)}
+ </list>
+ </if>
+ <if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="2">
+ <select name="operation">
+ <option value="" selected> </option>
+ <list l.object.operations as op>
+ <option value="${l.type};${l.object.id};${op}">${lang(l.type+".operation."+op)}</option>
+ </list>
+ </select>
+ </if>
</if>
</td>
- <td>${l.browser}</td>
- <td><if l.hitfiltertype>${lang("abuse.filtertype."+l.hitfiltertype)}</if></td>
- <td>${utility.encodeHTML(l.hitfilterexpression)}</td>
+ <td>${utility.encodeHTML(l.browser)}</td>
+ <td><if l.filtertag>${l.filtertag}</if></td>
</tr>
</list>
<tr>
<td colspan="6" class="table-foot"> </td>
</tr>
</table>
+ <if config["Mir.Localizer.Admin.ListOperationsFlavor"]!="0">
+ </form>
+ </if>
<p>
<a class="link-box" href="${config.actionRoot}?module=Abuse"> [ < ] ${lang("back")}</a>
- <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilters">${lang("abuse.showfilters")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilterconfiguration">${lang("abuse.showfilterconfiguration")}</a>
</p>
<include "foot.template">
<if config["Abuse.DisallowIPLogging"]!="1">
> <a href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a><br>
</if>
- > <a href="${config.actionRoot}?module=Abuse&do=showfilters">${lang("abuse.showfilters")}</a>
+ > <a href="${config.actionRoot}?module=Abuse&do=showfilterconfiguration">${lang("abuse.showfilterconfiguration")}</a>
</p>
</td>
<a href="${config.actionRoot}?module=Content&do=edit&id=${entry.to_content.id}">
${lang("edit")}
</a> |
-<comment>
- <a href="${entry.publicurl}">
- ${lang("start.show")}
- </a> |
-</comment>
<a href="${config.actionRoot}?module=Comment&do=articlecomments&articleid=${entry.to_content.id}">
${lang("commentlist.allcomments")}
</a>
</if>
- <b>${entry.title}</b> (${entry.id})
+ <b>${utility.encodeHTML(entry.title)}</b> (${entry.id})
<if entry.creator>
- ${lang("by")}: ${entry.creator}
+ ${lang("by")}: ${utility.encodeHTML(entry.creator)}
</if>
<br>
${utility.prettyEncodeHTML(utility.subString(entry.description, 0, config["Mir.Admin.ListTextLengthLimit"]))}
+
+ <br>
+ <if entry.to_all_media_images || entry.to_all_media_audio || entry.to_all_media_video || entry.to_all_media_other>
+ <call showCommentAttachment(entry, thisurl)>
+ </if>
+ <br>
- <if entry.main_url><br>URL: ${entry.main_url}</if>
+ <if entry.main_url><br>URL: ${utility.encodeHTML(entry.main_url)}</if>
<br>
- <!-- <div class="bg-neutral small">-->
<if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="0">
<list entry.operations as op>
[ <a href="${config.actionRoot}?module=Localizer&do=commentoperation&operation=${op}&id=${entry.id}&returnurl=${utility.encodeURI(thisurl + "#" + entry.id)}">${lang("comment.operation."+op)}</a> ]
</select>
</if>
<if entry.operations> | </if>
- <a href="${config.actionRoot}?module=Comment&do=edit&id=${entry.id}">${lang("edit")}</a>
- <!-- </div>-->
+ <a href="${config.actionRoot}?module=Comment&do=edit&id=${entry.id}">${lang("edit")}</a>
</td>
<td valign="top">
</tr>
</if>
</table>
-
+
+<if mayEdit=="1">
+ </form>
+</if>
+
<if new=="0">
<table width="90%" cellspacing="0" cellpadding="0">
</table>
</if>
-<if mayEdit=="1">
- </form>
-</if>
<include "foot.template">
</body>
<call ContentSearch ("layouted")>
</if>
-<if articles>
+<if entities>
<if showactions=="1">
<if config["Mir.Localizer.Admin.ListOperationsFlavor"]!="0">
</tr>
<assign grey="0">
- <list articles as entry>
+ <list entities as entry>
<tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"></if>>
<td class="x-small">
${entry.creationdate.format(config["Mir.DefaultDateTimeFormat"])}<br>
<p class="box-head" align="center"><font size="+2"><b>${lang("error.title")}</b></font></p>
<p align="center">${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
- <p align="center" class="bg-neutral"><br><font color="red">${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${errorstring}</font><br><br></p>
+ <p align="center" class="bg-neutral"><br><font color="red">${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${utility.encodeHTML(errorstring)}</font><br><br></p>
+ <p align="center" class="bg-neutral"><br><font color="red">${utility.prettyEncodeHTML(stacktrace)}</font><br><br></p>
<p align="center">${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
</td></tr></table>
--- /dev/null
+<html>
+<head>
+ <title>${lang("filter.htmltitle")}</title>
+ <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css"
+</head>
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+<include "FUNCTIONS.template">
+<include "EDITFUNCTIONS.template">
+
+<include "head.template">
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+ <if errormessage>
+ <p class="text-alert"> ${utility.prettyEncodeHTML(errormessage)}
+ </p>
+ </if>
+
+
+ <call EditStart(
+ ["module", "groupid", "id", "do"],
+ ["Abuse", groupid, id, "updatefilter"])>
+
+ <call EditPullDownNormal(lang("filter.type"), "type", filtertypes, "identifier", "resource", type, "filtertype.")>\r
+ <call EditTextNormal (lang("filter.expression"), 40, 255, "expression", expression)>
+ <call EditTextNormal (lang("filter.tag"), 40, 255, "tag", tag)>
+ <call EditPullDownNormal(lang("filter.articleaction"), "articleaction", articleactions, "identifier", "resource", articleaction, "content.operation.")>\r
+ <call EditPullDownNormal(lang("filter.commentaction"), "commentaction", commentactions, "identifier", "resource", commentaction, "comment.operation.")>\r
+ <call EditTextAreaNormal (lang("filter.comment"), "", 40, 3, "comments", comments)>
+
+ <tr>
+ <td class="table-foot" colspan="2" align="right">
+ <if id>
+ <input type="submit" class="majorbutton" name="save" value="${lang("save")}">
+ <else>
+ <input type="submit" class="majorbutton" name="save" value="${lang("insert")}">
+ </if>
+ </td>
+ </tr>
+
+ <call EditEnd()>
+ <p><a class="link-box" href="${config.actionRoot}?module=Abuse&do=listfilters&groupid=${groupid}">[<] ${lang("back")} </a> </p>
+ <include "foot.template">
+ </body>
+</html>
--- /dev/null
+<html>
+<head>
+ <title>${lang("abuse.filtergroup.htmltitle")}</title>
+ <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css"
+</head>
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+<include "FUNCTIONS.template">
+<include "EDITFUNCTIONS.template">
+
+<include "head.template">
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+ <call EditStart(
+ ["module", "id", "do"],
+ ["Abuse", id, "updatefiltergroup"])>
+
+ <call EditTextNormal (lang("filtergroup.name"), 40, 255, "name", name)>
+
+ <tr>
+ <td class="table-foot" colspan="2" align="right">
+ <if id>
+ <input type="submit" class="majorbutton" name="save" value="${lang("save")}">
+ <else>
+ <input type="submit" class="majorbutton" name="save" value="${lang("insert")}">
+ </if>
+ </td>
+ </tr>
+
+ <call EditEnd()>
+ <p><a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfiltergroups">[<] ${lang("back")} </a> </p>
+ <include "foot.template">
+ </body>
+</html>
--- /dev/null
+<html>
+<head>
+ <title>${config["Mir.Name"]} | ${lang("filtergrouplist.htmltitle")}</title>
+ <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+</head>
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+<include "LISTFUNCTIONS.template">
+<include "FUNCTIONS.template">
+<include "head.template">
+
+ <p>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse">[ < ] ${lang("back")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=addfiltergroup">[+] ${lang("add")}</a>
+ <if config["Abuse.DisallowIPLogging"]!="1">
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
+ </if>
+ <br><br>
+ </p>
+ <call ListStart()>\r
+ <call ListHead([
+ lang("filtergroup.name")])>
+
+ <list filtergroups as f>
+ <call ListEntry([
+ utility.encodeHTML(f.name)],
+ "module=Abuse&groupid="+f.id,
+ ["&do=movefiltergroupup", "&do=movefiltergroupdown", "&do=listfilters", "&do=deletefiltergroup"],
+ [lang("filtergroup.moveup"), lang("filtergroup.movedown"), lang("filtergroup.listfilters"), lang("delete")])
+ >
+ </list>\r
+
+ <call ListEnd()>\r
+
+ <p>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse">[ < ] ${lang("back")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=addfiltergroup">[+] ${lang("add")}</a>
+ <br><br>
+ </p>
+
+ <include "foot.template">
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<html>
+<head>
+ <title>${config["Mir.Name"]} | ${lang("filterlist.htmltitle")}</title>
+ <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+</head>
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+<include "LISTFUNCTIONS.template">
+<include "FUNCTIONS.template">
+<include "head.template">
+
+ <p>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfiltergroups">[ < ] ${lang("back")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&groupid=${groupid}&do=addfilter">[+] ${lang("add")}</a>
+ <if config["Abuse.DisallowIPLogging"]!="1">
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("showlog")}</a>
+ </if>
+ <br><br>
+ </p>
+ <call ListStart()>\r
+ <call SpannedListHead([
+ lang("filter.type"),
+ lang("filter.expression")], ["1","3"])>
+ <call ListHead([
+ lang("filter.articleaction"),
+ lang("filter.commentaction"),
+ lang("filter.tag"),
+ lang("filter.last_hit")])>
+ <call SpannedListHead([
+ lang("filter.comment")], ["4"])>
+ <list filters as f>
+ <call SpannedListEntry([
+ lang("filtertype."+f.type),
+ utility.encodeHTML(f.expression)],
+ ["1","3"],
+ "module=Abuse&id="+f.id+"&groupid="+groupid,
+ ["&do=editfilter", "&do=deletefilter"],
+ [lang("edit"), lang("delete")])>
+ <if f.lasthit>\r
+ <call ListEntry([
+ lang("content.operation."+f.articleaction),
+ lang("comment.operation."+f.commentaction),
+ utility.encodeHTML(f.tag),
+ f.lasthit.format(config["Mir.DefaultDateTimeFormat"], config["Mir.DefaultTimezone"])
+ ],
+ "module=Abuse&id="+f.id+"&groupid="+groupid,
+ ["&do=movefilterup", "&do=movefilterdown"],
+ [lang("filters.moveup"), lang("filters.movedown")])
+ >
+ <else>
+ <call ListEntry([
+ lang("content.operation."+f.articleaction),
+ lang("comment.operation."+f.commentaction),
+ utility.encodeHTML(f.tag),
+ "-"
+ ],
+ "module=Abuse&id="+f.id+"&groupid="+groupid,
+ ["&do=movefilterup", "&do=movefilterdown"],
+ [lang("filters.moveup"), lang("filters.movedown")])
+ >
+ </if>
+ <call SpannedListEntry([
+ utility.prettyEncodeHTML(f.comment)],
+ ["4"],
+ "module=Abuse&id="+f.id+"&groupid="+groupid,
+ ["&do=movefiltertop", "&do=movefilterbottom"],
+ [lang("filters.movetop"), lang("filters.movebottom")])>
+ <tr height="2" class="${TABLE_HEAD_CLASS}"><td colspan="6"> </td></tr>
+ </list>\r
+ <call ListEnd()>\r
+
+ <p>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfiltergroups">[ < ] ${lang("back")}</a>
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&groupid=${groupid}&do=addfilter">[+] ${lang("add")}</a>
+ <if config["Abuse.DisallowIPLogging"]!="1">
+ <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("showlog")}</a>
+ </if>
+ <br><br>
+ </p>
+
+ <include "foot.template">
+</body>
+</html>
+
+
+
+
+++ /dev/null
-<html>
-<head>
- <title>${config["Mir.Name"]} | ${lang("messagelist.htmltitle")}</title>
- <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-</head>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
- <include "FUNCTIONS.tmpl">
- <include "head.tmpl">
-
- <call showAddOrBack("1", "messageAdd.do", "index.do", "")>
-
- <if request.messages>
- <assign baselisturl = "/admin/messageList.do?offset=">
- <call showPrevNextLinks(baselisturl+request.lastoffset, baselisturl+request.nextoffset, "left")>
- <call EntityTable(request.messages, [
- "id", "title", "creator", "description"],
- [ lang("message.id"), lang("message.title"), lang("message.creator"), lang("message.text")],
- request.offset, request.nextoffset, "", "messageDelete.do", "messageEdit.do", "messageList.do")>
- <call showPrevNextLinks(baselisturl+request.lastoffset, baselisturl+request.nextoffset, "left")>
- <call showAddOrBack("1", "messageAdd.do", "index.do", "")>
- <else>
- <P align="center">${lang("no_matches_found")}</p>
- </if>
-
- <include "foot.template">
-
-</body>
-</html>
<comment> RIGHT COLUMN </comment>
- <td valign="top" rowspan="2">
+ <td width="10%" valign="top" rowspan="1">
<comment>internal messageboard</comment>
<if messages>
<list messages as m>
<p class="x-small">
- <if m.title><b>${m.title}</b><br></if>
- ${m.description}<br>
+ <if m.title><b>${utility.encodeHTML(m.title)}</b><br></if>
+ ${utility.prettyEncodeHTML(m.description)}<br>
<span class="x-small">
- <if m.creator><i>by: ${m.creator}</i> / </if>${m.creationdate.format(config["Mir.DefaultDateTimeFormat"])}}<br>
+ <if m.creator><i>by: ${utility.encodeHTML(m.creator)}</i> / </if>${m.creationdate.format(config["Mir.DefaultDateTimeFormat"])}}<br>
</span>
</p>
</list>
</td>
</tr>
-
+
<comment> BOTTOM ROW FOR SEARCH </comment>
<tr>
- <td colspan="3" valign="top">
+ <td colspan="5" valign="top">
<p class="box-head"><b>${lang("start.search.title")}</b></p>
<div class="box">
<call ContentSearch("")>
<table width="70%" align="center"><tr><td>
<p class="box-head" align="center"><font size="+2"><b>${lang("usererror.title")}</b></font></p>
- <p align="center" class="bg-neutral"><br><font color="red">${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${errorstring}</font><br><br></p>
+ <p align="center" class="bg-neutral"><br><font color="red">${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${utility.encodeHTML(errorstring)}</font><br><br></p>
<p align="center">${lang("usererror.what_to_do")}</p>
</td></tr></table>
--- /dev/null
+<project name="Mir" default="deploy" basedir=".">
+ <!--
+ - Build script for the binary distribution of the Mir project
+ -
+ - usefull tasks are:
+ - * deploy
+ - Creates the jars needed for a mir deployment
+ -->
+
+ <property name="version" value="1.1.0rc0"/>
+ <property name="app.name" value="mir"/>
+ <property name="deploy.home" value="."/>
+
+ <!-- The temporary files made during the build process
+ will be created here: -->
+ <property name="build" value="./build"/>
+ <property name="build.classes" value="./${build}/classes"/>
+ <property name="build.jars" value="./${build}/jars"/>
+ <property name="build.javadoc" value="${build}/javadoc"/>
+
+ <!-- retrieve environment variables -->
+ <property environment="env"/>
+
+ <property name="tomcat.home" value="${env.TOMCAT_HOME}"/>
+
+ <target name="deploy" depends="compile,generate-deployment-tree"
+ description="Sets up a deployment directory">
+ </target>
+
+ <target name="generate-deployment-tree">
+ <property name="destination" value="${deploy.home}"/>
+
+ <copy todir="${destination}/lib">
+ <fileset dir="${build.jars}" />
+ </copy>
+ </target>
+
+ <target name="clean">
+ <delete dir="${build}"/>
+ </target>
+
+ <!-- Construct the classpath -->
+ <path id="project.classpath">
+ <fileset dir="lib">
+ <include name="*.jar"/>
+ </fileset>
+ <fileset dir="etc/extralib">
+ <include name="*.jar"/>
+ </fileset>
+
+ <pathelement path="${tomcat.home}/lib/tomcat.jar"/>
+
+ <!-- for libs shared between tomcat and webapps (tomcat 3.3.x) -->
+ <fileset dir="${tomcat.home}">
+ <include name="lib/common/*.jar" />
+ </fileset>
+ <!-- for libs shared between webapps (tomcat 3.3.x) -->
+ <fileset dir="${tomcat.home}">
+ <include name="lib/apps/*.jar" />
+ </fileset>
+ <!-- for libs shared between tomcat and webapps (tomcat 4.x.x) -->
+ <fileset dir="${tomcat.home}">
+ <include name="common/lib/*.jar" />
+ </fileset>
+ <!-- for libs shared between webapps (tomcat 4.0.x) -->
+ <fileset dir="${tomcat.home}">
+ <include name="lib/*.jar" />
+ </fileset>
+ <!-- for libs shared between webapps (tomcat 4.1.x) -->
+ <fileset dir="${tomcat.home}">
+ <include name="shared/lib/*.jar" />
+ </fileset>
+
+ <fileset dir="${tomcat.home}">
+ <include name="common/endorsed/*.jar" />
+ </fileset>
+ </path>
+
+
+ <target name="prepare-compilation">
+ <mkdir dir="${build.classes}"/>
+ <mkdir dir="${build.jars}"/>
+ <uptodate property="up.to.date" targetfile="${build.jars}/mir.jar">
+ <srcfiles dir="lib" includes="*.jar"/>
+ <srcfiles dir="etc/extrasource" includes="**/*"/>
+ <srcfiles dir="etc/extralib" includes="*"/>
+ </uptodate>
+ </target>
+
+ <!-- compile target: compiles all files into the build/classes dir -->
+ <target name="compile" depends="prepare-compilation" unless="up.to.date"
+ description="Creates the jars needed for a mir deployment">
+
+ <javac destdir="${build.classes}" debug="true" deprecation="off" source="1.3">
+ <src path="etc/extrasource"/>
+ <classpath refid="project.classpath"/>
+ </javac>
+
+ <delete file="${build.jars}/mir.jar"/>
+
+ <jar
+ jarfile="${build.jars}/mir.jar">
+ <fileset dir="${build.classes}" includes="**/*.class" />
+ <manifest>
+ <attribute name="Built-By" value="${user.name}"/>
+ </manifest>
+ </jar>
+ </target>
+
+
+</project>
--- /dev/null
+#!/bin/sh
+
+# Where the installed system resides
+INSTDIR=`dirname $0`
+
+# The group all files belong to
+GROUP=www-data
+
+
+# No config required after this point. Hopefully.
+##################################################################
+
+# Needed to correct permissions
+
+function chm()
+{
+ # Parameters. $1 permissions
+ # $2 directory or file
+ # $3 mode: [d|f] (dir or file)
+
+ LIST=$(find $2 -type $3)
+ if [ "$LIST" != "" ]; then
+ echo "$LIST"
+ chmod $1 $LIST
+ fi
+}
+
+function grant()
+{
+ # Parameters: $1: permissions for dirs
+ # $2: permissions for files
+ # $3: directory or file
+
+ chmod $1 $3
+ UMASK=$(umask)
+ umask 044
+# chmod $1 $(find $3 -type d)
+# chmod $2 $(find $3 -type f)
+ chm $1 $3 d
+ chm $2 $3 f
+ umask $UMASK
+}
+
+chgrp $GROUP $INSTDIR -R #> /dev/null 2>&1
+grant 775 664 $INSTDIR > /dev/null 2>&1
+grant 750 640 etc/config.properties
+
+echo "Permissions set."