From 855ecf8acedb12afbab7a621b2e2c0cf45b2f98f Mon Sep 17 00:00:00 2001 From: zapata Date: Sun, 21 Dec 2003 13:32:01 +0000 Subject: [PATCH] Added features: - optional pessimistic locking - internal comments field for comments - extra fields for users: last login, comments, etc - content / uploaded media split up - cleanup of some tables --- bundles/admin_en.properties | 22 +- dbscripts/conversion/mir_oid.pl | 67 - dbscripts/create_pg.sql | 64 +- dbscripts/createmirdb.sh | 1 - dbscripts/dupetrigger/INSTALL | 48 - dbscripts/dupetrigger/Makefile-dist | 34 - dbscripts/dupetrigger/README | 16 - dbscripts/dupetrigger/dupetrigger.c | 298 ----- dbscripts/dupetrigger/postgresql.sript | 6 - dbscripts/help_users.sql | 10 +- dbscripts/lib/codec.pl | 156 --- dbscripts/lib/convert.pl | 51 - dbscripts/lib/log.pl | 70 -- dbscripts/lib/property.pl | 70 -- dbscripts/lib/subst.pl | 446 ------- dbscripts/update_all_sequences.sql | 10 +- dbscripts/update_database_01.sql | 20 - dbscripts/updates/update20031122.sql | 67 + dbscripts/updates/update20031124.sql | 97 ++ dbscripts/updates/update20031125.sql | 550 ++++++++ dbscripts/wiz_templates/show.template | 42 - dbscripts/wizard.pl | 83 -- source/Mir.java | 15 +- source/default.properties | 7 + source/mir/entity/Entity.java | 21 +- source/mir/entity/EntityList.java | 534 ++++---- .../entity/adapter/EntityAdapterDefinition.java | 68 +- source/mir/entity/adapter/EntityListAdapter.java | 242 ++-- source/mir/generator/FreemarkerGenerator.java | 2 +- source/mir/generator/TALGenerator.java | 176 +-- source/mir/generator/VelocityGenerator.java | 1312 ++++++++++---------- source/mir/generator/tal/MirExpressionParser.java | 290 ++--- source/mir/generator/tal/TALTemplate.java | 626 +++++----- source/mir/generator/tal/TALTemplateEngine.java | 128 +- source/mir/generator/tal/TALTemplateParser.java | 524 ++++---- source/mir/generator/tal/TALTest.java | 112 +- source/mir/media/MediaHandler.java | 442 +++---- source/mir/module/AbstractModule.java | 8 +- .../reader/DefaultProducerNodeBuilders.java | 18 +- source/mir/rss/RDFResource.java | 2 +- source/mir/servlet/ServletModule.java | 2 +- source/mircoders/accesscontrol/AccessControl.java | 78 ++ source/mircoders/entity/EntityContent.java | 344 +++-- source/mircoders/entity/EntityFeature.java | 62 - source/mircoders/entity/EntityUploadedMedia.java | 202 +-- source/mircoders/global/Abuse.java | 16 +- source/mircoders/global/JobQueue.java | 2 + source/mircoders/global/MirGlobal.java | 29 +- source/mircoders/global/ProducerEngine.java | 512 ++++---- .../localizer/MirAdminInterfaceLocalizer.java | 9 + .../localizer/MirAntiAbuseFilterType.java | 134 +- .../localizer/MirCachingLocalizerDecorator.java | 338 ++--- .../basic/MirBasicAdminInterfaceLocalizer.java | 67 +- .../basic/MirBasicChildArticlePostingHandler.java | 122 +- .../basic/MirBasicCommentPostingHandler.java | 362 +++--- .../basic/MirBasicDataModelLocalizer.java | 133 +- .../localizer/basic/MirBasicLocalizer.java | 142 +-- .../localizer/basic/MirBasicMediaLocalizer.java | 252 ++-- .../basic/MirBasicProducerAssistantLocalizer.java | 336 ++--- source/mircoders/media/MediaHandlerRealAudio.java | 260 ++-- source/mircoders/module/ModuleArticleType.java | 10 +- source/mircoders/module/ModuleComment.java | 16 +- source/mircoders/module/ModuleCommentStatus.java | 114 +- source/mircoders/module/ModuleContent.java | 100 +- source/mircoders/module/ModuleMediafolder.java | 10 +- source/mircoders/module/ModuleUsers.java | 48 +- source/mircoders/servlet/ServletModuleAdmin.java | 6 +- .../servlet/ServletModuleArticleType.java | 128 +- .../mircoders/servlet/ServletModuleBreaking.java | 132 +- source/mircoders/servlet/ServletModuleContent.java | 134 +- .../mircoders/servlet/ServletModuleLocalizer.java | 15 +- source/mircoders/servlet/ServletModuleUsers.java | 6 +- source/mircoders/storage/DatabaseArticleType.java | 10 +- source/mircoders/storage/DatabaseComment.java | 14 +- .../mircoders/storage/DatabaseCommentStatus.java | 6 +- source/mircoders/storage/DatabaseContent.java | 12 +- source/mircoders/storage/DatabaseImageColor.java | 4 +- source/mircoders/storage/DatabaseImageFormat.java | 4 +- source/mircoders/storage/DatabaseImageLayout.java | 4 +- source/mircoders/storage/DatabaseImageType.java | 126 +- source/mircoders/storage/DatabaseLanguage.java | 186 +-- source/mircoders/storage/DatabaseMediafolder.java | 118 +- source/mircoders/storage/DatabaseOther.java | 194 +-- source/mircoders/storage/DatabaseTopics.java | 182 +-- .../mircoders/storage/DatabaseUploadedMedia.java | 14 +- templates/admin/EDITFUNCTIONS.template | 9 + templates/admin/FUNCTIONS.template | 157 ++- templates/admin/FUNCTIONS_media.template | 114 +- templates/admin/comment.template | 1 + templates/admin/commentlist.template | 8 +- templates/admin/content.template | 301 +++-- templates/admin/start_admin.template | 6 +- templates/admin/user.template | 84 +- templates/admin/usererror.template | 52 +- templates/admin/userlist.template | 58 +- 95 files changed, 6180 insertions(+), 6360 deletions(-) delete mode 100755 dbscripts/conversion/mir_oid.pl delete mode 100755 dbscripts/dupetrigger/INSTALL delete mode 100755 dbscripts/dupetrigger/Makefile-dist delete mode 100755 dbscripts/dupetrigger/README delete mode 100755 dbscripts/dupetrigger/dupetrigger.c delete mode 100755 dbscripts/dupetrigger/postgresql.sript delete mode 100755 dbscripts/lib/codec.pl delete mode 100755 dbscripts/lib/convert.pl delete mode 100755 dbscripts/lib/log.pl delete mode 100755 dbscripts/lib/property.pl delete mode 100755 dbscripts/lib/subst.pl delete mode 100755 dbscripts/update_database_01.sql create mode 100755 dbscripts/updates/update20031122.sql create mode 100755 dbscripts/updates/update20031124.sql create mode 100755 dbscripts/updates/update20031125.sql delete mode 100755 dbscripts/wiz_templates/show.template delete mode 100755 dbscripts/wizard.pl delete mode 100755 source/mircoders/entity/EntityFeature.java diff --git a/bundles/admin_en.properties b/bundles/admin_en.properties index 081841af..52a44282 100755 --- a/bundles/admin_en.properties +++ b/bundles/admin_en.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: english -# $Id: admin_en.properties,v 1.48.2.19 2003/12/14 16:37:06 zapata Exp $ +# $Id: admin_en.properties,v 1.48.2.20 2003/12/21 13:32:01 zapata Exp $ languagename=English @@ -120,6 +120,8 @@ comment.html=HTML comment.status=Status comment.language=Language comment.allcomments=All comments +comment.comment=Internal Comment +comment.comment.info=(internal) comment.operation.hide=hide comment.operation.unhide=unhide @@ -185,6 +187,11 @@ content.content=Content content.html=HTML content.comment=Internal Comment content.internal=(internal) +content.keywords=Keywords +content.lockedby=Locked by {0} +content.lock=Lock +content.unlock=Unlock +content.forcelock=Force lock content.attachments=Attachments content.images=Images @@ -365,6 +372,15 @@ user.oldpassword=Old password user.password=Password user.password2=Password (confirmation) user.admin=Admin +user.is_disabled=Disabled ? +user.creationdate=Creation date +user.lastlogindate=Last login +user.email=Email address +user.comment=Comment +user.profile=Profile + + + userlist.htmltitle=Users @@ -463,8 +479,8 @@ abuse.log.filtertype=Filter type abuse.log.filterexpression=Expression abuse.filters = Filters -abuse.filters.movedown = move down -abuse.filters.moveup = move up +abuse.filters.movedown = down +abuse.filters.moveup = up abuse.filter.type = Type abuse.filter.expression = Expression diff --git a/dbscripts/conversion/mir_oid.pl b/dbscripts/conversion/mir_oid.pl deleted file mode 100755 index 6fa27a3e..00000000 --- a/dbscripts/conversion/mir_oid.pl +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/perl -w -use Pg; - -#if (!defined($ARGV[0])) { -# print "Usage: $0 name_of_filelist_file\n"; -# exit 1; -#} - -#$dump="$ARGV[0]"; - -my $conn = Pg::connectdb("dbname=indy3 user=postgres -host=localhost"); -( PGRES_CONNECTION_OK eq $conn->status ) - and print "Pg::connectdb ........... ok\n" - or die "Pg::connectdb ........... not ok: ", $conn->errorMessage; - - - #open(DUMP,"$dump") || die "can't open dump file $dump"; - - #$basedir="/cdrom"; - -Pg::doQuery($conn, "select content_data from content", \@ary); - -for $i ( 0 .. $#ary ) { - for $j ( 0 .. $#{$ary[$i]} ) { - print "$ary[$i][$j]\t"; - } - print "\n"; -} - -#while() { -# chomp; -# next if (/^$/ || /^\s*$/); -# -# # exception liste einlesen... -# -# -# # hier insert: -# -# $conn->exec("BEGIN"); -# $oid= $conn->lo_import("$filename"); -# print $conn->errorMessage."\n"; -# print "trying to insert icon\n"; -# $ioid= $conn->lo_import("/tmp/iconblob.jpg"); -# print $conn->errorMessage."\n"; -# $sql="INSERT INTO images -#(title,date,place,author,to_img_layout,to_img_type,is_classified,to_media_f -#older,to_img_color,comment,webdb_create,img_width,img_height,image_data,ico -#n_data) ". -# "VALUES ('".$titel."','20010108','".$ort. -# "','Hoch die Kampf -#dem','".$layout."','1','0','2','2','".$comment."',now(),'".$img_width."','" -#.$img_height. -# "','".$oid."','".$ioid."')"; -# print $sql."\n"; -# $conn->exec( $sql ); -# print $conn->errorMessage."\n"; -# $conn->exec("END"); -# -# -# -#} -## end of while -# - - - diff --git a/dbscripts/create_pg.sql b/dbscripts/create_pg.sql index 47835654..a355655a 100755 --- a/dbscripts/create_pg.sql +++ b/dbscripts/create_pg.sql @@ -80,7 +80,12 @@ CREATE TABLE "webdb_users" ( "password" character varying(255) NOT NULL, "is_admin" boolean DEFAULT '0' NOT NULL, "comment" text, - Constraint "webdb_users_pkey" Primary Key ("id") + "is_disabled" boolean DEFAULT '0' NOT NULL, + "email" character varying(255) DEFAULT '' NOT NULL, + "profile" text, + "webdb_create" timestamp with time zone NOT NULL, + "lastlogin" timestamp with time zone, + CONSTRAINT "webdb_users_pkey" Primary Key ("id") ); @@ -148,12 +153,11 @@ CREATE TABLE "comment" ( "to_language" integer DEFAULT '0' NOT NULL, "to_media" integer NOT NULL, "to_comment_status" smallint, - "checksum" integer, + "comment" text, "is_html" boolean DEFAULT '0' NOT NULL, Constraint "comment_pkey" Primary Key ("id") ); -CREATE INDEX "comment_checksum_index" on "comment" using btree ( "checksum" "int4_ops" ); CREATE INDEX "idx_comment_to_media" on "comment" using btree ( "to_media" "int4_ops" ); CREATE INDEX idx_comment_webdb_create on comment(webdb_create); CREATE INDEX "idx_comment_tomedia_ispublished" on "comment" using btree ( "to_media" "int4_ops", "is_published" "bool_ops" ); @@ -174,7 +178,12 @@ CREATE INDEX "idx_comment_tomedia_ispublished" on "comment" using btree ( -- CREATE SEQUENCE "media_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ; -CREATE TABLE "media" ( + +-- +-- uploaded_media +-- + +CREATE TABLE "uploaded_media" ( "id" integer DEFAULT nextval('media_id_seq'::text) NOT NULL, "title" character varying(255), "subtitle" character varying(255), @@ -188,12 +197,10 @@ CREATE TABLE "media" ( "description" text, "comment" text, "source" character varying(255), - "publish_date" timestamp with time zone, "publish_server" character varying(255), "publish_path" character varying(255), "is_published" boolean DEFAULT '0' NOT NULL, "is_produced" boolean DEFAULT '0' NOT NULL, - "to_feature" integer DEFAULT '0' NOT NULL, "to_media_folder" integer DEFAULT '0' NOT NULL, "to_media_type" smallint DEFAULT '0' NOT NULL, "to_publisher" integer NOT NULL, @@ -201,19 +208,11 @@ CREATE TABLE "media" ( "to_rights" integer DEFAULT '0', "webdb_create" timestamp with time zone NOT NULL, "webdb_lastchange" timestamp with time zone, - "to_media" integer -); - --- --- uploaded_media --- - -CREATE TABLE "uploaded_media" ( "icon_is_produced" boolean DEFAULT '0' NOT NULL, "icon_path" character varying(255), - "size" integer -) -INHERITS ("media"); + "size" integer, + Constraint "uploaded_media_pkey" Primary Key ("id") +); CREATE UNIQUE INDEX "idx_uploaded_media_id" on "uploaded_media" using btree ( "id" "int4_ops" ); CREATE UNIQUE INDEX "idx_uploaded_media_is_published" on "uploaded_media" using btree ( "id" "int4_ops", "is_published" "bool_ops" ); @@ -237,7 +236,7 @@ CREATE TABLE "images" ( ) INHERITS ("uploaded_media"); -CREATE INDEX "idx_images_is_published__icon_i" on "images" using btree ( "is_published" "bool_ops", "icon_is_produced" "bool_ops" ); +CREATE INDEX "idx_images_is_published" on "images" using btree ( "is_published" "bool_ops", "icon_is_produced" "bool_ops" ); CREATE UNIQUE INDEX "idx_images_id" on "images" using btree ( "id" "int4_ops" ); -- @@ -319,15 +318,36 @@ CREATE UNIQUE INDEX "idx_othermedia_id" on "other_media" using btree ( "id" "int -- CREATE TABLE "content" ( + "id" integer DEFAULT nextval('media_id_seq'::text) NOT NULL, + "title" character varying(255), + "subtitle" character varying(255), + "edittitle" character varying(255), + "date" character(8) NOT NULL, + "creator" character varying(80), + "creator_main_url" character varying(255), + "creator_email" character varying(80), + "creator_address" character varying(80), + "creator_phone" character varying(80), + "description" text, + "comment" text, + "source" character varying(255), + "is_published" boolean DEFAULT '0' NOT NULL, + "is_produced" boolean DEFAULT '0' NOT NULL, + "to_publisher" integer NOT NULL, + "to_language" integer DEFAULT '0', + "to_rights" integer DEFAULT '0', + "webdb_create" timestamp with time zone NOT NULL, + "webdb_lastchange" timestamp with time zone, "content_data" text, "is_html" boolean DEFAULT '0' NOT NULL, "to_article_type" smallint DEFAULT '0' NOT NULL, "to_content" integer, - "checksum" integer -) -INHERITS ("media"); + "keywords" text, + "to_locking_user" integer, + Constraint "content_pkey" Primary Key ("id") +); + -CREATE INDEX "content_checksum_index" on "content" using btree ( "checksum" "int4_ops" ); CREATE INDEX "idx_content_to_article_type" on "content" using btree ( "to_article_type" "int2_ops" ); CREATE INDEX "idx_content_is_produced" on "content" using btree ( "is_produced" "bool_ops" ); CREATE INDEX "idx_content_is_published__to_ar" on "content" using btree ( "is_published" "bool_ops", "to_article_type" "int2_ops" ); diff --git a/dbscripts/createmirdb.sh b/dbscripts/createmirdb.sh index 1be2e211..82f5f200 100755 --- a/dbscripts/createmirdb.sh +++ b/dbscripts/createmirdb.sh @@ -38,7 +38,6 @@ echo "grant all on img_color to $3;" >> ${SCRIPT_FILE} echo "grant all on language to $3;" >> ${SCRIPT_FILE} echo "grant all on rights to $3;" >> ${SCRIPT_FILE} echo "grant all on article_type to $3;" >> ${SCRIPT_FILE} -echo "grant all on media to $3;" >> ${SCRIPT_FILE} echo "grant all on breaking to $3;" >> ${SCRIPT_FILE} echo "grant all on messages to $3;" >> ${SCRIPT_FILE} echo "grant all on comment_status to $3;" >> ${SCRIPT_FILE} diff --git a/dbscripts/dupetrigger/INSTALL b/dbscripts/dupetrigger/INSTALL deleted file mode 100755 index e07b3e91..00000000 --- a/dbscripts/dupetrigger/INSTALL +++ /dev/null @@ -1,48 +0,0 @@ -The dupetrigger - -MOTIVATION - -Often, users commit their comments and articles multiple times if they -don't believe the comment has been inserted into the databases. This is -clearly one of the disadvantages of the otherwise clever caching strategy -used by Mir. Without proper handling, this duplicate content will enlarge -the database and make the appearance of the generated web pages be less -satisfactory. - - -SOLUTIONS - -There are two approaches to get rid of these duplicate entries -(hereafter called "dupes"). The first approach is the dupetrigger that -ensures that no entries in a given table are the same. This is the approach -currently pursued in Mir. If this trigger cannot be compiled or doesn't work -for any reason, you may work-around this problem by issuing the following -commands on your psql prompt: - -CREATE UNIQUE INDEX idx_content_dupe ON content (title, subtitle, creator, description, content_data); -CREATE UNIQUE INDEX idx_comment_dupe ON comment (creator, to_media, description, title); - -Please note that this approach will work but the implications on the Mir -software have not been tested, yet. Maybe Mir will respond with an error -or with other unexpected behaviour, but it should do no harm to the -database. The dupetrigger has been tested with Mir and is currently being -operated on de.indymedia.org. - - -HOW TO INSTALL THE DUPE TRIGGER - -To install the trigger do the following: - -# cp Makefile-dist Makefile - -# edit Makefile -(and change pathnames and PGVERSION if neccessary). - -# make -(This makes the trigger binary and places it in INSTALLDIR with permissions 644) - -# edit postgresql.script -(And change the path to dupetrigger.so to INSTALLDIR) - -# psql -Upostgres -f postgresql.script Mir -(This installs the the trigger binary and creates a new trigger.) diff --git a/dbscripts/dupetrigger/Makefile-dist b/dbscripts/dupetrigger/Makefile-dist deleted file mode 100755 index aa3cd0d5..00000000 --- a/dbscripts/dupetrigger/Makefile-dist +++ /dev/null @@ -1,34 +0,0 @@ -# Makefile - -# Set the following directory so that it contains spi.h and trigger.h -PGINC=/usr/include/postgresql/server - -#PGVERSION=-DPG70 -#PGVERSION=-DPG71 -PGVERSION=-DPG72 - -# If changed, also change postgresql.script -INSTALLDIR=/var/lib/postgres/data - - - -CC=gcc -CFLAGS=-I$(PGINC) $(PGVERSION) - -install: dupetrigger.so - cp dupetrigger.so $(INSTALLDIR) - chmod 644 $(INSTALLDIR)/dupetrigger.so - # - # Now, change the path to dupetrigger.so in postgresql.script to the - # absolute path where dupetrigger.so is installed (${INSTALLDIR}) - -dupetrigger.so: dupetrigger.o - $(CC) -shared -dynamic -o dupetrigger.so dupetrigger.o - -clean: - rm -rf dupetrigger.o dupetrigger.so - - -tidy: clean - rm -rf *~ - \ No newline at end of file diff --git a/dbscripts/dupetrigger/README b/dbscripts/dupetrigger/README deleted file mode 100755 index a506867e..00000000 --- a/dbscripts/dupetrigger/README +++ /dev/null @@ -1,16 +0,0 @@ -Dupe check Trigger -by Matthias "Trigger Hippy" Jordan - -The files in this directory are needed to create a PostgreSQL trigger that -is used to ensure that no comment and no article is posted twice. This -happens very often by accident and is very disturbing so we have to prevent -this somehow. Because Indymedia databases will hopefully grow big very fast, -we want to do this check as fast as possible. - -So Mir simply issues the INSERT. By this INSERT statement, a trigger gets, -well, triggered that calculates a CRC-32 checksum of the comment and -searches for rows with the same checksum. If it finds the checksum, the -INSERT gets aborted. If the checksum isn't found, it is appended to the row -and the INSERT is executed. - -The trigger works for INSERTs and UPDATEs. diff --git a/dbscripts/dupetrigger/dupetrigger.c b/dbscripts/dupetrigger/dupetrigger.c deleted file mode 100755 index ef823fad..00000000 --- a/dbscripts/dupetrigger/dupetrigger.c +++ /dev/null @@ -1,298 +0,0 @@ -// -// -// This File contructs a PostgreSQL trigger. -// -// USAGE: -// dupecheck(debug, column1, column2, ...); -// -// debug: if "yes" dupecheck generates debug output -// columns: the names of the columns that are used to calculate the -// checksum -// -// -// The trigger is normally fired BEFORE an INSERT or UPDATE of an -// article or comment. It first calculates a CRC-32 checksum of the -// specified columns of the row to be inserted or updated and -// checks whether there exists already another row with the same -// checksum. In this case, the trigger returns NULL and thus, -// aborts the SQL command. -// -// Author: Matthias Jordan -// - - -#include "executor/spi.h" -#include "commands/trigger.h" -#include "string.h" - - - -#ifndef PG70 - extern Datum dupecheck(PG_FUNCTION_ARGS); - PG_FUNCTION_INFO_V1(dupecheck); -#else - extern Datum dupecheck(void); -#endif - - - - - -// -// -// CRC32 stuff -// - -// crc32 table based on the following polynom -#define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */ - -u_long crc32_table[256] = - {0x0000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, - 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, - 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, - 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, - 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, - 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, - 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, - 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, - 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, - 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, - 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, - 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, - 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x54bf6a4, - 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, - 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, - 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, - 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, - 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, - 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, - 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, - 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, - 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, - 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, - 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, - 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, - 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0xe56f0ff, - 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, - 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, - 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, - 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, - 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, - 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, - 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, - 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, - 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, - 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0xfdc1bec, - 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, - 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, - 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, - 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, - 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, - 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, - 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4}; - - -static u_long crc32(u_char *buf, unsigned len) -{ - u_char *p; - u_long crc; - - crc = 0xffffffff; /* preload shift register, per CRC-32 spec */ - for (p = buf; len > 0; ++p, --len) - { - crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *p]; - } - return ~crc; /* transmit complement, per CRC-32 spec */ -} /* crc32 */ - - - - - -// -// -// Trigger stuff -// - - - - -#ifndef PG70 -Datum dupecheck(PG_FUNCTION_ARGS) -{ - TriggerData *trigdata = (TriggerData *) fcinfo->context; -#else -Datum dupecheck(void) -{ - TriggerData *trigdata = CurrentTriggerData; -#endif - TupleDesc tupdesc; - HeapTuple rettuple; - bool isnull, - debug_on; - int ret = 0, i, fnumber; - u_long rowstrlen = 0, - crc; - char **items, // will point to a malloc'ed array - *rowstring, - *query, - **args, - *relation; - int num, - nargs, - nitems; - - /* Make sure trigdata is pointing at what I expect */ -#ifdef PG70 - if (!CurrentTriggerData) -#else - if (!CALLED_AS_TRIGGER(fcinfo)) -#endif - elog(ERROR, "dupecheck: not fired by trigger manager"); - /* tuple to return to Executor */ - if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) - rettuple = trigdata->tg_newtuple; - else - rettuple = trigdata->tg_trigtuple; - - if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) - return PointerGetDatum(NULL); - - - // Initialize arguments and see whether the arguments are ok. - args = trigdata->tg_trigger->tgargs; - nargs = trigdata->tg_trigger->tgnargs; - - if (nargs < 2) - { - elog(DEBUG, "dupecheck: USAGE: dupeckeck(debug, col1, col2, ...)"); - return PointerGetDatum(NULL); - } - - debug_on = !strcmp("yes", args[0]); - - tupdesc = trigdata->tg_relation->rd_att; - - /* Connect to SPI manager */ - if ((ret = SPI_connect()) != SPI_OK_CONNECT) - { - elog(NOTICE, "dupecheck: SPI_connect returned error %d", ret); - } - - // Now we are connected to the database's SPI manager - // We will now construct a string of some important row values. - // First, we determine how long the string will be to allocate memory - // To include an additional item, add another SPI_getvalue line and - // increase maxitems above by 1 - - - // Allocate array for the argument pointers - nitems = nargs - 1; // don't take the debug parameter as a row name; - items = (char **) malloc(sizeof(char*) * nitems); - if (items == NULL) - { - SPI_finish(); - return PointerGetDatum(NULL); - } - - // Collect arguments - for (i = 1; (i < nargs); i++) - { - items[i-1] = SPI_getvalue(rettuple, tupdesc, SPI_fnumber(tupdesc, args[i])); - if (debug_on) - { - elog(DEBUG, "dupecheck: Argument %d: row %s -> %s\n", i, args[i], items[i-1]); - } - } - - - // Find out length of row string to be constructed - for (i=0; (i < nitems); i++) - { - if (items[i] != NULL) - { - rowstrlen += strlen(items[i]); - } - } - - rowstring = malloc(rowstrlen+1); // add space for 0-terminator - if (rowstring == NULL) - { - free(items); - SPI_finish(); - return PointerGetDatum(NULL); - } - - // Construct row string - *rowstring = 0; - for (i=0; (i < nitems); i++) - { - if (items[i] != NULL) - { - strcat(rowstring, items[i]); - } - } - - // rowstring now contains the data of the maxitems important - // items of the table record. Now we calculate the CRC-32 checksum - // of the rowstring - - crc = crc32(rowstring, rowstrlen); - - // Now we allocate some space and construct the SQL query - relation = SPI_getrelname(trigdata->tg_relation); - query = malloc(40 + strlen(relation) + 11 + 2 + 1); // SELECT part + relation + crc32 + "';" + 0-term - if (query == NULL) - { - // Big problem - free(items); - free(rowstring); - SPI_finish(); - return PointerGetDatum(NULL); - } - - sprintf(query, "SELECT count(*) FROM %s WHERE checksum='%ld';", relation, crc); - if (debug_on) - { - elog(DEBUG, "dupecheck: %s", query); - } - ret = SPI_exec(query, 2); - - if ((ret == SPI_OK_SELECT) && (SPI_processed > 0)) - { -#ifdef PG72 - num = (int) DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull)); -#else - num = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull); -#endif - } - - if ((ret == SPI_OK_SELECT) && (num > 0) && !(TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))) - { - elog(NOTICE, "dupecheck: UBD in %s detected, dupe dropped", relation); - rettuple = NULL; // reject operation - } - else - { - // The checksum wasn't found. So we modify the tuple to be - // inserted and add the fresh checksum. - int attnum; - Datum value; - char nulls = 0; - - if (debug_on) - { - elog(NOTICE, "dupecheck: Adding checksum to row"); - } - attnum = SPI_fnumber(tupdesc, "checksum"); - value = (Datum) crc; - rettuple = SPI_modifytuple(trigdata->tg_relation, rettuple, 1, &attnum, &value, &nulls); - } - - free(items); - free(rowstring); - free(query); - SPI_finish(); - return PointerGetDatum(rettuple); -} - diff --git a/dbscripts/dupetrigger/postgresql.sript b/dbscripts/dupetrigger/postgresql.sript deleted file mode 100755 index 9e526fc8..00000000 --- a/dbscripts/dupetrigger/postgresql.sript +++ /dev/null @@ -1,6 +0,0 @@ -DROP TRIGGER commdupetrigger ON comment; -DROP TRIGGER contentdupetrigger ON content; -DROP FUNCTION dupecheck(); -CREATE FUNCTION dupecheck() RETURNS OPAQUE AS '/var/lib/postgres/data/dupetrigger.so' LANGUAGE 'C'; -CREATE TRIGGER contentdupetrigger BEFORE INSERT OR UPDATE ON content FOR EACH ROW EXECUTE PROCEDURE dupecheck("no", "title", "subtitle", "creator", "description", "content_data"); -CREATE TRIGGER commdupetrigger BEFORE INSERT OR UPDATE ON comment FOR EACH ROW EXECUTE PROCEDURE dupecheck("no", "creator", "to_media", "description", "title"); diff --git a/dbscripts/help_users.sql b/dbscripts/help_users.sql index b3b9d0b9..d5dc9857 100755 --- a/dbscripts/help_users.sql +++ b/dbscripts/help_users.sql @@ -1,5 +1,5 @@ --- \connect - postgres -INSERT INTO "webdb_users" VALUES (1,'open','','f'); -INSERT INTO "webdb_users" VALUES (2,'redaktion','indymedia','t'); -INSERT INTO "webdb_users" VALUES (3,'tollendorf','indymedia','t'); -INSERT INTO "webdb_users" VALUES (4,'admin','indymedia','t'); +INSERT INTO webdb_users(login, password, is_admin, comment, is_disabled, email, profile, webdb_create) +VALUES ('open', '', 'f', 'Default open posting user', 'f', '', '', now()); + +INSERT INTO webdb_users(login, password, is_admin, comment, is_disabled, email, profile, webdb_create) +VALUES ('admin', 'indymedia', 't', 'Default admin user', 'f', '', '', now()); diff --git a/dbscripts/lib/codec.pl b/dbscripts/lib/codec.pl deleted file mode 100755 index 9fb09d7c..00000000 --- a/dbscripts/lib/codec.pl +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/perl - -################################################################ -### codec -### -### $VER: 2.1 (8bit,quoted-printable,perlish)$ -### USAGE: $codec=&Codec::new('perlish'); -### $encoded=$codec->encode($clear); -### $clear=$codec->decode($encoded); - -package Codec; - - -$VERSION="1.1"; - -sub new { - my($type)=shift; - my($res); - - return undef unless (defined $encode{$type}); - - $$res{'encode'}=$encode{$type}; - $$res{'decode'}=$decode{$type}; - $$res{'type'}=$type; - - bless $res, "Codec"; - - return $res; - } - -sub reset { - } - -sub encode { - my($obj,$str)=@_; - return &{$$obj{'encode'}}($str); - } - -sub decode { - my($obj,$str)=@_; - return &{$$obj{'decode'}}($str); - } - -sub name { - my($obj)=shift; - return $$obj{'type'}; - } - -################################################################ -### local - -$crlf=pack("CC",13,10); - -################################################################ -### id - -$encode{'8bit'}=sub { return $_[0]; }; -$decode{'8bit'}=sub { return $_[0]; }; - -################################################################ -### perlish - -sub quote_perlish { - my($str)=@_; - - $str=~s/\\/\\\\/g; - - $str=~s/\"/\\042/g; - $str=~s/\'/\\047/g; - - $str=~s/\@/\\@/g; - $str=~s/([\x80-\xFF])/sprintf("\\x%02x",ord($1))/eg; - $str=~s/([\x00-\x20])/sprintf("\\x%02x",ord($1))/eg; - return $str; - } - -sub convert_perlish { - my($item)=shift; - my($type,$key,$value,@res,$entry); - - $type=ref($item); - - if ((!defined $type)||($type eq "")) { - return "\042"."e_perlish($item)."\042"; - } - else { - if ($type eq "HASH") { - while (($key,$value)=each %$item) { - $entry="\042"."e_perlish($key)."\042"; - $entry.="=>"; - $entry.=&convert_perlish($value); - push(@res,$entry); - } - return "{".join(",",@res)."}"; - } - if ($type eq "ARRAY") { - foreach $value (@$item) { - push(@res,&convert_perlish($value)); - } - return "[".join(",",@res)."]"; - } - if ($type eq "SCALAR") { - return "\042"."e_perlish($item)."\042"; - } - return ""; - } - }; - -$encode{'perlish'}=\&convert_perlish; - -$decode{'perlish'}=sub { - my($str)=shift; - my($res); - - return eval($str); - }; - -################################################################ -### quoted-printable - -$encode{'quoted-printable'}=sub { - my($str)=shift; - my(@lines,$item); - - - $str=~s/=/=3D/g; - $str=~s/([\x00-\x1F\x80-\xFF])/sprintf("=%02X",ord($1))/eg; - - if (length($str)>75) { - while (length($str)>75) { - if (substr($str,73,1) eq "=") { - push(@lines,substr($str,0,73)."="); ### soft break - $str=substr($str,73); - } - elsif (substr($str,74,1) eq "=") { - push(@lines,substr($str,0,74)."="); ### soft break - $str=substr($str,74); - } - else { - push(@lines,substr($str,0,75)."="); ### soft break - $str=substr($str,75); - } - } - push(@lines,$str); - $str=join($HTTP::crlf,@lines); - } - - return $str; - }; - -$decode{'quoted-printable'}=sub { - $_[0]=~s/=([0-9a-fA-F][0-9a-fA-F])/pack("C", hex($1))/eg; - $_[0]=~s/=$crlf//g; - return $_[0]; - }; -1; diff --git a/dbscripts/lib/convert.pl b/dbscripts/lib/convert.pl deleted file mode 100755 index 5da5c63a..00000000 --- a/dbscripts/lib/convert.pl +++ /dev/null @@ -1,51 +0,0 @@ -# -# convert.pl -# - -sub mk_workfile { - my($props)=shift; - local(*HANLDE); - my($now,$count,$dir,$prefix); - - $dir=$$props{'convert'}{'work_dir'}; - $prefix=$$props{'convert'}{'work_prefix'}; - $now=time; - $count=0; - - while (-f $dir.$prefix.$now.".".$count) { $count++; } - - ## fast touch - if (sysopen(HANDLE,$dir.$prefix.$now.".".$count,O_CREATE|O_RDWR)) { close(HANDLE); } - - return $dir.$prefix.$now.".".$count; - } - -sub html_to_text { - my($props,$text)=@_; - local(*HANDLE); - my($file,$result); - - $file=&mk_workfile($props); - if (open(HANDLE,">".$file)) { - print HANDLE $text; - close(HANDLE); - } - else { - ## error - do not convert - return $text; - } - if (open(HANDLE,$$props{'bin'}{'html_to_text'}.$file."|")) { - while () { - $result.=$_; - } - close(HANDLE); - unlink($file); - return $result; - } - else { - unlink($file); - return $text; - } - } - -1; diff --git a/dbscripts/lib/log.pl b/dbscripts/lib/log.pl deleted file mode 100755 index 279ff81d..00000000 --- a/dbscripts/lib/log.pl +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/perl - -# -# Logfile Module (3.6.1998) -# -# USAGE: tie *HANDLE, 'Logfile', '', '1) && ($text[0]=~/^\d+$/)) { - my($level)=shift(@text); - return if ($level<$$obj{'loglevel'}); - } - - if (open(OUT,">>".$$obj{'filename'})) { - flock(OUT,$LOCK_EX); - seek(OUT,0,2); - printf OUT ("%02d.%02d.%s %02d:%02d:%02d [%d] %s: %s", - ($timestr[3]), - ($timestr[4]+1), - ($timestr[5]+1900), - $timestr[2],$timestr[1],$timestr[0], - $$,$$obj{'module'}, - join("",@text)); - flock(OUT,$LOCK_UN); - close(OUT); - } - } - -sub TIEHANDLE { - my $obj; - shift; - $$obj{'filename'}=&mkname(shift); - $$obj{'module'}=shift; - $$obj{'loglevel'}=(shift || 0); - - bless $obj, 'Logfile'; - - return $obj; - } -1; diff --git a/dbscripts/lib/property.pl b/dbscripts/lib/property.pl deleted file mode 100755 index 8ddbabf8..00000000 --- a/dbscripts/lib/property.pl +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/perl - -########################################################### -### property module -### -### $VER: 2.1$ - -package Property; - -sub compile { - my ($value)=shift; - $value=~s/\$\((\w+)\)/$ENV{$1}/e; - return $value; - } - -sub append { - my($hash,$file)=@_; - local(*FH); - my($line,$cat,$slot,$key,$value,$from,$to); - - $cat="public"; - if (open(FH,$file)) { - while () { - s/[\r\n]+//g; - next if /^\s*$/; - next if /^#/; - - if (/^\[(\w+)\]/) { - $cat=$1; - $$hash{$cat}{'_'}=$cat; - next; - } - if (/^\[(\w+)\]\s*=\>\s*\[(\w+)\]$/) { - $$hash{$2}=$$hash{$1}; - next; - } - if (/([^=\s]+)\s*=\s*(.*?)\s*$/) { - $$hash{$cat}{$1}=$2; - next; - } - if (/([^=\s]+)\s*:\s*(.*)/) { - $key=$1; $value=$2; - $value=&compile($value); - $$hash{$cat}{$key}=$value; - next; - } - if (/([^\<\s]+)\s*\<\<\s*(.*)/) { - $slot=$1; - undef @collect; - while () { - last if substr($_,0,2) eq "<<"; - push(@collect,$_); - } - $$hash{$cat}{$slot}=join("\n",@collect); - } - } - close(FH); - } - else { print "CANNOT OPEN $file --- $!\n"; } - } - -sub read { - my($file)=shift; - my($hash)={}; - - &append($hash,$file); - return $hash; - } - -1; diff --git a/dbscripts/lib/subst.pl b/dbscripts/lib/subst.pl deleted file mode 100755 index c45d74ce..00000000 --- a/dbscripts/lib/subst.pl +++ /dev/null @@ -1,446 +0,0 @@ -#!/usr/bin/perl - -################################################################ -### Preprocessor -### -### m -### -### $VER: 3.1.1 (% notation)$ - -require "codec.pl"; - -########################################################### -### token stuff - -package TokenStream; - -sub new { - local(*IN,$intro,$outro)=@_; - - $$stream{'handle'}=*IN; - $$stream{'buffer'}=[]; - $$stream{'intro'}=$intro; - $$stream{'outro'}=$outro; - - bless $stream, "TokenStream"; - - return $stream; - } - -sub fetch { - my($stream)=shift; - my($token,$old); - local(*IN); - - if (defined ($token=shift(@{$$stream{'buffer'}}))) { - return $token; - } - else { - $old=$/; - $/=$$stream{'outro'}; - *IN=$$stream{'handle'}; - - $token=; - - if (($index=index($token,$$stream{'intro'}))>0) { - push(@{$$stream{'buffer'}},substr($token,$index)); - $token=substr($token,0,$index); - } - - $/=$old; - - return $token; - } - } - -sub feed { - my($stream,$value)=@_; - - if (ref $value) { - unshift(@{$$stream{'buffer'}},@$value); - } - else { - unshift(@{$$stream{'buffer'}},$value); - } - } - -########################################################### -### prepro stuff - -package Subst; - -########################################################### -### local fun :-) - -$localfun{'store'}=sub { - my($args,$env,$stream)=@_; - my($token,$field,$count); - - # print "STORE $$args[1]\n"; - - $field=$$args[1]; - $count=0; - - $$env{$field}{'_data'}=[]; - while (($token=$stream->fetch) && ($token ne "<%/store%>")) { - push(@{$$env{$field}{'_data'}},$token); - $count++; - } - $$env{$field}{'_pos'}=0; - $$env{$field}{'_size'}=$count; - }; - -$localfun{'reset'}=sub { - my($args)=shift; - - $$env{$$args[1]}{'_pos'}=0; - }; - -$localfun{'insert'}=sub { - my($args,$env,$stream)=@_; - - #print main::DEBUG "INSERT $$args[1] size=",scalar(@{$$env{$$args[1]}{'_data'}})," time=$$env{$$args[1]}{'_pos'}\n"; - - $stream->feed($$env{$$args[1]}{'_data'}); - $$env{$$args[1]}{'_pos'}++; - }; - -$localfun{'loop'}=sub { - my($args,$env,$stream)=@_; - my($token,@loop,$count); - - - $count=$$args[1]; - #print "LOOP $count\n"; - while (($token=$stream->fetch) && ($token ne "<%/loop%>")) { - push(@loop,$token); - } - while ($count--) { - $stream->feed(\@loop); - } - }; - -sub clone { - my(@data)=@_; - return \@data; - } - -$localfun{'load'}=sub { - my($args,$env,$stream)=@_; - my(@temp,$count); - - # print ""; - - $$env{$$args[1]}{'_data'}=[]; - $count=0; - if (open(LOAD,$$args[2])) { - while () { - chomp; - #print "ROW: $_\n"; - @temp=split(/\t/); - push(@{$$env{$$args[1]}{'_data'}},&clone(@temp)); - undef @temp; - $count++; - } - close(LOAD); - } - $$env{$$args[1]}{'_size'}=$count; - $$env{$$args[1]}{'_pos'}=0; - - # print "LOAD $$args[2] into $$args[1] ($count)\n"; - }; - -$localfun{'loadvalues'}=sub { - my($args,$env,$stream)=@_; - local(*LOAD); - my($cat)="public"; - my($slot,$key,$value,@collect); - - if (open(LOAD,$$args[1])) { - while () { - s/[\r\n]+//g; - next if /^\s*$/; - next if /^#/; - - if (/^\[(\w+)\]/) { - $cat=$1; - next; - } - if (/^\[(\w+)\]\s*=\>\s*\[(\w+)\]$/) { - $$env{$2}=$$env{$1}; - next; - } - if (/([^=\s]+)\s*=\s*(.*?)\s*$/) { - $$env{$cat}{$1}=$2; - next; - } - if (/([^=\s]+)\s*:\s*(.*)/) { - $key=$1; $value=$2; - $value=~s/\$\((\w+)\)/$ENV{$value}/e; - $$env{$cat}{$key}=$value; - next; - } - if (/([^\<\s]+)\s*\<\<\s*(.*)/) { - $slot=$1; - undef @collect; - while () { - last if substr($_,0,2) eq "<<"; - push(@collect,$_); - } - $$env{$cat}{$slot}=join("\n",@collect); - } - } - close(LOAD); - } - else { - print "Cannot loadvalues ".$$args[1]."\n"; - } - }; - -$localfun{'bind'}=sub { - my($args,$env,$stream)=@_; - my($temp,$name,$var,$t,$item); - - shift(@$args); # function name - $name=shift(@$args); - $var=shift(@$args); - - #print "BIND from $name [$$env{$name}{'_pos'}] to $var : "; - - if ($$env{$name}{'_pos'}<$$env{$name}{'_size'}) { - $t=0; - $temp=$$env{$name}{'_data'}[$$env{$name}{'_pos'}]; - foreach $item (@$args) { - #print "\t$item=$$temp[$t]\n"; - $$env{$var}{$item}=$$temp[$t++]; - } - $$env{$name}{'_pos'}++; - } - else { - undef $$env{$var}; - } - }; - -### version 3.1 functions - -$localfun{'incr'}=sub { - my($args)=shift; - - #print main::DEBUG "INCR $$args[1]\n"; - - $$env{$$args[1]}{'_pos'}++; - }; - -$localfun{'alias'}=sub { - my($args,$env,$stream)=@_; - my($temp,$name,$var,$t,$item); - - shift(@$args); # function name - $name=shift(@$args); - $var=shift(@$args); - - #print main::DEBUG "ALIAS from $name [$$env{$name}{'_pos'}] to $var\n"; - - if ($$env{$name}{'_pos'}<$$env{$name}{'_size'}) { - $$env{$var}=$$env{$name}{'_data'}[$$env{$name}{'_pos'}]; - } - else { - undef $$env{$var}; - } - }; - -$localfun{'keyvalue'}=sub { - my($args,$env,$stream)=@_; - my($from,$to,@buffer,$key,$value); - - shift(@$args); # function name - $from=shift(@$args); - $to=shift(@$args); - - - while (($key,$value)=each %{$$env{$from}}) { - push(@buffer,{'key' => $key, 'value' => $value}); - } - $$env{$to}{'_data'}=\@buffer; - $$env{$to}{'_pos'}=0; - $$env{$to}{'_size'}=scalar(@buffer); - - #print main::DEBUG "keyvalue $from into $to ",scalar(@buffer),"\n"; - }; - -$localfun{'set'}=sub { - my($args,$env,$stream)=@_; - my($name,$value); - - shift(@$args); # function name - $name=shift(@$args); - $value=shift(@$args); - - $$env{'_flags'}{$name}=$value; - }; - -########################################################### -### if fun ?? - -$iffun{'ifdef'}=sub { - my($args,$env)=@_; - return ((defined (&getvalue($env,$$args[1]))) ? 0 : 1); - }; - -$iffun{'ifnz'}=sub { - my($args,$env)=@_; - return (&getvalue($env,$$args[1]) ? 0 : 1); - }; - -$iffun{'ifequal'}=sub { - my($args,$env)=@_; - return ((&getvalue($env,$$args[1]) eq $$args[2]) ? 0 : 1); - }; - -$iffun{'ifmember'}=sub { - my($args,$env)=@_; - return ((index($$args[1],$$args[2])<0) ? 1 : 0); - }; - -$iffun{'ifdecr'}=sub { - my($args,$env)=@_; - - if ($$args[1]=~/(\S+)\.(\S+)/) { - return (($$env{$1}{$2}-- > 0) ? 0 : 1); - } - else { - return (($$env{$$args[1]}-- > 0) ? 0 : 1); - } - }; - -$iffun{'ifiter'}=sub { - my($args,$env)=@_; - - if ($$args[2]=~/(\d+)\.(\d+)/) { - return (($$env{$$args[1]}{'_pos'} % $1) != $2); - } - else { - return (($$env{$$args[1]}{'_pos'} % $$argv[2]) != 0); - } - }; - - -### version 3.1 functions - -$iffun{'ifplus'}=sub { - my($args,$env)=@_; - return ((&getvalue($env,$$args[1])>0) ? 0 : 1); - }; - -$iffun{'ifminus'}=sub { - my($args,$env)=@_; - return ((&getvalue($env,$$args[1])<0) ? 0 : 1); - }; - -$iffun{'ifpluszero'}=sub { - my($args,$env)=@_; - return ((&getvalue($env,$$args[1])>=0) ? 0 : 1); - }; - -$iffun{'ifminuszero'}=sub { - my($args,$env)=@_; - return ((&getvalue($env,$$args[1])<=0) ? 0 : 1); - }; - - -########################################################### -### process - -sub process { - local(*IN,*OUT,$env,$post)=@_; - my($token,$ignore,@temp,$templine,$stream); - - $logfile=$$env{'logfile'}; - - $stream=&TokenStream::new(*IN,"<%","%>"); - - return undef unless defined $stream; - - #if (!defined $post) { $post=sub { print OUT $_[0] unless $_[0]=~/^\s*$/; }; } - if (!defined $post) { $post=sub { print OUT $_[0]; }; } - - $ignore=0; - - while ($token=$stream->fetch) { - # if-endif - if ($token eq "<%endif%>") { - $ignore-- if $ignore>0; - next; - } - - if (($ignore>0) && (substr($token,0,4) eq "<%if")) { - $ignore++; - next; - } - - if ($token eq "<%else%>") { - ($ignore == 0) && ($ignore=1, next); - ($ignore == 1) && ($ignore=0, next); - } - - next if $ignore; - - #$token=~s/\^(\'?[\w.]+)(\\)?/&getvalue($env,$1)/eg; - #$token=~s/\^(\[\w+\])?([\w.]+)(\\)?/&getvalue($env,$2,$1)/eg; - $token=~s/\^(\[\w+\])?([\w\x5b\x5d.]+)(\\)?/&getvalue($env,$2,$1)/eg; - - # handle none-special case - if (substr($token,0,2) ne "<%") { - &$post($token); - next; - } - - @temp=split(/\s+/,substr($token,2,-2)); - - if (defined $iffun{$temp[0]}) { - $ignore=&{$iffun{$temp[0]}}(\@temp,$env); - next; - } - - if (defined $localfun{$temp[0]}) { - &{$localfun{$temp[0]}}(\@temp,$env,$stream); - next; - } - - &$post($token); - } - } - -########################################################### -### binding - -$perlish=&Codec::new('perlish'); - -$convert{'[perl]'}=sub { return $perlish->encode(@_); }; - -$convert{'[scalar]'}=sub { return scalar($_[0]); }; - -$convert{'[javastyle]'}=sub { - my($value)=shift; - $value=lc($value); - substr($value,0,1)=uc(substr($value,0,1)); - return $value; - }; - -sub getvalue { - my($env,$key,$fun)=@_; - my($convert,$value); - -# $key=~s/\./\'\}\{\'/g; -# $value=eval "\$\$env{'$key'}"; - - $key=~s/\./\'\}\{\'/g; - $key="{'".$key."'}"; - $key=~s/(\[\d+\])\'\}/\'\}$1/g; - $value=eval "\$\$env$key"; - - if ((defined $fun) && (defined $convert{$fun})) { return &{$convert{$fun}}($value); } - else { return $value; } - } - -1; diff --git a/dbscripts/update_all_sequences.sql b/dbscripts/update_all_sequences.sql index a874112d..f8272522 100755 --- a/dbscripts/update_all_sequences.sql +++ b/dbscripts/update_all_sequences.sql @@ -1,6 +1,10 @@ -- This script updates all sequences in a postgres mir database -select setval('media_id_seq', (select max(id) from media)); +select + CASE WHEN (select max(id) from content)>(select max(id) from uploaded_media) + THEN setval('media_id_seq', (select max(id) from content)) + ELSE setval('media_id_seq', (select max(id) from uploaded_media)) + END; select setval('media_folder_id_seq', (select max(id) from media_folder)); select setval('topic_id_seq', (select max(id) from topic)); select setval('webdb_users_id_seq', (select max(id) from webdb_users)); @@ -11,7 +15,3 @@ select setval('media_type_id_seq', (select max(id) from media_type)); select setval('comment_status_id_seq',(select max(id) from comment_status)); select setval('article_type_id_seq', (select max(id) from article_type)); select setval('language_id_seq', (select max(id) from language)); - - - - diff --git a/dbscripts/update_database_01.sql b/dbscripts/update_database_01.sql deleted file mode 100755 index 96469e40..00000000 --- a/dbscripts/update_database_01.sql +++ /dev/null @@ -1,20 +0,0 @@ -\connect - postgres - -CREATE SEQUENCE "media_type_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ; - -DROP TABLE "media_type"; - -CREATE TABLE "media_type" ( - "id" integer DEFAULT nextval('media_type_id_seq'::text) NOT NULL, - "name" character varying(80) NOT NULL, - "mime_type" character varying(40) NOT NULL, - "classname" character varying(80) NOT NULL, - "tablename" character varying(80) NOT NULL, - "dcname" character varying(20) -); - - -CREATE TABLE "uploaded_media" ( - -) INHERITS ("media"); - diff --git a/dbscripts/updates/update20031122.sql b/dbscripts/updates/update20031122.sql new file mode 100755 index 00000000..02a9d3f8 --- /dev/null +++ b/dbscripts/updates/update20031122.sql @@ -0,0 +1,67 @@ +-- update script 2003-11-22 by Zapata +-- * added a bunch of fields to webdb_user: is_disabled, email, profile, creation date, +-- last login date +-- 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; + +ALTER TABLE "webdb_users" RENAME TO "webdb_users_old"; +DROP INDEX "webdb_users_pkey"; + +CREATE TABLE "webdb_users" ( + "id" integer DEFAULT nextval('webdb_users_id_seq'::text) NOT NULL, + "login" character varying(16) NOT NULL, + "password" character varying(255) NOT NULL, + "is_admin" boolean DEFAULT '0' NOT NULL, + "comment" text, + "is_disabled" boolean DEFAULT '0' NOT NULL, + "email" character varying(255) DEFAULT '' NOT NULL, + "profile" text, + "webdb_create" timestamp with time zone NOT NULL, + "lastlogin" timestamp with time zone, + CONSTRAINT "webdb_users_pkey" Primary Key ("id") +); + +INSERT INTO "webdb_users" ( + "id", + "login", + "password", + "is_admin", + "comment", + "is_disabled", + "email", + "profile", + "webdb_create", + "lastlogin" +) +SELECT + "id", + "login", + "password", + "is_admin", + '', + 'f', + '', + '', + now(), + null +FROM "webdb_users_old"; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='webdb_users_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='webdb_users_old') +WHERE + relname = 'webdb_users'; + + +-- to prevent this script from being run successfully for a second time +INSERT INTO webdb_users_old(login, password, is_admin) values('','','t'); + +DROP TABLE "webdb_users_old"; + +-- that's it! + +COMMIT TRANSACTION; diff --git a/dbscripts/updates/update20031124.sql b/dbscripts/updates/update20031124.sql new file mode 100755 index 00000000..99645ecf --- /dev/null +++ b/dbscripts/updates/update20031124.sql @@ -0,0 +1,97 @@ +-- update script 2003-11-25 by Zapata +-- * Clean up comments +-- * added a comment field for internal comments +-- This script will terminate with an error the second time it's run, +-- so running this script when it isn't needed is prevented from doing do any harm. + +BEGIN TRANSACTION; + +---------------------- +-- COMMENT changes +---------------------- + +ALTER TABLE "comment" RENAME TO "comment_old"; +DROP INDEX comment_pkey; +DROP INDEX comment_checksum_index; +DROP INDEX idx_comment_to_media; +DROP INDEX idx_comment_webdb_create; +DROP INDEX idx_comment_tomedia_ispublished; +DROP INDEX idx_comment_id; + +CREATE TABLE "comment" ( + "id" integer DEFAULT nextval('comment_id_seq'::text) NOT NULL, + "title" character varying(80) NOT NULL, + "creator" character varying(80) NOT NULL, + "description" text NOT NULL, + "main_url" character varying(255), + "email" character varying(80), + "address" character varying(80), + "phone" character varying(20), + "webdb_create" timestamp with time zone NOT NULL, + "webdb_lastchange" timestamp with time zone, + "is_published" boolean DEFAULT '1' NOT NULL, + "to_language" integer DEFAULT '0' NOT NULL, + "to_media" integer NOT NULL, + "to_comment_status" smallint, + "comment" text, + "is_html" boolean DEFAULT '0' NOT NULL, + Constraint "comment_pkey" Primary Key ("id") +); + +CREATE INDEX "idx_comment_to_media" on "comment" using btree ( "to_media" "int4_ops" ); +CREATE INDEX idx_comment_webdb_create on comment(webdb_create); +CREATE INDEX "idx_comment_tomedia_ispublished" on "comment" using btree ( "to_media" "int4_ops", "is_published" "bool_ops" ); +CREATE UNIQUE INDEX "idx_comment_id" on "comment" using btree ( "id" "int4_ops" ); + +INSERT INTO "comment" ( + "id", + "title", + "creator", + "description", + "main_url", + "email", + "address", + "phone", + "webdb_create", + "webdb_lastchange", + "is_published", + "to_language", + "to_media", + "to_comment_status", + "is_html", + "comment") +select + "id", + "title", + "creator", + "description", + "main_url", + "email", + "address", + "phone", + "webdb_create", + "webdb_lastchange", + "is_published", + "to_language", + "to_media", + "to_comment_status", + "is_html", + '' +from comment_old; + + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='comment_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='comment_old') +WHERE + relname = 'comment'; + +-- to prevent this script from being run successfully for a second time +INSERT INTO comment_old(to_media, description, checksum, title, creator, webdb_create) values(1, '', 1, '', '', now()); + +DROP TABLE comment_old; + +-- thats it! + +COMMIT TRANSACTION; diff --git a/dbscripts/updates/update20031125.sql b/dbscripts/updates/update20031125.sql new file mode 100755 index 00000000..c5e2f4bc --- /dev/null +++ b/dbscripts/updates/update20031125.sql @@ -0,0 +1,550 @@ +-- update script 2003-11-25 by Zapata +-- * Removal of media (uploaded_media and content are now independently) +-- * Clean up of content +-- * Added a field for content-locking +-- * Added a keywords field for content +-- This script will terminate with an error the second time it's run, +-- so running this script when it isn't needed is prevented from doing do any harm. + +DROP INDEX idx_content_webdb_create; +DROP INDEX idx_othermedia_is_published_produced; +DROP INDEX idx_othermedia_id; +DROP INDEX idx_video_id; + +BEGIN TRANSACTION; + +---------------------- +-- CONTENT changes +---------------------- + +ALTER TABLE "content" RENAME TO "content_old"; + +DROP INDEX "content_checksum_index"; +DROP INDEX "idx_content_to_article_type"; +DROP INDEX "idx_content_is_produced"; +DROP INDEX "idx_content_is_published__to_ar"; +DROP INDEX "idx_content_is_published__id"; +DROP INDEX "idx_content_is_pub__to_art__to_"; +DROP INDEX "idx_content_id"; +DROP INDEX "idx_content_is_published"; + +CREATE TABLE "content" ( + "id" integer DEFAULT nextval('media_id_seq'::text) NOT NULL, + "title" character varying(255), + "subtitle" character varying(255), + "edittitle" character varying(255), + "date" character(8) NOT NULL, + "creator" character varying(80), + "creator_main_url" character varying(255), + "creator_email" character varying(80), + "creator_address" character varying(80), + "creator_phone" character varying(80), + "description" text, + "comment" text, + "source" character varying(255), + "is_published" boolean DEFAULT '0' NOT NULL, + "is_produced" boolean DEFAULT '0' NOT NULL, + "to_publisher" integer NOT NULL, + "to_language" integer DEFAULT '0', + "to_rights" integer DEFAULT '0', + "webdb_create" timestamp with time zone NOT NULL, + "webdb_lastchange" timestamp with time zone, + "content_data" text, + "is_html" boolean DEFAULT '0' NOT NULL, + "to_article_type" smallint DEFAULT '0' NOT NULL, + "to_content" integer, + "keywords" text, + "to_locking_user" integer, + Constraint "content_pkey" Primary Key ("id") +); + + +CREATE INDEX "idx_content_to_article_type" on "content" using btree ( "to_article_type" "int2_ops" ); +CREATE INDEX "idx_content_is_produced" on "content" using btree ( "is_produced" "bool_ops" ); +CREATE INDEX "idx_content_is_published__to_ar" on "content" using btree ( "is_published" "bool_ops", "to_article_type" "int2_ops" ); +CREATE INDEX "idx_content_is_published__id" on "content" using btree ( "is_published" "bool_ops", "id" "int4_ops" ); +CREATE INDEX "idx_content_is_pub__to_art__to_" on "content" using btree ( "is_published" "bool_ops", "to_article_type" "int2_ops", "id" "int4_ops" ); +CREATE UNIQUE INDEX "idx_content_id" on "content" using btree ( "id" "int4_ops" ); +CREATE INDEX "idx_content_is_published" on "content" using btree ( "is_published" "bool_ops" ); + +INSERT INTO "content" ( + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "is_published", + "is_produced", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "content_data", + "is_html", + "to_article_type", + "to_content", + "keywords") +select + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "is_published", + "is_produced", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "content_data", + "is_html", + "to_article_type", + "to_content", + '' +from content_old; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='content_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='content_old') +WHERE + relname = 'content'; + +DROP table content_old; + +-- +-- uploaded_media +-- + +ALTER TABLE "uploaded_media" RENAME TO "uploaded_media_old"; +DROP INDEX "idx_uploaded_media_id"; +DROP INDEX "idx_uploaded_media_is_published"; + +CREATE TABLE "uploaded_media" ( + "id" integer DEFAULT nextval('media_id_seq'::text) NOT NULL, + "title" character varying(255), + "subtitle" character varying(255), + "edittitle" character varying(255), + "date" character(8) NOT NULL, + "creator" character varying(80), + "creator_main_url" character varying(255), + "creator_email" character varying(80), + "creator_address" character varying(80), + "creator_phone" character varying(20), + "description" text, + "comment" text, + "source" character varying(255), + "publish_server" character varying(255), + "publish_path" character varying(255), + "is_published" boolean DEFAULT '0' NOT NULL, + "is_produced" boolean DEFAULT '0' NOT NULL, + "to_media_folder" integer DEFAULT '0' NOT NULL, + "to_media_type" smallint DEFAULT '0' NOT NULL, + "to_publisher" integer NOT NULL, + "to_language" integer DEFAULT '0', + "to_rights" integer DEFAULT '0', + "webdb_create" timestamp with time zone NOT NULL, + "webdb_lastchange" timestamp with time zone, + "icon_is_produced" boolean DEFAULT '0' NOT NULL, + "icon_path" character varying(255), + "size" integer, + Constraint "uploaded_media_pkey" Primary Key ("id") +); + +CREATE UNIQUE INDEX "idx_uploaded_media_id" on "uploaded_media" using btree ( "id" "int4_ops" ); +CREATE UNIQUE INDEX "idx_uploaded_media_is_published" on "uploaded_media" using btree ( "id" "int4_ops", "is_published" "bool_ops" ); + +-- +-- images +-- + +ALTER TABLE "images" RENAME TO "images_old"; +DROP INDEX "idx_images_is_published__icon_i"; +DROP INDEX "idx_images_id"; + + +CREATE TABLE "images" ( + "image_data" oid, + "icon_data" oid, + "year" character varying(40), + "img_width" smallint, + "img_height" smallint, + "to_img_format" smallint DEFAULT '0' NOT NULL, + "to_img_layout" smallint DEFAULT '0' NOT NULL, + "to_img_type" smallint DEFAULT '0' NOT NULL, + "to_img_color" smallint DEFAULT '0' NOT NULL, + "icon_width" smallint, + "icon_height" smallint +) +INHERITS ("uploaded_media"); + +CREATE INDEX "idx_images_is_published" on "images" using btree ( "is_published" "bool_ops", "icon_is_produced" "bool_ops" ); +CREATE UNIQUE INDEX "idx_images_id" on "images" using btree ( "id" "int4_ops" ); + +INSERT INTO images( + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size", + "image_data", + "icon_data", + "year", + "img_width", + "img_height", + "to_img_format", + "to_img_layout", + "to_img_type", + "to_img_color", + "icon_width", + "icon_height" +) +SELECT + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size", + "image_data", + "icon_data", + "year", + "img_width", + "img_height", + "to_img_format", + "to_img_layout", + "to_img_type", + "to_img_color", + "icon_width", + "icon_height" +FROM images_old; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='images_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='images_old') +WHERE + relname = 'images'; + +DROP table images_old; + +-- +-- audio +-- + +ALTER TABLE "audio" RENAME TO "audio_old"; +DROP INDEX "idx_audio_is_published_produced"; +DROP INDEX "idx_audio_id"; + +CREATE TABLE "audio" ( + "kbits" smallint +) +INHERITS ("uploaded_media"); + +CREATE INDEX "idx_audio_is_published_produced" on "audio" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" ); +CREATE UNIQUE INDEX "idx_audio_id" on "audio" using btree ( "id" "int4_ops" ); + +INSERT INTO audio( + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size", + "kbits" +) +SELECT + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size", + "kbits" +FROM audio_old; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='audio_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='audio_old') +WHERE + relname = 'audio'; + +DROP table audio_old; + +-- +-- video +-- + +DROP INDEX "idx_video_is_published_produced"; +ALTER TABLE "video" RENAME TO "video_old"; + +CREATE TABLE "video" ( +) +INHERITS ("uploaded_media"); + +CREATE INDEX "idx_video_is_published_produced" on "video" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" ); + +INSERT INTO video( + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size" +) +SELECT + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size" +FROM video_old; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='video_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='video_old') +WHERE + relname = 'video'; + +DROP table video_old; + + +-- +-- other_media +-- + +ALTER TABLE "other_media" RENAME TO "other_media_old"; + +CREATE TABLE "other_media" ( +) +INHERITS ("uploaded_media"); + +INSERT INTO other_media( + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size" +) +SELECT + "id", + "title", + "subtitle", + "edittitle", + "date", + "creator", + "creator_main_url", + "creator_email", + "creator_address", + "creator_phone", + "description", + "comment", + "source", + "publish_server", + "publish_path", + "is_published", + "is_produced", + "to_media_folder", + "to_media_type", + "to_publisher", + "to_language", + "to_rights", + "webdb_create", + "webdb_lastchange", + "icon_is_produced", + "icon_path", + "size" +FROM other_media_old; + +UPDATE pg_class +SET + relowner = (SELECT relowner FROM pg_class WHERE relname='other_media_old'), + relacl = (SELECT relacl FROM pg_class WHERE relname='other_media_old') +WHERE + relname = 'other_media'; + +DROP table other_media_old; + +DROP table uploaded_media_old; +DROP table media; + +-- that's it! + +COMMIT TRANSACTION; + +CREATE INDEX idx_content_webdb_create on content(webdb_create); +CREATE INDEX "idx_othermedia_is_published_produced" on "other_media" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" ); +CREATE UNIQUE INDEX "idx_othermedia_id" on "other_media" using btree ( "id" "int4_ops" ); +CREATE UNIQUE INDEX "idx_video_id" on "video" using btree ( "id" "int4_ops" ); + + diff --git a/dbscripts/wiz_templates/show.template b/dbscripts/wiz_templates/show.template deleted file mode 100755 index c0c613e9..00000000 --- a/dbscripts/wiz_templates/show.template +++ /dev/null @@ -1,42 +0,0 @@ - - - -^tablename - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
^metadata.name : - -
- - - - -
- - - diff --git a/dbscripts/wizard.pl b/dbscripts/wizard.pl deleted file mode 100755 index adfe77f3..00000000 --- a/dbscripts/wizard.pl +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/perl - -# -# wizard -# - -use DBI; - -$0=~m#[^/]+$#; -$cmdpath=$`; -if ($cmdpath eq "") { $cmdpath="./"; } -unshift(@INC,$cmdpath."lib"); - -require "codec.pl"; -require "subst.pl"; - -sub USAGE { - print "USAGE: wizard.pl dsn user passwd table dir\n"; - exit(0); - } - -$dsn=shift(@ARGV) || &USAGE; -if (($dsn eq "-h") || ($dsn eq "--help")) { &USAGE; } -$user=shift(@ARGV) || &USAGE; -$passwd=shift(@ARGV) || &USAGE; -if ($passwd eq "-") { $passwd=""; } -$table=shift(@ARGV) || &USAGE; -$dir=shift(@ARGV) || &USAGE; - -$dbh=DBI->connect($dsn,$user,$passwd); -if (!defined $dsn) { - print "Error: cannot connect $dsn\n"; - &USAGE; - } - -$tables=$dbh->table_info; -while ($hash=$tables->fetchrow_hashref) { - #print $$hash{'TABLE_NAME'}."\n"; - - if ($$hash{'TABLE_NAME'} eq $table) { - - $sth=$dbh->prepare("show fields from ".$$hash{'TABLE_NAME'}); - $sth->execute; - while ($fieldhash=$sth->fetchrow_hashref) { - #print "\t".$$fieldhash{'Field'}.":".$$fieldhash{'Type'}."\n"; - push(@data,[$$fieldhash{'Field'},$$fieldhash{'Type'}]); - } - $sth->finish; - } - } - -$$env{'fields'}{'_data'}=\@data; -$$env{'fields'}{'_pos'}=0; -$$env{'fields'}{'_size'}=scalar(@data); - -$$env{'tablename'}=$table; - -print "prosessing files in $dir\n"; - -chdir $dir; - -if (opendir(DIR,".")) { - while ($file=readdir(DIR)) { - next unless (-f $file); - if ($file=~/\.template$/) { - $newfile=$`; - print "\t$file -> $newfile\n"; - if (open(IN,$file)) { - if (open(OUT,">$newfile")) { - &Subst::process(*IN,*OUT,$env); - close(OUT); - } - close(IN); - } - } - } - closedir(DIR); - } - - - - - diff --git a/source/Mir.java b/source/Mir.java index 70430462..24c111eb 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -70,8 +70,8 @@ import org.apache.struts.util.MessageResources; /** * Mir.java - main servlet, that dispatches to servletmodules * - * @author $Author: rk $ - * @version $Id: Mir.java,v 1.49.2.8 2003/10/23 14:55:26 rk Exp $ + * @author $Author: zapata $ + * @version $Id: Mir.java,v 1.49.2.9 2003/12/21 13:32:02 zapata Exp $ * */ public class Mir extends AbstractServlet { @@ -169,7 +169,8 @@ public class Mir extends AbstractServlet { if (user!=null) { ServletHelper.setUser(aRequest, user); - aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username)); + usersModule.recordLogin(user); + aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId())); } } @@ -360,17 +361,19 @@ public class Mir extends AbstractServlet { private class SessionTracker implements HttpSessionBindingListener { private String name; + private String id; - public SessionTracker(String aUserName) { + public SessionTracker(String aUserName, String anId) { name = aUserName; + id = anId; } public void valueBound(HttpSessionBindingEvent anEvent) { - MirGlobal.registerLogin(name); + MirGlobal.registerLogin(name, id); } public void valueUnbound(HttpSessionBindingEvent anEvent) { - MirGlobal.registerLogout(name); + MirGlobal.registerLogout(name, id); } } } diff --git a/source/default.properties b/source/default.properties index 3600aa94..15136d99 100755 --- a/source/default.properties +++ b/source/default.properties @@ -94,6 +94,13 @@ Mir.Admin.LogAdminActivity=0 # Which usernames have admin priviliges (, seperated usernames) AccessControl.SuperUsers = admin +# Locking enabled? +AccessControl.LockingEnabled = 0 + +# If locking enabled, should users lock articles before they +# can edit? +AccessControl.LockingOptional = 1 + # the templates Mir.Localizer.Producer.GeneratorLibrary= default=freemarker(etc/producer/) Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/) diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index d675ad61..e2e19c47 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -40,12 +40,13 @@ import mir.log.LoggerWrapper; import mir.storage.StorageObject; import mir.storage.StorageObjectExc; import mir.storage.StorageObjectFailure; +import mir.util.*; /** * Base class the entities are derived from. Provides base functionality of * an entity. Entities are used to represent rows of a database table.

* - * @version $Id: Entity.java,v 1.21.2.5 2003/10/23 14:55:28 rk Exp $ + * @version $Id: Entity.java,v 1.21.2.6 2003/12/21 13:32:03 zapata Exp $ * @author rk * */ @@ -253,5 +254,23 @@ public class Entity throw new StorageObjectFailure("Storage Object Exception in entity", e); } + + /** + * Helper method to append a line to a field + */ + public void appendLineToField(String aFieldName, String aLine) { + StringBuffer fieldContent = new StringBuffer(); + try { + fieldContent.append(StringRoutines.interpretAsString(getValue(aFieldName))); + } + catch (Throwable t) { + } + if (fieldContent.length() > 0 && fieldContent.charAt(fieldContent.length() - 1) != '\n') { + fieldContent.append('\n'); + } + + fieldContent.append(aLine); + setValueForProperty(aFieldName, fieldContent.toString()); + } } diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java index f7924137..0de6bba9 100755 --- a/source/mir/entity/EntityList.java +++ b/source/mir/entity/EntityList.java @@ -1,267 +1,267 @@ -/* - * 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.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.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; - -/** - * - * Container class for lists of Entities. - * Now implements @see mir.storage.store.StorableObject. - * - * @author - * first version 27.6.1999 - * - * @version 1.1 (cleaned up) - */ -public class EntityList implements StorableObject { - protected static MirPropertiesConfiguration configuration; - protected LoggerWrapper logger; - private ArrayList theEntityArrayList = new ArrayList(); - private String whereClause, orderClause; - private StorageObject theStorage; - private int count, offset, limit; - private int offsetnext = -1, offsetprev = -1; - - static { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException("Unable to get configuration: " + e.getMessage()); - } - } - - /** - * Constructor. - */ - 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 setLimit(int limit) { this.limit = limit; } - - /** - * 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) { - this.whereClause = 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) { - this.orderClause = 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) { - offset = i; - } - - /** - * Returns the offset - * @return offset - */ - public int getOffset() { - return offset; - } - - /** - * Sets the offset of the next batch of Entities. - * @param i The next offset - */ - public void setNextBatch(int i) { - offsetnext = i; - } - - /** - * Returns the offset of the next batch of Entities. - * @return offset of the next batch - */ - public int getNextBatch() { - return offsetnext; - } - - /** - * 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; - } - - /** - * Inserts an Entity into the EntityList. - * @param anEntity The entity to be inserted. - */ - - public void add (Entity anEntity) { - if (anEntity!=null) - theEntityArrayList.add(anEntity); - else - logger.warn("EntityList: add called with empty Entity"); - } - - - /** - * @return The number of Entities in the EntityList. - */ - - public int size() { - return theEntityArrayList.size(); - } - - - /** - * Returns the element at position i in the EntityList as Entity - * @param i the position of the element in question - * @return The element at position i. - */ - - public Entity elementAt(int i) { - /** @todo check if i is in list.size() */ - return (Entity)theEntityArrayList.get(i); - } - - - -// Methods to implement StorableObject - - public Set getNotifyOnReleaseSet() { return null; } - - public StoreIdentifier getStoreIdentifier() { - if ( theStorage!=null ) { - return - new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST, - StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(), - whereClause, orderClause, offset, limit )); - } - logger.warn("EntityList could not return StoreIdentifier"); - return 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.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.store.StorableObject; +import mir.storage.store.StoreContainerType; +import mir.storage.store.StoreIdentifier; +import mir.storage.store.StoreUtil; + +/** + * + * Container class for lists of Entities. + * Now implements @see mir.storage.store.StorableObject. + * + * @author + * first version 27.6.1999 + * + * @version 1.1 (cleaned up) + */ +public class EntityList implements StorableObject { + protected static MirPropertiesConfiguration configuration; + protected LoggerWrapper logger; + private ArrayList theEntityArrayList = new ArrayList(); + private String whereClause, orderClause; + private StorageObject theStorage; + private int count, offset, limit; + private int offsetnext = -1, offsetprev = -1; + + static { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new RuntimeException("Unable to get configuration: " + e.getMessage()); + } + } + + /** + * Constructor. + */ + 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 setLimit(int limit) { this.limit = limit; } + + /** + * 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) { + this.whereClause = 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) { + this.orderClause = 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) { + offset = i; + } + + /** + * Returns the offset + * @return offset + */ + public int getOffset() { + return offset; + } + + /** + * Sets the offset of the next batch of Entities. + * @param i The next offset + */ + public void setNextBatch(int i) { + offsetnext = i; + } + + /** + * Returns the offset of the next batch of Entities. + * @return offset of the next batch + */ + public int getNextBatch() { + return offsetnext; + } + + /** + * 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; + } + + /** + * Inserts an Entity into the EntityList. + * @param anEntity The entity to be inserted. + */ + + public void add (Entity anEntity) { + if (anEntity!=null) + theEntityArrayList.add(anEntity); + else + logger.warn("EntityList: add called with empty Entity"); + } + + + /** + * @return The number of Entities in the EntityList. + */ + + public int size() { + return theEntityArrayList.size(); + } + + + /** + * Returns the element at position i in the EntityList as Entity + * @param i the position of the element in question + * @return The element at position i. + */ + + public Entity elementAt(int i) { + /** @todo check if i is in list.size() */ + return (Entity)theEntityArrayList.get(i); + } + + + +// Methods to implement StorableObject + + public Set getNotifyOnReleaseSet() { return null; } + + public StoreIdentifier getStoreIdentifier() { + if ( theStorage!=null ) { + return + new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST, + StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(), + whereClause, orderClause, offset, limit )); + } + logger.warn("EntityList could not return StoreIdentifier"); + return null; + } + +} diff --git a/source/mir/entity/adapter/EntityAdapterDefinition.java b/source/mir/entity/adapter/EntityAdapterDefinition.java index 68cdf2f4..80cb4233 100755 --- a/source/mir/entity/adapter/EntityAdapterDefinition.java +++ b/source/mir/entity/adapter/EntityAdapterDefinition.java @@ -29,17 +29,22 @@ */ package mir.entity.adapter; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - -import mir.entity.Entity; -import mir.misc.StringUtil; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + +import mir.entity.Entity; +import mir.misc.StringUtil; import mir.util.GeneratorFormatAdapters; +/** + * EntityAdapterDefinition defines the fields for an entity adapter of + * a particular "type". Custom calculated fields can be defined. + * + */ public class EntityAdapterDefinition { private Map calculatedFields; @@ -47,31 +52,76 @@ public class EntityAdapterDefinition { calculatedFields = new HashMap(); } + /** + * + * + * @param anEntity the entity that will be wrapped by the entity adapter + * @param aModel the base model + * @return the resulting entity adapter + */ public EntityAdapter makeEntityAdapter(Entity anEntity, EntityAdapterModel aModel) { return new EntityAdapter(anEntity, this, aModel); } + /** + * + * @param aFieldName + * @return the CalculatedField if it exists. null otherwise + */ public CalculatedField getCalculatedField(String aFieldName) { return (CalculatedField) calculatedFields.get(aFieldName); } + /** + * + * @param aFieldName + * @return + */ public boolean hasCalculatedField(String aFieldName) { return calculatedFields.containsKey(aFieldName); } + /** + * + * @param aFieldName + * @param aField + */ public void addCalculatedField(String aFieldName, CalculatedField aField) { calculatedFields.put(aFieldName, aField); } + /** + * To add a calculated field based on a "mir" date field: a string field of the form yyyyMMdd[hhmm] + * + * @param aDestinationFieldName + * @param aSourceFieldName + * @param aDefaultTimezone + */ public void addMirDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) { addCalculatedField(aDestinationFieldName, new MirDateField(aSourceFieldName, aDefaultTimezone)); } + /** + * Adds a calculated field based on a db date field + * + * @param aDestinationFieldName the field name of the calculated field + * @param aSourceFieldName the field name of the entity (must be a date field) + * @param aDefaultTimezone the default timezone to use + */ public void addDBDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) { addCalculatedField(aDestinationFieldName, new DBDateField(aSourceFieldName, aDefaultTimezone)); } + /** + * a calculated field: field gets its value from other fields. + */ public interface CalculatedField { + /** + * Method to retrieve the calculated value of the field. + * + * @param anEntityAdapter the entity + * @return the value of the field. + */ public Object getValue(EntityAdapter anEntityAdapter); } diff --git a/source/mir/entity/adapter/EntityListAdapter.java b/source/mir/entity/adapter/EntityListAdapter.java index f7ae65de..7df00efa 100755 --- a/source/mir/entity/adapter/EntityListAdapter.java +++ b/source/mir/entity/adapter/EntityListAdapter.java @@ -1,122 +1,122 @@ -/* - * 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.entity.adapter; - -import java.util.AbstractList; -import java.util.List; -import java.util.Vector; - -import mir.entity.Entity; -import mir.entity.EntityBrowser; - -public class EntityListAdapter extends AbstractList { - private int skip; - private int maximumLength; - private EntityBrowser browser; - private EntityAdapterModel model; - private String definition; - private boolean exhausted = false; - private boolean skipped = false; - - private List cache; - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aSkip, int aMaximumLength) { - model = aModel; - definition = aDefinition; - browser = aBrowser; - skip = aSkip; - maximumLength = aMaximumLength; - cache = new Vector(); - } - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aMaximumLength) { - this(aModel, aDefinition, aBrowser, 0, aMaximumLength); - } - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser) { - this(aModel, aDefinition, aBrowser, 0, -1); - } - - private void skip() { - int i; - - try { - if (!skipped) { - for(i=0; i0 && cache.size()>=maximumLength) ; - } - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - - } - - private void exhaust() { - skip(); - - while (!exhausted) - fetchNext(); - } - - private void fetchUntil(int anIndex) { - skip(); - - while (!exhausted && anIndex>=cache.size()) - fetchNext(); - } - - public int size() { - exhaust(); - - return cache.size(); - } - - public Object get(int anIndex) { - fetchUntil(anIndex); - return cache.get(anIndex); - } +/* + * 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.entity.adapter; + +import java.util.AbstractList; +import java.util.List; +import java.util.Vector; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; + +public class EntityListAdapter extends AbstractList { + private int skip; + private int maximumLength; + private EntityBrowser browser; + private EntityAdapterModel model; + private String definition; + private boolean exhausted = false; + private boolean skipped = false; + + private List cache; + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aSkip, int aMaximumLength) { + model = aModel; + definition = aDefinition; + browser = aBrowser; + skip = aSkip; + maximumLength = aMaximumLength; + cache = new Vector(); + } + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aMaximumLength) { + this(aModel, aDefinition, aBrowser, 0, aMaximumLength); + } + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser) { + this(aModel, aDefinition, aBrowser, 0, -1); + } + + private void skip() { + int i; + + try { + if (!skipped) { + for(i=0; i0 && cache.size()>=maximumLength) ; + } + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + + } + + private void exhaust() { + skip(); + + while (!exhausted) + fetchNext(); + } + + private void fetchUntil(int anIndex) { + skip(); + + while (!exhausted && anIndex>=cache.size()) + fetchNext(); + } + + public int size() { + exhaust(); + + return cache.size(); + } + + public Object get(int anIndex) { + fetchUntil(anIndex); + return cache.get(anIndex); + } } \ No newline at end of file diff --git a/source/mir/generator/FreemarkerGenerator.java b/source/mir/generator/FreemarkerGenerator.java index 8ca243bd..c0ebb764 100755 --- a/source/mir/generator/FreemarkerGenerator.java +++ b/source/mir/generator/FreemarkerGenerator.java @@ -364,7 +364,7 @@ public class FreemarkerGenerator implements Generator { 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()+"/"+anIdentifier); } return new FreemarkerGenerator(template); diff --git a/source/mir/generator/TALGenerator.java b/source/mir/generator/TALGenerator.java index 3744b1fc..e8789da4 100755 --- a/source/mir/generator/TALGenerator.java +++ b/source/mir/generator/TALGenerator.java @@ -1,88 +1,88 @@ -/* - * 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.generator; - -import java.io.PrintWriter; -import java.util.Map; - -import mir.generator.tal.MirExpressionParser; -import mir.generator.tal.TALTemplate; -import mir.generator.tal.TALTemplateEngine; -import mir.log.LoggerWrapper; - -public class TALGenerator implements Generator { - private String templateIdentifier; - private TALGeneratorLibrary library; - private static LoggerWrapper logger = new LoggerWrapper("Generator.velocity"); - - public TALGenerator(String aTemplate, TALGeneratorLibrary aLibrary) { - templateIdentifier = aTemplate; - library = aLibrary; - } - - public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure { - TALTemplate template; - - try { - template = library.engine.loadTemplate(templateIdentifier); - if (template == null) { - throw new GeneratorExc("TALGeneratorLibrary: Can't find template " + templateIdentifier); - } - template.processTemplate(aValues, (PrintWriter) anOutputWriter); - } - catch (Throwable t) { - throw new GeneratorFailure(t); - } - } - - public static class TALGeneratorLibrary implements GeneratorLibrary { - private TALTemplateEngine engine; - - public TALGeneratorLibrary(String aTemplateRoot) throws GeneratorExc, GeneratorFailure { - engine = new TALTemplateEngine(new MirExpressionParser(), aTemplateRoot); - } - - public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure { - return new TALGenerator(anIdentifier, this); - } - } - - public static class TALGeneratorLibraryFactory implements GeneratorLibraryFactory { - private String basePath; - - public TALGeneratorLibraryFactory(String aBasePath) { - basePath = aBasePath; - } - - public GeneratorLibrary makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure { - return new TALGeneratorLibrary(basePath+anInitializationString); - }; - } -} +/* + * 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.generator; + +import java.io.PrintWriter; +import java.util.Map; + +import mir.generator.tal.MirExpressionParser; +import mir.generator.tal.TALTemplate; +import mir.generator.tal.TALTemplateEngine; +import mir.log.LoggerWrapper; + +public class TALGenerator implements Generator { + private String templateIdentifier; + private TALGeneratorLibrary library; + private static LoggerWrapper logger = new LoggerWrapper("Generator.velocity"); + + public TALGenerator(String aTemplate, TALGeneratorLibrary aLibrary) { + templateIdentifier = aTemplate; + library = aLibrary; + } + + public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure { + TALTemplate template; + + try { + template = library.engine.loadTemplate(templateIdentifier); + if (template == null) { + throw new GeneratorExc("TALGeneratorLibrary: Can't find template " + templateIdentifier); + } + template.processTemplate(aValues, (PrintWriter) anOutputWriter); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public static class TALGeneratorLibrary implements GeneratorLibrary { + private TALTemplateEngine engine; + + public TALGeneratorLibrary(String aTemplateRoot) throws GeneratorExc, GeneratorFailure { + engine = new TALTemplateEngine(new MirExpressionParser(), aTemplateRoot); + } + + public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure { + return new TALGenerator(anIdentifier, this); + } + } + + public static class TALGeneratorLibraryFactory implements GeneratorLibraryFactory { + private String basePath; + + public TALGeneratorLibraryFactory(String aBasePath) { + basePath = aBasePath; + } + + public GeneratorLibrary makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure { + return new TALGeneratorLibrary(basePath+anInitializationString); + }; + } +} diff --git a/source/mir/generator/VelocityGenerator.java b/source/mir/generator/VelocityGenerator.java index e827cc50..a6c0a77e 100755 --- a/source/mir/generator/VelocityGenerator.java +++ b/source/mir/generator/VelocityGenerator.java @@ -1,656 +1,656 @@ -/* - * 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.generator; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.AbstractList; -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 org.apache.commons.beanutils.MethodUtils; -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.context.Context; -import org.apache.velocity.exception.ParseErrorException; -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"); - - /** - * - * @param aTemplate - * @param aLibrary - */ - - public VelocityGenerator(String aTemplate, VelocityGeneratorLibrary aLibrary) { - templateIdentifier = aTemplate; - library = aLibrary; - } - - /** - * - * @param anOutputWriter - * @param aValues - * @param aLogger - * @throws GeneratorExc - * @throws GeneratorFailure - */ - public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure { - Template template; - Context context = makeMapAdapter(aValues); - StringWriter stringWriter = new StringWriter(); - - try { - template = library.engine.getTemplate(templateIdentifier); - if (template == null) { - throw new GeneratorExc("VelocityGeneratorLibrary: Can't find template " + templateIdentifier); - } - template.merge(context, stringWriter); - - ( (PrintWriter) anOutputWriter).print(stringWriter.toString()); - } - catch (ResourceNotFoundException t) { - throw new GeneratorExc("VelocityGeneratorLibrary: Can't find template " + templateIdentifier); - } - catch (ParseErrorException t) { - ( (PrintWriter) anOutputWriter).print(t.toString()); - } - catch (Throwable t) { - throw new GeneratorFailure(t); - } - - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class ContextAdapter implements Context { - public boolean containsKey(java.lang.Object key) { - return false; - } - - public Object get(java.lang.String key) { - return null; - } - - public Object[] getKeys() { - return new Object[] {}; - } - - public Object put(java.lang.String key, java.lang.Object value) { - return null; - } - - public Object remove(java.lang.Object key) { - return null; - } - } - - /** - * - * @param aMap - * @return - */ - private static Context makeMapAdapter(Map aMap) { - return new MapAdapter(aMap); - } - - /** - * - * @param anIterator - * @return - */ - private static List makeIteratorAdapter(Iterator anIterator) { - return new IteratorAdapter(anIterator); - } - - /** - * - * @param aList - * @return - */ - private static List makeListAdapter(List aList) { - return new ListAdapter(aList); - } - - /** - * - * @param aFunction - * @return - */ - private static Object makeFunctionAdapter(Generator.GeneratorFunction aFunction) { - return new FunctionAdapter(aFunction); - } - - /** - * - * @param anObject - * @return - */ - private static Object makeBeanAdapter(Object anObject) { - return new BeanAdapter(anObject); - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private interface VelocityAdapter { - public Object getOriginal(); - } - - /** - * - * @param anObject - * @return - */ - public static Object unmakeAdapter(Object anObject) { - if (anObject instanceof VelocityAdapter) { - return ((VelocityAdapter) anObject).getOriginal(); - } - else - return anObject; - } - - /** - * - * @param anObject - * @return - */ - public static Object makeAdapter(Object anObject) { - if (anObject == null) - return null; - - if (anObject instanceof Context) - return anObject; - - else if (anObject instanceof Generator.GeneratorFunction) - return makeFunctionAdapter((Generator.GeneratorFunction) anObject); - else if (anObject instanceof Integer) - return anObject; - else if (anObject instanceof Boolean) - return anObject; - else if (anObject instanceof String) - return 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 makeListAdapter(((List) anObject)); - 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); - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - public static class FunctionAdapter implements VelocityAdapter { - private GeneratorFunction function; - - public Object getOriginal() { - return function; - } - - private FunctionAdapter(GeneratorFunction aFunction) { - function = aFunction; - } - - public Object call(Object aParameters[]) throws GeneratorExc { - List parameters = new Vector(); - - for (int i = 0; iTitle:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class MapAdapter implements Context, VelocityAdapter { - private Map map; - private Map valuesCache; - - private MapAdapter(Map aMap) { - map = aMap; - valuesCache = new HashMap(); - } - - public Object getOriginal() { - return map; - } - - public boolean containsKey(Object aKey) { - return map.containsKey(aKey); - } - - public Object get(String aKey) { - try { - if (!valuesCache.containsKey(aKey)) { - Object value = map.get(aKey); - - if (value == null && !map.containsKey(aKey)) { - return "no key "+aKey+" available"; - } - else - valuesCache.put(aKey, makeAdapter(value)); - } - - return valuesCache.get(aKey); - } - catch (Throwable t) { - throw new GeneratorFailure(t); - } - } - - public Object[] getKeys() { - return new Object[] {}; - } - - public Object put(String aKey, Object aValue) { - valuesCache.remove(aKey); - map.put(aKey, unmakeAdapter(aValue)); - - return aValue; - } - - public Object remove(java.lang.Object key) { - return null; - } - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class IteratorAdapter extends AbstractList implements VelocityAdapter { - private Iterator iterator; - private List valuesCache; - private int position; - - private IteratorAdapter(Iterator anIterator) { - iterator = anIterator; - - valuesCache = new Vector(); - position=0; - - - if (iterator instanceof RewindableIterator) { - ((RewindableIterator) iterator).rewind(); - } - } - - private void getUntil(int anIndex) { - while ((anIndex==-1 || valuesCache.size()<=anIndex) && iterator.hasNext()) - { - valuesCache.add(makeAdapter(iterator.next())); - } - }; - - public Object getOriginal() { - return iterator; - } - - public Object get(int anIndex) { - Object result; - - getUntil(anIndex); - - if (anIndexTitle:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class ListAdapter extends AbstractList implements VelocityAdapter { - private List list; - private List valuesCache; - private int position; - - private ListAdapter(List aList) { - list = aList; - - valuesCache = new Vector(); - position=0; - } - - private void getUntil(int anIndex) { - while ((anIndex==-1 || valuesCache.size()<=anIndex) && valuesCache.size()Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class BeanAdapter implements Context, VelocityAdapter { - private Object object; - - public BeanAdapter(Object anObject) { - object = anObject; - } - - public boolean containsKey(Object key) { - return true; - } - - public Object getOriginal() { - return object; - } - - public Object get(String aKey) { - try { - if (PropertyUtils.isReadable(object, aKey)) - return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey)); - else - return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey)); - } - catch (Throwable t) { - throw new GeneratorFailure(t); - } - } - - public Object[] getKeys() { - return new Object[] {}; - } - - public Object put(String aKey, Object aValue) { - try { - if (PropertyUtils.isWriteable(object, aKey)) - PropertyUtils.setSimpleProperty(object, aKey, unmakeAdapter(aValue)); - else - MethodUtils.invokeExactMethod(object, "set", new Object[] {aKey, unmakeAdapter(aValue)}); - - return this; - } - catch (Throwable t) { - throw new GeneratorFailure(t); - } - } - - public Object remove(Object aKey) { - throw new RuntimeException("BeanAdapter.remove not supported"); - } - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - private static class VelocityLoggerWrapper implements LogSystem { - private LoggerWrapper logger; - - public VelocityLoggerWrapper(LoggerWrapper aLogger) { - logger = aLogger; - } - - public void init(RuntimeServices aRuntimeServices) { - } - - public void logVelocityMessage(int aLevel, String aMessage) { - switch (aLevel) { - case DEBUG_ID: - logger.debug(aMessage); - break; - case ERROR_ID: - logger.error(aMessage); - break; - case INFO_ID: - logger.info(aMessage); - break; - default: - logger.warn(aMessage); - break; - } - } - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - public static class VelocityGeneratorLibrary implements GeneratorLibrary { - private VelocityEngine engine; - - public VelocityGeneratorLibrary(String aTemplateRoot) throws GeneratorExc, GeneratorFailure { - try { - engine = new VelocityEngine(); - try { - engine.setProperty(VelocityEngine.RESOURCE_LOADER, "file"); - } - catch (Throwable t) { - logger.error(VelocityEngine.RESOURCE_LOADER); - } - - try { - engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); - } - catch (Throwable t) { - logger.error("file.resource.loader.class"); - } - - try { - engine.setProperty("file.resource.loader.path", aTemplateRoot); - } - catch (Throwable t) { - logger.error("file.resource.loader.path"); - - } - try { - engine.setProperty("file.resource.loader.cache", "true"); - } - catch (Throwable t) { - logger.error("file.resource.loader.cache"); - - } - try { - engine.setProperty("file.resource.loader.modificationCheckInterval", "10"); - } - catch (Throwable t) { - logger.error("file.resource.loader.modificationCheckInterval"); - - } - - try { - engine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityLoggerWrapper(logger)); - } - catch (Throwable t) { - logger.error(VelocityEngine.RUNTIME_LOG_LOGSYSTEM); - - } - 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); - } - } - - /** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - public static class VelocityGeneratorLibraryFactory implements GeneratorLibraryFactory { - private String basePath; - - public VelocityGeneratorLibraryFactory(String aBasePath) { - basePath = aBasePath; - } - - public GeneratorLibrary makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure { - return new VelocityGeneratorLibrary(basePath+anInitializationString); - }; - } -} +/* + * 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.generator; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.AbstractList; +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 org.apache.commons.beanutils.MethodUtils; +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.context.Context; +import org.apache.velocity.exception.ParseErrorException; +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"); + + /** + * + * @param aTemplate + * @param aLibrary + */ + + public VelocityGenerator(String aTemplate, VelocityGeneratorLibrary aLibrary) { + templateIdentifier = aTemplate; + library = aLibrary; + } + + /** + * + * @param anOutputWriter + * @param aValues + * @param aLogger + * @throws GeneratorExc + * @throws GeneratorFailure + */ + public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure { + Template template; + Context context = makeMapAdapter(aValues); + StringWriter stringWriter = new StringWriter(); + + try { + template = library.engine.getTemplate(templateIdentifier); + if (template == null) { + throw new GeneratorExc("VelocityGeneratorLibrary: Can't find template " + templateIdentifier); + } + template.merge(context, stringWriter); + + ( (PrintWriter) anOutputWriter).print(stringWriter.toString()); + } + catch (ResourceNotFoundException t) { + throw new GeneratorExc("VelocityGeneratorLibrary: Can't find template " + templateIdentifier); + } + catch (ParseErrorException t) { + ( (PrintWriter) anOutputWriter).print(t.toString()); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class ContextAdapter implements Context { + public boolean containsKey(java.lang.Object key) { + return false; + } + + public Object get(java.lang.String key) { + return null; + } + + public Object[] getKeys() { + return new Object[] {}; + } + + public Object put(java.lang.String key, java.lang.Object value) { + return null; + } + + public Object remove(java.lang.Object key) { + return null; + } + } + + /** + * + * @param aMap + * @return + */ + private static Context makeMapAdapter(Map aMap) { + return new MapAdapter(aMap); + } + + /** + * + * @param anIterator + * @return + */ + private static List makeIteratorAdapter(Iterator anIterator) { + return new IteratorAdapter(anIterator); + } + + /** + * + * @param aList + * @return + */ + private static List makeListAdapter(List aList) { + return new ListAdapter(aList); + } + + /** + * + * @param aFunction + * @return + */ + private static Object makeFunctionAdapter(Generator.GeneratorFunction aFunction) { + return new FunctionAdapter(aFunction); + } + + /** + * + * @param anObject + * @return + */ + private static Object makeBeanAdapter(Object anObject) { + return new BeanAdapter(anObject); + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private interface VelocityAdapter { + public Object getOriginal(); + } + + /** + * + * @param anObject + * @return + */ + public static Object unmakeAdapter(Object anObject) { + if (anObject instanceof VelocityAdapter) { + return ((VelocityAdapter) anObject).getOriginal(); + } + else + return anObject; + } + + /** + * + * @param anObject + * @return + */ + public static Object makeAdapter(Object anObject) { + if (anObject == null) + return null; + + if (anObject instanceof Context) + return anObject; + + else if (anObject instanceof Generator.GeneratorFunction) + return makeFunctionAdapter((Generator.GeneratorFunction) anObject); + else if (anObject instanceof Integer) + return anObject; + else if (anObject instanceof Boolean) + return anObject; + else if (anObject instanceof String) + return 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 makeListAdapter(((List) anObject)); + 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); + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class FunctionAdapter implements VelocityAdapter { + private GeneratorFunction function; + + public Object getOriginal() { + return function; + } + + private FunctionAdapter(GeneratorFunction aFunction) { + function = aFunction; + } + + public Object call(Object aParameters[]) throws GeneratorExc { + List parameters = new Vector(); + + for (int i = 0; iTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class MapAdapter implements Context, VelocityAdapter { + private Map map; + private Map valuesCache; + + private MapAdapter(Map aMap) { + map = aMap; + valuesCache = new HashMap(); + } + + public Object getOriginal() { + return map; + } + + public boolean containsKey(Object aKey) { + return map.containsKey(aKey); + } + + public Object get(String aKey) { + try { + if (!valuesCache.containsKey(aKey)) { + Object value = map.get(aKey); + + if (value == null && !map.containsKey(aKey)) { + return "no key "+aKey+" available"; + } + else + valuesCache.put(aKey, makeAdapter(value)); + } + + return valuesCache.get(aKey); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object[] getKeys() { + return new Object[] {}; + } + + public Object put(String aKey, Object aValue) { + valuesCache.remove(aKey); + map.put(aKey, unmakeAdapter(aValue)); + + return aValue; + } + + public Object remove(java.lang.Object key) { + return null; + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class IteratorAdapter extends AbstractList implements VelocityAdapter { + private Iterator iterator; + private List valuesCache; + private int position; + + private IteratorAdapter(Iterator anIterator) { + iterator = anIterator; + + valuesCache = new Vector(); + position=0; + + + if (iterator instanceof RewindableIterator) { + ((RewindableIterator) iterator).rewind(); + } + } + + private void getUntil(int anIndex) { + while ((anIndex==-1 || valuesCache.size()<=anIndex) && iterator.hasNext()) + { + valuesCache.add(makeAdapter(iterator.next())); + } + }; + + public Object getOriginal() { + return iterator; + } + + public Object get(int anIndex) { + Object result; + + getUntil(anIndex); + + if (anIndexTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class ListAdapter extends AbstractList implements VelocityAdapter { + private List list; + private List valuesCache; + private int position; + + private ListAdapter(List aList) { + list = aList; + + valuesCache = new Vector(); + position=0; + } + + private void getUntil(int anIndex) { + while ((anIndex==-1 || valuesCache.size()<=anIndex) && valuesCache.size()Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class BeanAdapter implements Context, VelocityAdapter { + private Object object; + + public BeanAdapter(Object anObject) { + object = anObject; + } + + public boolean containsKey(Object key) { + return true; + } + + public Object getOriginal() { + return object; + } + + public Object get(String aKey) { + try { + if (PropertyUtils.isReadable(object, aKey)) + return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey)); + else + return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey)); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object[] getKeys() { + return new Object[] {}; + } + + public Object put(String aKey, Object aValue) { + try { + if (PropertyUtils.isWriteable(object, aKey)) + PropertyUtils.setSimpleProperty(object, aKey, unmakeAdapter(aValue)); + else + MethodUtils.invokeExactMethod(object, "set", new Object[] {aKey, unmakeAdapter(aValue)}); + + return this; + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object remove(Object aKey) { + throw new RuntimeException("BeanAdapter.remove not supported"); + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class VelocityLoggerWrapper implements LogSystem { + private LoggerWrapper logger; + + public VelocityLoggerWrapper(LoggerWrapper aLogger) { + logger = aLogger; + } + + public void init(RuntimeServices aRuntimeServices) { + } + + public void logVelocityMessage(int aLevel, String aMessage) { + switch (aLevel) { + case DEBUG_ID: + logger.debug(aMessage); + break; + case ERROR_ID: + logger.error(aMessage); + break; + case INFO_ID: + logger.info(aMessage); + break; + default: + logger.warn(aMessage); + break; + } + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class VelocityGeneratorLibrary implements GeneratorLibrary { + private VelocityEngine engine; + + public VelocityGeneratorLibrary(String aTemplateRoot) throws GeneratorExc, GeneratorFailure { + try { + engine = new VelocityEngine(); + try { + engine.setProperty(VelocityEngine.RESOURCE_LOADER, "file"); + } + catch (Throwable t) { + logger.error(VelocityEngine.RESOURCE_LOADER); + } + + try { + engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); + } + catch (Throwable t) { + logger.error("file.resource.loader.class"); + } + + try { + engine.setProperty("file.resource.loader.path", aTemplateRoot); + } + catch (Throwable t) { + logger.error("file.resource.loader.path"); + + } + try { + engine.setProperty("file.resource.loader.cache", "true"); + } + catch (Throwable t) { + logger.error("file.resource.loader.cache"); + + } + try { + engine.setProperty("file.resource.loader.modificationCheckInterval", "10"); + } + catch (Throwable t) { + logger.error("file.resource.loader.modificationCheckInterval"); + + } + + try { + engine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityLoggerWrapper(logger)); + } + catch (Throwable t) { + logger.error(VelocityEngine.RUNTIME_LOG_LOGSYSTEM); + + } + 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); + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class VelocityGeneratorLibraryFactory implements GeneratorLibraryFactory { + private String basePath; + + public VelocityGeneratorLibraryFactory(String aBasePath) { + basePath = aBasePath; + } + + public GeneratorLibrary makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure { + return new VelocityGeneratorLibrary(basePath+anInitializationString); + }; + } +} diff --git a/source/mir/generator/tal/MirExpressionParser.java b/source/mir/generator/tal/MirExpressionParser.java index ef608fc8..5aaa797d 100755 --- a/source/mir/generator/tal/MirExpressionParser.java +++ b/source/mir/generator/tal/MirExpressionParser.java @@ -1,146 +1,146 @@ -/* - * 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.generator.tal; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mir.generator.tal.interfaces.TALExpressionParser; -import mir.util.ParameterExpander; -import mir.util.RewindableIterator; - -public class MirExpressionParser implements TALExpressionParser { - public Object preparseExpression(String anExpression) { - return anExpression; - } - public Object preparseStringExpression(String anExpression) { - return anExpression; - } - - public Object preparseBooleanExpression(String anExpression) { - return anExpression; - } - - public Object preparseReferenceExpression(String anExpression) { - return anExpression; - } - - public Object preparseListExpression(String anExpression) { - return anExpression; - } - - public Object preparseTRUE() { - return "1==1"; - } - - public Object preparseFALSE() { - return "0==1"; - } - - public Object evaluateExpression(Object aContext, Object aPreparsedExpression) { - try { - return ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public String evaluateStringExpression(Object aContext, Object aPreparsedExpression) { - try { - return ParameterExpander.evaluateStringExpression(aContext, (String) aPreparsedExpression); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public boolean evaluateBooleanExpression(Object aContext, Object aPreparsedExpression) { - try { - return ParameterExpander.evaluateBooleanExpression(aContext, (String) aPreparsedExpression); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public Iterator evaluateListExpression(Object aContext, Object aPreparsedExpression) { - try { - Object list = ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); - - if (list instanceof List) - return ((List) list).iterator(); - - if (list instanceof RewindableIterator) { - ((RewindableIterator) list).rewind(); - return (RewindableIterator) list; - } - - if (list instanceof Iterator) { - return (Iterator) list; - } - - throw new TALExc("Not a list: " + list); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public void processAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aPreparsedExpression) { - try { - ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression)); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public void processDirectAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aValue) { - try { - ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, aValue); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public void processPseudoAssignment(Object aContext, String aName, Object aValue) { - try { - ParameterExpander.setValueForKey( (Map) aContext, aName, aValue); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, 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.List; +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.util.ParameterExpander; +import mir.util.RewindableIterator; + +public class MirExpressionParser implements TALExpressionParser { + public Object preparseExpression(String anExpression) { + return anExpression; + } + public Object preparseStringExpression(String anExpression) { + return anExpression; + } + + public Object preparseBooleanExpression(String anExpression) { + return anExpression; + } + + public Object preparseReferenceExpression(String anExpression) { + return anExpression; + } + + public Object preparseListExpression(String anExpression) { + return anExpression; + } + + public Object preparseTRUE() { + return "1==1"; + } + + public Object preparseFALSE() { + return "0==1"; + } + + public Object evaluateExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public String evaluateStringExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.evaluateStringExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public boolean evaluateBooleanExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.evaluateBooleanExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public Iterator evaluateListExpression(Object aContext, Object aPreparsedExpression) { + try { + Object list = ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); + + if (list instanceof List) + return ((List) list).iterator(); + + if (list instanceof RewindableIterator) { + ((RewindableIterator) list).rewind(); + return (RewindableIterator) list; + } + + if (list instanceof Iterator) { + return (Iterator) list; + } + + throw new TALExc("Not a list: " + list); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aPreparsedExpression) { + try { + ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression)); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processDirectAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aValue) { + try { + ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, aValue); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processPseudoAssignment(Object aContext, String aName, Object aValue) { + try { + ParameterExpander.setValueForKey( (Map) aContext, aName, aValue); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + } \ No newline at end of file diff --git a/source/mir/generator/tal/TALTemplate.java b/source/mir/generator/tal/TALTemplate.java index 68a2c0e3..0dca83b7 100755 --- a/source/mir/generator/tal/TALTemplate.java +++ b/source/mir/generator/tal/TALTemplate.java @@ -1,314 +1,314 @@ -/* - * 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.generator.tal; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import mir.generator.tal.interfaces.TALExpressionParser; -import mir.util.HTMLRoutines; - -/** - * {@link http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4} - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class TALTemplate { - private TemplateNode rootNode; - private TALExpressionParser parser; - - public TALTemplate(TALExpressionParser aParser, TemplateNode aRootNode) { - rootNode = aRootNode; - parser = aParser; - } - - public void processTemplate(Object aContext, PrintWriter aDestination) { - StringBuffer output = new StringBuffer(); - - rootNode.process(parser, aContext, output); - aDestination.print(output); - } - - public interface TemplateNode { - public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination); - } - - public static class CompositeTemplateNode - implements TemplateNode { - private List parts; - - public CompositeTemplateNode() { - parts = new Vector(); - } - - public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { - Iterator i = parts.iterator(); - - while (i.hasNext()) { - ((TemplateNode) i.next()).process(aParser, aContext, aDestination); - } - } - - public void appendSubNode(TemplateNode aNode) { - if (aNode instanceof CompositeTemplateNode) { - Iterator i = ((CompositeTemplateNode) aNode).parts.iterator(); - while (i.hasNext()) { - appendSubNode((TemplateNode) i.next()); - } - } - else if (aNode instanceof PlainTextTemplateNode && parts.size()>0 && - (parts.get(parts.size()-1) instanceof PlainTextTemplateNode)) { - - ((PlainTextTemplateNode) parts.get(parts.size()-1)).appendText(((PlainTextTemplateNode) aNode).getText()); - } - else { - parts.add(aNode); - } - } - } - - public static class PlainTextTemplateNode - implements TemplateNode { - private String text; - - public PlainTextTemplateNode() { - this(""); - } - - public PlainTextTemplateNode(String aText) { - text = aText; - } - - public void appendText(String aText) { - text = text + aText; - } - - protected String getText() { - return text; - } - - public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { - aDestination.append(text); - } - } - - public static class SmartTemplateNode 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 SmartTemplateNode(String aTag) { - tag = aTag; - - fixedAttributes = new HashMap(); - attributeModifiers = new HashMap(); - - definitions = new Vector(); - 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) { - 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); - } - } - else { - innerProcess(aParser, aContext, aDestination); - } - } - }; - - private void innerProcess(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { - boolean omitTag = false; - if (omitTagExpression != null) - omitTag = aParser.evaluateBooleanExpression(aContext, omitTagExpression); - - if (!omitTag) { - Map generatedAttributes = new HashMap(fixedAttributes); - - Iterator i = attributeModifiers.keySet().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("\""); - } - aDestination.append(">"); - } - - StringBuffer destination = aDestination; - if (errorExpression != null) { - destination = new StringBuffer(); - } - try { - if (contentExpression != null) { - destination.append(aParser.evaluateStringExpression(aContext, contentExpression)); - } - else { - if (body != null) - body.process(aParser, aContext, destination); - } - } - catch (RuntimeException t) { - if (errorExpression != null) { - try { - destination.delete(0, destination.length()); - - aParser.processPseudoAssignment(aContext, "exception", t); - destination.append(aParser.evaluateStringExpression(aContext, errorExpression)); - } - catch (Throwable s) { - } - } - else - throw t; - } - finally { - if (errorExpression != null) { - aDestination.append(destination); - } - } - if (!omitTag) { - aDestination.append(""); - } - } - } +/* + * 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.generator.tal; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.util.HTMLRoutines; + +/** + * {@link http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4} + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class TALTemplate { + private TemplateNode rootNode; + private TALExpressionParser parser; + + public TALTemplate(TALExpressionParser aParser, TemplateNode aRootNode) { + rootNode = aRootNode; + parser = aParser; + } + + public void processTemplate(Object aContext, PrintWriter aDestination) { + StringBuffer output = new StringBuffer(); + + rootNode.process(parser, aContext, output); + aDestination.print(output); + } + + public interface TemplateNode { + public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination); + } + + public static class CompositeTemplateNode + implements TemplateNode { + private List parts; + + public CompositeTemplateNode() { + parts = new Vector(); + } + + public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { + Iterator i = parts.iterator(); + + while (i.hasNext()) { + ((TemplateNode) i.next()).process(aParser, aContext, aDestination); + } + } + + public void appendSubNode(TemplateNode aNode) { + if (aNode instanceof CompositeTemplateNode) { + Iterator i = ((CompositeTemplateNode) aNode).parts.iterator(); + while (i.hasNext()) { + appendSubNode((TemplateNode) i.next()); + } + } + else if (aNode instanceof PlainTextTemplateNode && parts.size()>0 && + (parts.get(parts.size()-1) instanceof PlainTextTemplateNode)) { + + ((PlainTextTemplateNode) parts.get(parts.size()-1)).appendText(((PlainTextTemplateNode) aNode).getText()); + } + else { + parts.add(aNode); + } + } + } + + public static class PlainTextTemplateNode + implements TemplateNode { + private String text; + + public PlainTextTemplateNode() { + this(""); + } + + public PlainTextTemplateNode(String aText) { + text = aText; + } + + public void appendText(String aText) { + text = text + aText; + } + + protected String getText() { + return text; + } + + public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { + aDestination.append(text); + } + } + + public static class SmartTemplateNode 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 SmartTemplateNode(String aTag) { + tag = aTag; + + fixedAttributes = new HashMap(); + attributeModifiers = new HashMap(); + + definitions = new Vector(); + 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) { + 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); + } + } + else { + innerProcess(aParser, aContext, aDestination); + } + } + }; + + private void innerProcess(TALExpressionParser aParser, Object aContext, StringBuffer aDestination) { + boolean omitTag = false; + if (omitTagExpression != null) + omitTag = aParser.evaluateBooleanExpression(aContext, omitTagExpression); + + if (!omitTag) { + Map generatedAttributes = new HashMap(fixedAttributes); + + Iterator i = attributeModifiers.keySet().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("\""); + } + aDestination.append(">"); + } + + StringBuffer destination = aDestination; + if (errorExpression != null) { + destination = new StringBuffer(); + } + try { + if (contentExpression != null) { + destination.append(aParser.evaluateStringExpression(aContext, contentExpression)); + } + else { + if (body != null) + body.process(aParser, aContext, destination); + } + } + catch (RuntimeException t) { + if (errorExpression != null) { + try { + destination.delete(0, destination.length()); + + aParser.processPseudoAssignment(aContext, "exception", t); + destination.append(aParser.evaluateStringExpression(aContext, errorExpression)); + } + catch (Throwable s) { + } + } + else + throw t; + } + finally { + if (errorExpression != null) { + aDestination.append(destination); + } + } + if (!omitTag) { + aDestination.append(""); + } + } + } } \ No newline at end of file diff --git a/source/mir/generator/tal/TALTemplateEngine.java b/source/mir/generator/tal/TALTemplateEngine.java index 74b4b371..47596183 100755 --- a/source/mir/generator/tal/TALTemplateEngine.java +++ b/source/mir/generator/tal/TALTemplateEngine.java @@ -1,65 +1,65 @@ -/* - * 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.generator.tal; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import mir.generator.tal.interfaces.TALExpressionParser; - -public class TALTemplateEngine { - private TALExpressionParser expressionParser; - private String basePath; - private CachingFileLoader loader; - - public TALTemplateEngine(TALExpressionParser anExpressionParser, String aBasePath) { - expressionParser = anExpressionParser; - basePath = aBasePath; - loader = new CachingFileLoader(100, new TemplateFactory()); - } - - public TALTemplate loadTemplate(String aName) throws IOException { - File location = new File(basePath, aName); - return (TALTemplate) loader.retrieveFile(location.getCanonicalPath()); - } - - private class TemplateFactory implements CachingFileLoader.CachedFileObjectFactory { - public Object constructObject(InputStream aStream) { - try { - return TALTemplateParser.parseInputStream(aStream, expressionParser); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, 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 mir.generator.tal.interfaces.TALExpressionParser; + +public class TALTemplateEngine { + private TALExpressionParser expressionParser; + private String basePath; + private CachingFileLoader loader; + + public TALTemplateEngine(TALExpressionParser anExpressionParser, String aBasePath) { + expressionParser = anExpressionParser; + basePath = aBasePath; + loader = new CachingFileLoader(100, new TemplateFactory()); + } + + public TALTemplate loadTemplate(String aName) throws IOException { + File location = new File(basePath, aName); + return (TALTemplate) loader.retrieveFile(location.getCanonicalPath()); + } + + private class TemplateFactory implements CachingFileLoader.CachedFileObjectFactory { + public Object constructObject(InputStream aStream) { + try { + return TALTemplateParser.parseInputStream(aStream, expressionParser); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + } } \ No newline at end of file diff --git a/source/mir/generator/tal/TALTemplateParser.java b/source/mir/generator/tal/TALTemplateParser.java index 5bd4dd0e..f63876d7 100755 --- a/source/mir/generator/tal/TALTemplateParser.java +++ b/source/mir/generator/tal/TALTemplateParser.java @@ -1,262 +1,262 @@ -/* - * 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.generator.tal; - -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mir.generator.tal.interfaces.TALExpressionParser; -import mir.util.HTMLRoutines; -import mir.util.StringRoutines; -import mir.util.XMLReader; -import mir.util.XMLReader.AbstractSectionHandler; - -public class TALTemplateParser { - private int bal; - private static final String TAL_PREFIX = "tal"; - - public static TALTemplate parseString(String aData, TALExpressionParser aParser) throws TALExc, TALFailure { - try { - TALHandler handler = new TALHandler(aParser); - XMLReader reader = new XMLReader(false); - - reader.parseString(true, aData, handler); - - return new TALTemplate(aParser, handler.getNode()); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - public static TALTemplate parseInputStream(InputStream anInputStream, TALExpressionParser aParser) throws TALExc, TALFailure { - try { - TALHandler handler = new TALHandler(aParser); - XMLReader reader = new XMLReader(false); - - reader.parseInputStream(true, anInputStream, handler); - - return new TALTemplate(aParser, handler.getNode()); - } - catch (Throwable t) { - throw new TALFailure(t); - } - } - - private static String normalizeXMLName(XMLReader.XMLName aName) { - String result = aName.getLocalName(); - if (aName.getPrefix().length() > 0) - result = aName.getPrefix() + ":" + result; - - return result; - } - - - - 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 ONERROR_ATTRIBUTE = "onerror"; - private static final String OMITTAG_ATTRIBUTE = "omit-tag"; - private static final String ATTRIBUTE_ATTRIBUTE = "attributes"; - - - protected static class TALHandler extends XMLReader.AbstractSectionHandler { - private TALTemplate.CompositeTemplateNode compositeNode; - private StringBuffer data; - private TALExpressionParser parser; - private TALTemplate.SmartTemplateNode smartNode; - private boolean smartTag; - private String currentTag; - - public TALHandler(TALExpressionParser aParser) { - parser = aParser; - data = new StringBuffer(); - compositeNode = new TALTemplate.CompositeTemplateNode(); - } - - private void flushData() { - if (data.length()!=0) { - compositeNode.appendSubNode(new TALTemplate.PlainTextTemplateNode(data.toString())); - data.delete(0, data.length()); - } - } - - public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc { - smartTag = false; - - currentTag = normalizeXMLName(aTag); - - smartTag = (aTag.getPrefix().equals(TAL_PREFIX)); - - Iterator i = anAttributes.keySet().iterator(); - - while (!smartTag && i.hasNext()) { - String name = (String) i.next(); - smartTag = smartTag || (name.startsWith(TAL_PREFIX+":")); - } - - if (!smartTag) { - appendCode("<"+currentTag); - i = anAttributes.entrySet().iterator(); - - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - - appendCode(" "+ entry.getKey()); - appendCode("=\""); - appendText((String) entry.getValue()); - appendCode("\""); - } - appendCode(">"); - } - else { - smartNode = new TALTemplate.SmartTemplateNode(currentTag); - if (aTag.getPrefix().equals(TAL_PREFIX)) - smartNode.setOmitTag(parser.preparseTRUE()); - - i = anAttributes.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - String fullAttributeName = (String) entry.getKey(); - List attributeParts = StringRoutines.separateString(fullAttributeName, ":"); - String prefix = ""; - String name = ""; - if (attributeParts.size()==2) { - name = (String) attributeParts.get(1); - prefix = (String) attributeParts.get(0); - } - else { - name = (String) attributeParts.get(0); - } - - if (!prefix.equals(TAL_PREFIX)) { - smartNode.addFixedAttribute(fullAttributeName, (String) entry.getValue()); - } - else { - if (name.equalsIgnoreCase(DEFINITION_ATTRIBUTE)) { - List definitions = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); - - Iterator j = definitions.iterator(); { - List parts = StringRoutines.separateString((String) i.next(), " "); - - if (parts.size()==2) { - smartNode.addDefinition(parser.preparseReferenceExpression((String) parts.get(0)), parser.preparseExpression((String) parts.get(1))); - } - } - } - else if (name.equalsIgnoreCase(CONDITION_ATTRIBUTE)) { - smartNode.setCondition(parser.preparseBooleanExpression((String) entry.getValue())); - } - else if (name.equalsIgnoreCase(CONTENT_ATTRIBUTE)) { - smartNode.setContent(parser.preparseStringExpression((String) entry.getValue())); - } - else if (name.equalsIgnoreCase(ERROR_ATTRIBUTE)) { - smartNode.setError(parser.preparseStringExpression((String) entry.getValue())); - } - else if (name.equalsIgnoreCase(OMITTAG_ATTRIBUTE)) { - if (((String) entry.getValue()).trim().length()==0) - smartNode.setOmitTag(parser.preparseTRUE()); - else - smartNode.setOmitTag(parser.preparseBooleanExpression((String) entry.getValue())); - } - else if (name.equalsIgnoreCase(REPLACE_ATTRIBUTE)) { - smartNode.setOmitTag(parser.preparseTRUE()); - smartNode.setContent(parser.preparseStringExpression((String) entry.getValue())); - } - else if (name.equalsIgnoreCase(REPEAT_ATTRIBUTE)) { - List parts = StringRoutines.separateString((String) entry.getValue(), " "); - - if (parts.size()==2) { - smartNode.setRepeat(parser.preparseReferenceExpression((String) parts.get(0)), parser.preparseExpression((String) parts.get(1))); - } - } - else if (name.equalsIgnoreCase(ATTRIBUTE_ATTRIBUTE)) { - List attributes = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); - - Iterator j = attributes.iterator(); { - List parts = StringRoutines.separateString((String) i.next(), " "); - - if (parts.size()==2) { - smartNode.addModifiedAttribute((String) parts.get(0), parser.preparseExpression((String) parts.get(1))); - } - } - } - } - } - } - - flushData(); - - return new TALHandler(parser); - }; - - public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { - if (!smartTag) { - appendSubNode(((TALHandler) aHandler).getNode()); - appendCode(""); - } - else { - smartNode.setBody(((TALHandler) aHandler).getNode()); - appendSubNode(smartNode); - smartNode=null; - } - }; - - protected void appendSubNode(TALTemplate.TemplateNode aNode) { - compositeNode.appendSubNode(aNode); - } - - protected void appendCode(String aCode) { - data.append(aCode); - } - - protected void appendText(String aText) { - data.append(HTMLRoutines.encodeHTML(aText)); - } - - public void finishSection() throws XMLReader.XMLReaderExc { - flushData(); - } - - public TALTemplate.TemplateNode getNode() { - return compositeNode; - } - - public void characters(String aCharacters) throws XMLReader.XMLReaderExc { - appendText(aCharacters); - } - } -} +/* + * 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.generator.tal; + +import java.io.InputStream; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.util.HTMLRoutines; +import mir.util.StringRoutines; +import mir.util.XMLReader; +import mir.util.XMLReader.AbstractSectionHandler; + +public class TALTemplateParser { + private int bal; + private static final String TAL_PREFIX = "tal"; + + public static TALTemplate parseString(String aData, TALExpressionParser aParser) throws TALExc, TALFailure { + try { + TALHandler handler = new TALHandler(aParser); + XMLReader reader = new XMLReader(false); + + reader.parseString(true, aData, handler); + + return new TALTemplate(aParser, handler.getNode()); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public static TALTemplate parseInputStream(InputStream anInputStream, TALExpressionParser aParser) throws TALExc, TALFailure { + try { + TALHandler handler = new TALHandler(aParser); + XMLReader reader = new XMLReader(false); + + reader.parseInputStream(true, anInputStream, handler); + + return new TALTemplate(aParser, handler.getNode()); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + private static String normalizeXMLName(XMLReader.XMLName aName) { + String result = aName.getLocalName(); + if (aName.getPrefix().length() > 0) + result = aName.getPrefix() + ":" + result; + + return result; + } + + + + 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 ONERROR_ATTRIBUTE = "onerror"; + private static final String OMITTAG_ATTRIBUTE = "omit-tag"; + private static final String ATTRIBUTE_ATTRIBUTE = "attributes"; + + + protected static class TALHandler extends XMLReader.AbstractSectionHandler { + private TALTemplate.CompositeTemplateNode compositeNode; + private StringBuffer data; + private TALExpressionParser parser; + private TALTemplate.SmartTemplateNode smartNode; + private boolean smartTag; + private String currentTag; + + public TALHandler(TALExpressionParser aParser) { + parser = aParser; + data = new StringBuffer(); + compositeNode = new TALTemplate.CompositeTemplateNode(); + } + + private void flushData() { + if (data.length()!=0) { + compositeNode.appendSubNode(new TALTemplate.PlainTextTemplateNode(data.toString())); + data.delete(0, data.length()); + } + } + + public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc { + smartTag = false; + + currentTag = normalizeXMLName(aTag); + + smartTag = (aTag.getPrefix().equals(TAL_PREFIX)); + + Iterator i = anAttributes.keySet().iterator(); + + while (!smartTag && i.hasNext()) { + String name = (String) i.next(); + smartTag = smartTag || (name.startsWith(TAL_PREFIX+":")); + } + + if (!smartTag) { + appendCode("<"+currentTag); + i = anAttributes.entrySet().iterator(); + + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + + appendCode(" "+ entry.getKey()); + appendCode("=\""); + appendText((String) entry.getValue()); + appendCode("\""); + } + appendCode(">"); + } + else { + smartNode = new TALTemplate.SmartTemplateNode(currentTag); + if (aTag.getPrefix().equals(TAL_PREFIX)) + smartNode.setOmitTag(parser.preparseTRUE()); + + i = anAttributes.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + String fullAttributeName = (String) entry.getKey(); + List attributeParts = StringRoutines.separateString(fullAttributeName, ":"); + String prefix = ""; + String name = ""; + if (attributeParts.size()==2) { + name = (String) attributeParts.get(1); + prefix = (String) attributeParts.get(0); + } + else { + name = (String) attributeParts.get(0); + } + + if (!prefix.equals(TAL_PREFIX)) { + smartNode.addFixedAttribute(fullAttributeName, (String) entry.getValue()); + } + else { + if (name.equalsIgnoreCase(DEFINITION_ATTRIBUTE)) { + List definitions = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); + + Iterator j = definitions.iterator(); { + List parts = StringRoutines.separateString((String) i.next(), " "); + + if (parts.size()==2) { + smartNode.addDefinition(parser.preparseReferenceExpression((String) parts.get(0)), parser.preparseExpression((String) parts.get(1))); + } + } + } + else if (name.equalsIgnoreCase(CONDITION_ATTRIBUTE)) { + smartNode.setCondition(parser.preparseBooleanExpression((String) entry.getValue())); + } + else if (name.equalsIgnoreCase(CONTENT_ATTRIBUTE)) { + smartNode.setContent(parser.preparseStringExpression((String) entry.getValue())); + } + else if (name.equalsIgnoreCase(ERROR_ATTRIBUTE)) { + smartNode.setError(parser.preparseStringExpression((String) entry.getValue())); + } + else if (name.equalsIgnoreCase(OMITTAG_ATTRIBUTE)) { + if (((String) entry.getValue()).trim().length()==0) + smartNode.setOmitTag(parser.preparseTRUE()); + else + smartNode.setOmitTag(parser.preparseBooleanExpression((String) entry.getValue())); + } + else if (name.equalsIgnoreCase(REPLACE_ATTRIBUTE)) { + smartNode.setOmitTag(parser.preparseTRUE()); + smartNode.setContent(parser.preparseStringExpression((String) entry.getValue())); + } + else if (name.equalsIgnoreCase(REPEAT_ATTRIBUTE)) { + List parts = StringRoutines.separateString((String) entry.getValue(), " "); + + if (parts.size()==2) { + smartNode.setRepeat(parser.preparseReferenceExpression((String) parts.get(0)), parser.preparseExpression((String) parts.get(1))); + } + } + else if (name.equalsIgnoreCase(ATTRIBUTE_ATTRIBUTE)) { + List attributes = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); + + Iterator j = attributes.iterator(); { + List parts = StringRoutines.separateString((String) i.next(), " "); + + if (parts.size()==2) { + smartNode.addModifiedAttribute((String) parts.get(0), parser.preparseExpression((String) parts.get(1))); + } + } + } + } + } + } + + flushData(); + + return new TALHandler(parser); + }; + + public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc { + if (!smartTag) { + appendSubNode(((TALHandler) aHandler).getNode()); + appendCode(""); + } + else { + smartNode.setBody(((TALHandler) aHandler).getNode()); + appendSubNode(smartNode); + smartNode=null; + } + }; + + protected void appendSubNode(TALTemplate.TemplateNode aNode) { + compositeNode.appendSubNode(aNode); + } + + protected void appendCode(String aCode) { + data.append(aCode); + } + + protected void appendText(String aText) { + data.append(HTMLRoutines.encodeHTML(aText)); + } + + public void finishSection() throws XMLReader.XMLReaderExc { + flushData(); + } + + public TALTemplate.TemplateNode getNode() { + return compositeNode; + } + + public void characters(String aCharacters) throws XMLReader.XMLReaderExc { + appendText(aCharacters); + } + } +} diff --git a/source/mir/generator/tal/TALTest.java b/source/mir/generator/tal/TALTest.java index 64d7f858..d40df51c 100755 --- a/source/mir/generator/tal/TALTest.java +++ b/source/mir/generator/tal/TALTest.java @@ -1,55 +1,59 @@ -/* - * 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.generator.tal; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -public class TALTest { - public static void main(String args[]) { - try { - TALTemplateParser parser = new TALTemplateParser(); - MirExpressionParser expressionParser = new MirExpressionParser(); - Map test = new HashMap(); - test.put("name", "zapata"); - - TALTemplate template = parser.parseString("

test

", expressionParser); - PrintWriter o = new PrintWriter(System.out); - template.processTemplate(test, o); - o.close(); - } - catch (Throwable t) { - System.out.println("Exception: " + t.toString()); - t.printStackTrace(System.out); - } - - } +/* + * 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.generator.tal; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +public class TALTest { + public static void main(String args[]) { + try { + int b=4; + int c=6; + int a = b = c; + + TALTemplateParser parser = new TALTemplateParser(); + MirExpressionParser expressionParser = new MirExpressionParser(); + Map test = new HashMap(); + test.put("name", "zapata"); + + TALTemplate template = parser.parseString("

test

", expressionParser); + PrintWriter o = new PrintWriter(System.out); + template.processTemplate(test, o); + o.close(); + } + catch (Throwable t) { + System.out.println("Exception: " + t.toString()); + t.printStackTrace(System.out); + } + + } } \ No newline at end of file diff --git a/source/mir/media/MediaHandler.java b/source/mir/media/MediaHandler.java index c6d607e6..33a45f41 100755 --- a/source/mir/media/MediaHandler.java +++ b/source/mir/media/MediaHandler.java @@ -1,221 +1,221 @@ -/* - * 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.media; - -import java.io.InputStream; -import java.util.List; - -import mir.entity.Entity; - -/** - * Interface for Media handling in Mir. All media handlers - * must implement this interface. Each specific media type, - * be it Gif, Jpeg, Mp3 audio, Real Audio or quicktime video - * has special needs when it comes to representation on the various - * pages (article, list, summary), must be stored differently and has a - * different URL, etc... This interface allows Mir to support - * an infinite (I hope) number of media types. Once this is done, - * no code at any other level in Mir needs to be changed other than - * adding the content-type <-> media handler name mapping in the - * media_type table. The following is an example of the media_type - * table: - *

- * id | name | mime_type | classname | tablename | dcname
- *---+---------+--------------------------+-----------+---------------+-------
- * 2 | unknown | application/octet-stream | -- | UploadedMedia |
- * 3 | jpg | image/gif | ImagesGif | Images |
- * 4 | mp3 | audio/mp3 | Audio | UploadedMedia |
- *

- * The "id" field is used as a mapping in the table that contains the media type - * to the media_type table. For example, the images table has a to_media_type - * field that contains the id in the media_type table. - *

- * The "name" field is used for various display/filenaming purposes. it should - * match a valid file extension name for a media_type (we could have used the - * content-type map for this....). - *

- * 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 - * 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. - *

- * The "classname" field is the name of the media handler (e.g MediaHandlerAudio) - * we use it to call the MediaHandler methods via reflection. - *

- * 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. - * - * Most media handlers should just extend MediaHandlerGeneric (i.e inherit from - * ) and just override the things that need to be specific. see MediaHandlerAudio - * - * @author , the Mir-coders group - * @version $Id: MediaHandler.java,v 1.1.2.1 2003/12/14 16:37:06 zapata Exp $ - */ - -public interface MediaHandler { - /** - * Takes the uploaded media data itself, along with the media Entity - * which contains the Media metadata plus the MediaType entity containing - * all the info for the specific media type itself. It's job is store the - * Media data (content) itself, this could be on the local filesystem, in the - * DB or even on a remote host. It then inserts the MetaData in the DB. - * @param InputStream, a stream of the uploaded data. - * @param ent, an Entity holding the media MetaData - * @param mediaType, an Entity holding the media_table entry - * @return boolean, success/fail - * @see mir.entity.Entity - */ - public void store(InputStream in, Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure; - - public void produce(Entity ent, Entity mediaTypeEnt ) 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*). - * @param ent, an Entity holding the media MetaData - * @param mediaType, an Entity holding the media_table entry - * @return java.io.InputStream - * @see mir.entity.Entity - */ - public InputStream getMedia (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; - - /** - * Pretty much like get() above. But get's the specific Icon - * representation. useful for media stored in the DB. - * @param ent, an Entity holding the media MetaData - * @return java.io.InputStream - * @see mir.entity.Entity - */ - public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure; - - - /** - * - * @param ent - * @return - * @throws MediaExc - * @throws MediaFailure - */ - 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. - * @param ent, an Entity holding the media MetaData - * @param mediaTypeEnt, an Entity holding the media_table entry - * @return String, the url. - * @see mir.entity.Entity - * @see mir.misc.StringUtil - */ - public List getURL (Entity ent, Entity mediaTypeEnt) 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. - * @return String, the path. - * @see mir.misc.MirConfig - */ - public String getStoragePath () 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() - * This path is usually defined - * in the configuration wich is accessible through the MirConfig - * class. - * @return String, the path. - * @see mir.misc.MirConfig - */ - public String getIconStoragePath () 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 - * ,the templates use it. - * It is usually defined - * in the configuration witch is accessible through the MirConfig - * class. - * @return String, the base URL to the host. - * @see mir.misc.MirConfig - */ - 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 - * in the configuration wich is accessible through the MirConfig - * class. - * @return String, the icon filename. - * @see mir.misc.MirConfig - */ - 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. - * It is usually defined - * in the configuration wich is accessible through the MirConfig - * class. - * @return String, the icon filename. - * @see mir.misc.MirConfig - */ - public String getTinyIconName (); - - /** - * Returns the IMG SRC "ALT" text to be used - * for the Icon representations - * @return String, the ALT text. - */ - public String getIconAltName (); - - /** - * returns a brief text dscription of what this - * media type is. - * @return String - */ - public String getDescr (Entity mediaTypeEnt); - -} - - +/* + * 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.media; + +import java.io.InputStream; +import java.util.List; + +import mir.entity.Entity; + +/** + * Interface for Media handling in Mir. All media handlers + * must implement this interface. Each specific media type, + * be it Gif, Jpeg, Mp3 audio, Real Audio or quicktime video + * has special needs when it comes to representation on the various + * pages (article, list, summary), must be stored differently and has a + * different URL, etc... This interface allows Mir to support + * an infinite (I hope) number of media types. Once this is done, + * no code at any other level in Mir needs to be changed other than + * adding the content-type <-> media handler name mapping in the + * media_type table. The following is an example of the media_type + * table: + *

+ * id | name | mime_type | classname | tablename | dcname
+ *---+---------+--------------------------+-----------+---------------+-------
+ * 2 | unknown | application/octet-stream | -- | UploadedMedia |
+ * 3 | jpg | image/gif | ImagesGif | Images |
+ * 4 | mp3 | audio/mp3 | Audio | UploadedMedia |
+ *

+ * The "id" field is used as a mapping in the table that contains the media type + * to the media_type table. For example, the images table has a to_media_type + * field that contains the id in the media_type table. + *

+ * The "name" field is used for various display/filenaming purposes. it should + * match a valid file extension name for a media_type (we could have used the + * content-type map for this....). + *

+ * 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 + * 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. + *

+ * The "classname" field is the name of the media handler (e.g MediaHandlerAudio) + * we use it to call the MediaHandler methods via reflection. + *

+ * 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. + * + * Most media handlers should just extend MediaHandlerGeneric (i.e inherit from + * ) and just override the things that need to be specific. see MediaHandlerAudio + * + * @author , the Mir-coders group + * @version $Id: MediaHandler.java,v 1.1.2.2 2003/12/21 13:32:03 zapata Exp $ + */ + +public interface MediaHandler { + /** + * Takes the uploaded media data itself, along with the media Entity + * which contains the Media metadata plus the MediaType entity containing + * all the info for the specific media type itself. It's job is store the + * Media data (content) itself, this could be on the local filesystem, in the + * DB or even on a remote host. It then inserts the MetaData in the DB. + * @param InputStream, a stream of the uploaded data. + * @param ent, an Entity holding the media MetaData + * @param mediaType, an Entity holding the media_table entry + * @return boolean, success/fail + * @see mir.entity.Entity + */ + public void store(InputStream in, Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure; + + public void produce(Entity ent, Entity mediaTypeEnt ) 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*). + * @param ent, an Entity holding the media MetaData + * @param mediaType, an Entity holding the media_table entry + * @return java.io.InputStream + * @see mir.entity.Entity + */ + public InputStream getMedia (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; + + /** + * Pretty much like get() above. But get's the specific Icon + * representation. useful for media stored in the DB. + * @param ent, an Entity holding the media MetaData + * @return java.io.InputStream + * @see mir.entity.Entity + */ + public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure; + + + /** + * + * @param ent + * @return + * @throws MediaExc + * @throws MediaFailure + */ + 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. + * @param ent, an Entity holding the media MetaData + * @param mediaTypeEnt, an Entity holding the media_table entry + * @return String, the url. + * @see mir.entity.Entity + * @see mir.misc.StringUtil + */ + public List getURL (Entity ent, Entity mediaTypeEnt) 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. + * @return String, the path. + * @see mir.misc.MirConfig + */ + public String getStoragePath () 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() + * This path is usually defined + * in the configuration wich is accessible through the MirConfig + * class. + * @return String, the path. + * @see mir.misc.MirConfig + */ + public String getIconStoragePath () 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 + * ,the templates use it. + * It is usually defined + * in the configuration witch is accessible through the MirConfig + * class. + * @return String, the base URL to the host. + * @see mir.misc.MirConfig + */ + 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 + * in the configuration wich is accessible through the MirConfig + * class. + * @return String, the icon filename. + * @see mir.misc.MirConfig + */ + 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. + * It is usually defined + * in the configuration wich is accessible through the MirConfig + * class. + * @return String, the icon filename. + * @see mir.misc.MirConfig + */ + public String getTinyIconName (); + + /** + * Returns the IMG SRC "ALT" text to be used + * for the Icon representations + * @return String, the ALT text. + */ + public String getIconAltName (); + + /** + * returns a brief text dscription of what this + * media type is. + * @return String + */ + public String getDescr (Entity mediaTypeEnt); + +} + + diff --git a/source/mir/module/AbstractModule.java b/source/mir/module/AbstractModule.java index 7d0c5c54..aa9b6318 100755 --- a/source/mir/module/AbstractModule.java +++ b/source/mir/module/AbstractModule.java @@ -29,10 +29,10 @@ */ package mir.module; -import java.util.Map; - -import mir.entity.Entity; -import mir.entity.EntityList; +import java.util.Map; + +import mir.entity.Entity; +import mir.entity.EntityList; import mir.storage.StorageObject; diff --git a/source/mir/producer/reader/DefaultProducerNodeBuilders.java b/source/mir/producer/reader/DefaultProducerNodeBuilders.java index f7fe8a3f..cac15306 100755 --- a/source/mir/producer/reader/DefaultProducerNodeBuilders.java +++ b/source/mir/producer/reader/DefaultProducerNodeBuilders.java @@ -245,9 +245,13 @@ public class DefaultProducerNodeBuilders { limit = (String) anAttributes.get(ENUMERATION_LIMIT_ATTRIBUTE); skip = (String) anAttributes.get(ENUMERATION_SKIP_ATTRIBUTE); extraTables = StringRoutines.splitString(XMLReaderTool.getStringAttributeWithDefault(anAttributes, ENUMERATION_EXTRATABLES_ATTRIBUTE,"").trim(), ","); - List parts = StringRoutines.splitString(definition.trim()," "); - if (parts.size()>0) definition=(String)parts.get(0); - if (parts.size()>1) mainTablePrefix=(String)parts.get(1); + if (definition!=null) { + 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() { @@ -441,9 +445,9 @@ public class DefaultProducerNodeBuilders { skip = (String) anAttributes.get(LIST_SKIP_ATTRIBUTE); extraTables = StringRoutines.splitString(XMLReaderTool.getStringAttributeWithDefault(anAttributes, LIST_EXTRATABLES_ATTRIBUTE,"").trim(), ","); List parts = StringRoutines.splitString(definition.trim()," "); - if (parts.size()>0) definition=(String)parts.get(0); + if (parts.size()>0) definition=(String)parts.get(0); if (parts.size()>1) mainTablePrefix=(String)parts.get(1); - + }; public ProducerNode constructNode() { @@ -867,10 +871,10 @@ public class DefaultProducerNodeBuilders { batchSize = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_BATCHSIZE_ATTRIBUTE, "20" ); minBatchSize = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_MINBATCHSIZE_ATTRIBUTE, "0" ); skip = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_SKIP_ATTRIBUTE, "0" ); - process = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_PROCESS_ATTRIBUTE, "-1" ); + process = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_PROCESS_ATTRIBUTE, "-1" ); extraTables = StringRoutines.splitString(XMLReaderTool.getStringAttributeWithDefault(anAttributes, BATCHER_EXTRATABLES_ATTRIBUTE,"").trim(), ","); List parts = StringRoutines.splitString(definition.trim()," "); - if (parts.size()>0) definition=(String)parts.get(0); + if (parts.size()>0) definition=(String)parts.get(0); if (parts.size()>1) mainTablePrefix=(String)parts.get(1); }; diff --git a/source/mir/rss/RDFResource.java b/source/mir/rss/RDFResource.java index b0c68a94..2aa8eaf9 100755 --- a/source/mir/rss/RDFResource.java +++ b/source/mir/rss/RDFResource.java @@ -29,7 +29,7 @@ */ package mir.rss; -import java.util.HashMap; +import java.util.HashMap; import java.util.Map; public class RDFResource { diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index 72329284..3eda4993 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -172,7 +172,7 @@ public abstract class ServletModule { */ public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { try { - aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery)); + aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery)); } catch (Throwable t) { throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); diff --git a/source/mircoders/accesscontrol/AccessControl.java b/source/mircoders/accesscontrol/AccessControl.java index 7e15db7d..9f0dc3b0 100755 --- a/source/mircoders/accesscontrol/AccessControl.java +++ b/source/mircoders/accesscontrol/AccessControl.java @@ -36,10 +36,13 @@ import java.util.Vector; import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; import mircoders.entity.EntityUsers; +import mircoders.module.*; +import mircoders.storage.*; public class AccessControl { private UserAccessControl user; private GeneralAccessControl general; + private ArticleAccessControl article; protected LoggerWrapper logger = new LoggerWrapper("Global.AccessControl"); protected MirPropertiesConfiguration configuration; @@ -49,6 +52,9 @@ public class AccessControl { user = new UserAccessControl(configuration.getVector("AccessControl.SuperUsers")); general = new GeneralAccessControl(); + article = new ArticleAccessControl( + configuration.getString("AccessControl.LockingEnabled", "0").equals("1"), + configuration.getString("AccessControl.LockingOptional", "0").equals("1")); } catch (Throwable t) { throw new RuntimeException(t.toString()); @@ -63,6 +69,10 @@ public class AccessControl { return general; } + public ArticleAccessControl article() { + return article; + } + public class GeneralAccessControl { public boolean mayDeleteArticles(EntityUsers aSubject) { return configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1"); @@ -115,6 +125,10 @@ public class AccessControl { return superusers.contains(aSubject.getValue("login")); } + protected boolean isSuperUser(EntityUsers aUser) { + return superusers.contains(aUser.getValue("login")); + } + public void assertMayEditUser(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure { try { if (!mayEditUser(aSubject, anObject)) @@ -166,4 +180,68 @@ public class AccessControl { } } } + + public class ArticleAccessControl { + private ModuleContent contentModule; + private boolean lockingEnabled; + private boolean lockingOptional; + + public ArticleAccessControl(boolean aLockingEnabled, boolean aLockingOptional) { + contentModule = new ModuleContent(DatabaseContent.getInstance()); + lockingEnabled = aLockingEnabled; + lockingOptional = aLockingOptional; + } + + public boolean mayEditArticle(EntityUsers aSubject, String anArticleId) { + String userId = aSubject.getId(); + + if (userId==null) + return false; + if (!lockingEnabled) + return true; + + String lockingUser = contentModule.queryArticleLock(anArticleId); + + return userId.equals(lockingUser) || ((lockingUser==null) && lockingOptional); + } + + public boolean mayLockArticle(EntityUsers aSubject, String anArticleId) { + String userId = aSubject.getId(); + + if (userId==null) + return false; + if (!lockingEnabled) + return false; + + String lockingUser = contentModule.queryArticleLock(anArticleId); + + return (lockingUser==null); + } + + public boolean mayForceLockArticle(EntityUsers aSubject, String anArticleId) { + String userId = aSubject.getId(); + + if (userId==null) + return false; + if (!lockingEnabled) + return false; + + String lockingUser = contentModule.queryArticleLock(anArticleId); + + return (lockingUser!=null) && !userId.equals(lockingUser) && user().isSuperUser(aSubject); + } + + public boolean mayUnlockArticle(EntityUsers aSubject, String anArticleId) { + String userId = aSubject.getId(); + + if (userId==null) + return false; + if (!lockingEnabled) + return false; + + String lockingUser = contentModule.queryArticleLock(anArticleId); + + return userId.equals(lockingUser); + } + } } diff --git a/source/mircoders/entity/EntityContent.java b/source/mircoders/entity/EntityContent.java index 3fa7b38b..59ed4784 100755 --- a/source/mircoders/entity/EntityContent.java +++ b/source/mircoders/entity/EntityContent.java @@ -1,181 +1,163 @@ -/* - * 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.entity; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mir.util.StringRoutines; -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.19.2.3 2003/09/19 23:34:20 zapata Exp $ - * @author mir-coders group - * - */ - - -public class EntityContent extends Entity -{ - // constructors - - public EntityContent() - { - super(); - - logger = new LoggerWrapper("Entity.Content"); - } - - public EntityContent(StorageObject theStorage) { - this(); - - setStorage(theStorage); - } - - // - // methods - - /** - * set is_produced flag for the article - */ - - public void setProduced(boolean yesno) throws StorageObjectFailure - { - String value = (yesno) ? "1":"0"; - if (value.equals( getValue("is_produced") )) return; - - Connection con=null;Statement stmt=null; - String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'"; - try { - con = theStorageObject.getPooledCon(); - /** @todo should be preparedStatement: faster!! */ - stmt = con.createStatement(); - theStorageObject.executeUpdate(stmt,sql); - } - catch (StorageObjectFailure e) { - throwStorageObjectFailure(e, "\n -- set produced failed"); - } - catch (SQLException e) { - throwStorageObjectFailure(e, "\n -- set produced failed"); - } - finally { - theStorageObject.freeConnection(con,stmt); - } - } - - /** - * Deattaches media from an article - * - * @param anArticleId - * @param aMediaId - * @throws StorageObjectFailure - */ - public void dettach(String anArticleId, String aMediaId) throws StorageObjectFailure - { - if (aMediaId!=null){ - try{ - DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId); - } - catch (Exception e){ - throwStorageObjectFailure(e, "\n -- failed to get instance"); - } - - setProduced(false); - } - } - - /** - * Attaches media to an article - * - * @param mid - * @throws StorageObjectFailure - */ - - public void attach(String aMediaId) throws StorageObjectFailure - { - if (aMediaId!=null) { - try{ - DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId); - } - catch(StorageObjectFailure e){ - throwStorageObjectFailure(e, "attach: could not get the instance"); - } - setProduced(false); - } - else { - logger.error("EntityContent: attach without mid"); - } - } - - /** - * overridden method setValues to patch creator_main_url - */ - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (theStringValues.containsKey("creator_main_url")){ - if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){ - theStringValues.remove("creator_main_url"); - } - else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){ - theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url"))); - } - } - } - super.setValues(theStringValues); - } - - public void appendToComments(String aLine) { - StringBuffer comment = new StringBuffer(); - try { - comment.append(StringRoutines.interpretAsString(getValue("comment"))); - } - catch (Throwable t) { - } - if (comment.length() > 0 && comment.charAt(comment.length() - 1) != '\n') { - comment.append('\n'); - } - - comment.append(aLine); - setValueForProperty("comment", comment.toString()); - } - - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.entity; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mir.util.StringRoutines; +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.19.2.4 2003/12/21 13:32:04 zapata Exp $ + * @author mir-coders group + * + */ + + +public class EntityContent extends Entity +{ + // constructors + + public EntityContent() + { + super(); + + logger = new LoggerWrapper("Entity.Content"); + } + + public EntityContent(StorageObject theStorage) { + this(); + + setStorage(theStorage); + } + + // + // methods + + /** + * set is_produced flag for the article + */ + + public void setProduced(boolean yesno) throws StorageObjectFailure + { + String value = (yesno) ? "1":"0"; + if (value.equals( getValue("is_produced") )) return; + + Connection con=null;Statement stmt=null; + String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'"; + try { + con = theStorageObject.getPooledCon(); + /** @todo should be preparedStatement: faster!! */ + stmt = con.createStatement(); + theStorageObject.executeUpdate(stmt,sql); + } + catch (StorageObjectFailure e) { + throwStorageObjectFailure(e, "\n -- set produced failed"); + } + catch (SQLException e) { + throwStorageObjectFailure(e, "\n -- set produced failed"); + } + finally { + theStorageObject.freeConnection(con,stmt); + } + } + + /** + * Deattaches media from an article + * + * @param anArticleId + * @param aMediaId + * @throws StorageObjectFailure + */ + public void dettach(String anArticleId, String aMediaId) throws StorageObjectFailure + { + if (aMediaId!=null){ + try{ + DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId); + } + catch (Exception e){ + throwStorageObjectFailure(e, "\n -- failed to get instance"); + } + + setProduced(false); + } + } + + /** + * Attaches media to an article + * + * @param mid + * @throws StorageObjectFailure + */ + + public void attach(String aMediaId) throws StorageObjectFailure + { + if (aMediaId!=null) { + try{ + DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId); + } + catch(StorageObjectFailure e){ + throwStorageObjectFailure(e, "attach: could not get the instance"); + } + setProduced(false); + } + else { + logger.error("EntityContent: attach without mid"); + } + } + + /** + * overridden method setValues to patch creator_main_url + */ + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (theStringValues.containsKey("creator_main_url")){ + if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){ + theStringValues.remove("creator_main_url"); + } + else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){ + theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url"))); + } + } + } + super.setValues(theStringValues); + } +} diff --git a/source/mircoders/entity/EntityFeature.java b/source/mircoders/entity/EntityFeature.java deleted file mode 100755 index 94a02945..00000000 --- a/source/mircoders/entity/EntityFeature.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -import mir.entity.Entity; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mircoders.storage.DatabaseContent; -/** - * Diese Klasse enth?lt die Daten eines MetaObjekts - * - * @author RK - * @version 29.6.1999 - */ - - -public class EntityFeature extends Entity -{ - public EntityFeature() - { - super(); - } - - public EntityFeature(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - public void update() throws StorageObjectFailure{ - super.update(); - DatabaseContent dbContent = DatabaseContent.getInstance(); - dbContent.setUnproduced("to_feature="+getId()); - } -} diff --git a/source/mircoders/entity/EntityUploadedMedia.java b/source/mircoders/entity/EntityUploadedMedia.java index de17fc22..8c38e50f 100755 --- a/source/mircoders/entity/EntityUploadedMedia.java +++ b/source/mircoders/entity/EntityUploadedMedia.java @@ -1,101 +1,101 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.entity; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mircoders.media.MediaHelper; -import mir.media.MediaHandler; -import mir.misc.NumberUtils; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mircoders.storage.DatabaseUploadedMedia; - -/** - * - * @author mh, mir-coders group - * @version $Id: EntityUploadedMedia.java,v 1.26.2.4 2003/12/14 16:37:07 zapata Exp $ - */ - - -public class EntityUploadedMedia extends Entity { - public EntityUploadedMedia() { - super(); - - logger = new LoggerWrapper("Entity.UploadedMedia"); - } - - public EntityUploadedMedia(StorageObject theStorage) { - this(); - - setStorage(theStorage); - } - - public void update() throws StorageObjectFailure { - super.update(); - - try { - theStorageObject.executeUpdate( "update content set is_produced='0' where exists(select * from content_x_media where content_id=content.id and media_id=" + getId()+")"); - theStorageObject.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) { - throwStorageObjectFailure(e, "EntityUploadedMedia :: update :: failed!! "); - } - } - - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (!theStringValues.containsKey("is_published")) - theStringValues.put("is_published", "0"); - } - super.setValues(theStringValues); - } - - - /** - * fetches the MediaType entry assiciated w/ this media - * - * @return mir.entity.Entity - */ - public Entity getMediaType() throws StorageObjectFailure { - Entity ent = null; - try { - ent = DatabaseUploadedMedia.getInstance().getMediaType(this); - } - catch (StorageObjectFailure e) { - throwStorageObjectFailure(e, "get MediaType failed -- "); - } - return ent; - } -} +/* + * 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.entity; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mircoders.media.MediaHelper; +import mir.media.MediaHandler; +import mir.misc.NumberUtils; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mircoders.storage.DatabaseUploadedMedia; + +/** + * + * @author mh, mir-coders group + * @version $Id: EntityUploadedMedia.java,v 1.26.2.5 2003/12/21 13:32:04 zapata Exp $ + */ + + +public class EntityUploadedMedia extends Entity { + public EntityUploadedMedia() { + super(); + + logger = new LoggerWrapper("Entity.UploadedMedia"); + } + + public EntityUploadedMedia(StorageObject theStorage) { + this(); + + setStorage(theStorage); + } + + public void update() throws StorageObjectFailure { + super.update(); + + try { + theStorageObject.executeUpdate( "update content set is_produced='0' where exists(select * from content_x_media where content_id=content.id and media_id=" + getId()+")"); + theStorageObject.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) { + throwStorageObjectFailure(e, "EntityUploadedMedia :: update :: failed!! "); + } + } + + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (!theStringValues.containsKey("is_published")) + theStringValues.put("is_published", "0"); + } + super.setValues(theStringValues); + } + + + /** + * fetches the MediaType entry assiciated w/ this media + * + * @return mir.entity.Entity + */ + public Entity getMediaType() throws StorageObjectFailure { + Entity ent = null; + try { + ent = DatabaseUploadedMedia.getInstance().getMediaType(this); + } + catch (StorageObjectFailure e) { + throwStorageObjectFailure(e, "get MediaType failed -- "); + } + return ent; + } +} diff --git a/source/mircoders/global/Abuse.java b/source/mircoders/global/Abuse.java index 8ddcdb5d..1ee0f018 100755 --- a/source/mircoders/global/Abuse.java +++ b/source/mircoders/global/Abuse.java @@ -173,6 +173,20 @@ public class Abuse { if (filterRule != null) { logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'"); filterRule.setLastHit(new GregorianCalendar().getTime()); + + StringBuffer line = new StringBuffer(); + + line.append(DateTimeFunctions.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()+")"); + aComment.appendLineToField("comment", line.toString()); + MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction()); setCookie(aResponse); save(); @@ -211,7 +225,7 @@ public class Abuse { line.append(" "); line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")"); - anArticle.appendToComments(line.toString()); + anArticle.appendLineToField("comment", line.toString()); MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction()); setCookie(aResponse); diff --git a/source/mircoders/global/JobQueue.java b/source/mircoders/global/JobQueue.java index 1f1fab7b..f6093dcd 100755 --- a/source/mircoders/global/JobQueue.java +++ b/source/mircoders/global/JobQueue.java @@ -76,6 +76,7 @@ public class JobQueue { jobCleanupTreshold = 900; // seconds queueRunner = new JobQueueRunner(logger); thread = new Thread(queueRunner); + thread.setDaemon(true); thread.start(); } @@ -401,6 +402,7 @@ public class JobQueue { logger.debug(" starting job ("+job.getIdentifier()+"): " +job.getDescription()); job.runJob(); logger.debug(" finished job ("+job.getIdentifier()+"): " +job.getDescription()); + job=null; } else { try { diff --git a/source/mircoders/global/MirGlobal.java b/source/mircoders/global/MirGlobal.java index ea8e599f..b2f42326 100755 --- a/source/mircoders/global/MirGlobal.java +++ b/source/mircoders/global/MirGlobal.java @@ -59,6 +59,7 @@ public class MirGlobal { static private Map articleOperations; static private Map commentOperations; static private Map loggedInUsers = new HashMap(); + static private Map loggedInUserIds = new HashMap(); static private LoggerWrapper logger = new LoggerWrapper("Global"); static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage"); @@ -209,6 +210,11 @@ public class MirGlobal { } } + public static boolean isUserLoggedIn(String anId) { + synchronized (loggedInUserIds) { + return loggedInUserIds.containsKey(anId); + } + } public static List getLoggedInUsers() { List result = new Vector(); @@ -229,15 +235,15 @@ public class MirGlobal { return result; } - public static void registerLogin(String aName) { - modifyLoggedInCount(aName, 1); + public static void registerLogin(String aName, String anId) { + modifyLoggedInCount(aName, anId, 1); } - public static void registerLogout(String aName) { - modifyLoggedInCount(aName, -1); + public static void registerLogout(String aName, String anId) { + modifyLoggedInCount(aName, anId, -1); } - private static void modifyLoggedInCount(String aName, int aModifier) { + private static void modifyLoggedInCount(String aName, String anId, int aModifier) { synchronized (loggedInUsers) { Integer count = (Integer) loggedInUsers.get(aName); if (count==null) @@ -250,6 +256,19 @@ public class MirGlobal { 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)); + } + } } public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) { diff --git a/source/mircoders/global/ProducerEngine.java b/source/mircoders/global/ProducerEngine.java index f905bd08..8e46e57c 100755 --- a/source/mircoders/global/ProducerEngine.java +++ b/source/mircoders/global/ProducerEngine.java @@ -1,257 +1,257 @@ -/* - * 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 java.io.PrintWriter; -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.util.GeneratorFormatAdapters; -import mir.util.StringRoutines; -import multex.Exc; -import multex.Failure; - -public class ProducerEngine { -// private Map producers; - private JobQueue producerJobQueue; - private LoggerWrapper logger; - - - protected ProducerEngine() { - logger = new LoggerWrapper("Producer"); - producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue")); - } - - public void addJob(String aProducerFactory, String aVerb) { - producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb); - } - - public void cancelJobs(List aJobs) { - producerJobQueue.cancelJobs(aJobs); - }; - - public void cancelAllJobs() { - producerJobQueue.cancelAllJobs(); - }; - - public void addTask(ProducerTask aTask) { - addJob(aTask.getProducer(), aTask.getVerb()); - } - - public void addTasks(List aTasks) { - Iterator i = aTasks.iterator(); - - while (i.hasNext()) { - addTask((ProducerTask) i.next()); - } - } - - 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())); - result.put("runningtime", new Double( (double) aJob.getRunningTime() / 1000)); - result.put("status", convertStatus(aJob)); - result.put("lastchange", new GeneratorFormatAdapters.DateFormatAdapter(aJob.getLastChange(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"))); - result.put("finished", new Boolean( - aJob.getStatus() == JobQueue.STATUS_PROCESSED || - aJob.getStatus() == JobQueue.STATUS_CANCELLED || - aJob.getStatus() == JobQueue.STATUS_ABORTED)); - - return result; - } - catch (Throwable t) { - throw new RuntimeException(t.toString()); - } - } - - private List convertJobInfoList(List aJobInfoList) { - List result = new Vector(); - - Iterator i = aJobInfoList.iterator(); - - while (i.hasNext()) - result.add(convertJob((JobQueue.JobInfo) i.next())); - - return result; - } - - public List getQueueStatus() { - return convertJobInfoList(producerJobQueue.getJobsInfo()); - } - - private class ProducerJob implements JobQueue.Job { - private String factoryName; - private String verb; - private Producer producer; - - public ProducerJob(String aFactory, String aVerb) { - factoryName = aFactory; - verb = aVerb; - producer=null; - } - - public String getFactoryName() { - return factoryName; - } - - public String getVerb() { - return verb; - } - - public void abort() { - if (producer!=null) { - producer.abort(); - } - } - - 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); - - startTime = System.currentTimeMillis(); - logger.info("Producing job: "+factoryName+"."+verb); - - try { - factory = MirGlobal.localizer().producers().getFactoryForName( factoryName ); - - if (factory!=null) { - MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap); - - synchronized(factory) { - producer = factory.makeProducer(verb, startingMap); - } - if (producer!=null) { - result = producer.produce(logger); - } - } - } - catch (Throwable t) { - logger.error("Exception occurred while producing " + factoryName + "." + verb + t.getMessage()); - t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(logger, LoggerWrapper.ERROR_MESSAGE))); - } - endTime = System.currentTimeMillis(); - logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms"); - - return result; - } - - boolean isAborted() { - return false; - } - } - - public static class ProducerEngineExc extends Exc { - public ProducerEngineExc(String aMessage) { - super(aMessage); - } - } - - public static class ProducerEngineRuntimeExc extends Failure { - public ProducerEngineRuntimeExc(String msg, Exception cause){ - super(msg,cause); - } - } - - public static class ProducerTask { - private String producer; - private String verb; - - public ProducerTask(String aProducer, String aVerb) { - producer = aProducer; - verb = aVerb; - } - - public String getVerb() { - return verb; - } - - public String getProducer() { - return producer; - } - - public static List parseProducerTaskList(String aList) throws ProducerEngineExc { - Iterator i; - List result = new Vector(); - - 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) - throw new ProducerEngineExc("Invalid producer expression: '" + taskExpression + "'"); - else - result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1))); - } - } - - return result; - } - } +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, 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 java.io.PrintWriter; +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.util.GeneratorFormatAdapters; +import mir.util.StringRoutines; +import multex.Exc; +import multex.Failure; + +public class ProducerEngine { +// private Map producers; + private JobQueue producerJobQueue; + private LoggerWrapper logger; + + + protected ProducerEngine() { + logger = new LoggerWrapper("Producer"); + producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue")); + } + + public void addJob(String aProducerFactory, String aVerb) { + producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb); + } + + public void cancelJobs(List aJobs) { + producerJobQueue.cancelJobs(aJobs); + }; + + public void cancelAllJobs() { + producerJobQueue.cancelAllJobs(); + }; + + public void addTask(ProducerTask aTask) { + addJob(aTask.getProducer(), aTask.getVerb()); + } + + public void addTasks(List aTasks) { + Iterator i = aTasks.iterator(); + + while (i.hasNext()) { + addTask((ProducerTask) i.next()); + } + } + + 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())); + result.put("runningtime", new Double( (double) aJob.getRunningTime() / 1000)); + result.put("status", convertStatus(aJob)); + result.put("lastchange", new GeneratorFormatAdapters.DateFormatAdapter(aJob.getLastChange(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"))); + result.put("finished", new Boolean( + aJob.getStatus() == JobQueue.STATUS_PROCESSED || + aJob.getStatus() == JobQueue.STATUS_CANCELLED || + aJob.getStatus() == JobQueue.STATUS_ABORTED)); + + return result; + } + catch (Throwable t) { + throw new RuntimeException(t.toString()); + } + } + + private List convertJobInfoList(List aJobInfoList) { + List result = new Vector(); + + Iterator i = aJobInfoList.iterator(); + + while (i.hasNext()) + result.add(convertJob((JobQueue.JobInfo) i.next())); + + return result; + } + + public List getQueueStatus() { + return convertJobInfoList(producerJobQueue.getJobsInfo()); + } + + private class ProducerJob implements JobQueue.Job { + private String factoryName; + private String verb; + private Producer producer; + + public ProducerJob(String aFactory, String aVerb) { + factoryName = aFactory; + verb = aVerb; + producer=null; + } + + public String getFactoryName() { + return factoryName; + } + + public String getVerb() { + return verb; + } + + public void abort() { + if (producer!=null) { + producer.abort(); + } + } + + 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); + + startTime = System.currentTimeMillis(); + logger.info("Producing job: "+factoryName+"."+verb); + + try { + factory = MirGlobal.localizer().producers().getFactoryForName( factoryName ); + + if (factory!=null) { + MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap); + + synchronized(factory) { + producer = factory.makeProducer(verb, startingMap); + } + if (producer!=null) { + result = producer.produce(logger); + } + } + } + catch (Throwable t) { + logger.error("Exception occurred while producing " + factoryName + "." + verb + t.getMessage()); + t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(logger, LoggerWrapper.ERROR_MESSAGE))); + } + endTime = System.currentTimeMillis(); + logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms"); + + return result; + } + + boolean isAborted() { + return false; + } + } + + public static class ProducerEngineExc extends Exc { + public ProducerEngineExc(String aMessage) { + super(aMessage); + } + } + + public static class ProducerEngineRuntimeExc extends Failure { + public ProducerEngineRuntimeExc(String msg, Exception cause){ + super(msg,cause); + } + } + + public static class ProducerTask { + private String producer; + private String verb; + + public ProducerTask(String aProducer, String aVerb) { + producer = aProducer; + verb = aVerb; + } + + public String getVerb() { + return verb; + } + + public String getProducer() { + return producer; + } + + public static List parseProducerTaskList(String aList) throws ProducerEngineExc { + Iterator i; + List result = new Vector(); + + 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) + throw new ProducerEngineExc("Invalid producer expression: '" + taskExpression + "'"); + else + result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1))); + } + } + + return result; + } + } } \ No newline at end of file diff --git a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java index 5e66c4b7..a322cc3e 100755 --- a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java @@ -62,6 +62,15 @@ public interface MirAdminInterfaceLocalizer { */ public String makePasswordDigest(String aPassword); + /** + * Allows different "generators" (templates) to be used for certain pages + * + * @param aPage The identifier of the page + * @param aUser the user (can be used to allow different users to see different pages + * @param aDefault The default generator + * @return + */ + public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser, String aDefault); /** * diff --git a/source/mircoders/localizer/MirAntiAbuseFilterType.java b/source/mircoders/localizer/MirAntiAbuseFilterType.java index d14ea320..f5a126c4 100755 --- a/source/mircoders/localizer/MirAntiAbuseFilterType.java +++ b/source/mircoders/localizer/MirAntiAbuseFilterType.java @@ -1,68 +1,68 @@ -/* - * 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; - -/** - * - * - *

Title: Anti-abuse filter type

- *

Description: Interface to define filter types for the anti-abuse system - *

- *

Copyright: Copyright (c) 2003

- *

Company: Mir coders

- * @author Zapata - * @version 1.0 - */ - -public interface MirAntiAbuseFilterType { - /** - * The identifying name of the filter type. Must be unique. - * - * @return - */ - public String getName(); - - /** - * Must return true if the expression is valid for this filter. false if not. - * @param anExpression - * @return - */ - public boolean validate(String anExpression); - - /** - * Must return true if the posting matches the filter. - * @param anExpression - * @return - */ - public boolean test(String anExpression, Entity anEntity, Request aRequest); +/* + * 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; + +/** + * + * + *

Title: Anti-abuse filter type

+ *

Description: Interface to define filter types for the anti-abuse system + *

+ *

Copyright: Copyright (c) 2003

+ *

Company: Mir coders

+ * @author Zapata + * @version 1.0 + */ + +public interface MirAntiAbuseFilterType { + /** + * The identifying name of the filter type. Must be unique. + * + * @return + */ + public String getName(); + + /** + * Must return true if the expression is valid for this filter. false if not. + * @param anExpression + * @return + */ + public boolean validate(String anExpression); + + /** + * Must return true if the posting matches the filter. + * @param anExpression + * @return + */ + public boolean test(String anExpression, Entity anEntity, Request aRequest); } \ No newline at end of file diff --git a/source/mircoders/localizer/MirCachingLocalizerDecorator.java b/source/mircoders/localizer/MirCachingLocalizerDecorator.java index ab828f20..7d2be0ae 100755 --- a/source/mircoders/localizer/MirCachingLocalizerDecorator.java +++ b/source/mircoders/localizer/MirCachingLocalizerDecorator.java @@ -1,170 +1,170 @@ -/* - * 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.GeneratorLibrary producerGeneratorLibrary; - private Generator.GeneratorLibrary adminGeneratorLibrary; - private Generator.GeneratorLibrary openPostingGeneratorLibrary; - - public MirCachingGeneratorLocalizer(MirGeneratorLocalizer aMaster) { - master = aMaster; - } - - public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure { - if (writerEngine==null) { - writerEngine = master.makeWriterEngine(); - } - - return writerEngine; - }; - - public Generator.GeneratorLibrary makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { - if (producerGeneratorLibrary==null) { - producerGeneratorLibrary = master.makeProducerGeneratorLibrary(); - } - - return producerGeneratorLibrary; - }; - - public Generator.GeneratorLibrary makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { - if (adminGeneratorLibrary==null) { - adminGeneratorLibrary = master.makeAdminGeneratorLibrary(); - } - - return adminGeneratorLibrary; - }; - - public Generator.GeneratorLibrary makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { - if (openPostingGeneratorLibrary==null) { - openPostingGeneratorLibrary = master.makeOpenPostingGeneratorLibrary(); - } - - return openPostingGeneratorLibrary; - }; - } - +/* + * 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.GeneratorLibrary producerGeneratorLibrary; + private Generator.GeneratorLibrary adminGeneratorLibrary; + private Generator.GeneratorLibrary openPostingGeneratorLibrary; + + public MirCachingGeneratorLocalizer(MirGeneratorLocalizer aMaster) { + master = aMaster; + } + + public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure { + if (writerEngine==null) { + writerEngine = master.makeWriterEngine(); + } + + return writerEngine; + }; + + public Generator.GeneratorLibrary makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { + if (producerGeneratorLibrary==null) { + producerGeneratorLibrary = master.makeProducerGeneratorLibrary(); + } + + return producerGeneratorLibrary; + }; + + public Generator.GeneratorLibrary makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { + if (adminGeneratorLibrary==null) { + adminGeneratorLibrary = master.makeAdminGeneratorLibrary(); + } + + return adminGeneratorLibrary; + }; + + public Generator.GeneratorLibrary makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure { + if (openPostingGeneratorLibrary==null) { + openPostingGeneratorLibrary = master.makeOpenPostingGeneratorLibrary(); + } + + return openPostingGeneratorLibrary; + }; + } + } \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index 58f56a68..2eaab939 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -77,6 +77,10 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0")); } + public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser, String aDefault) { + return aDefault; + } + public String makePasswordDigest(String aPassword) { return aPassword; } @@ -126,9 +130,11 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation { private String name; + private boolean logOperation; - protected EntityModifyingOperation(String aName) { + protected EntityModifyingOperation(String aName, boolean aLogOperation) { name = aName; + logOperation = aLogOperation; } public String getName() { @@ -149,6 +155,30 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz Entity entity = anEntity.getEntity(); try { performModification(aUser, entity); + + if (logOperation) { + try { + StringBuffer line = new StringBuffer(); + + line.append(DateTimeFunctions.advancedDateFormat( + MirGlobal.config().getString("Mir.DefaultDateTimeFormat"), + (new GregorianCalendar()).getTime(), + MirGlobal.config().getString("Mir.DefaultTimezone"))); + line.append(" "); + if (aUser != null) + line.append(aUser.get("login")); + else + line.append("unknown"); + + line.append(" "); + line.append(getName()); + entity.appendLineToField("comment", line.toString()); + } + catch (Throwable t) { + logger.error("Error while trying to log an article operation: " + t.toString()); + } + } + entity.update(); } catch (Throwable t) { @@ -161,8 +191,12 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz } public static abstract class CommentModifyingOperation extends EntityModifyingOperation { + public CommentModifyingOperation(String aName, boolean aLogOperation) { + super(aName, aLogOperation); + } + public CommentModifyingOperation(String aName) { - super(aName); + this(aName, true); } protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { @@ -179,12 +213,8 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz } public static abstract class ArticleModifyingOperation extends EntityModifyingOperation { - private boolean logOperation; - public ArticleModifyingOperation(String aName, boolean aLogOperation) { - super(aName); - - logOperation = aLogOperation; + super(aName, aLogOperation); } protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { @@ -194,29 +224,6 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { performModification(aUser, (EntityContent) anEntity); anEntity.setValueForProperty("is_produced", "0"); - - if (logOperation) { - try { - StringBuffer line = new StringBuffer(); - - line.append(DateTimeFunctions.advancedDateFormat( - MirGlobal.config().getString("Mir.DefaultDateTimeFormat"), - (new GregorianCalendar()).getTime(), - MirGlobal.config().getString("Mir.DefaultTimezone"))); - line.append(" "); - if (aUser != null) - line.append(aUser.get("login")); - else - line.append("unknown"); - - line.append(" "); - line.append(getName()); - ( (EntityContent) anEntity).appendToComments(line.toString()); - } - catch (Throwable t) { - logger.error("Error while trying to log an article operation: " + t.toString()); - } - } }; protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ; diff --git a/source/mircoders/localizer/basic/MirBasicChildArticlePostingHandler.java b/source/mircoders/localizer/basic/MirBasicChildArticlePostingHandler.java index 4a2cee78..3525fcd3 100755 --- a/source/mircoders/localizer/basic/MirBasicChildArticlePostingHandler.java +++ b/source/mircoders/localizer/basic/MirBasicChildArticlePostingHandler.java @@ -1,62 +1,62 @@ -/* - * 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.Session; -import mir.session.SessionExc; -import mir.session.SessionFailure; -import mircoders.entity.EntityContent; - - -public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler { - public MirBasicChildArticlePostingHandler() { - super(); - - setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate")); - } - - public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure { - super.finalizeArticle(aRequest, aSession, anArticle); - - anArticle.setValueForProperty("to_content", (String) aSession.getAttribute("to_content")); - } - - protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure { - super.initializeSession(aRequest, aSession); - - String parentId = aRequest.getParameter("to_content"); - if (parentId==null) - throw new SessionExc("initializeSession: parent id not set!"); - - aSession.setAttribute("to_content", parentId); - }; +/* + * 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.Session; +import mir.session.SessionExc; +import mir.session.SessionFailure; +import mircoders.entity.EntityContent; + + +public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler { + public MirBasicChildArticlePostingHandler() { + super(); + + setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate")); + } + + public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure { + super.finalizeArticle(aRequest, aSession, anArticle); + + anArticle.setValueForProperty("to_content", (String) aSession.getAttribute("to_content")); + } + + protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure { + super.initializeSession(aRequest, aSession); + + String parentId = aRequest.getParameter("to_content"); + if (parentId==null) + throw new SessionExc("initializeSession: parent id not set!"); + + aSession.setAttribute("to_content", parentId); + }; } \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicCommentPostingHandler.java b/source/mircoders/localizer/basic/MirBasicCommentPostingHandler.java index df9634b7..567f31e6 100755 --- a/source/mircoders/localizer/basic/MirBasicCommentPostingHandler.java +++ b/source/mircoders/localizer/basic/MirBasicCommentPostingHandler.java @@ -1,181 +1,181 @@ -/* - * 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.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mir.entity.Entity; -import mir.session.Request; -import mir.session.Response; -import mir.session.Session; -import mir.session.SessionExc; -import mir.session.SessionFailure; -import mir.session.UploadedFile; -import mir.session.ValidationHelper; -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.DatabaseComment; -import mircoders.storage.DatabaseCommentStatus; -import mircoders.storage.DatabaseCommentToMedia; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseMediafolder; - -/** - * - *

Title: Experimental session handler for comment postings

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author Zapata - * @version 1.0 - */ - -public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler { - protected ModuleComment commentModule = new ModuleComment(DatabaseComment.getInstance()); - protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance(); - - - public MirBasicCommentPostingHandler() { - super(); - - setResponseGenerators( - configuration.getString("Localizer.OpenSession.comment.EditTemplate"), - configuration.getString("Localizer.OpenSession.comment.DupeTemplate"), - configuration.getString("Localizer.OpenSession.comment.UnsupportedMediaTemplate"), - configuration.getString("Localizer.OpenSession.comment.DoneTemplate")); - } - - protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { - super.initializeResponseData(aRequest, aSession, aResponse); - - Iterator i = DatabaseComment.getInstance().getFields().iterator(); - while (i.hasNext()) { - String field = (String) i.next(); - aResponse.setResponseValue(field, aRequest.getParameter(field)); - } - } - - public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure { - super.validate(aResults, aRequest, aSession); - - ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults); - ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults); - ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults); - } - - protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure { - super.initializeSession(aRequest, aSession); - - String articleId = aRequest.getParameter("to_media"); - if (articleId==null) - 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.setValueForProperty("is_published", "1"); - ModuleCommentStatus module = new ModuleCommentStatus(DatabaseCommentStatus.getInstance()); - aComment.setValueForProperty("to_comment_status", module.commentStatusIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultCommentStatus"))); - aComment.setValueForProperty("is_html", "0"); - aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media")); - } - catch (Throwable t) { - throw new SessionFailure(t); - } - } - - public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure { - try { - String id; - Map values = getIntersectingValues(aRequest, DatabaseComment.getInstance()); - - EntityComment comment = (EntityComment) commentModule.createNew(); - comment.setValues(values); - finalizeComment(aRequest, aSession, comment); - id = comment.insert(); - if (id == null) { - logger.info("Duplicate comment rejected"); - throw new DuplicateCommentExc("Duplicate comment rejected"); - } - aSession.setAttribute("comment", comment); - } - catch (Throwable t) { - throw new SessionFailure(t); - } - } - - public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure { - try { - Map values = new HashMap(); - values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title")); - values.put("creator", aRequest.getParameter("creator")); - values.put("to_publisher", "0"); - values.put("is_published", "1"); - ModuleMediafolder module = new ModuleMediafolder(DatabaseMediafolder.getInstance()); - values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultMediaFolder"))); - - Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values); - mediaItem.update(); - commentToMedia.addMedia(((EntityComment) aSession.getAttribute("comment")).getId(), mediaItem.getId()); - } - catch (Throwable t) { - throw new SessionFailure(t); - } - } - - public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure { - EntityComment comment = (EntityComment) aSession.getAttribute("comment"); - - MirGlobal.abuse().checkComment(comment, aRequest, null); - try { - MirGlobal.localizer().openPostings().afterCommentPosting(comment); - } - catch (Throwable t) { - throw new SessionFailure(t); - } - DatabaseContent.getInstance().setUnproduced("id=" + comment.getValue("to_media")); - logger.info("Comment posted"); - }; - - protected static class DuplicateCommentExc extends SessionExc { - public DuplicateCommentExc(String aMessage) { - super(aMessage); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.localizer.basic; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mir.entity.Entity; +import mir.session.Request; +import mir.session.Response; +import mir.session.Session; +import mir.session.SessionExc; +import mir.session.SessionFailure; +import mir.session.UploadedFile; +import mir.session.ValidationHelper; +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.DatabaseComment; +import mircoders.storage.DatabaseCommentStatus; +import mircoders.storage.DatabaseCommentToMedia; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseMediafolder; + +/** + * + *

Title: Experimental session handler for comment postings

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author Zapata + * @version 1.0 + */ + +public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler { + protected ModuleComment commentModule = new ModuleComment(DatabaseComment.getInstance()); + protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance(); + + + public MirBasicCommentPostingHandler() { + super(); + + setResponseGenerators( + configuration.getString("Localizer.OpenSession.comment.EditTemplate"), + configuration.getString("Localizer.OpenSession.comment.DupeTemplate"), + configuration.getString("Localizer.OpenSession.comment.UnsupportedMediaTemplate"), + configuration.getString("Localizer.OpenSession.comment.DoneTemplate")); + } + + protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure { + super.initializeResponseData(aRequest, aSession, aResponse); + + Iterator i = DatabaseComment.getInstance().getFields().iterator(); + while (i.hasNext()) { + String field = (String) i.next(); + aResponse.setResponseValue(field, aRequest.getParameter(field)); + } + } + + public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure { + super.validate(aResults, aRequest, aSession); + + ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults); + ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults); + ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults); + } + + protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure { + super.initializeSession(aRequest, aSession); + + String articleId = aRequest.getParameter("to_media"); + if (articleId==null) + 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.setValueForProperty("is_published", "1"); + ModuleCommentStatus module = new ModuleCommentStatus(DatabaseCommentStatus.getInstance()); + aComment.setValueForProperty("to_comment_status", module.commentStatusIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultCommentStatus"))); + aComment.setValueForProperty("is_html", "0"); + aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media")); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + } + + public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure { + try { + String id; + Map values = getIntersectingValues(aRequest, DatabaseComment.getInstance()); + + EntityComment comment = (EntityComment) commentModule.createNew(); + comment.setValues(values); + finalizeComment(aRequest, aSession, comment); + id = comment.insert(); + if (id == null) { + logger.info("Duplicate comment rejected"); + throw new DuplicateCommentExc("Duplicate comment rejected"); + } + aSession.setAttribute("comment", comment); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + } + + public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure { + try { + Map values = new HashMap(); + values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title")); + values.put("creator", aRequest.getParameter("creator")); + values.put("to_publisher", "0"); + values.put("is_published", "1"); + ModuleMediafolder module = new ModuleMediafolder(DatabaseMediafolder.getInstance()); + values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultMediaFolder"))); + + Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values); + mediaItem.update(); + commentToMedia.addMedia(((EntityComment) aSession.getAttribute("comment")).getId(), mediaItem.getId()); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + } + + public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure { + EntityComment comment = (EntityComment) aSession.getAttribute("comment"); + + MirGlobal.abuse().checkComment(comment, aRequest, null); + try { + MirGlobal.localizer().openPostings().afterCommentPosting(comment); + } + catch (Throwable t) { + throw new SessionFailure(t); + } + DatabaseContent.getInstance().setUnproduced("id=" + comment.getValue("to_media")); + logger.info("Comment posted"); + }; + + protected static class DuplicateCommentExc extends SessionExc { + public DuplicateCommentExc(String aMessage) { + super(aMessage); + } + } +} diff --git a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java index 1523560d..937e9c45 100755 --- a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java @@ -41,9 +41,8 @@ import mir.entity.adapter.EntityAdapter; import mir.entity.adapter.EntityAdapterDefinition; import mir.entity.adapter.EntityAdapterModel; import mir.log.LoggerWrapper; -import mircoders.media.MediaHelper; -import mir.misc.NumberUtils; import mir.media.MediaHandler; +import mir.misc.NumberUtils; import mir.util.ParameterExpander; import mir.util.RewindableIterator; import mir.util.StructuredContentParser; @@ -53,6 +52,8 @@ import mircoders.localizer.MirAdminInterfaceLocalizer; import mircoders.localizer.MirDataModelLocalizer; import mircoders.localizer.MirLocalizerExc; import mircoders.localizer.MirLocalizerFailure; +import mircoders.media.MediaHelper; +import mircoders.module.ModuleContent; import mircoders.storage.DatabaseArticleType; import mircoders.storage.DatabaseAudio; import mircoders.storage.DatabaseBreaking; @@ -93,6 +94,10 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { 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 ContentToUserField("to_locking_user")); + anEntityAdapterDefinition.addCalculatedField("is_locked", new ContentToIsLockedField()); + anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField()); anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField()); anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField()); @@ -231,7 +236,13 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition()); result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition()); result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition()); - result.addMapping( "user", DatabaseUsers.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( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition()); result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition()); @@ -734,95 +745,45 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { } } } -} - + protected class ContentToUserField implements EntityAdapterDefinition.CalculatedField { + /** + * + * @param aFieldName the source field. will be mapped to the id field in the user + * table + */ + private String fieldName; -/* - public String getValue(String key) { - String returnValue = null; - - if (key != null) { - if (key.equals("big_icon")) - returnValue = getBigIconName(); - else if (key.equals("descr") || key.equals("media_descr")) - returnValue = getDescr(); - else if (key.equals("mediatype")) - returnValue = getMediaTypeString(); - else if (key.equals("mimetype")) - returnValue = getMimeType(); - else - returnValue = super.getValue(key); + public ContentToUserField(String aFieldName) { + fieldName = aFieldName; } - return returnValue; - } - - // @todo all these methods should be merged into 1 - // and the MediaHandler should be cached somehow. - private String getMediaTypeString() { - if (this instanceof EntityImages) - return "image"; - if (this instanceof EntityAudio) - return "audio"; - if (this instanceof EntityVideo) - return "video"; - else - return "other"; - } - -private String getBigIconName() { - MediaHandler mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getBigIconName(); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); - } - return null; -} -private List getUrl() { - MediaHandler mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getURL(this, mediaType); - } - catch (Throwable t) { - logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString()); + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id=" + anEntityAdapter.get(fieldName), + "id", + "user"); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } } - return null; -} -private String getDescr() { - MediaHandler mediaHandler = null; - Entity mediaType = null; + protected class ContentToIsLockedField implements EntityAdapterDefinition.CalculatedField { + private ModuleContent contentModule; - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getDescr(mediaType); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString()); - } - return null; -} -private String getMimeType() { - Entity mediaType = null; + public ContentToIsLockedField() { + contentModule = new ModuleContent(DatabaseContent.getInstance()); + } - try { - mediaType = getMediaType(); - return mediaType.getValue("mime_type"); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return new Boolean(contentModule.queryArticleLock(anEntityAdapter.getEntity().getId())!=null); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } } - return null; } -*/ \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicLocalizer.java b/source/mircoders/localizer/basic/MirBasicLocalizer.java index b59521b5..d5de268e 100755 --- a/source/mircoders/localizer/basic/MirBasicLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicLocalizer.java @@ -1,72 +1,72 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, 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 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; - -public class MirBasicLocalizer implements MirLocalizer { - - public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicProducerLocalizer(); - } - - public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicGeneratorLocalizer(); - } - - public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicOpenPostingLocalizer(); - } - - public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicProducerAssistantLocalizer(); - } - - public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicDataModelLocalizer(); - }; - - public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicAdminInterfaceLocalizer(); - } - - public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc { - return new MirBasicMediaLocalizer(); - } +/* + * 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 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; + +public class MirBasicLocalizer implements MirLocalizer { + + public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicProducerLocalizer(); + } + + public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicGeneratorLocalizer(); + } + + public MirOpenPostingLocalizer openPostings() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicOpenPostingLocalizer(); + } + + public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicProducerAssistantLocalizer(); + } + + public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicDataModelLocalizer(); + }; + + public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicAdminInterfaceLocalizer(); + } + + public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc { + return new MirBasicMediaLocalizer(); + } } \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicMediaLocalizer.java b/source/mircoders/localizer/basic/MirBasicMediaLocalizer.java index 4835d69d..ea55ad73 100755 --- a/source/mircoders/localizer/basic/MirBasicMediaLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicMediaLocalizer.java @@ -1,127 +1,127 @@ -/* - * 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.HashMap; -import java.util.Map; - -import mir.media.MediaHandler; -import mir.config.*; -import mircoders.localizer.MirLocalizerExc; -import mircoders.localizer.MirLocalizerFailure; -import mircoders.localizer.MirMediaLocalizer; -import mircoders.media.*; - -/** - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class MirBasicMediaLocalizer implements MirMediaLocalizer { - private Map mediaHandlers; - - /** - * - * @throws MirLocalizerExc - * @throws MirLocalizerFailure - */ - public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure { - MirPropertiesConfiguration configuration; - - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (Throwable t) { - throw new MirLocalizerFailure("Can't get configuration", t); - } - - mediaHandlers = new HashMap(); - - - registerMediaHandler("Audio", new MediaHandlerAudio()); - registerMediaHandler("Generic", new MediaHandlerGeneric()); - registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern()); - registerMediaHandler("ImagesJpeg", new MediaHandlerImagesJpeg()); - registerMediaHandler("ImagesPng", new MediaHandlerImagesPng()); - registerMediaHandler("Mp3", new MediaHandlerMp3()); - registerMediaHandler("Ogg", new MediaHandlerOgg()); - registerMediaHandler("RealAudio", new MediaHandlerRealAudio()); - registerMediaHandler("RealVideo", new MediaHandlerRealVideo()); - registerMediaHandler("Video", new MediaHandlerVideo()); - - registerMediaHandler("VideoUrl", new URLMediaHandler( - configuration.getString("Producer.Icon.BigVideo"), - configuration.getString("Producer.Icon.TinyVideo"), - "Video Url")); - - registerMediaHandler("AudioUrl", new URLMediaHandler( - configuration.getString("Producer.Icon.BigAudio"), - configuration.getString("Producer.Icon.TinyAudio"), - "Audio Url")); - - registerMediaHandler("ImageUrl", new URLMediaHandler( - configuration.getString("Producer.Icon.BigImage"), - configuration.getString("Producer.Icon.TinyImage"), - "Image Url")); - - registerMediaHandler("OtherUrl", new URLMediaHandler( - configuration.getString("Producer.Icon.BigAudio"), - configuration.getString("Producer.Icon.TinyAudio"), - "Url")); - } - - /** returns the {@link MediaHandler} associated with name aName by way of - * an internal Map. This Map can be manipulated by calling - * registerMediaHandler and unregisterMediaHandler - */ - public MediaHandler getHandler(String aName) { - synchronized (mediaHandlers) { - return (MediaHandler) mediaHandlers.get(aName); - } - } - - /** adds a media handler to the registry */ - public void registerMediaHandler(String aName, MediaHandler aHandler) { - synchronized (mediaHandlers) { - mediaHandlers.put(aName, aHandler); - } - } - - /** removes a media handler from the registry*/ - public void unregisterMediaHandler(String aName) { - synchronized (mediaHandlers) { - mediaHandlers.remove(aName); - } - } +/* + * 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.HashMap; +import java.util.Map; + +import mir.media.MediaHandler; +import mir.config.*; +import mircoders.localizer.MirLocalizerExc; +import mircoders.localizer.MirLocalizerFailure; +import mircoders.localizer.MirMediaLocalizer; +import mircoders.media.*; + +/** + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class MirBasicMediaLocalizer implements MirMediaLocalizer { + private Map mediaHandlers; + + /** + * + * @throws MirLocalizerExc + * @throws MirLocalizerFailure + */ + public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure { + MirPropertiesConfiguration configuration; + + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (Throwable t) { + throw new MirLocalizerFailure("Can't get configuration", t); + } + + mediaHandlers = new HashMap(); + + + registerMediaHandler("Audio", new MediaHandlerAudio()); + registerMediaHandler("Generic", new MediaHandlerGeneric()); + registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern()); + registerMediaHandler("ImagesJpeg", new MediaHandlerImagesJpeg()); + registerMediaHandler("ImagesPng", new MediaHandlerImagesPng()); + registerMediaHandler("Mp3", new MediaHandlerMp3()); + registerMediaHandler("Ogg", new MediaHandlerOgg()); + registerMediaHandler("RealAudio", new MediaHandlerRealAudio()); + registerMediaHandler("RealVideo", new MediaHandlerRealVideo()); + registerMediaHandler("Video", new MediaHandlerVideo()); + + registerMediaHandler("VideoUrl", new URLMediaHandler( + configuration.getString("Producer.Icon.BigVideo"), + configuration.getString("Producer.Icon.TinyVideo"), + "Video Url")); + + registerMediaHandler("AudioUrl", new URLMediaHandler( + configuration.getString("Producer.Icon.BigAudio"), + configuration.getString("Producer.Icon.TinyAudio"), + "Audio Url")); + + registerMediaHandler("ImageUrl", new URLMediaHandler( + configuration.getString("Producer.Icon.BigImage"), + configuration.getString("Producer.Icon.TinyImage"), + "Image Url")); + + registerMediaHandler("OtherUrl", new URLMediaHandler( + configuration.getString("Producer.Icon.BigAudio"), + configuration.getString("Producer.Icon.TinyAudio"), + "Url")); + } + + /** returns the {@link MediaHandler} associated with name aName by way of + * an internal Map. This Map can be manipulated by calling + * registerMediaHandler and unregisterMediaHandler + */ + public MediaHandler getHandler(String aName) { + synchronized (mediaHandlers) { + return (MediaHandler) mediaHandlers.get(aName); + } + } + + /** adds a media handler to the registry */ + public void registerMediaHandler(String aName, MediaHandler aHandler) { + synchronized (mediaHandlers) { + mediaHandlers.put(aName, aHandler); + } + } + + /** removes a media handler from the registry*/ + public void unregisterMediaHandler(String aName) { + synchronized (mediaHandlers) { + mediaHandlers.remove(aName); + } + } } \ No newline at end of file diff --git a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java index 05eb5970..5589145e 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java @@ -1,168 +1,168 @@ -/* - * 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.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.util.GeneratorDateTimeFunctions; -import mir.util.GeneratorExpressionFunctions; -import mir.util.GeneratorFormatAdapters; -import mir.util.GeneratorHTMLFunctions; -import mir.util.GeneratorIntegerFunctions; -import mir.util.GeneratorListFunctions; -import mir.util.GeneratorRegularExpressionFunctions; -import mir.util.GeneratorStringFunctions; -import mircoders.global.MirGlobal; -import mircoders.localizer.MirLocalizerExc; -import mircoders.localizer.MirLocalizerFailure; -import mircoders.localizer.MirProducerAssistantLocalizer; - -public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer { - protected LoggerWrapper logger; - - public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure { - try { - Iterator i; - - Map configMap = new HashMap(); - Map utilityMap = new HashMap(); - - logger = new LoggerWrapper("Localizer.ProducerAssistant"); - -// obsolete: - configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot")); - configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot")); - configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost")); - configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction")); - configMap.put("docRoot", MirGlobal.config().getString("RootUri")); - configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir"); - configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone"))); - configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host")); - configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host")); - configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host")); - configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path")); - configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version")); - configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding")); - -// "new": - configMap.putAll(MirPropertiesConfiguration.instance().allSettings()); - - utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace()); - utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction()); - utilityMap.put("prettyEncodeHTML", new GeneratorHTMLFunctions.prettyEncodeHTMLGeneratorFunction()); - utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction()); - utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction()); - utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction()); - utilityMap.put("subList", new GeneratorListFunctions.subListFunction()); - utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction()); - utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction()); - utilityMap.put("evaluate", new GeneratorExpressionFunctions.evaluateExpressionFunction()); - utilityMap.put("constructString", new GeneratorStringFunctions.constructStructuredStringFunction()); - utilityMap.put("parseStructuredString", new GeneratorStringFunctions.structuredStringParserFunction()); - utilityMap.put("escapeJDBCString", new GeneratorStringFunctions.jdbcStringEscapeFunction()); - utilityMap.put("regexpreplace", new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction()); - utilityMap.put("regexpmatch", new GeneratorRegularExpressionFunctions.regularExpressionMatchFunction()); - utilityMap.put("datetime", new GeneratorDateTimeFunctions.DateTimeFunctions( - MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"))); - - aValueSet.put("config", configMap); - aValueSet.put("utility", utilityMap); - - aValueSet.put("languages", - new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language")); - - aValueSet.put("topics", - new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); - - Map articleTypeMap = new HashMap(); - articleTypeMap.put("openposting", "0"); - articleTypeMap.put("newswire", "1"); - articleTypeMap.put("feature", "2"); - articleTypeMap.put("topicspecial", "3"); - articleTypeMap.put("startspecial", "4"); - - i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType"); - while (i.hasNext()) { - EntityAdapter articleType = (EntityAdapter) i.next(); - - articleTypeMap.put(articleType.get("name"), articleType.get("id")); - } - aValueSet.put("articletype", articleTypeMap); - - Map commentStatusMap = new HashMap(); - i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"); - while (i.hasNext()) { - EntityAdapter commentStatus = (EntityAdapter) i.next(); - - commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id")); - } - aValueSet.put("commentstatus", commentStatusMap); - } - catch (Throwable t) { - logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage()); - throw new RuntimeException(t.getMessage()); - } - - }; - - public String filterNonHTMLText(String aText) { - - 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") - ); - logger.debug("done filtering non-HTML text "); - return result; - } - catch (Throwable t) { - logger.error("error while filtering non-HTML text: " + t.toString()); - - throw new RuntimeException(t.toString()); - } - } - - public String filterHTMLText(String aText) { - return StringUtil.deleteForbiddenTags(aText); - } -} +/* + * 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.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.adapter.EntityAdapter; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.util.GeneratorDateTimeFunctions; +import mir.util.GeneratorExpressionFunctions; +import mir.util.GeneratorFormatAdapters; +import mir.util.GeneratorHTMLFunctions; +import mir.util.GeneratorIntegerFunctions; +import mir.util.GeneratorListFunctions; +import mir.util.GeneratorRegularExpressionFunctions; +import mir.util.GeneratorStringFunctions; +import mircoders.global.MirGlobal; +import mircoders.localizer.MirLocalizerExc; +import mircoders.localizer.MirLocalizerFailure; +import mircoders.localizer.MirProducerAssistantLocalizer; + +public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer { + protected LoggerWrapper logger; + + public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure { + try { + Iterator i; + + Map configMap = new HashMap(); + Map utilityMap = new HashMap(); + + logger = new LoggerWrapper("Localizer.ProducerAssistant"); + +// obsolete: + configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot")); + configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot")); + configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost")); + configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction")); + configMap.put("docRoot", MirGlobal.config().getString("RootUri")); + configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir"); + configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone"))); + configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host")); + configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host")); + configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host")); + configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path")); + configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version")); + configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding")); + +// "new": + configMap.putAll(MirPropertiesConfiguration.instance().allSettings()); + + utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace()); + utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction()); + utilityMap.put("prettyEncodeHTML", new GeneratorHTMLFunctions.prettyEncodeHTMLGeneratorFunction()); + utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction()); + utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction()); + utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction()); + utilityMap.put("subList", new GeneratorListFunctions.subListFunction()); + utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction()); + utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction()); + utilityMap.put("evaluate", new GeneratorExpressionFunctions.evaluateExpressionFunction()); + utilityMap.put("constructString", new GeneratorStringFunctions.constructStructuredStringFunction()); + utilityMap.put("parseStructuredString", new GeneratorStringFunctions.structuredStringParserFunction()); + utilityMap.put("escapeJDBCString", new GeneratorStringFunctions.jdbcStringEscapeFunction()); + utilityMap.put("regexpreplace", new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction()); + utilityMap.put("regexpmatch", new GeneratorRegularExpressionFunctions.regularExpressionMatchFunction()); + utilityMap.put("datetime", new GeneratorDateTimeFunctions.DateTimeFunctions( + MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"))); + + aValueSet.put("config", configMap); + aValueSet.put("utility", utilityMap); + + aValueSet.put("languages", + new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language")); + + aValueSet.put("topics", + new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + + Map articleTypeMap = new HashMap(); + articleTypeMap.put("openposting", "0"); + articleTypeMap.put("newswire", "1"); + articleTypeMap.put("feature", "2"); + articleTypeMap.put("topicspecial", "3"); + articleTypeMap.put("startspecial", "4"); + + i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType"); + while (i.hasNext()) { + EntityAdapter articleType = (EntityAdapter) i.next(); + + articleTypeMap.put(articleType.get("name"), articleType.get("id")); + } + aValueSet.put("articletype", articleTypeMap); + + Map commentStatusMap = new HashMap(); + i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"); + while (i.hasNext()) { + EntityAdapter commentStatus = (EntityAdapter) i.next(); + + commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id")); + } + aValueSet.put("commentstatus", commentStatusMap); + } + catch (Throwable t) { + logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage()); + throw new RuntimeException(t.getMessage()); + } + + }; + + public String filterNonHTMLText(String aText) { + + 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") + ); + logger.debug("done filtering non-HTML text "); + return result; + } + catch (Throwable t) { + logger.error("error while filtering non-HTML text: " + t.toString()); + + throw new RuntimeException(t.toString()); + } + } + + public String filterHTMLText(String aText) { + return StringUtil.deleteForbiddenTags(aText); + } +} diff --git a/source/mircoders/media/MediaHandlerRealAudio.java b/source/mircoders/media/MediaHandlerRealAudio.java index de0842d7..dca1bf15 100755 --- a/source/mircoders/media/MediaHandlerRealAudio.java +++ b/source/mircoders/media/MediaHandlerRealAudio.java @@ -1,130 +1,130 @@ -/* - * 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.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; - - - -/** - * Handles realAudio .it manages the ram file. - * - * 03.2002 - reworked Realmedia handling. -mh - * - * @see mir.media.MediaHandlerGeneric - * @see mir.media.MediaHandler - * @author john , mh - * @version $Id: MediaHandlerRealAudio.java,v 1.19.2.2 2003/12/14 16:37:08 zapata Exp $ - */ - - -public class MediaHandlerRealAudio extends MediaHandlerAudio implements MediaHandler -{ - public MediaHandlerRealAudio() { - logger = new LoggerWrapper("Media.Audio.Real"); - } - - public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure { - - // first see if the file exists - super.produce(ent, mediaTypeEnt); - - String baseName = ent.getId(); - String date = ent.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String rtspDir = configuration.getString("Producer.RealMedia.Path"); - String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); - - String RealMediaPointer = rtspMediaHost+ent.getValue("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"); - } - catch (Throwable e) { - logger.error("MediaHandlerRealAudio.produce: " + e.toString()); - throw new MediaFailure(e); - } - } - - public List getURL(Entity ent, Entity mediaTypeEnt) - { - List theList = new Vector(); - - //String stringSize = ent.getValue("size"); - //int size = Integer.parseInt(stringSize, 10)/1024; - theList.add(ent); - - String basePath=StringUtil.regexpReplace(ent.getValue("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() - { - return configuration.getString("Producer.RealMedia.Path"); - } - - public String getDescr(Entity mediaType) - { - return "RealMedia"; - } - - public String getPublishHost() - { - return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); - } - -} - - - +/* + * 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.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; + + + +/** + * Handles realAudio .it manages the ram file. + * + * 03.2002 - reworked Realmedia handling. -mh + * + * @see mir.media.MediaHandlerGeneric + * @see mir.media.MediaHandler + * @author john , mh + * @version $Id: MediaHandlerRealAudio.java,v 1.19.2.3 2003/12/21 13:32:05 zapata Exp $ + */ + + +public class MediaHandlerRealAudio extends MediaHandlerAudio implements MediaHandler +{ + public MediaHandlerRealAudio() { + logger = new LoggerWrapper("Media.Audio.Real"); + } + + public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure { + + // first see if the file exists + super.produce(ent, mediaTypeEnt); + + String baseName = ent.getId(); + String date = ent.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String rtspDir = configuration.getString("Producer.RealMedia.Path"); + String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); + + String RealMediaPointer = rtspMediaHost+ent.getValue("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"); + } + catch (Throwable e) { + logger.error("MediaHandlerRealAudio.produce: " + e.toString()); + throw new MediaFailure(e); + } + } + + public List getURL(Entity ent, Entity mediaTypeEnt) + { + List theList = new Vector(); + + //String stringSize = ent.getValue("size"); + //int size = Integer.parseInt(stringSize, 10)/1024; + theList.add(ent); + + String basePath=StringUtil.regexpReplace(ent.getValue("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() + { + return configuration.getString("Producer.RealMedia.Path"); + } + + public String getDescr(Entity mediaType) + { + return "RealMedia"; + } + + public String getPublishHost() + { + return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); + } + +} + + + diff --git a/source/mircoders/module/ModuleArticleType.java b/source/mircoders/module/ModuleArticleType.java index 9e52a298..85b1a1aa 100755 --- a/source/mircoders/module/ModuleArticleType.java +++ b/source/mircoders/module/ModuleArticleType.java @@ -29,11 +29,11 @@ */ package mircoders.module; -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; import mir.util.JDBCStringRoutines; public class ModuleArticleType extends AbstractModule { diff --git a/source/mircoders/module/ModuleComment.java b/source/mircoders/module/ModuleComment.java index b936159f..7e52745d 100755 --- a/source/mircoders/module/ModuleComment.java +++ b/source/mircoders/module/ModuleComment.java @@ -29,14 +29,14 @@ */ package mircoders.module; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; import mircoders.storage.DatabaseContent; diff --git a/source/mircoders/module/ModuleCommentStatus.java b/source/mircoders/module/ModuleCommentStatus.java index 9fe5142c..43b1c099 100755 --- a/source/mircoders/module/ModuleCommentStatus.java +++ b/source/mircoders/module/ModuleCommentStatus.java @@ -1,57 +1,57 @@ -/* - * 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.module; - -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; -import mir.util.JDBCStringRoutines; - -public class ModuleCommentStatus extends AbstractModule { - static LoggerWrapper logger = new LoggerWrapper("Module.CommentStatus"); - - public ModuleCommentStatus (StorageObject theStorage) { - if (theStorage == null) - logger.warn("ModuleCommentStatus -- StorageObject was null!"); - - this.theStorage = theStorage; - } - - public String commentStatusIdForName(String aName) throws ModuleExc, ModuleFailure { - try { - return theStorage.executeFreeSingleValueSql("select id from comment_status where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'"); - } - catch (Throwable t) { - throw new ModuleFailure(t); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.module; + +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; +import mir.util.JDBCStringRoutines; + +public class ModuleCommentStatus extends AbstractModule { + static LoggerWrapper logger = new LoggerWrapper("Module.CommentStatus"); + + public ModuleCommentStatus (StorageObject theStorage) { + if (theStorage == null) + logger.warn("ModuleCommentStatus -- StorageObject was null!"); + + this.theStorage = theStorage; + } + + public String commentStatusIdForName(String aName) throws ModuleExc, ModuleFailure { + try { + return theStorage.executeFreeSingleValueSql("select id from comment_status where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'"); + } + catch (Throwable t) { + throw new ModuleFailure(t); + } + } +} diff --git a/source/mircoders/module/ModuleContent.java b/source/mircoders/module/ModuleContent.java index e3cb48f1..ae16645c 100755 --- a/source/mircoders/module/ModuleContent.java +++ b/source/mircoders/module/ModuleContent.java @@ -18,24 +18,23 @@ * Foundation, Inc., 59 Temple Place, Suite 330, 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, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. * If you do not wish to do so, delete this exception statement from your version. */ package mircoders.module; -import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; import mir.storage.StorageObject; +import mir.util.JDBCStringRoutines; +import mircoders.global.*; /** * @@ -55,16 +54,85 @@ public class ModuleContent extends AbstractModule super(); } - public ModuleContent(StorageObject theStorage) { - this.theStorage = theStorage; + public ModuleContent(StorageObject aStorage) { + theStorage = aStorage; } - public EntityList getContent(String whereClause, String orderBy,int offset, int limit) throws ModuleExc, ModuleFailure { + public void expireArticleLock(String anId, String aUserId) { + if (!MirGlobal.isUserLoggedIn(anId)) { + unlockArticle(anId, aUserId, false); + } + } + + /** + * Locks an article. Forced (that is, without checking wether it's already locked) + * if necessary. + * + * @param anId The article number + * @param aUserId The locking user + * @param aForce Should it e forced? + * @return + */ + public boolean lockArticle(String anId, String aUserId, boolean aForce) { + try { + String query = + "update content set to_locking_user=" + JDBCStringRoutines.escapeStringLiteral(aUserId) + + " where id = " + JDBCStringRoutines.escapeStringLiteral(anId); + + if (!aForce) + query = query + " and to_locking_user is null"; + + return theStorage.executeUpdate(query) > 0; + } + catch (Throwable t) { + return false; + } + } + + /** + * Unlocks an article. Forced (that is, without checking wether it's locked by + * the person that unlocks it) if necessary. + * + * @param anId The article number + * @param aUserId The user that unlocks + * @param aForce Should it e forced? + * @return true if successfull, false if not + */ + public boolean unlockArticle(String anId, String aUserId, boolean aForce) { try { - return theStorage.selectByWhereClause(whereClause, orderBy, offset, limit); + String query = + "update content set to_locking_user=null" + + " where id = " + JDBCStringRoutines.escapeStringLiteral(anId); + + if (!aForce) + query = query + " and to_locking_user = "+JDBCStringRoutines.escapeStringLiteral(aUserId); + + return theStorage.executeUpdate(query) > 0; + } + catch (Throwable t) { + return false; + } + } + + /** + * Returns the id of the locking user of an article. null otherwise. + * + * @param anId + * @return + */ + public String queryArticleLock(String anId) { + try { + String result = theStorage.executeFreeSingleValueSql("select to_locking_user from content where id = " + JDBCStringRoutines.escapeStringLiteral(anId)); + + if (result!=null && !MirGlobal.isUserLoggedIn(result)) { + expireArticleLock(anId, result); + result = null; + } + + return result; } - catch (Throwable e){ - throw new ModuleFailure(e); + catch (Throwable t) { + return null; } } } diff --git a/source/mircoders/module/ModuleMediafolder.java b/source/mircoders/module/ModuleMediafolder.java index f9a2babe..287338ce 100755 --- a/source/mircoders/module/ModuleMediafolder.java +++ b/source/mircoders/module/ModuleMediafolder.java @@ -38,11 +38,11 @@ package mircoders.module; * @version */ -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; import mir.util.JDBCStringRoutines; diff --git a/source/mircoders/module/ModuleUsers.java b/source/mircoders/module/ModuleUsers.java index 7c0f3041..39cc7e13 100755 --- a/source/mircoders/module/ModuleUsers.java +++ b/source/mircoders/module/ModuleUsers.java @@ -55,12 +55,12 @@ public class ModuleUsers extends AbstractModule { static LoggerWrapper logger = new LoggerWrapper("Module.Users"); - public ModuleUsers(StorageObject theStorage) + public ModuleUsers(StorageObject aStorage) { - if (theStorage == null) + if (aStorage == null) logger.warn("ModuleUsers(): StorageObject was null!"); - this.theStorage = theStorage; + theStorage = aStorage; } /** @@ -84,10 +84,16 @@ public class ModuleUsers extends AbstractModule EntityList userList = getByWhereClause(whereString, -1); - if (userList != null && userList.getCount() == 1) - return (EntityUsers) userList.elementAt(0); - else - return null; + if (userList != null && userList.getCount() == 1) { + EntityUsers result = (EntityUsers) userList.elementAt(0); + + if (result.getValue("is_disabled") == null || + result.getValue("is_disabled").equals("0")) + return result; + + } + + return null; } catch (Throwable t) { throw new ModuleFailure(t); @@ -122,6 +128,14 @@ public class ModuleUsers extends AbstractModule return result; } + /** + * + * @param theValues + * @return + * @throws ModuleExc + * @throws ModuleFailure + */ + public String add (Map theValues) throws ModuleExc, ModuleFailure { try { return super.add(digestPassword(theValues)); @@ -132,10 +146,11 @@ public class ModuleUsers extends AbstractModule } /** - * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren - * @param theValues Hash mit Spalte/Wert-Paaren - * @return Id des eingef?gten Objekts - * @exception ModuleException + * + * @param theValues + * @return + * @throws ModuleExc + * @throws ModuleFailure */ public String set (Map theValues) throws ModuleExc, ModuleFailure { try { @@ -145,4 +160,15 @@ public class ModuleUsers extends AbstractModule throw new ModuleFailure(t); } } + + public void recordLogin(EntityUsers aUser) throws ModuleExc, ModuleFailure { + try { + String sql = "update webdb_users set lastlogin=now() where id = " + aUser.getId(); + + theStorage.executeUpdate(sql); + } + catch (Throwable t) { + throw new ModuleFailure(t); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleAdmin.java b/source/mircoders/servlet/ServletModuleAdmin.java index ac41a316..ccc81ece 100755 --- a/source/mircoders/servlet/ServletModuleAdmin.java +++ b/source/mircoders/servlet/ServletModuleAdmin.java @@ -72,7 +72,7 @@ public class ServletModuleAdmin extends ServletModule } public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) { - String startTemplate = configuration.getString("Mir.StartTemplate"); + String defaultStartTemplate = configuration.getString("Mir.StartTemplate"); String sessionUrl = aResponse.encodeURL(""); try { @@ -94,6 +94,10 @@ public class ServletModuleAdmin extends ServletModule mergeData.put("selectarticleurl", null); mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames()); + String startTemplate = MirGlobal.localizer().adminInterface().getAdminPageGenerator( + "admin.start", mergeData, + ServletHelper.getUserAdapter(aRequest), defaultStartTemplate); + ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate); } catch (Exception e) { diff --git a/source/mircoders/servlet/ServletModuleArticleType.java b/source/mircoders/servlet/ServletModuleArticleType.java index 63de8b3c..3073b8bf 100755 --- a/source/mircoders/servlet/ServletModuleArticleType.java +++ b/source/mircoders/servlet/ServletModuleArticleType.java @@ -1,64 +1,64 @@ -/* - * 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 mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleArticleType; -import mircoders.storage.DatabaseArticleType; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ -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 { - model = MirGlobal.localizer().dataModel().adapterModel(); - definition = "articleType"; - mainModule = new ModuleArticleType(DatabaseArticleType.getInstance()); - } - catch (Exception e) { - logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, 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 mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleArticleType; +import mircoders.storage.DatabaseArticleType; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ +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 { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "articleType"; + mainModule = new ModuleArticleType(DatabaseArticleType.getInstance()); + } + catch (Exception e) { + logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index ca659814..3a7a06b3 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -1,66 +1,66 @@ -/* - * 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 mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleBreaking; -import mircoders.storage.DatabaseBreaking; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -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 { - model = MirGlobal.localizer().dataModel().adapterModel(); - definition = "breakingNews"; - mainModule = new ModuleBreaking(DatabaseBreaking.getInstance()); - } - catch (Exception e) { - logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage()); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, 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 mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleBreaking; +import mircoders.storage.DatabaseBreaking; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +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 { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "breakingNews"; + mainModule = new ModuleBreaking(DatabaseBreaking.getInstance()); + } + catch (Exception e) { + logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage()); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index 7e8684af..4080dac1 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -54,7 +54,7 @@ import mir.util.JDBCStringRoutines; import mir.util.SQLQueryBuilder; import mir.util.StringRoutines; import mir.util.URLBuilder; -import mircoders.entity.EntityContent; +import mircoders.entity.*; import mircoders.global.MirGlobal; import mircoders.module.ModuleContent; import mircoders.storage.DatabaseContent; @@ -64,7 +64,7 @@ import mircoders.storage.DatabaseContentToTopics; * ServletModuleContent - * deliver html for the article admin form. * - * @version $Id: ServletModuleContent.java,v 1.52.2.12 2003/10/23 14:55:25 rk Exp $ + * @version $Id: ServletModuleContent.java,v 1.52.2.13 2003/12/21 13:32:06 zapata Exp $ * @author rk, mir-coders * */ @@ -73,6 +73,7 @@ public class ServletModuleContent extends ServletModule { private static ServletModuleContent instance = new ServletModuleContent(); public static ServletModule getInstance() { return instance; } + private static ModuleContent contentModule; private ServletModuleContent() { super(); @@ -80,7 +81,8 @@ public class ServletModuleContent extends ServletModule logger = new LoggerWrapper("ServletModule.Content"); try { - mainModule = new ModuleContent(DatabaseContent.getInstance()); + contentModule = new ModuleContent(DatabaseContent.getInstance()); + mainModule = contentModule; } catch (Throwable e) { logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); @@ -157,10 +159,8 @@ public class ServletModuleContent extends ServletModule editObject(aRequest, aResponse, null); } - public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { -//theLog.printDebugInfo(":: content :: trying to insert"); try { Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); @@ -200,7 +200,10 @@ public class ServletModuleContent extends ServletModule editObject(aRequest, aResponse, idParam); } -// methods for attaching media file + /** + * Attaches media to an article + * + */ public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String mediaIdParam = aRequest.getParameter("mid"); @@ -209,6 +212,9 @@ public class ServletModuleContent extends ServletModule if (articleId == null || mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: articleid/mid missing"); + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + try { EntityContent entContent = (EntityContent) mainModule.getById(articleId); entContent.attach(mediaIdParam); @@ -222,6 +228,9 @@ public class ServletModuleContent extends ServletModule editObject(aRequest, aResponse, articleId); } + /** + * Deattaches media from an article + */ public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String articleId = aRequest.getParameter("articleid"); @@ -231,6 +240,9 @@ public class ServletModuleContent extends ServletModule if (midParam == null) throw new ServletModuleExc("smod content :: dettach :: mid missing"); + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + try { EntityContent entContent = (EntityContent)mainModule.getById(articleId); entContent.dettach(articleId, midParam); @@ -244,6 +256,78 @@ public class ServletModuleContent extends ServletModule editObject(aRequest, aResponse, articleId); } + /** + * Locks an article + */ + public void lock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) + throw new ServletModuleExc("Unable to lock"); + + contentModule.lockArticle(idParam, user.getId(), false); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Unlocks an article + */ + public void unlock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) + throw new ServletModuleExc("Unable to unlock"); + + contentModule.unlockArticle(idParam, user.getId(), false); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Forcelocks an article + */ + public void forcelock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayForceLockArticle(user, idParam)) + throw new ServletModuleExc("Unable to force lock"); + + contentModule.lockArticle(idParam, user.getId(), true); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Stores an article + */ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { try { @@ -255,6 +339,9 @@ public class ServletModuleContent extends ServletModule if (idParam == null) throw new ServletModuleExc("Wrong call: (id) is missing"); + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) + throw new ServletModuleExc("Article has been locked"); + Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); String content_id = aRequest.getParameter("id"); @@ -275,11 +362,12 @@ public class ServletModuleContent extends ServletModule DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic")); - if (returnUrl!=null && !returnUrl.equals("")){ - redirect(aResponse, returnUrl); + if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) && + (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) { + contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false); } - else - editObject(aRequest, aResponse, idParam); + + editObject(aRequest, aResponse, idParam); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -288,15 +376,10 @@ public class ServletModuleContent extends ServletModule /** - * HelperMethod shows the basic article editing form. - * - * if the "id" parameter is null, it means show an empty form to add a new - * article. + * Returns the basic article editing form. * - * @param id - * @param aRequest - * @param aResponse - * @throws ServletModuleExc + * @param id identifier of the article. null, means show an + * empty form to add a new article. */ public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id) throws ServletModuleExc { @@ -315,6 +398,13 @@ public class ServletModuleContent extends ServletModule if (id!=null) { responseData.put("new", Boolean.FALSE); article = model.makeEntityAdapter("content", mainModule.getById(id)); + + 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))); } else { List fields = DatabaseContent.getInstance().getFields(); @@ -328,6 +418,11 @@ public class ServletModuleContent extends ServletModule article.put("to_topics", null); MirGlobal.localizer().adminInterface().initializeArticle(article); + + responseData.put("mayEdit", Boolean.TRUE); + responseData.put("mayLock", Boolean.FALSE); + responseData.put("mayForceLock", Boolean.FALSE); + responseData.put("mayUnlock", Boolean.FALSE); } responseData.put("article", article); @@ -521,6 +616,9 @@ public class ServletModuleContent extends ServletModule String parentId = aRequest.getParameter("id"); String returnUrl = aRequest.getParameter("returnurl"); + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + try { EntityContent article = (EntityContent) mainModule.getById(articleId); article.setValueForProperty("to_content", parentId); diff --git a/source/mircoders/servlet/ServletModuleLocalizer.java b/source/mircoders/servlet/ServletModuleLocalizer.java index c880b125..d6cd2088 100755 --- a/source/mircoders/servlet/ServletModuleLocalizer.java +++ b/source/mircoders/servlet/ServletModuleLocalizer.java @@ -92,10 +92,19 @@ public class ServletModuleLocalizer extends ServletModule { catch (Exception e) { logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage()); } - - } + /** + * Performs a localizer operation on an article. + * + * See also + * {@link mircoders.localizer.MirAdminInterfaceLocalizer#simpleArticleOperations()} + * {@link mircoders.localizer.MirAdminInterfaceLocalizer$MirSimpleEntityOperation()} + * + * @param aRequest The originating request + * @param anId The id of the article + * @param anOperation The identifier of the operation to perform + */ public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) { MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; EntityAdapter comment; @@ -166,7 +175,7 @@ public class ServletModuleLocalizer extends ServletModule { if (entity != null) { MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation); logger.info("Operation " + anOperation + " successfully performed on article " + anId); - logAdminUsage(aRequest, "article."+anId, "operation " + anOperation + " performed"); + logAdminUsage(aRequest, "article." + anId, "operation " + anOperation + " performed"); } else { logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null"); diff --git a/source/mircoders/servlet/ServletModuleUsers.java b/source/mircoders/servlet/ServletModuleUsers.java index 51279ec6..5c2d9f8c 100755 --- a/source/mircoders/servlet/ServletModuleUsers.java +++ b/source/mircoders/servlet/ServletModuleUsers.java @@ -119,8 +119,8 @@ public class ServletModuleUsers extends ServletModule { if ( (aRequestParser.getParameter("newpassword") != null && aRequestParser.getParameter("newpassword").length() > 0) || - (aRequestParser.getParameter("newpassword2") != null && - aRequestParser.getParameter("newpassword2").length() > 0) + (aRequestParser.getParameter("newpassword2") != null && + aRequestParser.getParameter("newpassword2").length() > 0) ) { String newPassword = aRequestParser.getParameterWithDefault("newpassword", ""); String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", ""); @@ -190,6 +190,8 @@ public class ServletModuleUsers extends ServletModule Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); if (!withValues.containsKey("is_admin")) withValues.put("is_admin","0"); + if (!withValues.containsKey("is_disabled")) + withValues.put("is_disabled","0"); String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); if (newPassword!=null) diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index d6ed1826..f7936be1 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -39,11 +39,11 @@ package mircoders.storage; * @version 1.0 */ -import java.util.List; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.util.List; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; public class DatabaseArticleType extends Database implements StorageObject{ diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index 56f3e336..ba675791 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -30,13 +30,13 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; /** diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index 7cd02d85..7fe19ef8 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -39,9 +39,9 @@ package mircoders.storage; * @version 1.0 */ -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; diff --git a/source/mircoders/storage/DatabaseContent.java b/source/mircoders/storage/DatabaseContent.java index b28c5e0c..6d172732 100755 --- a/source/mircoders/storage/DatabaseContent.java +++ b/source/mircoders/storage/DatabaseContent.java @@ -30,12 +30,12 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.Statement; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.sql.Connection; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; /** diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index bbf37db6..cb364bf5 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 26f2a8d8..76a3f290 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index 641f9035..2e517d51 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index a924eb59..87e30008 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -1,63 +1,63 @@ -/* - * 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; -import mir.storage.StorageObject; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class DatabaseImageType extends Database implements StorageObject{ - private static DatabaseImageType instance; - - public synchronized static DatabaseImageType getInstance() { - if (instance == null) { - instance = new DatabaseImageType(); - } - return instance; - } - - private DatabaseImageType() { - super(); - logger = new LoggerWrapper("Database.ImageType"); - - hasTimestamp = false; - theTable = "img_type"; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseImageType extends Database implements StorageObject{ + private static DatabaseImageType instance; + + public synchronized static DatabaseImageType getInstance() { + if (instance == null) { + instance = new DatabaseImageType(); + } + return instance; + } + + private DatabaseImageType() { + super(); + logger = new LoggerWrapper("Database.ImageType"); + + hasTimestamp = false; + theTable = "img_type"; + } +} diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index a1ed74da..7595fd03 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -1,93 +1,93 @@ -/* - * 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; - -/** - * Title: DatabaseLanguage - * Description: - * Copyright: Copyright (c) 2001 - * Company: Indymedia - * @author - * @version 1.0 - */ - -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; - - -public class DatabaseLanguage extends Database implements StorageObject{ - 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 { - if (instance == null) { - instance = new DatabaseLanguage(); - } - return instance; - } - - private DatabaseLanguage() throws StorageObjectFailure { - super(); - logger = new LoggerWrapper("Database.Language"); - - this.hasTimestamp = false; - this.theTable = "language"; - } - - public List getPopupData() throws StorageObjectFailure { - List result = new Vector(); - Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0); - - while (i.hasNext()) { - Entity e = (Entity) i.next(); - Map entry = new HashMap(); - entry.put("key", e.getId()); - entry.put("value", e.getValue("name")); - - result.add(entry); - } - - return result; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +/** + * Title: DatabaseLanguage + * Description: + * Copyright: Copyright (c) 2001 + * Company: Indymedia + * @author + * @version 1.0 + */ + +import 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; + + +public class DatabaseLanguage extends Database implements StorageObject{ + 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 { + if (instance == null) { + instance = new DatabaseLanguage(); + } + return instance; + } + + private DatabaseLanguage() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Language"); + + this.hasTimestamp = false; + this.theTable = "language"; + } + + public List getPopupData() throws StorageObjectFailure { + List result = new Vector(); + Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0); + + while (i.hasNext()) { + Entity e = (Entity) i.next(); + Map entry = new HashMap(); + entry.put("key", e.getId()); + entry.put("value", e.getValue("name")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseMediafolder.java b/source/mircoders/storage/DatabaseMediafolder.java index aaccbe4c..3e967084 100755 --- a/source/mircoders/storage/DatabaseMediafolder.java +++ b/source/mircoders/storage/DatabaseMediafolder.java @@ -1,59 +1,59 @@ -/* - * 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; -import mir.storage.StorageObject; - -public class DatabaseMediafolder extends Database implements StorageObject{ - private static DatabaseMediafolder instance; - - public synchronized static DatabaseMediafolder getInstance() { - if (instance == null) { - instance = new DatabaseMediafolder(); - } - return instance; - } - - private DatabaseMediafolder() { - super(); - - logger = new LoggerWrapper("Database.Mediafolder"); - - hasTimestamp = false; - theTable="media_folder"; - } -} +/* + * 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; +import mir.storage.StorageObject; + +public class DatabaseMediafolder extends Database implements StorageObject{ + private static DatabaseMediafolder instance; + + public synchronized static DatabaseMediafolder getInstance() { + if (instance == null) { + instance = new DatabaseMediafolder(); + } + return instance; + } + + private DatabaseMediafolder() { + super(); + + logger = new LoggerWrapper("Database.Mediafolder"); + + hasTimestamp = false; + theTable="media_folder"; + } +} diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index 712f542f..167ba857 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -1,97 +1,97 @@ -/* - * 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 java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class DatabaseOther extends Database implements StorageObject{ - private static DatabaseOther instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseOther getInstance() { - if (instance == null) { - instance = new DatabaseOther(); - } - return instance; - } - - private DatabaseOther() { - super(); - - logger = new LoggerWrapper("Database.OtherMedia"); - - hasTimestamp = true; - theTable = "other_media"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityOther.class; - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.storage; + + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseOther extends Database implements StorageObject{ + private static DatabaseOther instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseOther getInstance() { + if (instance == null) { + instance = new DatabaseOther(); + } + return instance; + } + + private DatabaseOther() { + super(); + + logger = new LoggerWrapper("Database.OtherMedia"); + + hasTimestamp = true; + theTable = "other_media"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityOther.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index 95f5df8b..e18e92eb 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -1,91 +1,91 @@ -/* - * 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 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; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class DatabaseTopics extends Database implements StorageObject{ - private static DatabaseTopics instance; - - public synchronized static DatabaseTopics getInstance() { - if (instance == null) { - instance = new DatabaseTopics(); - } - return instance; - } - - private DatabaseTopics() throws StorageObjectFailure { - super(); - - logger = new LoggerWrapper("Database.Topics"); - - hasTimestamp = false; - theTable = "topic"; - theEntityClass = mircoders.entity.EntityTopics.class; - } - - public List getPopupData() throws StorageObjectFailure { - List result = new Vector(); - Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0); - - while (i.hasNext()) { - Entity e = (Entity) i.next(); - Map entry = new HashMap(); - entry.put("key", e.getId()); - entry.put("value", e.getValue("title")); - - result.add(entry); - } - - return result; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.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; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseTopics extends Database implements StorageObject{ + private static DatabaseTopics instance; + + public synchronized static DatabaseTopics getInstance() { + if (instance == null) { + instance = new DatabaseTopics(); + } + return instance; + } + + private DatabaseTopics() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Topics"); + + hasTimestamp = false; + theTable = "topic"; + theEntityClass = mircoders.entity.EntityTopics.class; + } + + public List getPopupData() throws StorageObjectFailure { + List result = new Vector(); + Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0); + + while (i.hasNext()) { + Entity e = (Entity) i.next(); + Map entry = new HashMap(); + entry.put("key", e.getId()); + entry.put("value", e.getValue("title")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index 8c2000f0..8c4e0bc0 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -30,13 +30,13 @@ package mircoders.storage; -import java.util.Iterator; - -import mir.entity.Entity; -import mir.entity.EntityBrowser; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.util.Iterator; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; public class DatabaseUploadedMedia extends Database implements StorageObject { diff --git a/templates/admin/EDITFUNCTIONS.template b/templates/admin/EDITFUNCTIONS.template index 0d4c7fff..5a374a90 100755 --- a/templates/admin/EDITFUNCTIONS.template +++ b/templates/admin/EDITFUNCTIONS.template @@ -81,7 +81,16 @@ checked>   + + + + ${lang("yes")}${lang("no")}   + + + + + diff --git a/templates/admin/FUNCTIONS.template b/templates/admin/FUNCTIONS.template index e2b84e25..ff59dcb0 100755 --- a/templates/admin/FUNCTIONS.template +++ b/templates/admin/FUNCTIONS.template @@ -112,6 +112,27 @@

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

+ + + + + + + + + + + + ${label}: + + + + ${lang(langprefix+a[valuefield])}${a[valuefield]} + + + + + @@ -127,13 +148,26 @@ + + + + + + + + + + - - - - + + + + + + + @@ -147,13 +181,13 @@ - + ${label}: - + ${utility.encodeHTML(fieldcontent)} @@ -185,19 +219,38 @@ - + + + + + + + + + + + + + + + + + + ${label}: + +
+ ${hint} +
- checked>   + ${utility.prettyEncodeHTML(fieldcontent)} - -
- +
@@ -357,15 +410,15 @@ functions to show media for an article/comment edit page - - + + - + - + @@ -385,40 +438,47 @@ ${lang("content.images")}: - - [+] ${lang("content.addimage")} | - ${lang("content.uploadimage")} - + + + [+] ${lang("content.addimage")} | + ${lang("content.uploadimage")} + + edit  - - [-] ${lang("delete")} - + + + [-] ${lang("delete")} + + - ${lang("content.audio")}: - - [+] ${lang("content.addaudio")} | - ${lang("content.uploadaudio")} - + + + [+] ${lang("content.addaudio")} | + ${lang("content.uploadaudio")} + + edit  - - [-] ${lang("delete")} - + + + [-] ${lang("delete")} + + @@ -427,39 +487,48 @@ ${lang("content.video")}: - - [+] ${lang("content.addvideo")} | - ${lang("content.uploadvideo")} - + + + [+] ${lang("content.addvideo")} | + ${lang("content.uploadvideo")} + + edit  - - [-] ${lang("delete")} - + + + [-] ${lang("delete")} + + + ${lang("content.other")}: - - [+] ${lang("content.addother")} | - ${lang("content.uploadother")} - + + + [+] ${lang("content.addother")} | + ${lang("content.uploadother")} + + edit  - - [-] ${lang("delete")} - + + + [-] ${lang("delete")} + + diff --git a/templates/admin/FUNCTIONS_media.template b/templates/admin/FUNCTIONS_media.template index eea0e7ee..70ec3e1d 100755 --- a/templates/admin/FUNCTIONS_media.template +++ b/templates/admin/FUNCTIONS_media.template @@ -7,64 +7,64 @@ -
- - - - - - - - - - - - - - - - - - - - - + + + + + +
${lang("search")}:${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: [+] ${lang("add")}
- - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - -
${lang("search")}:${lang("medialist.search_text_in")}:${lang("media.published")}:${lang("media.mediafolder")}: [+] ${lang("add")}
+ + + + + + + - - - - - -   -
- - - +
+ + +   +
+ + + diff --git a/templates/admin/comment.template b/templates/admin/comment.template index 0c727513..6b1c7a68 100755 --- a/templates/admin/comment.template +++ b/templates/admin/comment.template @@ -89,6 +89,7 @@ + diff --git a/templates/admin/commentlist.template b/templates/admin/commentlist.template index 229f7568..30d7c090 100755 --- a/templates/admin/commentlist.template +++ b/templates/admin/commentlist.template @@ -91,6 +91,9 @@ ${lang("comment.article")} / ${lang("comment.title")} / ${lang("comment.creator")} / ${lang("comment.text")} + ${lang("comment.comment")} + +   @@ -141,7 +144,7 @@ ${lang("by")}: ${entry.creator}
- ${utility.encodeHTML(entry.description)} + ${utility.prettyEncodeHTML(entry.description)}
URL: ${entry.main_url}

@@ -170,6 +173,9 @@ + ${utility.prettyEncodeHTML(entry.comment)} + +   [${lang("delete")}] diff --git a/templates/admin/content.template b/templates/admin/content.template index b28ec630..5f97cccd 100755 --- a/templates/admin/content.template +++ b/templates/admin/content.template @@ -9,6 +9,52 @@ + + + + + + +
+ + + + ${lang("content.lockedby", article.lockinguser.login)} + + + +
+ + + + + +
+
+ +
+ + + + + +
+
+ +
+ + + + + +
+
+
+
+ +
@@ -18,39 +64,37 @@ +
- - - ${lang("content.published")} : - checked> - - + + checked> + + + + + - + ${lang("yes")}${lang("no")}
- - - - + + - - - - + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + - - - + + + + +
+ id # : @@ -72,140 +116,149 @@ ${lang("content.create_date")}: - ${utility.encodeHTML(article.creationdate.format(config["Mir.DefaultDateTimeFormat"]))}
${lang("edit")}: -   (yyyy-mm-dd [HH:mm]) + ${utility.encodeHTML(article.creationdate.format(config["Mir.DefaultDateTimeFormat"]))} + +
${lang("edit")}: +   (yyyy-mm-dd [HH:mm]) +
- ${lang(r.key)}: - - - - - - - - - - - - - - - - + + + -
- checked> - ${t.title} - -   -
+ ${lang(r.key)}: + + + + + + + + + + + + + + + + + + + +
+ checked> + ${t.title} + +   +
+ + + + + -
- - - + - + + ${t.title}
+
- -
- - - - - -
+ + + + + +
- - - - - - - -
- - - - - - +
- ${lang("content.family")} -
+ - - - + - - +
- ${lang("content.parent")}: - - - ${utility.encodeHTML(article.parent.title)}
- ${lang("content.viewparent")} | - ${lang("content.clearparent")} | -
-  ${lang("content.selectparent")} -
-
- ${lang("content.children")}: - - ${lang("content.viewchildren")} + + + + + + + + + + + + + + +
+ ${lang("content.family")} +
+ ${lang("content.parent")}: + + + ${utility.encodeHTML(article.parent.title)}
+ ${lang("content.viewparent")} | + ${lang("content.clearparent")} | +
+ +  ${lang("content.selectparent")} + +
+ ${lang("content.children")}: + + ${lang("content.viewchildren")} +
+
+
-
- -
-
- - + + + diff --git a/templates/admin/start_admin.template b/templates/admin/start_admin.template index 5e5a86fa..958b6c91 100755 --- a/templates/admin/start_admin.template +++ b/templates/admin/start_admin.template @@ -11,7 +11,7 @@ -
+

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

@@ -58,7 +58,7 @@ Middle column -

+

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

@@ -139,7 +139,7 @@ RIGHT COLUMN -
+ internal messageboard diff --git a/templates/admin/user.template b/templates/admin/user.template index ddef833c..399a7da2 100755 --- a/templates/admin/user.template +++ b/templates/admin/user.template @@ -9,51 +9,61 @@ -
- - - - - - - - - - - + + + + + + + + + + + + - - - + + - - + + + + + + - - + + + - + - + + + + + - - - -
- - - - - - - -
- - - + + + + + + + + + + + - + + + + + diff --git a/templates/admin/usererror.template b/templates/admin/usererror.template index 4409c367..3b7bc0ce 100755 --- a/templates/admin/usererror.template +++ b/templates/admin/usererror.template @@ -1,37 +1,19 @@ - -${lang("usererror.htmltitle")} - - - - - - - - - - - - - - - - -
-

${lang("usererror.title")}

-
-
-

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

-

-

${data.errorstring} -

-

-

-

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

-

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

${lang("usererror.title")}

+


${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${errorstring}

+

${lang("usererror.what_to_do")}

+ +
+ + + diff --git a/templates/admin/userlist.template b/templates/admin/userlist.template index c97ebfb1..aaecaebb 100755 --- a/templates/admin/userlist.template +++ b/templates/admin/userlist.template @@ -7,17 +7,61 @@ + - - - - - - + + + + + + + + + + + + + + + + + + +

${lang("no_matches_found")}

+
-

${lang("no_matches_found")}

+ + + + + + + + +

${lang("no_matches_found")}

+
-- 2.11.0