compiles.. but I actually think it is good.
+++ /dev/null
-#
-#
-# This scpript can be copied to build.post and is automatically
-# executed after execution of build.sh
-# For expamples rsyncing the web-app to another server
-#
-
-
-
-
LIB_HOME=lib
TOMCAT_HOME=/usr/share/tomcat
-CP=$LIB_HOME/servlet.jar
+CP=$LIB_HOME/servlet-2.2.jar
CP=$CP:$ANT_HOME/ant.jar:$ANT_HOME/xerces.jar
CP=$CP:$LOCALCLASSPATH
CP=$CP:$TOMCAT_HOME/lib/tomcat.jar
CP=$CP:$JAVA_HOME/lib/tools.jar
CP=$CP:$JAVA_HOME/lib/rt.jar
CP=$CP:$LIB_HOME/strutsmesg.jar
+CP=$CP:$LIB_HOME/poolman.jar
+CP=$CP:$LIB_HOME/log4j.jar
+CP=$CP:$LIB_HOME/jdbc-se2.0.jar
+CP=$CP:$LIB_HOME/postgresql.jar
# The path to ANT
#ANT_HOME=/usr/share/ant/lib # use own ant
$JAVA_HOME/bin/java -classpath $CP:$CLASSPATH org.apache.tools.ant.Main \
-Dtomcat.home=$TOMCAT_HOME "$@"
-
-#
-# execute postbuild script if present
-
-if [ -f ./build.post ]; then
- echo "Executing build.post"
- sh build.post
-fi
-
+# Set permissions correctly
+./perms.sh-dist
<property name="dist.src" value="${app.name}.jar"/>
<property name="dist.war" value="${app.name}.war"/>
<property name="javadoc.home" value="${deploy.home}/javadoc"/>
- <property name="build.compiler" value="jikes"/>
<!-- The "prepare" target is used to construct the deployment home
<copy todir="${deploy.home}/WEB-INF/classes">
<fileset dir="source" includes="**/*.properties"/>
</copy>
+ <copy todir="${deploy.home}/WEB-INF/classes">
+ <fileset dir="source" includes="**/*.xml"/>
+ </copy>
<copy todir="${deploy.home}">
<fileset dir="source" includes="**/content-types.properties"/>
- <fileset dir="source" includes="**/server.xml"/>
</copy>
</target>
--- /dev/null
+<project name="Mir" default="compile" basedir=".">
+
+
+<!-- What this file is all about
+
+ You can use this version of build.xml to use directly with ant
+ i.e. without the build.sh script. Simply call ant and let it all
+ happen.
+-->
+
+<!-- Property Definitions
+ app.name Base name of this application, used to
+ construct filenames and directories.
+
+ deploy.home The name of the directory into which the
+ deployment hierarchy will be created.
+ Normally, this will be the name of a
+ subdirectory under $TOMCAT_HOME/webapps.
+
+ dist.home The name of the base directory in which
+ distribution files are created.
+
+ dist.src The name of the distribution JAR file
+ containing the application source code,
+ to be stored in the "dist.home" directory.
+ This filename should end with ".jar".
+
+ dist.war The name of the Web ARchive (WAR) file
+ containing our deployable application.
+ This filename should end with ".war".
+
+ javadoc.home The name of the base directory in which
+ the JavaDoc documentation for this application
+ is generated.
+
+ tomcat.home The name of the base directory in which
+ Tomcat has been installed. This value is
+ normally set automatically from the value
+ of the TOMCAT_HOME environment variable.
+
+ java.home The location of your Java SDK.
+
+ java.localhome Where your local java classes and jar files
+ are located.
+
+ tomcat.home The location of the tomcat root directory.
+
+-->
+
+ <property name="app.name" value="Mir"/>
+ <property name="deploy.home" value="../${app.name}"/>
+ <property name="dist.home" value="${deploy.home}"/>
+ <property name="dist.src" value="${app.name}.jar"/>
+ <property name="dist.war" value="${app.name}.war"/>
+ <property name="javadoc.home" value="${deploy.home}/javadoc"/>
+
+ <property name="java.home" value="/usr/lib/j2sdk1.3/"/>
+ <property name="java.localhome" value="/usr/share/java/"/>
+ <property name="tomcat.home" value="/usr/share/tomcat/"/>
+
+
+ <!-- Construct the classpath -->
+ <path id="project.class.path">
+ <pathelement path="${deploy.home}"/>
+ <pathelement path="${deploy.home}/WEB-INF/classes"/>
+ <pathelement path="source"/>
+ <fileset dir="lib">
+ <include name="*.jar"/>
+ </fileset>
+ <fileset dir="${java.home}/lib">
+ <include name="tools.jar"/>
+ <include name="rt.jar"/>
+ </fileset>
+ <fileset dir="${java.localhome}">
+ <include name="*.jar"/>
+ </fileset>
+ <pathelement path="${tomcat.home}/lib/tomcat.jar"/>
+ </path>
+
+
+
+<!-- The "prepare" target is used to construct the deployment home
+ directory structure (if necessary), and to copy in static files
+ as required. In the example below, Ant is instructed to create
+ the deployment directory, copy the contents of the "web/" source
+ hierarchy, and set up the WEB-INF subdirectory appropriately.
+-->
+
+ <target name="prepare">
+ <mkdir dir="${deploy.home}"/>
+ <copy todir="${deploy.home}">
+ <fileset dir="web"/>
+ </copy>
+ <mkdir dir="${deploy.home}/templates"/>
+ <copy todir="${deploy.home}/templates">
+ <fileset dir="templates"/>
+ </copy>
+ <mkdir dir="${deploy.home}/src"/>
+ <copy todir="${deploy.home}/src">
+ <fileset dir="source"/>
+ </copy>
+
+ <mkdir dir="${deploy.home}/WEB-INF"/>
+ <copy file="etc/web.xml" tofile="${deploy.home}/WEB-INF/web.xml"/>
+ <mkdir dir="${deploy.home}/WEB-INF/classes"/>
+ <mkdir dir="${deploy.home}/WEB-INF/lib"/>
+ <copy todir="${deploy.home}/WEB-INF/lib">
+ <fileset dir="lib">
+ <exclude name="ant.jar"/>
+ <exclude name="xerces.jar"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${javadoc.home}"/>
+ <mkdir dir="${deploy.home}/log"/>
+
+ </target>
+
+
+<!-- The "clean" target removes the deployment home directory structure,
+ so that the next time the "compile" target is requested, it will need
+ to compile everything from scratch.
+-->
+
+
+ <target name="clean">
+ <delete dir="${deploy.home}"/>
+ </target>
+
+
+<!-- The "compile" target is used to compile (or recompile) the Java classes
+ that make up this web application. The recommended source code directory
+ structure makes this very easy because the <javac> task automatically
+ works its way down a source code hierarchy and compiles any class that
+ has not yet been compiled, or where the source file is newer than the
+ class file.
+
+ Feel free to adjust the compilation option parameters (debug,
+ optimize, and deprecation) to suit your requirements. It is also
+ possible to base them on properties, so that you can adjust this
+ behavior at runtime.
+
+ The "compile" task depends on the "prepare" task, so the deployment
+ home directory structure will be created if needed the first time.
+-->
+
+ <target name="compile" depends="prepare">
+ <javac srcdir="source" destdir="${deploy.home}/WEB-INF/classes"
+ debug="on" optimize="off" deprecation="on">
+ <classpath refid="project.class.path"/>
+ </javac>
+ <copy todir="${deploy.home}/WEB-INF/classes">
+ <fileset dir="source" includes="**/*.properties"/>
+ </copy>
+ <copy todir="${deploy.home}">
+ <fileset dir="source" includes="**/content-types.properties"/>
+ </copy>
+ <echo>
+ Now you should call perms.sh(-dist) in order to set
+ the permissions of your installed files to a meaningful
+ value.
+ Have fun with Mir!
+ </echo>
+ </target>
+
+
+<!-- The "javadoc" target is used to create the Javadoc API documentation
+ for the Java classes in this web application. It is assumed that
+ this documentation is included in the deployed application, so the
+ example below generates the Javadoc HTML files in a subdirectory under
+ the deployment home directory. Feel free to customize the options for
+ the JavaDoc task, after consulting the Ant documentation.
+-->
+
+ <target name="javadoc" depends="prepare">
+ <javadoc packagenames="mir.*, mircoders.*"
+ sourcefiles="source/${app.name}.java,source/Open${app.name}.java"
+ sourcepath="source"
+ destdir="${javadoc.home}">
+ <classpath refid="project.class.path"/>
+ </javadoc>
+ </target>
+
+
+<!-- The "all" target rebuilds everything by executing the "clean"
+ target first, which forces the "compile" target to compile all
+ source code instead of just the files that have been changed.
+-->
+
+ <target name="all" depends="clean,prepare,compile,javadoc"/>
+
+
+<!-- The "dist" target builds the distribution Web ARchive (WAR) file
+ for this application, suitable for distribution to sites that wish
+ to install your application. It also creates a JAR file containing
+ the source code for this application, if you wish to distribute
+ that separately.
+-->
+ <target name="dist" depends="prepare,compile">
+ <jar jarfile="mirbase.jar"
+ includes="mir/**"
+ basedir="../Mir/WEB-INF/classes"/>
+ <jar jarfile="${dist.src}"
+ basedir="./source"/>
+ <jar jarfile="${dist.war}"
+ basedir="${deploy.home}"/>
+ </target>
+
+</project>
--- /dev/null
+#!/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(<DUMP>) {
+# 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
+#
+
+
+
--
\connect - postgres
--
--- TOC Entry ID 2 (OID 28714)
+-- TOC Entry ID 2 (OID 19796)
--
-- Name: media_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "media_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 3 (OID 28733)
+-- TOC Entry ID 3 (OID 19815)
--
-- Name: media_folder_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "media_folder_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 5 (OID 28771)
+-- TOC Entry ID 4 (OID 19834)
--
-- Name: feature_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "feature_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 6 (OID 28790)
+-- TOC Entry ID 5 (OID 19853)
--
-- Name: topic_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "topic_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 7 (OID 28809)
+-- TOC Entry ID 6 (OID 19872)
--
-- Name: webdb_users_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "webdb_users_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 8 (OID 28828)
+-- TOC Entry ID 7 (OID 19891)
--
-- Name: comment_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "comment_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 9 (OID 28847)
+-- TOC Entry ID 8 (OID 19910)
--
-- Name: breaking_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "breaking_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 10 (OID 28866)
+-- TOC Entry ID 9 (OID 19929)
--
-- Name: messages_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "messages_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 10 (OID 28866)
+-- TOC Entry ID 10 (OID 19948)
--
-- Name: media_type_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "media_type_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 12 (OID 28885)
+-- TOC Entry ID 12 (OID 19967)
--
-- Name: media_folder Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 13 (OID 28918)
+-- TOC Entry ID 13 (OID 20000)
--
-- Name: media_type Type: TABLE Owner: postgres
--
CREATE TABLE "media_type" (
- "id" integer DEFAULT nextval('media_type_id_seq'::text) NOT NULL,
+ "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,
);
--
--- TOC Entry ID 14 (OID 28932)
+-- TOC Entry ID 14 (OID 20016)
--
-- Name: img_format Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 15 (OID 28946)
+-- TOC Entry ID 15 (OID 20030)
--
-- Name: img_layout Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 16 (OID 28957)
+-- TOC Entry ID 16 (OID 20041)
--
-- Name: img_type Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 17 (OID 28968)
+-- TOC Entry ID 17 (OID 20052)
--
-- Name: img_color Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 18 (OID 28979)
+-- TOC Entry ID 18 (OID 20063)
--
-- Name: language Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 19 (OID 28994)
+-- TOC Entry ID 19 (OID 20078)
--
-- Name: rights Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 21 (OID 29043)
+-- TOC Entry ID 20 (OID 20108)
--
-- Name: feature Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 22 (OID 29078)
+-- TOC Entry ID 21 (OID 20143)
--
-- Name: webdb_users Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 23 (OID 29096)
+-- TOC Entry ID 22 (OID 20161)
--
-- Name: content_x_topic Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 24 (OID 29107)
+-- TOC Entry ID 23 (OID 20172)
--
-- Name: article_type Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 25 (OID 29118)
+-- TOC Entry ID 24 (OID 20183)
--
-- Name: topic Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 26 (OID 29154)
+-- TOC Entry ID 25 (OID 20219)
--
-- Name: comment Type: TABLE Owner: postgres
--
"to_language" integer DEFAULT '0' NOT NULL,
"to_media" integer NOT NULL,
"to_comment_status" smallint,
- "checksum" integer,
+ "checksum" integer,
Constraint "comment_pkey" Primary Key ("id")
);
-CREATE INDEX comment_checksum_index ON comment (checksum);
-
--
--- TOC Entry ID 27 (OID 29196)
+-- TOC Entry ID 26 (OID 20266)
--
-- Name: media Type: TABLE Owner: postgres
--
"subtitle" character varying(30),
"edittitle" character varying(30),
"date" character(8) NOT NULL,
- "place" character varying(80),
"creator" character varying(80),
"creator_main_url" character varying(255),
"creator_email" character varying(80),
);
--
--- TOC Entry ID 28 (OID 29257)
---
--- Name: images Type: TABLE Owner: postgres
---
-
---
--- TOC Entry ID 32 (OID 29446)
+-- TOC Entry ID 27 (OID 20326)
--
-- Name: uploaded_media Type: TABLE Owner: postgres
--
CREATE TABLE "uploaded_media" (
"icon_is_produced" boolean DEFAULT '0' NOT NULL,
"icon_path" character varying(255),
- "size" integer
-) INHERITS ("media");
+ "size" integer
+)
+INHERITS ("media");
+
+--
+-- TOC Entry ID 28 (OID 20392)
+--
+-- Name: images Type: TABLE Owner: postgres
+--
CREATE TABLE "images" (
"image_data" oid,
"icon_data" oid,
- "icon_is_produced" boolean DEFAULT '0' NOT NULL,
- "icon_path" character varying(255),
"year" character varying(40),
"img_width" smallint,
"img_height" smallint,
"icon_width" smallint,
"icon_height" smallint
)
-INHERITS ("media");
+INHERITS ("uploaded_media");
--
--- TOC Entry ID 29 (OID 29338)
+-- TOC Entry ID 29 (OID 20474)
--
-- Name: content Type: TABLE Owner: postgres
--
"link_url" character varying(255),
"is_html" boolean DEFAULT '0' NOT NULL,
"is_stored" boolean DEFAULT '0' NOT NULL,
- "is_mail_sent" boolean DEFAULT '1' NOT NULL,
- "is_digest_sent" boolean DEFAULT '1' NOT NULL,
"to_article_type" smallint DEFAULT '0' NOT NULL,
"to_content" integer,
"checksum" integer
)
INHERITS ("media");
-CREATE INDEX content_checksum_index ON content (checksum);
-
--
--- TOC Entry ID 30 (OID 29418)
+-- TOC Entry ID 30 (OID 20549)
--
-- Name: breaking Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 31 (OID 29431)
+-- TOC Entry ID 31 (OID 20562)
--
-- Name: messages Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 33 (OID 30026)
+-- TOC Entry ID 32 (OID 20577)
--
-- Name: comment_status Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 34 (OID 30064)
+-- TOC Entry ID 33 (OID 20588)
--
-- Name: content_x_media Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 11 (OID 32812)
+-- TOC Entry ID 11 (OID 20599)
--
-- Name: links_imcs_id_seq Type: SEQUENCE Owner: postgres
--
CREATE SEQUENCE "links_imcs_id_seq" start 1 increment 1 maxvalue 2147483647 minvalue 1 cache 1 ;
--
--- TOC Entry ID 35 (OID 32831)
+-- TOC Entry ID 34 (OID 20618)
--
-- Name: links_imcs Type: TABLE Owner: postgres
--
);
--
--- TOC Entry ID 40 (OID 29078)
+-- TOC Entry ID 35 (OID 37215)
+--
+-- Name: audio Type: TABLE Owner: postgres
+--
+
+CREATE TABLE "audio" (
+ "audio_data" oid,
+ "kbits" smallint
+)
+INHERITS ("uploaded_media");
+
+--
+-- TOC Entry ID 36 (OID 37284)
+--
+-- Name: video Type: TABLE Owner: postgres
+--
+
+CREATE TABLE "video" (
+ "video_data" oid
+)
+INHERITS ("uploaded_media");
+
+--
+-- TOC Entry ID 37 (OID 45396)
+--
+-- Name: other_media Type: TABLE Owner: postgres
+--
+
+CREATE TABLE "other_media" (
+
+)
+INHERITS ("uploaded_media");
+
+--
+-- TOC Entry ID 40 (OID 20143)
--
-- Name: "idx_webdb_user_log_pas_is_admin" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_webdb_user_log_pas_is_admin" on "webdb_users" using btree ( "login" "varchar_ops", "password" "varchar_ops", "is_admin" "bool_ops" );
--
--- TOC Entry ID 44 (OID 29078)
+-- TOC Entry ID 41 (OID 20143)
--
-- Name: "idx_webdb_user_log_pas" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_webdb_user_log_pas" on "webdb_users" using btree ( "login" "varchar_ops", "password" "varchar_ops" );
--
--- TOC Entry ID 43 (OID 29096)
+-- TOC Entry ID 42 (OID 20161)
--
-- Name: "idx_content" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_content" on "content_x_topic" using btree ( "content_id" "int4_ops", "topic_id" "int4_ops" );
--
--- TOC Entry ID 45 (OID 29096)
+-- TOC Entry ID 43 (OID 20161)
--
-- Name: "idx_topic" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_topic" on "content_x_topic" using btree ( "topic_id" "int4_ops", "content_id" "int4_ops" );
--
--- TOC Entry ID 46 (OID 29118)
+-- TOC Entry ID 44 (OID 20183)
--
-- Name: "idx_topic_title" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_topic_title" on "topic" using btree ( "title" "varchar_ops" );
--
--- TOC Entry ID 51 (OID 29118)
+-- TOC Entry ID 45 (OID 20183)
--
-- Name: "idx_topic_id" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_topic_id" on "topic" using btree ( "id" "int4_ops" );
--
--- TOC Entry ID 36 (OID 29154)
+-- TOC Entry ID 38 (OID 20219)
+--
+-- Name: "comment_checksum_index" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "comment_checksum_index" on "comment" using btree ( "checksum" "int4_ops" );
+
+--
+-- TOC Entry ID 46 (OID 20219)
--
-- Name: "idx_comment_to_media" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_comment_to_media" on "comment" using btree ( "to_media" "int4_ops" );
--
--- TOC Entry ID 47 (OID 29257)
+
+--
+-- TOC Entry ID 59 (OID 20326)
+--
+-- Name: "idx_uploaded_media_id" Type: INDEX Owner: postgres
+--
+
+CREATE UNIQUE INDEX "idx_uploaded_media_id" on "uploaded_media" using btree ( "id" "int4_ops" );
+
+--
+-- TOC Entry ID 60 (OID 20326)
+--
+-- Name: "idx_uploaded_media_is_published" Type: INDEX Owner: postgres
+--
+
+CREATE UNIQUE INDEX "idx_uploaded_media_is_published" on "uploaded_media" using btree ( "id" "int4_ops", "is_published" "bool_ops" );
+
+--
+-- TOC Entry ID 47 (OID 20392)
--
-- Name: "idx_images_is_published__icon_i" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_images_is_published__icon_i" on "images" using btree ( "is_published" "bool_ops", "icon_is_produced" "bool_ops" );
--
--- TOC Entry ID 49 (OID 29257)
+-- TOC Entry ID 48 (OID 20392)
--
-- Name: "idx_images_id" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_images_id" on "images" using btree ( "id" "int4_ops" );
--
--- TOC Entry ID 37 (OID 29338)
+-- TOC Entry ID 39 (OID 20474)
+--
+-- Name: "content_checksum_index" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "content_checksum_index" on "content" using btree ( "checksum" "int4_ops" );
+
+--
+-- TOC Entry ID 49 (OID 20474)
--
-- Name: "idx_content_to_article_type" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_content_to_article_type" on "content" using btree ( "to_article_type" "int2_ops" );
--
--- TOC Entry ID 38 (OID 29338)
+-- TOC Entry ID 50 (OID 20474)
--
-- Name: "idx_content_is_produced" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_content_is_produced" on "content" using btree ( "is_produced" "bool_ops" );
--
--- TOC Entry ID 39 (OID 29338)
+-- TOC Entry ID 51 (OID 20474)
--
-- Name: "idx_content_is_published__to_ar" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_content_is_published__to_ar" on "content" using btree ( "is_published" "bool_ops", "to_article_type" "int2_ops" );
--
--- TOC Entry ID 41 (OID 29338)
+-- TOC Entry ID 52 (OID 20474)
--
-- Name: "idx_content_is_stored" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_content_is_stored" on "content" using btree ( "is_stored" "bool_ops" );
--
--- TOC Entry ID 42 (OID 29338)
+-- TOC Entry ID 53 (OID 20474)
--
-- Name: "idx_content_is_published__id" Type: INDEX Owner: postgres
--
CREATE INDEX "idx_content_is_published__id" on "content" using btree ( "is_published" "bool_ops", "id" "int4_ops" );
--
--- TOC Entry ID 48 (OID 29338)
+-- TOC Entry ID 54 (OID 20474)
--
-- Name: "idx_content_is_pub__to_art__to_" Type: INDEX Owner: postgres
--
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" );
--
--- TOC Entry ID 50 (OID 29338)
+-- TOC Entry ID 55 (OID 20474)
--
-- Name: "idx_content_id" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_content_id" on "content" using btree ( "id" "int4_ops" );
--
--- TOC Entry ID 52 (OID 30064)
+-- TOC Entry ID 56 (OID 20588)
--
-- Name: "idx_content_media" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_content_media" on "content_x_media" using btree ( "content_id" "int4_ops", "media_id" "int4_ops" );
--
--- TOC Entry ID 53 (OID 30064)
+-- TOC Entry ID 57 (OID 20588)
--
-- Name: "idx_media_content" Type: INDEX Owner: postgres
--
CREATE UNIQUE INDEX "idx_media_content" on "content_x_media" using btree ( "media_id" "int4_ops", "content_id" "int4_ops" );
+--
+-- TOC Entry ID 62 (OID 37215)
+--
+-- Name: "idx_audio_is_published_produced" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "idx_audio_is_published_produced" on "audio" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" );
+
+--
+-- TOC Entry ID 64 (OID 37215)
+--
+-- Name: "idx_audio_id" Type: INDEX Owner: postgres
+--
+
+CREATE UNIQUE INDEX "idx_audio_id" on "audio" using btree ( "id" "int4_ops" );
+
+--
+-- TOC Entry ID 65 (OID 37215)
+--
+-- Name: "idx_video_id" Type: INDEX Owner: postgres
+--
+
+CREATE UNIQUE INDEX "idx_video_id" on "audio" using btree ( "id" "int4_ops" );
+
+--
+-- TOC Entry ID 63 (OID 37284)
+--
+-- Name: "idx_video_is_published_produced" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "idx_video_is_published_produced" on "video" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" );
+
+
+--
+-- TOC Entry ID 37 (OID 520246)
+--
+-- Name: "idx_content_is_published" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "idx_content_is_published" on "content" using btree ( "is_published" "bool_ops" );
+
+--
+-- TOC Entry ID 47 (OID 465036)
+--
+-- Name: "idx_comment_tomedia_ispublished" Type: INDEX Owner: postgres
+--
+
+CREATE INDEX "idx_comment_tomedia_ispublished" on "comment" using btree ( "to_media" "int4_ops", "is_published" "bool_ops" );
+
+
+++ /dev/null
---
--- create_views.sql
---
-
-
--- TESTING:
---
--- creating list views in database to speed up selection of lists.
---
-
-
-CREATE VIEW v_content_list AS
- SELECT id, title, subtitle, date, place, creator, description, comment, is_published,
- is_produced, to_feature, webdb_create, webdb_lastchange FROM content;
\ No newline at end of file
-- Selected TOC Entries:
--
--
--- Data for TOC Entry ID 2 (OID 88609)
+-- Data for TOC Entry ID 2 (OID 46975)
--
-- Name: media_type Type: TABLE DATA Owner: postgres
--
-- Disable triggers
UPDATE "pg_class" SET "reltriggers" = 0 WHERE "relname" = 'media_type';
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (2,'unknown','application/octet-stream','Generic','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (3,'jpg','image/gif','ImagesGif','Images',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (4,'mp3','audio/mp3','Mp3','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (5,'jpg','image/jpeg','ImagesJpeg','Images',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (6,'pdf','application/pdf','Generic','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (7,'mpg','video/mpeg','Video','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (8,'mov','video/quicktime','Video','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (9,'avi','video/x-msvideo','Video','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (10,'ra','audio/vnd.rn-realaudio','RealAudio','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (11,'rm','video/vnd.rn-realvideo','RealVideo','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (12,'ra','audio/x-pn-realaudio','RealAudio','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (13,'mp3','audio/x-mp3','Mp3','UploadedMedia',NULL);
-INSERT INTO "media_type" ("id","name","mime_type","classname","tablename","dcname") VALUES (14,'mp3','audio/x-mpeg','Mp3','UploadedMedia',NULL);
-
-
+INSERT INTO "media_type" VALUES (4,'mp3','audio/mp3','Mp3','Audio',NULL);
+INSERT INTO "media_type" VALUES (13,'mp3','audio/x-mp3','Mp3','Audio',NULL);
+INSERT INTO "media_type" VALUES (14,'mp3','audio/x-mpeg','Mp3','Audio',NULL);
+INSERT INTO "media_type" VALUES (10,'ra','audio/vnd.rn-realaudio','RealAudio','Audio',NULL);
+INSERT INTO "media_type" VALUES (12,'ra','audio/x-pn-realaudio','RealAudio','Audio',NULL);
+INSERT INTO "media_type" VALUES (11,'rm','video/vnd.rn-realvideo','RealVideo','Audio',NULL);
+INSERT INTO "media_type" VALUES (8,'mov','video/quicktime','Video','Video',NULL);
+INSERT INTO "media_type" VALUES (7,'mpg','video/mpeg','Video','Video',NULL);
+INSERT INTO "media_type" VALUES (9,'avi','video/x-msvideo','Video','Video',NULL);
+INSERT INTO "media_type" VALUES (2,'unknown','application/octet-stream','Generic','Other',NULL);
+INSERT INTO "media_type" VALUES (6,'pdf','application/pdf','Generic','Other',NULL);
+INSERT INTO "media_type" VALUES (15,'png','image/*','Images','Images',NULL);
+INSERT INTO "media_type" VALUES (3,'jpg','- deprecated -','Images','Images',NULL);
+INSERT INTO "media_type" VALUES (5,'jpg','- deprecated -','Images','Images',NULL);
-- Enable triggers
-
UPDATE pg_class SET reltriggers = (SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) WHERE relname = 'media_type';
--
--- TOC Entry ID 1 (OID 88557)
+-- TOC Entry ID 1 (OID 46923)
--
-- Name: media_type_id_seq Type: SEQUENCE SET Owner:
--
now customize config.properties for your needs.
- modify etc/web.xml to change the xml-config
- parameter to point to where your server.xml file is
- (in ../Mir i.e /path/to/Mir/server.xml)
-
3. configure the build.sh file with java_home
cp build.sh-dist build.sh
4. copy the mir/templates-dist-directory to mir/templates
-5. compile
+5. compile (do this as root so the permissions script is able to set
+the permissions and owners correctly).
+
sh build.sh
cat dbscripts/help*.sql | psql -Upostgres dbname
cat dbscripts/populate*.sql | psql -Upostgres dbname
+
10. Add the dupe prevention trigger to the database:
cd dbscripts/dupetrigger
There, read INSTALL and follow the instructions.
-11. Set permissions
+11. Set permissions -- IMPORTANT! READ THIS!
We provide a script that sets all files' and direcories' permissions to
a quite reasonable state. The most important thing you have to do after
the invokation of this script is to ensure that the log files --
in Mir/src nor in Mir/WEB-INF/classes) is world-readable. Else you wouldn't
have to install a password, anyway.
-If you can't access PostgreSQL after this for any reason, try to change
-"password" in /etc/postgresql/pg_hba.conf into "trust". This should disable
+If you can't access PostgreSQL after this for any reason, try and change
+"password" in /etc/postgresql/pg_hba.conf to "trust". This should disable
any authentication method and make the database accessible again.
-15. configure apache's mod_mime to recognize .m3u and .pls files:
-
-The web server (of the media host) must recognize the .m3u and .pls file
-extensions and send the proper "audio/x-mpegurl" and "audio/x-scpls" mime-types
-respectively. If the web server is apache, it's easy, just add:
- *
-audio/x-mpegurl m3u
-audio/x-scpl pls
- *
-to the file pointed to by the "TypesConfig" command in your apache config file.
-Or add and equivalent AddType command to your httpd.conf. Of course this
-assumes that the mod_mime is loaded.
- *
-If the web server is not apache, then your on your own.
-
that's it :)
now the admin-application is accesable via:
http://host/OpenMir
standard login is redaktion/indymedia
+
+
+
+TROUBLESHOOTING
+
+You can give these a try if anything goes wrong:
+
++ Restart Tomcat. Especially after compiling the sources Tomcat has to be
+ restarted.
+
++ Check file permissions and ownership. Try and run perms.sh.
\ No newline at end of file
edit the start-script in /etc/init.d/postgresql, and make sure
postgresql is started with the "-i" option. to enable this insert
- "-o '-i'" after 'start', which should look like:
+ '-o "-i"' after 'start', which should look like:
start)
$ECHO_N "Starting PostgreSQL: "$ECHO_C
To restore the database:
psql <dbname> < <dbname>.sql
pgdump_lo -i -d <dbname> -s /dumpdir/dir
+
+Every once in a while (or make a script) postgresql database should
+be "cleaned". See postgresql docs for commands VACUUM and VACUUM ANALYZE
+
+Every once in a while (or make a script) postgresql database should
+be "cleaned". See postgresql docs for commands VACUUM and VACUUM ANALYZE
+
+We also have misc. perl scripts to merge Large Objects from other DB's.
+these can be used as a basis to write your own custom scripts.
-[Updated 26.10.2001. -mh]
+[Updated 28.02.2002. -mh]
+
+General/Forever valid:
+
+a) watch performance.. mimimize SQL
+b) try to use more freemarker feature like transformations when possible
+instead of putting it in Java code. i.e make it more localizable.
Version 1.0:
Bugfixes/Improvements:
a) installation-procedure
-- config.porperties has to be cleaned and has to be better documentated. (half done, mh) --> config.properties is being replaced with new config system.
-- build.sh should be more intelligent.
-- templates-directory should be splittet in two directories: "internal"- (openmir and mir
-templates) and "external"-templates (producer-templates)
+- templates-directory should be splittet in two directories: "internal"- (openmir and mir templates) and "external"-templates (producer-templates)
+- build.sh should be more intelligent. (underway, convert to build.xml, mj)
b) code-cleaning
- the variable-names for the freemarker should be better: the same name for the same thing
c) We have to make sure that all errors are handled intelligently. e.g. if an
-article is corrupt, do we just ignore it, etc..
-d) Admin interface needs to be made aware of media handlers (mj)
-e) insposting() in ServletModuleOpenIndy should not insert article text if any associated media upload is wrong. (mh)
-
-c) documentation
+article is corrupt, do we just ignore it, etc.. (done, mh)
+d) Admin interface needs to be made aware of media handlers (mh, tob)
+e) insposting() in ServletModuleOpenIndy should not insert article text if any associated media upload is wrong. (done, mh) (in 1.1 to be done via transactions)
+f) documentation
- it lacks a documentation for creating the producer-templates
-d) new layout Mir/OpenMir (gilad)
-e) translating the templates/code-comments to english
-f) mission-statement and licensing
-g) there are no memory-leaks
+g) new layout Mir/OpenMir (underway, indy de team??)
+h) translating the templates/code-comments to english (underway, mir-coders)
+i) mission-statement and licensing
+j) there are no memory-leaks (3/4 confirmed)
+k) tomcat 4.x (needs testing)
+l) poolman (done, idfx)
+m) re-tweak media infrastructure (underway, -mh)
+ - wildcard support for content-type mappings (done)
+ - handle all image types and transparency (done)
+ - convert other media types for DB storage for consistency (started, mh)
+ - handle generic media
+ - better extension handling
+ - handle external meta links
+ - rework creation of audio (video too?) meta-data
+ - make getUrl() return a list of SimpleHashes
+ - use added flexibility in templates
+ - add miless code for better secondary content-type guessing. i.e read the
+ bytes
+n) CVS id, author stamps
+o) make Entity implement freemarke TemplateModel (done, rk)
+p) don't use deprecated methods. specifically the SimpleList stuff
New Features:
a) Multifile-Upload in OpenMir and Mir (done, idfx)
-b) Video and audio-upload in OpenMir and Mir: How will this files be stored, what has to
-be done in the producer-code? (done, mh)
+b) Video and audio-upload in OpenMir and Mir: How will this files be stored, what has to be done in the producer-code? (done, mh)
c) Coverage: Alternative start-page for e.g. a event like genua. every article that has
something to do with this event can be seen on this page. (nn)
-d) Multilanguage-Support (Step 1): Producing html-pages with navigation for every
-language. Topics and coverage-titles have to be saved in the db in every language that is
-needed. (idfx) A
-d.1) Templates should be made common for all languages. (kellan)
e) It should be possible to choose between direct and indirect open posting. (09/14/2001,
done, idfx).
-f) Editing producer-templates in the mir-servlet. (idfx)
g) "Upcoming Events"-include-file (ha)
-e) indymedia-links (fh)
+h) indymedia-links (fh)
+i) objectStore (underway, -rk)
Version 1.1:
+Vital:
+a) Multilanguage-Support (Step 1): Producing html-pages with navigation for every
+language. Topics and coverage-titles have to be saved in the db in every language that is
+needed. (idfx)
+a.1) Templates should be made common for all languages. (kellan, br1)
New Features:
a) Multilanguage-Support (Step 2): Separate OpenMir-servlet to publish a tranlation of an
article. If a article has translations, only the translated versions are produced in the language
the translated article is.
+b) single template for all languages. i.e use gettext like system for templates.
+(underway, kellan, br1)
b) P2P-Data-Transfer/Content-Syndication: Implementing RDF/RSS-Support or a own
indymedia-protocoll.
c) dynamically creating "internal"-templates for new languages.
d) email-article-to-a-friend-servlet
e) semidynamic create-pdf-from-article-servlet: every requested pdf should be cached
+f) servletapi-2.3: Filters for file upload (also in cos.jar)
+g) servletapi-2.3: use web.xml for simpler/better error handling.
+h) servletapi-2.3: set character encoding properly based on what the template
+says
+i) servletapi-2.3: servletapi-2.3 requires tomcat-4.x, so require it
+j) use some JMF (Java Media Framework at sun.com) features for nifty media
+tricks
+k) better transaction support in the DB/Persistance layer for more efficient
+use of DB.
+l) - config.porperties has to be cleaned and has to be better documentated. (half done, mh) --> config.properties is being replaced with new config system.
+m) Editing producer-templates in the mir-servlet. (idfx)
Version 2:
Database-Layer
-a) Container Managed Persistance (EJB)
+a) Container Managed Persistance (EJB) or Castor?
+b) MySQL compatibility?
Testing:
-- tomcat 4.0 (kellan)
- resin (idfx)
-- poolman instead of dbconnectionbroker
<param-name>Config</param-name>
<param-value>config</param-value>
</init-param>
- <init-param>
- <param-name>xml-config</param-name>
- <param-value>/home/heckmann/mir/Mir/server.xml</param-value>
- </init-param>
</servlet>
<param-name>Config</param-name>
<param-value>config</param-value>
</init-param>
- <init-param>
- <param-name>xml-config</param-name>
- <param-value>/home/heckmann/mir/Mir/server.xml</param-value>
- </init-param>
</servlet>
grant 775 664 $INSTDIR > /dev/null 2>&1
grant 750 640 $INSTDIR/WEB-INF/classes/config.properties
grant 740 640 $INSTDIR/src/config.properties
+
+echo "Permissions set."
\ No newline at end of file
--- /dev/null
+Sample scrips for autmatic tarball generation for mir.indymedia.org.
+Not ready yet.
+
--- /dev/null
+mkdir mir
+mkdir mirstable
+mkdir tarballs
+
+#
+# stable part
+
+cd mirstable
+cvs co -r STABLE-pre1_0 co
+cd ..
+
+#
+# unstable part
+
+cd mir
+cvs co mir
+cd ..
+
--- /dev/null
+#
+# this script makes four tarballs:
+#
+# 1. STABLE-pre1_0: with and without libs
+# 2. current with and without libs
+
+MIR_TARHOME=/home/rk/autotar/tarballs
+MIR_HOME=/home/rk/autotar/mir
+MIR_STABLEHOME=/home/rk/autotar/mirstable
+
+
+
+echo "[updating cvs stable in $MIR_STABLEHOME]"
+cd $MIR_STABLEHOME/mir
+cvs -q update -dP
+cd ..
+echo "[tar stable in $MIR_TARHOME] .."
+tar cfz $MIR_TARHOME/mir_stable.tar.gz --exclude "mir/lib" --exclude "CVS" mir
+echo "[tar stable+libs in $MIR_TARHOME] .."
+tar cfz $MIR_TARHOME/mir_stable+libs.tar.gz --exclude "CVS" mir
+
+echo "[updating cvs current in $MIR_HOME]"
+cd $MIR_HOME/mir
+cvs -q update -dP
+cd ..
+
+echo "[tar current in $MIR_TARHOME] .."
+tar cfz $MIR_TARHOME/mir.tar.gz --exclude "mir/lib" --exclude "CVS" mir
+echo "[tar current+libs in $MIR_TARHOME] .."
+tar cfz $MIR_TARHOME/mir+libs.tar.gz --exclude "CVS" mir
+
import java.lang.reflect.*;
import javax.servlet.*;
import javax.servlet.http.*;
+import javax.servlet.UnavailableException;
import java.sql.*;
import freemarker.template.*;
import mir.misc.*;
import mir.servlet.*;
+import mir.storage.StorageObjectException;
import mircoders.servlet.*;
import mircoders.module.*;
*/
-public class Mir extends AbstractServlet
-{
+public class Mir extends AbstractServlet {
- private static ModuleUsers usersModule=null;
- private static ModuleMessage messageModule=null;
- private static boolean confed=false;
- public HttpSession session;
+ private static ModuleUsers usersModule=null;
+ private static ModuleMessage messageModule=null;
+ private final static HashMap servletModuleInstanceHash = new HashMap();
+ public HttpSession session;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ throws ServletException, IOException, UnavailableException {
- long startTime = (new java.util.Date()).getTime();
- Class theServletModule;
- ServletModule smod;
+ long startTime = System.currentTimeMillis();
long sessionConnectTime=0;
String http="";
// get the configration
- if (!confed){
- confed = getConfig(req);
+ if(getServletContext().getAttribute("mir.confed") == null) {
+ getConfig(req);
}
MirConfig.setServletName(getServletName());
setLanguage(session,getAcceptLanguage(req));
}
+ /** @todo for cleanup and readability this should be moved to
+ * method loginIfNecessary() */
+
// Authentifizierung
if (moduleName!=null && moduleName.equals("login")) {
String user=req.getParameter("login");
_sendStartPage(res,req, res.getWriter(),userEntity);
return;
}
+ // end of auth
- //From now on regular dispatching...
+ // From now on regular dispatching...
try {
- try {
- theServletModule = Class.forName("mircoders.servlet.ServletModule" + moduleName);
- } catch (ClassNotFoundException e) {
- // searching servletmodule in mir.servlet-classes
- theServletModule = Class.forName("mir.servlet.ServletModule" + moduleName);
- }
- //Instantiate the ServletModule
- Method m = theServletModule.getMethod("getInstance",null);
- smod = (ServletModule)m.invoke(null,null);
+ // get servletmodule by parameter and continue with dispacher
+ ServletModule smod = getServletModuleForName(moduleName);
ServletModuleDispatch.dispatch(smod,req,res);
}
- catch (NoSuchMethodException e) { handleError( res,res.getWriter(), "ServletModule" + moduleName + " getInstance() not found."); }
- catch (InvocationTargetException e) { handleError( res,res.getWriter(), "ServletModule" + moduleName + " target not found."); }
- catch (ClassNotFoundException e) { handleError(res, res.getWriter(), "ServletModule" + moduleName + " not found."); }
- catch (IllegalArgumentException e) { handleError( res,res.getWriter(), "ServletModule" + moduleName + " not found."); }
- catch (ServletModuleException e){ handleError(res,res.getWriter(), "ServletException in Module ServletModule" + moduleName + " -- " + e.toString()); }
- catch (IllegalAccessException e){
- handleError(res,res.getWriter(), "No access to class ServletModule" + moduleName + " -- " + e.toString()); }
+ catch (ServletModuleException e) {
+ handleError(res, res.getWriter(), "ServletException in Module " + moduleName + " -- " + e.toString());
+ }
+ catch (ServletModuleUserException e) {
+ handleUserError(res,res.getWriter(), "User error" + e.toString());
+ }
// timing...
- sessionConnectTime = new java.util.Date().getTime() - startTime;
+ sessionConnectTime = System.currentTimeMillis() - startTime;
theLog.printInfo("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
}
+
+ /**
+ * Private method getServletModuleForName returns ServletModule
+ * from Cache
+ *
+ * @return ServletModule
+ *
+ */
+ private static ServletModule getServletModuleForName(String moduleName)
+ throws ServletModuleException {
+
+ // Instance in Map ?
+ if (!servletModuleInstanceHash.containsKey(moduleName)) {
+ // was not found in hash...
+ try {
+ Class theServletModuleClass=null;
+ try {
+ // first we try to get ServletModule from stern.che3.servlet
+ theServletModuleClass = Class.forName("mircoders.servlet.ServletModule" + moduleName);
+ } catch (ClassNotFoundException e) {
+ // on failure, we try to get it from lib-layer
+ theServletModuleClass = Class.forName("mir.servlet.ServletModule"+ moduleName);
+ }
+ Method m = theServletModuleClass.getMethod("getInstance", null);
+ ServletModule smod = (ServletModule)m.invoke(null, null);
+ // we put it into map for further reference
+ servletModuleInstanceHash.put(moduleName,smod);
+ return smod;
+ } catch (Exception e) {
+ throw new ServletModuleException("*** error resolving classname for " +
+ moduleName +" -- "+ e.toString());
+ }
+ }
+ else return (ServletModule)servletModuleInstanceHash.get(moduleName);
+ }
+
+
private void handleError(HttpServletResponse res, PrintWriter out, String errorString) {
+
try {
theLog.printError(errorString);
SimpleHash modelRoot = new SimpleHash();
}
}
+ private void handleUserError(HttpServletResponse res,PrintWriter out, String errorString) {
+
+ try {
+ theLog.printError(errorString);
+ SimpleHash modelRoot = new SimpleHash();
+ modelRoot.put("errorstring", new SimpleScalar(errorString));
+ modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
+ HTMLTemplateProcessor.process(res,MirConfig.getProp("Mir.UserErrorTemplate"),modelRoot,out);
+ out.close();
+ }
+ catch (Exception e) {
+ System.err.println("Fehler in UserErrorTemplate");
+ }
+
+ }
/**
* evaluate login for user / password
*/
try {
if (usersModule == null) usersModule = new ModuleUsers(DatabaseUsers.getInstance());
return usersModule.getUserForLogin(user, password);
+ } catch(Exception e) {
+ theLog.printDebugInfo(e.toString());
+ e.printStackTrace();
+ return null;
}
- catch(Exception e) { theLog.printDebugInfo(e.toString()); return null; }
}
// Redirect-methods
// merge with logged in user and messages
SimpleHash mergeData = new SimpleHash();
mergeData.put("session",sessionUrl);
- mergeData.put("login_user", HTMLTemplateProcessor.makeSimpleHash(userEntity));
+ mergeData.put("login_user", userEntity);
if (messageModule == null) messageModule = new ModuleMessage(DatabaseMessages.getInstance());
- mergeData.put("messages", HTMLTemplateProcessor.makeSimpleList(messageModule.getByWhereClause(null, "webdb_create desc",0,10)));
+ mergeData.put("messages", messageModule.getByWhereClause(null, "webdb_create desc",0,10));
HTMLTemplateProcessor.process(res,getLanguage(req,session)+"/"+startTemplate, mergeData,out);
}
catch(Exception e) {
import freemarker.template.*;
import mir.misc.*;
-import mir.xml.XmlConfigurator;
import mir.servlet.*;
import mircoders.servlet.*;
public class OpenMir extends AbstractServlet {
- private static boolean confed=false;
+ //private static boolean confed=false;
private static String lang;
public HttpSession session;
doPost(req,res);
}
- public void init() throws ServletException {
- try {
- XmlConfigurator xmlXonfigurator = XmlConfigurator.getInstance();
- xmlXonfigurator.addRequiredTag("/mir/class:mir.storage.DatabaseConfig/property:username");
- xmlXonfigurator.addRequiredTag("/mir/class:mir.storage.DatabaseConfig/property:password");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:password");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:username");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:host");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:adaptor");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:limit");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:poolMax");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:poolMin");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:poolResetTime");
- xmlXonfigurator.addComesFirstTag("/mir/class:mir.storage.DatabaseConfig/property:poolLog");
- xmlXonfigurator.configure(new File(getInitParameter("xml-config")));
- System.err.println("INIT");
- /*try {
- MirXmlParser xmlParser = new MirXmlParser();
- xmlParser.parse("/home/heckmann/server.xml");*/
- } catch (Exception e) {
- e.printStackTrace();
- throw new UnavailableException ("Error loading Config file: "+e.toString(), 0);
- }
- System.err.println("DONE INIT");
- }
-
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
long sessionConnectTime=0;
- if (!confed){
- confed = getConfig(req);
- }
+ // get the configration
+ if(getServletContext().getAttribute("mir.confed") == null) {
+ getConfig(req);
+ }
session = req.getSession();
if(session.getAttribute("Language")==null){
try {
ServletModuleDispatch.dispatch(ServletModuleOpenIndy.getInstance(),req,res);
}
+ catch (ServletModuleUserException e) {
+ handleUserError(res,res.getWriter(), e.getMsg());
+ }
catch (ServletModuleException e){
e.printStackTrace();
handleError(res,res.getWriter(), "OpenIndy :: ServletException in Module ServletModule -- " + e.toString());
theLog.printInfo("EXECTIME (ServletModuleOpenIndy): " + sessionConnectTime + " ms");
}
+ private void handleUserError(HttpServletResponse res,PrintWriter out, String errorString) {
+
+ try {
+ theLog.printError(errorString);
+ SimpleHash modelRoot = new SimpleHash();
+ modelRoot.put("errorstring", new SimpleScalar(errorString));
+ modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
+ HTMLTemplateProcessor.process(res,MirConfig.getProp("Mir.UserErrorTemplate"),modelRoot,out);
+ out.close();
+ }
+ catch (Exception e) {
+ System.err.println("Fehler in UserErrorTemplate");
+ }
+
+ }
+
private void handleError(HttpServletResponse res,PrintWriter out, String errorString) {
try {
# image specific storage directories
# absolute directory, where the images are saved
-Producer.Image.Path=/pub/Dokumente/Indymedia/de-tech/Mir/produced/images
+Producer.Image.Path=/pub/Dokumente/Indymedia/de-tech/Mir/produced/images/
# media specific storage directories
# absolute directory, where the media files are saved
Database.Username=postgres
Database.Password=
Database.Host=localhost
+Database.Name=Mir
#
# this sets the adaptor to be used
Mir.Logfile=log/mir.log
Mir.ErrorTemplate=fehler.template
+Mir.UserErrorTemplate=usererror.template
ServletModule.Schwerpunkt.ConfirmTemplate=confirm.template
ServletModule.Schwerpunkt.ObjektTemplate=schwerpunkt.template
Producer.Navigation.Template=producer/navigation.template
Producer.Content.Template=producer/content.template
-Producer.Content.Batchsize=20
+Producer.Content.Batchsize=10
Producer.Startseite.Template=producer/startseite.template
Producer.Startseite.Entries=7
Producer.StartPage.Items=10
Producer.StartPage.Newswire=30
-Producer.Wap.Template=producer/wap.template
-Producer.Wap.Items=10
+
+# todo: do we need those?
Xsl.Content=producer/content.xsl
Xsl.Fo.Content=producer/frontpage_fo.xsl
/**
* Base class the entities are derived from. Provides base functionality of
- * an entity<p>
+ * an entity. Entities are used to represent rows of a database table.<p>
*/
protected static Logfile theLog;
protected ArrayList streamedInput=null;
private static int instances = 0;
+ static {
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Entity.Logfile"));
+ }
public Entity() {
- theLog = Logfile.getInstance(this.getClass().getName());
+
this.changed = false;
instances++;
Integer i = new Integer(instances);
}
/**
- * Konstruktor
+ * Constructor
+ * @param StorageObject The StorageObject of the Entity.
*/
public Entity (StorageObject StorageObject) {
this();
}
/*
- * Setzt das StorageObject der Entity.
+ * Sets the StorageObject of the Entity.
*/
public void setStorage (StorageObject storage) {
this.theStorageObject = storage;
}
/**
- * Setzt die Werte der Entity
- * @param theStringValues
+ * Sets the values of the Entity.
+ * @param theStringValues HashMap containing the new values of the Entity
*/
public void setValues(HashMap theStringValues)
{
/** @todo should be synchronized */
- theValuesHash = new HashMap();
- String aKey;
- Set set = theStringValues.keySet();
- Iterator it = set.iterator();
- int size = set.size();
- for (int i = 0; i < size; i++) {
- aKey = (String)it.next();
- theValuesHash.put(aKey, (String)theStringValues.get(aKey));
+ if (theStringValues!=null) {
+ theValuesHash = new HashMap();
+ String aKey;
+ Set set = theStringValues.keySet();
+ Iterator it = set.iterator();
+ int size = set.size();
+ for (int i = 0; i < size; i++) {
+ aKey = (String)it.next();
+ theValuesHash.put(aKey, (String)theStringValues.get(aKey));
+ }
}
+ else theLog.printWarning("Entity.setValues called with null HashMap");
}
/**
- * Liefert boolschen Wert, ob sich der Inhalt der Entity geändert hat.
+ * Returns whether the content of the Entity has changed.
* @return true wenn ja, sonst false
*/
public boolean changed () {
}
/**
- * Liefert den Primärschluessel der Entity zurueck
+ * Returns the primary key of the Entity.
* @return String Id
*/
public String getId () {
}
/**
- * Setzt den Primaerschluessel der Entity
+ * Defines the primary key of the Entity
* @param id
*/
public void setId (String id) {
}
/**
- * Liefert den Wert für einen Feldnamen zurueck
- * @param theFieldString
- * @return Wert für Feld
+ * Returns the value of a field by field name.
+ * @param field The name of the field
+ * @return value of the field
*/
public String getValue (String field) {
String returnValue = null;
}
/**
- * Fügt Entity via StorageObject in Datenbank ein.
- * @return Primary Key der Entity
+ * Insers Entity into the database via StorageObject
+ * @return Primary Key of the Entity
* @exception StorageObjectException
*/
public String insert () throws StorageObjectException {
}
/**
- * Aktualisiert Aenderungen an der Entity in der Datenbank
+ * Saves changes of this Entity to the database
* @exception StorageObjectException
*/
public void update () throws StorageObjectException {
}
/**
- * Setzt den Wert fuer ein Feld
- * @param theProp
- * @param theValue
+ * Sets the value for a field. Issues a log message if the field name supplied was not found in the Entity.
+ * @param theProp The field name whose value has to be set
+ * @param theValue The new value of the field
* @exception StorageObjectException
*/
public void setValueForProperty (String theProp, String theValue) throws StorageObjectException {
this.changed = true;
if (isField(theProp))
theValuesHash.put(theProp, theValue);
- else
+ else {
theLog.printWarning("Property not found: " + theProp+theValue);
+ }
}
/**
- * Gibt die Feldnamen der Entity als ArrayList zurueck
- * @return ArrayList mit Feldnamen
- * @exception StorageObjectException wird geworfen, wenn kein Zugriff auf die Datenbank
- * möglich.
+ * Returns the field names of the Entity as ArrayListe.
+ * @return ArrayList with field names
+ * @exception StorageObjectException is throuwn if database access was impossible
*/
public ArrayList getFields () throws StorageObjectException {
return theStorageObject.getFields();
}
/**
- * Liefert ein int[] mit den Typen der Felder zurueck
- * @return int[] mit den Feldtypen
+ * Returns an int[] with the types of the fields
+ * @return int[] that contains the types of the fields
* @exception StorageObjectException
*/
public int[] getTypes () throws StorageObjectException {
}
/**
- * Liefert ArrayListe mit Feldnamen zurueck.
- * @return Liste mit Feldnamen
+ * Returns an ArrayList with field names
+ * @return List with field names
* @exception StorageObjectException
*/
public ArrayList getLabels () throws StorageObjectException {
}
/**
- * Liefert eine Hashmap mit allen Werten der Entity zurueck
- * @return HashMap mit Feldname/Wert
+ * Returns a Hashmap with all values of the Entity.
+ * @return HashMap with field name as key and the corresponding values
*
* @deprecated This method is deprecated and will be deleted in the next release.
- * AbstractEntity interfaces freemarker.template.TemplateHashModel now and can
+ * Entity interfaces freemarker.template.TemplateHashModel now and can
* be used in the same way as SimpleHash.
*/
public HashMap getValues() {
+ theLog.printWarning("## using deprecated Entity.getValues() - a waste of resources");
return theValuesHash;
}
/**
+ * Returns an ArrayList with all database fields that can
+ * be evaluated as streamedInput.
+ * Could be automated by the types (blob, etc.)
+ * Until now to be created manually in the inheriting class
+ *
* Liefert einen ArrayList mit allen Datenbankfeldern, die
* als streamedInput ausgelesen werden muessen.
* Waere automatisierbar ueber die types (blob, etc.)
return streamedInput;
}
- /* Fragt ab, ob fieldName einem Feld entspricht
+ /** Returns whether fieldName is a valid field name of this Entity.
* @param fieldName
- * @return true, wennn ja, sonst false
+ * @return true in case fieldName is a field name, else false.
* @exception StorageObjectException
*/
public boolean isField (String fieldName) throws StorageObjectException {
return theStorageObject.getFields().contains(fieldName);
}
- /** Liefert Anzahl der Instanzen zurück
- * @return int
+ /** Returns the number of instances of this Entity
+ * @return int The number of instances
*/
public int getInstances() {
return instances;
}
+
+ protected void throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
+ theLog.printError( e.toString() + " Funktion: "+ wo);
+ throw new StorageObjectException("Storage Object Exception in entity" +e.toString());
+ }
+
/**
- * Gibt eine Instanz frei
+ * Frees an instance
*/
- public void finalize () {
+ /*public void finalize () {
instances--;
+ Integer i = new Integer(instances);
+ System.err.println("Removing abstract entity instance: "+i.toString());
try {
super.finalize();
} catch (Throwable t) {
System.err.println(t.toString());
}
- }
+ }*/
// Now implements freemarkers TemplateHashModel
public boolean isEmpty() throws TemplateModelException
{
- if (theValuesHash==null || theValuesHash.isEmpty())
- return true;
- return false;
+ return (theValuesHash==null || theValuesHash.isEmpty()) ? true : false;
}
public TemplateModel get(java.lang.String key) throws TemplateModelException
{
- theLog.printDebugInfo("trying to get: " + key);
return new SimpleScalar(getValue(key));
}
public void put(java.lang.String key, TemplateModel model)
{
- // empty for testing
+ // putting should only take place via setValue and is limited to the
+ // database fields associated with the entity. no additional freemarker
+ // stuff will be available via Entity.
+ theLog.printWarning("### put is called on entity! - the values will be lost!");
}
public void remove(java.lang.String key)
{
- // empty for testing
+ // do we need this?
}
/*
- * put your module comment here
+ * The former (German) documentation of this classe
+ * stated that this class is an abstract one. There is,
+ * however, not a single abstract method in this class.
*/
import java.lang.*;
import java.util.*;
+
+import freemarker.template.*;
+
import mir.misc.*;
/**
*
- * abstrakte Containerklasse für Listen von Entities.
+ * Container class for lists of Entities.
*
* @author <RK>
* @version 27.6.1999
*/
-public class EntityList {
- private static Logfile theLog;
- private ArrayList theEntityArrayList;
- private String whereClause;
- private String orderClause;
- private int count;
- private int offset;
- private int offsetnext = -1;
- private int offsetprev = -1;
+public class EntityList implements TemplateListModel {
+
+ private static Logfile theLog;
+ private ArrayList theEntityArrayList;
+ private String whereClause;
+ private String orderClause;
+ private int count;
+ private int offset;
+ private int offsetnext = -1;
+ private int offsetprev = -1;
+ private int freemarkerListPointer=-1;
+
+
+ static {
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Entity.Logfile"));
+ }
/**
- * Konstruktor für leere Liste von Entities
+ * Constructor. Creates an empty EntityList
*/
public EntityList(){
this.theEntityArrayList = new ArrayList();
- if (theLog == null)
- this.theLog = Logfile.getInstance(this.getClass().getName());
}
+
/**
- * Setzt die WhereClause, mit der die Entitis dieser Liste geholt wurden.
- * @param wc
+ * 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;
}
/**
- * Liefert die WhereClause zurueck, mit der die Entities geholt wurden.
- * @return whereClause
+ * Returns the WHERE clause that returned this EntityList from the database
+ * @return whereClause The WHERE clause
*/
public String getWhere() {
return whereClause;
}
+
/**
- * Setzt das Sortierkriterium fest, mit der die Entities in die Liste
- * gestellt wurden.
- *
+ * Sets the sorting criterium of this EntityList
* @param oc
*/
public void setOrder(String oc) {
}
/**
- * Liefert das Sortierkriterium der Liste zurueck.
- * @return orderClause
+ * Returns the sorting criterium.
+ * @return orderClause The sort order
*/
public String getOrder() {
return orderClause;
}
/**
- * Setzt die Anzahl der Datensätze fest, die WhereClause erfüllen.
- * @param i
+ * 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;
}
/**
- * Liefert Anzahle der Datensätze, die WhereClause erfüllen.
- * @return
+ * Returns the number of rows that match the WHERE clause
+ * @return The number of rows ...
*/
public int getCount() {
return count;
}
/**
- * Setzt den Offset fest.
- * @param i
+ * Sets the offset
+ * @param i The offset
*/
public void setOffset(int i) {
offset = i;
}
/**
- * Liefert den Offset zurueck
+ * Returns the offset
* @return offset
*/
public int getOffset() {
}
/**
- * Setzt den offset für das naechste Batch von Entities fest.
- * @param i
+ * Sets the offset of the next batch of Entities.
+ * @param i The next offset
*/
public void setNextBatch(int i) {
offsetnext = i;
}
/**
- * Liefert den offset für das naechste Batch von Entities
- * @return offset für naechstes Batch
+ * Returns the offset of the next batch of Entities.
+ * @return offset of the next batch
*/
public int getNextBatch() {
return offsetnext;
}
/**
- * Fragt ab, ob es noch nachfolgendes Batch innerhalb der WhereClause gibt
- * @return
+ * Returns whether there is a next batch within the WHERE clause
+ * @return true if yes, false if no.
*/
public boolean hasNextBatch() {
return (offsetnext >= 0);
}
/**
- * Setzt offset des vorhergehenden Batches fest.
- * @param i
+ * Sets the offset of the previous batch.
+ * @param i the previous offset
*/
public void setPrevBatch(int i) {
offsetprev = i;
}
/**
- * Liefert offset des vorhergehenden Batches zurueck.
- * @return offset des vorhergehenden Batches.
+ * Returns the offset of the previous batch.
+ * @return offset of the previous batch
*/
public int getPrevBatch() {
return offsetprev;
}
/**
- * Fragt ab, ob es ein vorhergehendes Batch gibt
- * @return true wenn ja, sont false
+ * Returns whether there is a previous batch.
+ * @return true if yes, false if no
*/
public boolean hasPrevBatch() {
return (offsetprev >= 0);
}
/**
- * Liefert den Startindex des Batches zurueck.
+ * Returns the start index of the batch.
* @return
*/
public int getFrom() {
}
/**
- * Liefert den Endindex des Batches zurueck.
+ * Returns the end index of the batch.
* @return
*/
public int getTo() {
- if (hasNextBatch())
- return offsetnext;
- else
- return count;
- }
-
- /**
- * Fügt eine Entity in die Liste ein
- * @param anEntity
- */
- public void add (Entity anEntity) {
- if (anEntity!=null)
- theEntityArrayList.add(anEntity);
- else
- theLog.printWarning("add (EntityList) mit leerer Entity");
- }
-
- /**
- * @return Anzahl der Entities in der Liste
- */
- public int size() {
- return theEntityArrayList.size();
- }
-
-
-
-
-
-
- public Entity elementAt(int i) {
- return (Entity)theEntityArrayList.get(i);
- }
+ 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
+ theLog.printWarning("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);
+ }
+
+
+ // The following methods have to be implemented
+ // for this class to be an implementation of the
+ // TemplateListModel of the Freemarker packages
+
+ public TemplateModel get(int i) { return elementAt(i); }
+ public boolean isRewound() { return (freemarkerListPointer==-1) ? true : false; }
+ public void rewind() { freemarkerListPointer=-1; }
+
+ public TemplateModel next() {
+ if (hasNext()) {
+ freemarkerListPointer++;return get(freemarkerListPointer); }
+ else return null;
+ }
+
+
+ /**
+ * Returns whether there is a next element
+ * @return true if there is a next element, else false
+ */
+
+ public boolean hasNext() {
+ return theEntityArrayList.size()>0 && freemarkerListPointer+2<=theEntityArrayList.size();
+ }
+
+
+ /**
+ * Returns whether EntityList is empty or not
+ * @return true in case of empty list, false otherwise
+ */
+
+ public boolean isEmpty() {
+ if (theEntityArrayList!=null)
+ return theEntityArrayList.size()<1 ;
+ else return false;
+ }
}
}
/**
- * @return Liefert ein freemarker.template.SimpleHash mit den verknuepften
- * Entities, wenn es sich um eine TO_ONE Beziehung handelt, ansonsten
- * null.
- */
-
- public Entity getOneAsSimpleHash(Entity entity) throws StorageObjectException {
- if (type==TO_ONE) {
- Entity returnEntity = (Entity)getOne(entity);
- if (returnEntity!=null) return returnEntity;
- }
- return null;
- }
-
- /**
* @return Liefert eine freemarker.template.SimpleList mit den verknuepften
* Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
* null.
}
/**
- * @return Liefert eine freemarker.template.SimpleList mit den verknuepften
- * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
- * null.
- */
-
- public SimpleList getManyAsSimpleList(Entity entity)
- throws StorageObjectException {
-
- if (type==TO_MANY) {
- EntityList returnList = getMany(entity);
- if (returnList!=null) return HTMLTemplateProcessor.makeSimpleList(returnList);
- }
- return null;
- }
-
- /**
- * @return Liefert eine freemarker.template.SimpleList mit den verknuepften
- * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
- * null.
- */
-
- public SimpleList getManyAsSimpleList(Entity entity, String order)
- throws StorageObjectException {
-
- if (type==TO_MANY) {
- EntityList returnList = getMany(entity, order);
- if (returnList!=null) return HTMLTemplateProcessor.makeSimpleList(returnList);
- }
- return null;
- }
-
- /**
- * @return Liefert eine freemarker.template.SimpleList mit den verknuepften
- * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
- * null.
- */
-
- public SimpleList getManyAsSimpleList(Entity entity, String order, String whereClause)
- throws StorageObjectException {
-
- if (type==TO_MANY) {
- EntityList returnList = getMany(entity, order, whereClause);
- if (returnList!=null) return HTMLTemplateProcessor.makeSimpleList(returnList);
- }
- return null;
- }
- /**
- * @return Liefert den Referenznamen der abhaengigen Tabelle
+ * @return The reference name of the related table.
*/
public String getName() {
package mir.entity;
/**
- * Standard-Entity-Container. Wenn keine Zusatzfunktionalitaeten für die Kapselung einer
- * Datenbankzeile nötig sind, d.h. zu einem Database-Objekt keine eigene Entity-Klasse
- * implementiert wird, so wird dieser Standard-Container verwendet.
+ * Standard Entity container.
+ * If no additional functionality is neccessary for the encapsulation
+ * of a database row, i.e. no separate Entity class is implemented
+ * for a database object, this standard container is used.
*
* @author /rk
* @version 1.2
*/
-public class GenericEntity extends Entity
- {}
+public class GenericEntity extends Entity {}
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-/**
- * Handles audio media, like mp3 and maybe it could also handle some other.
- * It is MediaHandlerGeneric with different icons.
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author mh <heckmann@hbe.ca>
- * @version 24.09.2001
- */
-
-public class MediaHandlerAudio extends MediaHandlerGeneric implements MirMedia
-{
-
- private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
- private static String bigIcon = MirConfig.getProp("Producer.Icon.BigAudio");
-
- public String getTinyIcon()
- {
- return tinyIcon;
- }
-
- public String getBigIcon()
- {
- return bigIcon;
- }
-
- public String getIconAlt()
- {
- return "Audio";
- }
-
- public boolean isAudio()
- {
- return true;
- }
-}
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-/**
- * This is the Generic MediaHandler. It stores the media data on
- * the filesystem and keeps basic metadata (size, type...) in the
- * DB. Usually only representation needs to be overridden.
- * See the MediaHandlerAudio class to see an example of how one
- * could override it.
- * <p>
- * Most media handlers should override this class.
- * <p>
- * In theory, it could be used to handle miscellaneous media that
- * we don't have entered in the media_type table, (like RTF documents,
- * PS, PDF, etc..)
- * <p>
- * Of course it implements the MirMedia interface.
- *
- * @see mir.media.MirMedia
- * @author mh <heckmann@hbe.ca>
- * @version 24.09.2001
- */
-
-public class MediaHandlerGeneric implements MirMedia
-{
-
- protected String imageHost = MirConfig.getProp("Producer.Image.Host");
- protected String imageRoot = MirConfig.getProp("Producer.ImageRoot");
- protected Logfile theLog = Logfile.getInstance(this.getClass().getName());
- public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt ) {
- String ext = mediaTypeEnt.getValue("name");
- String dir = MirConfig.getProp("Producer.Media.Path");
- String mediaHost = MirConfig.getProp("Producer.Media.Host");
- String mediaFname = ent.getId()+"."+ext;
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- Integer size = new Integer(uploadedData.length);
- if(FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData)) {
- //if(FileUtil.write(dir+"/"+mediaFname, uploadedData)) {
- //were done with the data, dereference.
- uploadedData=null;
-
- try {
- ent.setValueForProperty("is_produced", "1");
- ent.setValueForProperty("icon_is_produced", "1");
- ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
- //ent.setValueForProperty("publish_path", mediaFname);
- ent.setValueForProperty("publish_server", mediaHost);
- ent.setValueForProperty("size", size.toString());
- ent.update();
- } catch (StorageObjectException e) {
- theLog.printError("StorageObjectException: "+e.toString());
- return false;
- }
- } else {
- theLog.printError("could not write FILE!");
- return false;
- }
-
- return true;
- }
-
- //a class that will probably never get used..
- private byte[] getFile (String fileName) {
- long size = FileUtil.getSize(fileName);
- if (size < 0) return null;
-
- byte[] container = new byte[(int)size];
-
- if(!FileUtil.read(fileName, container))
- return null;
-
- return container;
- }
-
- public byte[] get (Entity ent, Entity mediaTypeEnt) {
- return null;
- }
-
- public byte[] getIcon (Entity ent) {
- String name = "/path/to/some/generic/icon";
- return getFile(name);
- }
-
- public String getStoragePath()
- {
- return MirConfig.getProp("Producer.Media.Path");
- }
-
- public String getIconStoragePath()
- {
- return MirConfig.getProp("Producer.Image.IconPath");
- }
-
- public String getPublishHost()
- {
- return MirConfig.getProp("Producer.Media.Host");
- }
-
- public String getTinyIcon()
- {
- return MirConfig.getProp("Producer.Icon.TinyText");
- }
-
- public String getBigIcon()
- {
- return MirConfig.getProp("Producer.Icon.BigText");
- }
-
- public String getIconAlt()
- {
- return "Generic media";
- }
-
- public String getURL(Entity ent, Entity mediaTypeEnt)
- {
- String stringSize = ent.getValue("size");
- if (stringSize == null)
- return null;
- int size = Integer.parseInt(stringSize, 10)/1024;
- String title = ent.getValue("title")+
- " - "+mediaTypeEnt.getValue("name")+" "+
- size+" KB";
- return StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+
- ent.getValue("publish_path"), title, imageRoot, getBigIcon());
- }
-
- public String getListView(Entity ent, Entity mediaTypeEnt)
- {
- //String title = ent.getValue("title")+
- // " - "+mediaTypeEnt.getValue("name")+" "+
- // ent.getValue("size")+" Bytes";
- return StringUtil.createIMGLinks(imageHost+
- getBigIcon(), null, null, null);
- }
-
- public boolean isVideo()
- {
- return false;
- }
-
- public boolean isAudio()
- {
- return false;
- }
-
- public boolean isImage()
- {
- return false;
- }
-
-}
-
-
-
+++ /dev/null
-
-package mir.media;
-
-import java.lang.*;
-import java.io.*;
-import java.util.*;
-import java.lang.reflect.*;
-
-import mir.misc.*;
-import mir.entity.*;
-
-/**
- * This class handles saving, fetching creating representations
- * for all images. The image content is stored in the DB. The content is
- * written out to a file at the ProducerImages level.
- * Remember that Handlers for specific image types, Gif, Jpeg, etc..
- * should override it.
- * It implements the MirMedia interface.
- * <p>
- * ok. this is a big hack, it's cause putting the image in the DB
- * and fetching it from the DB needs low level db connections for
- * some reason. Does anyone know how to get around this?
- * -mh 25.09.2001
- *
- * @see mir.media.MirMedia
- * @author mh
- * @version 24.09.2001
- */
-
-
-public class MediaHandlerImages
-{
- protected final String WEBDB_JPG="0";
- protected final String WEBDB_GIF="1";
-
- protected String imageType="0";
- private Logfile theLog = Logfile.getInstance(this.getClass().getName());
-
- public byte[] get(Entity ent, Entity mediaTypeEnt)
- {
- byte[] image_data = null;
-
- try {
- Method method = ent.getClass().getMethod("getImage",null);
- image_data = (byte[])method.invoke(ent, null);
- } catch ( NoSuchMethodException e) {
- theLog.printDebugInfo("method lookup unsuccesful: "+e.toString());
- } catch ( IllegalAccessException e) {
- theLog.printDebugInfo("method illegal: "+e.toString());
- } catch ( InvocationTargetException e) {
- theLog.printDebugInfo("get: invocation target illegal: "+e.toString());
- }
-
-
- return image_data;
- }
-
- protected boolean set(byte[] uploadData, Entity ent, Entity mediaTypeEnt)
- {
- try {
- Class[] params = {byte[].class, String.class};
- theLog.printDebugInfo("NAME: "+ent.getClass().getName()+" "+
- mediaTypeEnt.getClass().getName()+" "+uploadData.length+" "+
- imageType);
- Method method = ent.getClass().getMethod("setImage",params);
- method.invoke(ent, new Object[] {uploadData, imageType});
- } catch ( NoSuchMethodException e) {
- theLog.printDebugInfo("method lookup unsuccesful: "+e.toString());
- return false;
- } catch ( IllegalAccessException e) {
- theLog.printDebugInfo("method illegal: "+e.toString());
- return false;
- } catch ( InvocationTargetException e) {
- theLog.printDebugInfo("set: invocation target illegal: "+e.toString());
- return false;
- }
- //deref. -mh
- uploadData=null;
-
- return true;
- }
-
- public byte[] getIcon(Entity ent)
- {
- byte[] icon_data = null;
-
- try {
- Method method = ent.getClass().getMethod("getIcon",null);
- icon_data = (byte[])method.invoke(ent, null);
- } catch ( NoSuchMethodException e) {
- theLog.printDebugInfo("method lookup unsuccesful: "+e.toString());
- } catch ( IllegalAccessException e) {
- theLog.printDebugInfo("method illegal: "+e.toString());
- } catch ( InvocationTargetException e) {
- theLog.printDebugInfo("getIcon: invocation target illegal: "+e.toString());
- }
-
- return icon_data;
- }
-
- public String getURL(Entity ent, Entity mediaTypeEnt)
- {
- String title = ent.getValue("title");
- return StringUtil.createIMGLinks(ent.getValue("publish_server")+
- ent.getValue("publish_path"), title, ent.getValue("img_height"),
- ent.getValue("img_width"));
- }
-
- public String getListView(Entity ent, Entity mediaTypeEnt)
- {
- //String title = ent.getValue("title");
- return StringUtil.createIMGLinks( MirConfig.getProp("Producer.ProductionHost")+
- ent.getValue("icon_path"), null, ent.getValue("icon_height"),
- ent.getValue("icon_width"));
- }
-
- public String getStoragePath()
- {
- return MirConfig.getProp("Producer.Image.Path");
- }
-
- public String getIconStoragePath()
- {
- return MirConfig.getProp("Producer.Image.IconPath");
- }
-
- public String getPublishHost()
- {
- return MirConfig.getProp("Producer.Image.Host");
- }
-
- public String getTinyIcon ()
- {
- return MirConfig.getProp("Producer.Icon.TinyImage");
- }
-
- public String getBigIcon ()
- {
- return MirConfig.getProp("Producer.Icon.BigImage");
- }
-
- public String getIconAlt ()
- {
- return "Image";
- }
-
- public boolean isVideo ()
- {
- return false;
- }
-
- public boolean isAudio ()
- {
- return false;
- }
-
- public boolean isImage ()
- {
- return true;
- }
-
-}
+++ /dev/null
-
-package mir.media;
-
-import java.lang.*;
-import java.io.*;
-import java.util.*;
-import java.sql.*;
-
-import mir.entity.*;
-
-/**
- * This class handles saving, fetching creating representations
- * for gif images. it overrides MediaHandlerImages.
- *
- * @see mir.media.MediaHandlerImages
- * @see mir.media.MirMedia
- * @author mh
- * @version 24.09.2001
- */
-
-
-public class MediaHandlerImagesGif extends MediaHandlerImages implements MirMedia
-{
-
- public boolean set(byte[] uploadData, Entity ent, Entity mediaTypeEnt)
- {
- imageType = WEBDB_GIF;
- return super.set(uploadData, ent, mediaTypeEnt);
- }
-}
+++ /dev/null
-
-package mir.media;
-
-import java.lang.*;
-import java.io.*;
-import java.util.*;
-import java.sql.*;
-
-import mir.entity.*;
-
-/**
- * This class handles saving, fetching creating representations
- * for jpeg images. it overrides MediaHandlerImages.
- *
- * @see mir.media.MediaHandlerImages
- * @see mir.media.MirMedia
- * @author mh <heckmann@hbe.ca>
- * @version 24.09.2001
- */
-
-
-public class MediaHandlerImagesJpeg extends MediaHandlerImages implements MirMedia
-{
- public boolean set(byte[] uploadData, Entity ent, Entity mediaTypeEnt)
- {
- imageType = WEBDB_JPG;
- return super.set(uploadData, ent, mediaTypeEnt);
- }
-}
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-/**
- * Please note: this media handler produces
- * 3 media files, the raw .mp3, a .m3u which is
- * contains the URL for the mp3 and a .pls which
- * contains the URL to the mp3 in shoutcast playlist
- * format. What's important is that the web server (of
- * the media host) must recognize the .m3u and .pls file
- * extensions and send the proper "audio/x-mpegurl"
- * and "audio/x-scpls" mime-types respectively.
- * If the web server is apache, it's easy, just
- * add:
- *
- * audio/x-mpegurl m3u
- * audio/x-scpl pls
- *
- * to the file pointed to by the "TypesConfig"
- * command in your apache config file. Or add
- * and equivalent AddType command to your httpd.conf.
- * Of course this assumes that the mod_mime is loaded.
- *
- * If the web server is not apache, then your on your own.
- *
- * @see mir.media.MirMedia
- * @author mh <heckmann@hbe.ca>
- * @version 01.12.2001
- */
-
-public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia
-{
-
- public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt ) {
- String ext = mediaTypeEnt.getValue("name");
- String dir = MirConfig.getProp("Producer.Media.Path");
- String mediaHost = MirConfig.getProp("Producer.Media.Host");
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- String baseName = ent.getId();
- String mediaFname = baseName+"."+ext;
- String mp3Pointer = mediaHost+datePath+mediaFname;
- String mpegURLFile = baseName+".m3u";
- String playlistFile = baseName+".pls";
- Integer size = new Integer(uploadedData.length);
- if(FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData)) {
- //if(FileUtil.write(dir+"/"+mediaFname, uploadedData)) {
- //were done with the data, dereference.
- uploadedData=null;
-
- try {
- //write the "meta" files
- //first the .m3u since it only contains one line
- FileUtil.write(dir+"/"+datePath+"/"+mpegURLFile,mp3Pointer.getBytes());
- //now the .pls file
- FileUtil.write(dir+"/"+datePath+"/"+playlistFile,mp3Pointer.getBytes());
- ent.setValueForProperty("is_produced", "1");
- ent.setValueForProperty("icon_is_produced", "1");
- ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
- //ent.setValueForProperty("publish_path", mediaFname);
- ent.setValueForProperty("publish_server", mediaHost);
- ent.setValueForProperty("size", size.toString());
- ent.update();
- } catch (StorageObjectException e) {
- theLog.printError("StorageObjectException: "+e.toString());
- return false;
- }
- } else {
- theLog.printError("could not write FILE!");
- return false;
- }
-
- return true;
- }
-
- public String getURL(Entity ent, Entity mediaTypeEnt)
- {
- String stringSize = ent.getValue("size");
- if (stringSize == null)
- return null;
- int size = Integer.parseInt(stringSize, 10)/1024;
- String rawTitle = ent.getValue("title")+
- " - "+mediaTypeEnt.getValue("name")+" "+
- size+" KB "+"download";
- String m3uTitle = ent.getValue("title")+
- " - "+mediaTypeEnt.getValue("name")+" "+
- "streaming URL";
- String plsTitle = ent.getValue("title")+
- " - "+mediaTypeEnt.getValue("name")+" "+
- "playlist URL";
-
- String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), ".mp3$","");
-
- String m3uURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+basePath+".m3u", m3uTitle, imageRoot, getBigIcon());
- String plsURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+basePath+".pls", plsTitle, imageRoot, getBigIcon());
- String rawURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+ent.getValue("publish_path"), rawTitle, imageRoot, getBigIcon());
-
- return m3uURL+"\n<p>"+plsURL+"\n<p>"+rawURL;
-
- }
-
-}
-
-
-
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-
-/**
- * Handles real audio. like MediaHandlerAudio, except it manages the ram file, too.
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author john <john@manifestor.org>
- * @version 11.10.2001
- */
-
-
-public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia
-{
-
- public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt ) {
- String ext = mediaTypeEnt.getValue("name");
- String dir = MirConfig.getProp("Producer.Media.Path");
- String rtspDir = MirConfig.getProp("Producer.RealMedia.Path");
- String mediaHost = MirConfig.getProp("Producer.Media.Host");
- String rtspMediaHost = MirConfig.getProp("Producer.RealMedia.Host");
-
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- String mediaFname = ent.getId()+"."+ext;
- String realMediaPointer = rtspMediaHost+datePath+mediaFname;
- String realMediaFile = ent.getId()+".ram";
- Integer size = new Integer(uploadedData.length);
- if(FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData)) {
- //if(FileUtil.write(rtspDir+"/"+mediaFname, uploadedData)) {
- //were done with the data, dereference.
- uploadedData=null;
-
- try {
- //write a ram file
- FileUtil.write(dir+"/"+datePath+"/"+realMediaFile,realMediaPointer.getBytes());
- ent.setValueForProperty("is_produced", "1");
- ent.setValueForProperty("icon_is_produced", "1");
- ent.setValueForProperty("publish_path",datePath+"/"+realMediaFile);
- //ent.setValueForProperty("publish_path", realMediaFile);
- ent.setValueForProperty("publish_server", mediaHost);
- ent.setValueForProperty("size", size.toString());
- ent.update();
- } catch (StorageObjectException e) {
- theLog.printError("StorageObjectException: "+e.toString());
- return false;
- }
- } else {
- theLog.printError("could not write FILE!");
- return false;
- }
-
- return true;
- }
-
-}
-
-
-
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-
-/**
- * Handles real video. like MediaHandlerAudio, except it manages the ram file, too.
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author john <john@manifestor.org>
- * @version 11.10.2001
- */
-
-
-public class MediaHandlerRealVideo extends MediaHandlerGeneric implements MirMedia
-{
-
- private String imageHost = MirConfig.getProp("Producer.Image.Host");
- private static String imageRoot = MirConfig.getProp("Producer.ImageRoot");
- private Logfile theLog = Logfile.getInstance(this.getClass().getName());
- public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt ) {
- String ext = mediaTypeEnt.getValue("name");
- String dir = MirConfig.getProp("Producer.Media.Path");
- String rtspDir = MirConfig.getProp("Producer.RealMedia.Path");
- String mediaHost = MirConfig.getProp("Producer.Media.Host");
- String rtspMediaHost = MirConfig.getProp("Producer.RealMedia.Host");
-
- String mediaFname = ent.getId()+"."+ext;
- String RealMediaPointer = rtspMediaHost+mediaFname;
- String RealMediaFile = ent.getId()+".ram";
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- Integer size = new Integer(uploadedData.length);
- if(FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData)) {
- //if(FileUtil.write(rtspDir+"/"+mediaFname, uploadedData)) {
- //were done with the data, dereference.
- uploadedData=null;
-
- try {
-//write an rm file
-FileUtil.write(dir+"/"+RealMediaFile,RealMediaPointer.getBytes());
-
- ent.setValueForProperty("is_produced", "1");
- ent.setValueForProperty("icon_is_produced", "1");
- ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
- //ent.setValueForProperty("publish_path", RealMediaFile);
- ent.setValueForProperty("publish_server", mediaHost);
- ent.setValueForProperty("size", size.toString());
- ent.update();
- } catch (StorageObjectException e) {
- theLog.printError("StorageObjectException: "+e.toString());
- return false;
- }
- } else {
- theLog.printError("could not write FILE!");
- return false;
- }
-
- return true;
- }
-
-
-
-
-
- public String getPublishHost()
- {
- return MirConfig.getProp("Producer.Media.Host");
- }
-
-
-
- public String getURL(Entity ent, Entity mediaTypeEnt)
- {
- int size = Integer.parseInt(ent.getValue("size"), 10)/1024;
- String title = ent.getValue("title")+
- " - "+mediaTypeEnt.getValue("name")+" "+
- size+" KB";
- return StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+
- ent.getValue("publish_path"), title, imageRoot, getBigIcon());
- }
-
-
- private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
- private static String bigIcon = MirConfig.getProp("Producer.Icon.BigVideo");
-
- public String getTinyIcon()
- {
- return tinyIcon;
- }
-
- public String getBigIcon()
- {
- return bigIcon;
- }
-
- public String getIconAlt()
- {
- return "Video";
- }
-
- public boolean isVideo()
- {
- return true;
- }
-
-}
-
-
-
+++ /dev/null
-/*
- * put your module comment here
- */
-
-
-package mir.media;
-
-import java.util.*;
-
-import mir.entity.*;
-import mir.misc.*;
-import mir.storage.*;
-
-
-/**
- * Handles video media, like mpeg, av, and qt
- * It is like MediaHandlerAudio with different icons.
- * It is MediaHandlerGeneric with different icons.
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author john <john@manifestor.org>
- * @version 11.10.2001
- */
-
-public class MediaHandlerVideo extends MediaHandlerGeneric implements MirMedia
-{
-
- private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
- private static String bigIcon = MirConfig.getProp("Producer.Icon.BigVideo");
-
- public String getTinyIcon()
- {
- return tinyIcon;
- }
-
- public String getBigIcon()
- {
- return bigIcon;
- }
-
- public String getIconAlt()
- {
- return "Video";
- }
-
- public boolean isVideo()
- {
- return true;
- }
-}
--- /dev/null
+package mir.media;
+
+import java.lang.reflect.*;
+import java.lang.*;
+
+import mir.entity.Entity;
+import mir.storage.Database;
+
+
+/**
+ * helper class to resolve media handlers using reflection
+ *
+ * @author mh
+ * @version 2002
+ */
+
+public final class MediaHelper {
+
+ static String _classPrefix = "mircoders.media.MediaHandler";
+
+ public static MirMedia getHandler( Entity mediaType )
+ throws MirMediaException {
+
+ MirMedia mediaHandler;
+ String handlerName = mediaType.getValue("classname");
+ try {
+ Class handlerClass = Class.forName(_classPrefix+handlerName);
+ return mediaHandler = (MirMedia)handlerClass.newInstance();
+ } catch (Exception e) {
+ throw new MirMediaException ("getHandler -- error in reflection "
+ +e.toString());
+ }
+ }
+
+ public static Database getStorage(Entity mediaType, String classPrefix)
+ throws MirMediaException {
+
+ Database mediaStorage;
+ String storageName = mediaType.getValue("tablename");
+ try {
+ Class storageClass = Class.forName(classPrefix+storageName);
+ Method m = storageClass.getMethod("getInstance", null);
+ return mediaStorage = (Database)m.invoke(null, null);
+ } catch (Exception e) {
+ throw new MirMediaException ("getStorage -- error in reflection "
+ +e.toString());
+ }
+ }
+
+}
+
+
+
* @return boolean, success/fail
* @see mir.entity.Entity
*/
- public abstract boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt );
+ public abstract boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt ) throws MirMediaException;
/**
* Get's the media data from storage and returns it as a byte array
* @return byte[]
* @see mir.entity.Entity
*/
- public abstract byte[] get (Entity ent, Entity mediaTypeEnt);
+ public abstract byte[] get (Entity ent, Entity mediaTypeEnt)
+ throws MirMediaException;
/**
* Pretty much like get() above. But get's the specific Icon
* @return byte[]
* @see mir.entity.Entity
*/
- public abstract byte[] getIcon (Entity ent);
+ public abstract byte[] getIcon (Entity ent) throws MirMediaException;
/**
* gets the final content representation for the media
* @see mir.entity.Entity
* @see mir.misc.StringUtil
*/
- public abstract String getURL (Entity ent, Entity mediaTypeEnt);
+ public abstract String getURL (Entity ent, Entity mediaTypeEnt)
+ throws MirMediaException;
/**
* gets the summary representation for the media
* @see mir.entity.Entity
* @see mir.misc.StringUtil
*/
- public abstract String getListView (Entity ent, Entity mediaTypeEnt);
+ public abstract String getListView (Entity ent, Entity mediaTypeEnt)
+ throws MirMediaException;
/**
* Returns the absolute filesystem path to where the media
* @return String, the path.
* @see mir.misc.MirConfig
*/
- public abstract String getStoragePath ();
+ public abstract String getStoragePath () throws MirMediaException;
/**
* Returns the *relative* filesystem path to where the media
* @return String, the path.
* @see mir.misc.MirConfig
*/
- public abstract String getIconStoragePath ();
+ public abstract String getIconStoragePath () throws MirMediaException;
/**
* Returns the base URL to that the media is accessible from
* This is used in the Metadata stored in the DB and later on
* ,the templates use it.
* It is usually defined
- * in the configuration wich is accessible through the MirConfig
+ * in the configuration witch is accessible through the MirConfig
* class.
* @return String, the base URL to the host.
* @see mir.misc.MirConfig
*/
- public abstract String getPublishHost ();
+ public abstract String getPublishHost () throws MirMediaException;
/**
* Returns the file name of the Icon representing the media type.
--- /dev/null
+package mir.media;
+
+import java.lang.*;
+
+/*
+ * MirMediaException -
+ *
+ * @version 29.1.2002
+ * @author mh
+ *
+ */
+
+public final class MirMediaException extends Exception
+{
+ String msg;
+
+ public MirMediaException(String msg) {
+ super(msg);
+ this.msg = msg;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+}
+
static {
System.setProperty("content.types.user.table", MirConfig.getProp("Home")+"content-types.properties");
- System.err.println("DDD: "+MirConfig.getProp("Home")+"content-types.properties");
fileNameMap = sun.net.www.MimeTable.loadTable();
producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
}
private FileUtil () {
}
- public static boolean write(String filename, byte[] in) {
+ public static boolean write(String filename, byte[] in)
+ throws IOException {
boolean retVal = false;
outStream.write(in);
outStream.close();
retVal = true;
- } catch(IOException exception) {}
+ } catch(IOException e) {
+ throw new IOException(e.toString());
+ }
}
return retVal;
}
- public static boolean read(String filename, byte out[]) {
+ public static boolean read(String filename, byte out[])
+ throws IOException {
File f = null;
f = new File(filename);
inStream = new FileInputStream(f);
inStream.read(out);
inStream.close();
- } catch(IOException exception) {
- return false;
+ } catch(IOException e) {
+ throw new IOException(e.toString());
}
} else {
return false;
public static String guessContentTypeFromName(String fname) {
String contentType = null;
- System.err.println("NAME: "+fname);
contentType = getFileNameMap().getContentTypeFor(fname);
- System.err.println("TYPE: "+contentType);
+
return contentType;
}
// init
static {
-
+ /** @todo either in the above block or here :) //rk */
templateDir = MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
templateCache = new FileTemplateCache(templateDir);
templateCache.setLoadingPolicy(templateCache.LOAD_ON_DEMAND);
- // gone in freemarker 1.71
+ // gone in freemarker 1.7.1
// templateCache.startAutoUpdate();
-
+ theLog = Logfile.getInstance(MirConfig.getPropWithHome("HTMLTemplateProcessor.Logfile"));
docRoot = MirConfig.getProp("RootUri");
- theLog=Logfile.getInstance("HTMLTemplateProcessor");
-
//the quick hack is back in effect as it was more broken than ever before
// -mh
// sorry: nadir back in town, i have to debug the mirbase.jar in the
// nadir evironment. from my point of coding, this needs an urgent
// fixxx.
// yeah, from my point too - tob.
- //actionRoot = docRoot + "/servlet/" + MirConfig.getProp("ServletName");
+ //actionRoot = docRoot + "/servlet/" + MirConfig.getProp("ServletName");
//actionRoot = docRoot + "/servlet/NadirAktuell";
actionRoot = docRoot + "/servlet/Mir";
/**
* empty private constructor, to avoid instantiation
*/
- private HTMLTemplateProcessor () {}
+ private HTMLTemplateProcessor () { }
// process-methods to merge different datastructures
session=res.encodeURL("");
}
+ /** @todo why do we double those? should be cleaned up and
+ * statically initialized, we do not need to assemble a config
+ * hash everytime we give out a page, only exception is
+ * date "now" // rk */
// put standard configuration into tempalteRootmodel
SimpleHash configHash = new SimpleHash();
configHash.put("docroot", new SimpleScalar(producerDocRoot));
tmr.put("videoHost", new SimpleScalar(videoHost));
tmr.put("audioHost", new SimpleScalar(audioHost));
tmr.put("imageHost", new SimpleScalar(imageHost));
+ // this conform to updated freemarker syntax
+ tmr.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace() );
tmr.put("config", configHash);
tmpl.process(tmr, out);
* Converts Entity-List to SimpleList of SimpleHashes.
* @param aList ist eine Liste von Entity
* @return eine freemarker.template.SimpleList von SimpleHashes.
+ *
+ * @deprecated EntityLists comply with TemplateListModel now.
*/
public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectException
{
+ theLog.printWarning("## using deprecated makeSimpleList(entityList) - a waste of resources");
SimpleList simpleList = new SimpleList();
if (aList != null) {
for(int i=0;i<aList.size();i++) {
* @param entity ist die Entity
* @return SimpleHash mit den entsprechenden freemarker Daten
*
- * @deprecated This method is deprecated and will be deleted in the next release.
- * AbstractEntity interfaces freemarker.template.TemplateHashModel now and can
- * be used in the same way as SimpleHash.
+ * @deprecated This method is deprecated and will be deleted in the next
+ * release. Entity interfaces freemarker.template.TemplateHashModel now
+ * and can be used in the same way as SimpleHash. It is not necessary any
+ * more to make a SimpleHash from an Entity
*/
public static SimpleHash makeSimpleHash(Entity entity) {
- if (entity != null)
+ if (entity != null) {
+ theLog.printWarning("## using deprecated makeSimpleHash(entity) - a waste of resources");
return makeSimpleHash(entity.getValues());
+ }
else
return null;
}
public static SimpleHash makeSimpleHashWithEntitylistInfos(EntityList entList) throws StorageObjectException {
SimpleHash modelRoot = new SimpleHash();
if (entList!=null) {
- modelRoot.put("contentlist", makeSimpleList(entList));
+ modelRoot.put("contentlist", entList);
modelRoot.put("count", new SimpleScalar((new Integer(entList.getCount())).toString()));
if (entList.getWhere()!=null) {
modelRoot.put("where", new SimpleScalar(entList.getWhere()));
{
Template returnTemplate = null;
if (templateFilename!=null)
- returnTemplate = templateCache.getTemplate(templateFilename);
+ returnTemplate = (Template)templateCache.getItem(templateFilename,"template");
if (returnTemplate==null) {
private RandomAccessFile raf;
private String fileName;
- //config var, required since it's "null"
- //TODO: should have a defaul value once I figure out
- //how to disperse home dir. -mh
- private static String logDir="/tmp/";
-
/**
* lineSeparator ermitteln und Repository anlegen
*/
* @return Logfile
*/
public static Logfile getInstance(String fileName) {
- //TODO: tokenize the CallerClass name (fileName)
Logfile returnLogfile = null;
System.err.println(fileName);
if (fileName != null) {
} else {
returnLogfile = new Logfile(fileName);
instanceRepository.put(fileName, returnLogfile);
- Integer i = new Integer(instanceRepository.size());
- System.err.println("SIZZE: "+i.toString());
}
} else {
System.err.println("Fehler bei Instantiierung von Logfile");
* Privater Konstruktor
* @param String fileName
*/
- private Logfile(String file){
- this.fileName = logDir+file;
- System.err.println("FILENAME "+fileName+"DD");
+ private Logfile(String fileName){
+ this.fileName = fileName;
try {
- File f = new File(this.fileName);
+ File f = new File(fileName);
File dir = new File(f.getParent());
dir.mkdirs();
raf = new RandomAccessFile(fileName, "rw");
}
}
- //TODO: should have a defaul value once I figure out
- //how to disperse home dir. -mh
- public static void setLogDir(String dir) {
- logDir=StringUtil.addSeparator(dir);
- System.err.println("set logDir "+logDir);
- }
-
/**
* Private Methode, um eine Zeile auszugeben
*
import java.io.*;
import java.util.*;
import java.lang.*;
-import com.javaexchange.dbConnectionBroker.*;
+import mir.storage.StorageObjectException;
+import mir.storage.DatabaseAdaptor;
+import com.codestudio.util.*;
/**
* Title: Mir
public class MirConfig extends Configuration {
- private static HashMap configHash = new HashMap();
+ private static HashMap configHash = null;
private static HashMap brokerHash = new HashMap();
private static int instances=0;
* @param name, The name of the servlet (usually "Mir")
* @param confName, the name of the config file to load.
*/
- public static void initConfig(String home, String uri, String name, String confName) {
+ public static synchronized void initConfig(String home, String uri,
+ String name, String confName) {
initConfResource(confName);
-
+ configHash = new HashMap();
configHash.put("Home", home);
configHash.put("RootUri", uri);
public static void setServletName(String servletName) {
configHash.put("ServletName",servletName);
}
-
+
/**
* Returns the property asked for by pulling it out a HashMap
* @param a String containing the property name (key)
(String)configHash.get(propName);
}
- public static void addBroker(String driver, String URL){
+ public static void initDbPool () throws StorageObjectException {
+ if (configHash == null) {
+ throw new StorageObjectException("MirConfig -- Trying initialize "+
+ "DB pool when system not yet "+
+ "configured");
+ }
+ String dbUser=getProp("Database.Username");
+ String dbPassword=getProp("Database.Password");
+ String dbHost=getProp("Database.Host");
+ String dbAdapName=getProp("Database.Adaptor");
+ DatabaseAdaptor adaptor;
+ try {
+ adaptor = (DatabaseAdaptor)Class.forName(dbAdapName).newInstance();
+ } catch (Exception e) {
+ throw new StorageObjectException("Could not load DB adapator: "+
+ e.toString());
+ }
+ String dbDriver=adaptor.getDriver();
+ String dbUrl=adaptor.getURL(dbUser,dbPassword, dbHost);
+ System.out.println("adding Broker with: " +dbDriver+":"+dbUrl );
+ addBroker( dbDriver, dbUrl);
+ }
- String username,passwd,min,max,log,reset;
+ public static void addBroker(String driver, String URL)
+ throws StorageObjectException {
+
+ if (configHash == null) {
+ throw new StorageObjectException("MirConfig -- Trying initialize "+
+ "DB pool when system not yet "+
+ "configured");
+ }
+ String username,passwd,min,max,log,reset,dbname,dblogfile;
if(!brokerHash.containsKey("Pool.broker")){
username=getProp("Database.Username");
passwd=getProp("Database.Password");
min=getProp("Database.poolMin");
max=getProp("Database.poolMax");
- log=getProp("Home") + configHash.get("Database.PoolLog");
+ dbname=getProp("Database.Name");
+ log=getProp("Home")+ configHash.get("Database.PoolLog");
reset=getProp("Database.poolResetTime");
-
- try{
- System.err.println("-- making Broker for -"
- +driver+" - " +URL
- + " log " + log + " user "
- + username + " pass: " + passwd);
-
- DbConnectionBroker br = new DbConnectionBroker(driver,URL,username,passwd,(new Integer(min)).intValue(),
- (new Integer(max)).intValue(),log,(new Float(reset)).floatValue());
- if (br!=null){
- instances++;
- brokerHash.put("Pool.broker",br);
- } else {
- throw new Exception();
- }
- } catch(Exception e){
- System.err.println("Der ConnectionBroker konnte nicht initializiert werden"+ e.toString());e.printStackTrace();
+ dblogfile=getPropWithHome("Database.Logfile");
+
+ System.err.println("-- making Broker for -"
+ +driver+" - " +URL
+ + " log " + log + " user "
+ + username + " pass: " + passwd);
+
+ JDBCPoolMetaData meta = new JDBCPoolMetaData();
+ meta.setDbname(dbname);
+ meta.setDriver(driver);
+ meta.setURL(URL);
+ meta.setUserName(username);
+ meta.setPassword(passwd);
+ meta.setJNDIName("mir");
+ meta.setMaximumSize(Integer.parseInt(max));
+ meta.setMinimumSize(Integer.parseInt(min));
+ meta.setCacheEnabled(false);
+ meta.setCacheSize(15);
+ meta.setDebugging(false);
+ meta.setLogFile(dblogfile+".pool");
+
+ JDBCPool pool = SQLManager.getInstance().createPool(meta);
+
+ if (pool!=null){
+ instances++;
+ brokerHash.put("Pool.broker",pool);
}
- } // end if
- }
- /**
- * Liefert DBConnectionBroker einer Configuration zurueck
- * @param confFilename
- * @return DBConnectionBroker
- */
- public static DbConnectionBroker getBroker() {
- DbConnectionBroker broker=null;
- broker=(DbConnectionBroker)brokerHash.get("Pool.broker");
- if (broker==null) {
- System.err.println("Konnte kein ConnectionPoolBroker initialisiert werden");
- }
- return broker;
- }
-
- /**
- * Liefert Anzahl der Instantiierten DBConnectionBroker zurueck
- * @return
- */
- public static int getBrokerInstances() {
- return instances;
- }
-
- public static DbConnectionBroker getBrokerInfo(){
- return (DbConnectionBroker)brokerHash.get("Pool.broker");
+ } // end if
}
/**
String fileName=null;
String fileContentType=null;
- public MpRequest(byte[] i_uploadData, String i_fileName, String i_contentType){
+ public MpRequest(byte[] i_uploadData, String i_fileName,
+ String i_contentType){
setFilename(i_fileName);
setContentType(i_contentType);
setMedia(i_uploadData);
*/
public final class StringUtil {
- /**
- * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
- * @param theDate
- * @return 8-ziffriger String (yyyymmdd)
- */
-
- public static final String date2webdbDate (GregorianCalendar theDate) {
- StringBuffer webdbDate = new StringBuffer();
- webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
- webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
- webdbDate.append(pad2(theDate.get(Calendar.DATE)));
- return webdbDate.toString();
- }
-
- /**
- * wandelt Calendar in dd.mm.yyyy / hh.mm um
- * @param theDate
- * @return String mit (dd.mm.yyyy / hh.mm um)
- */
- public static String date2readableDateTime (GregorianCalendar theDate) {
- String readable = "";
- int hour;
- readable += pad2(theDate.get(Calendar.DATE));
- readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
- readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
- hour = theDate.get(Calendar.HOUR);
- if (theDate.get(Calendar.AM_PM) == Calendar.PM)
- hour += 12;
- readable += " / " + pad2(hour);
- readable += ":" + pad2(theDate.get(Calendar.MINUTE));
- return readable;
- }
-
- /**
- * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
- * getrennt ist.
- *
- * @param webdbDate
- * @return String mit <code>/yyyy/mm/dd</code>
- */
- public static final String webdbDate2path (String webdbDate) {
- StringBuffer path = new StringBuffer();
- path.append("/").append(webdbDate.substring(0, 4));
- path.append("/").append(webdbDate.substring(4, 6));
- path.append("/");
- //who did this?
- //path.append("/").append(webdbDate.substring(6, 8));
- return path.toString();
- }
-
- /**
- * wandelt Calendar in dd.mm.yyyy um
- *
- * @param theDate
- * @return String mit <code>dd.mm.yyyy</code>
- */
- public static final String webdbDate2readableDate (String webdbDate) {
- String date = "";
- date += webdbDate.substring(6, 8);
- date += "." + webdbDate.substring(4, 6);
- date += "." + webdbDate.substring(0, 4);
- return date;
- }
-
-
- /**
- * converts string from format: yyyy-mm-dd__hh:mm:ss.d
- * to dd.mm.yyyy hh:mm
- */
- public static String dateToReadableDate(String date) {
- StringBuffer returnDate = new StringBuffer();
- if (date!=null) {
-
- returnDate.append(date.substring(8,10)).append('.');
- returnDate.append(date.substring(5,7)).append('.');
- returnDate.append(date.substring(0,4)).append(' ');
- returnDate.append(date.substring(11,16));
- }
- return returnDate.toString();
- }
-
-
- /**
- * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
- *
- * @return gequoteter String
- */
- public static String quoteIfNecessary(String s) {
- for (int i = 0; i < s.length(); i++)
- if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
- return quote(s, '"');
- return s;
- }
-
- /**
- * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
- * "gefährliche" Zeichen innerhalb des Strings
- * Quotes special SQL-characters in <code>s</code>
- *
- * @return geqoteter String
- */
- public static String quote(String s)
- {
- //String s2 = quote(s, '\'');
-
- //Quickhack
- //Because of '?-Bug in Postgresql-JDBC-Driver
- StringBuffer temp = new StringBuffer();
- for(int i=0;i<s.length();i++){
- if(s.charAt(i)=='\''){
- temp.append("´");
- } else {
- temp.append(s.charAt(i));
- }
- }
- String s2 = temp.toString();
- //Quickhack end
-
- s2 = quote(s2, '\"');
- return s2;
- }
-
- /**
- * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
- * "gefährliche" Zeichen innerhalb des Strings
- *
- * @param s String, der gequoted werden soll
- * @param quoteChar zu quotendes Zeichen
- * @return gequoteter String
- */
- public static String quote(String s, char quoteChar)
- {
- StringBuffer buf = new StringBuffer(s.length());
- int pos = 0;
- while (pos < s.length()) {
- int i = s.indexOf(quoteChar, pos);
- if (i < 0) i = s.length();
- buf.append(s.substring(pos, i));
- pos = i;
- if (pos < s.length()) {
- buf.append('\\');
- buf.append(quoteChar);
- pos++;
- }
- }
- return buf.toString();
- }
-
- /**
- * replaces dangerous characters in <code>s</code>
- *
- */
-
- public static String unquote(String s)
- {
- char quoteChar='\'';
- StringBuffer buf = new StringBuffer(s.length());
- int pos = 0;
- String searchString = "\\"+quoteChar;
- while (pos < s.length()) {
- int i = s.indexOf(searchString, pos);
- if (i < 0) i = s.length();
- buf.append(s.substring(pos, i));
- pos = i+1;
- }
- return buf.toString();
- }
-
- /**
- * Wandelet String in byte[] um.
- * @param s
- * @return byte[] des String
- */
-
- public static byte[] stringToBytes(String s) {
- String crlf = System.getProperty("line.separator");
- if (!crlf.equals("\n"))
- s = replace(s, "\n", crlf);
- // byte[] buf = new byte[s.length()];
- byte[] buf = s.getBytes();
- return buf;
- }
-
- /**
- * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
- * @param s
- * @param pattern
- * @param substitute
- * @return String mit den Ersetzungen
- */
- public static String replace(String s, String pattern, String substitute) {
- int i = 0, pLen = pattern.length(), sLen = substitute.length();
- StringBuffer buf = new StringBuffer(s.length());
- while (true) {
- int j = s.indexOf(pattern, i);
- if (j < 0) {
- buf.append(s.substring(i));
- break;
- } else {
- buf.append(s.substring(i, j));
- buf.append(substitute);
- i = j+pLen;
- }
- }
- return buf.toString();
- }
-
- /**
- * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
- * @param s
- * @param pattern
- * @param substitute
- * @return String mit den Ersetzungen
- */
- public static String regexpReplace(String haystack, String pattern, String substitute) {
- try {
- RE regex = new RE(pattern);
- return regex.substituteAll(haystack,substitute);
- } catch(REException ex){
- return null;
- }
- }
-
-
-
-
- /**
- * Fügt einen Separator an den Pfad an
- * @param path
- * @return Pfad mit Separator am Ende
- */
- public static final String addSeparator (String path) {
- return path.length() == 0 || path.endsWith(File.separator) ? path : path
- + File.separatorChar;
- }
-
- /**
- * Fügt ein <code>/</code> ans ende des Strings and
- * @param path
- * @return Pfad mit <code>/</code> am Ende
- */
- public static final String addSlash (String path) {
- return path.length() == 0 || path.endsWith("/") ? path : path + '/';
- }
-
- /**
- * Löscht <code>/</code> am Ende des Strings, falls vorhanden
- * @param path
- * @return String ohne <code>/</code> am Ende
- */
- public static final String removeSlash (String path) {
- return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
- - 1) : path;
- }
-
- /**
- * Checks to see if the path is absolute by looking for a leading file
- * separater
- * @todo deal with windows drive letters.
- * @param path
- * @return
- */
- public static boolean isAbsolutePath (String path) {
- return path.startsWith(File.separator);
- }
-
- /**
- * Löscht Slash am Anfang des Strings
- * @param path
- * @return
- */
- public static String removeFirstSlash (String path) {
- return path.startsWith("/") ? path.substring(1) : path;
- }
-
- /**
- * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
- * @return zwistellige Zahl
- */
- public static String pad2 (int number) {
- return number < 10 ? "0" + number : String.valueOf(number);
- }
-
- /**
- * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
- *
- * @return 3-stellige Zahl
- */
- public static String pad3 (int number) {
- return number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
- }
-
- /**
- * Konvertiert Unix-Linefeeds in Win-Linefeeds
- * @param s
- * @return Konvertierter String
- */
- public static String unixLineFeedsToWin(String s) {
- int i = -1;
- while (true) {
- i = s.indexOf('\n', i+1);
- if (i < 0) break;
- if ((i == 0 || s.charAt(i-1) != '\r') &&
- (i == s.length()-1 || s.charAt(i+1) != '\r')) {
- s = s.substring(0, i)+'\r'+s.substring(i);
- i++;
- }
- }
- return s;
- }
-
-
- /**
- * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen
- * und Spaces werden zu Underscores
- *
- * @return gültige Url
- */
- public static String convert2url(String s) {
- s = toLowerCase(s);
- StringBuffer buf = new StringBuffer();
- for(int i = 0; i < s.length(); i++ ) {
- switch( s.charAt( i ) ) {
- case 'ö':
- buf.append( "oe" ); break;
- case 'ä':
- buf.append( "ae" ); break;
- case 'ü':
- buf.append( "ue" ); break;
- case 'ã':
- buf.append( "a" ); break;
- case '´':
- case '.':
- buf.append( "_" ); break;
- case ' ':
- if( buf.charAt( buf.length() - 1 ) != '_' ) {
- buf.append( "_" );
- }
- break;
- default:
- buf.append( s.charAt( i ) );
- }
- }
- return buf.toString();
- }
-
- /**
- * wandelt Sonderzeichen in Quotes um
- *
- * @return Kovertierter String
- */
- public static String encodeHtml(String s) {
- StringBuffer buf = new StringBuffer();
- for(int i=0;i < s.length(); i++ ) {
-
- /** @todo looks inefficient */
- if (s.charAt(i)=='&') {
- // convert html to xml-parsable representation
- if( s.indexOf( "ö", i ) == i ) {
- buf.append( "ö" ); i += 5;
- continue;
- }
- if( s.indexOf( "ä", i ) == i ) {
- buf.append( "ä" ); i += 5;
- continue;
- }
- if( s.indexOf( "ü", i ) == i ) {
- buf.append( "ü" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ö", i ) == i ) {
- buf.append( "Ö" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ä", i ) == i ) {
- buf.append( "Ä" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ü", i ) == i ) {
- buf.append( "Ü" ); i += 5;
- continue;
- }
- if( s.indexOf( "ß", i ) == i ) {
- buf.append( "ß" ); i += 6;
- continue;
- }
-
- /** @todo should only escape outside of tags */
-
- if( s.indexOf( """, i ) == i ) {
- buf.append( "ß" ); i += 5;
- continue;
- }
- if( s.indexOf( "–", i ) == i ) {
- buf.append( "–" ); i += 6;
- continue;
- }
- if( s.indexOf( "—", i ) == i ) {
- buf.append( "—" ); i += 6;
- continue;
- }
- if( s.indexOf( "“", i ) == i ) {
- buf.append( "“" ); i += 6;
- continue;
- }
- if( s.indexOf( "”", i ) == i ) {
- buf.append( "”" ); i += 6;
- continue;
- }
- if( s.indexOf( "„", i ) == i ) {
- buf.append( "„" ); i += 6;
- continue;
- }
-
- //looks pretty stupid
- if( s.indexOf( "<", i ) == i ) {
- buf.append( "<" ); i += 3;
- continue;
- }
- if( s.indexOf( ">", i ) == i ) {
- buf.append( ">" ); i += 3;
- continue;
- }
- if( s.indexOf( "´", i ) == i ) {
- buf.append( "´" ); i += 6;
- continue;
- }
- if( s.indexOf( " ", i ) == i ) {
- buf.append( " " ); i += 5;
- continue;
- }
- //has to be the last
- if( s.indexOf( "&", i ) == i ) {
- buf.append( "&" ); i += 0;
- continue;
- }
- }
- // convert umlauts an other special charakters
- switch( s.charAt(i) ) {
- case 'ö': buf.append( "ö" ); break;
- case 'ä': buf.append( "ä" ); break;
- case 'ü': buf.append( "ü" ); break;
- case 'Ö': buf.append( "Ö" ); break;
- case 'Ä': buf.append( "Ä" ); break;
- case 'Ü': buf.append( "Ü" ); break;
- case 'ß': buf.append( "ß" ); break;
- case 'é': buf.append( "é" ); break;
- case 'è': buf.append( "è" ); break;
- case 'á': buf.append( "á" ); break;
- case 'à': buf.append( "à" ); break;
- case 'â': buf.append( "â" ); break;
- case 'ã': buf.append( "ã" ); break;
- case '¬': buf.append( "¬" ); break;
- case '¹': buf.append( "¹" ); break;
- case '²': buf.append( "²" ); break;
- case '³': buf.append( "³" ); break;
- case '¼': buf.append( "¼" ); break;
- case '½': buf.append( "½" ); break;
- case '¾': buf.append( "¾" ); break;
- case '¶': buf.append( "¶" ); break;
- case 'æ': buf.append( "æ" ); break;
- case 'ð': buf.append( "ð" ); break;
- case '|': buf.append( "¦" ); break;
- case '·': buf.append( "·" ); break;
- case '°': buf.append( "°" ); break;
- case '§': buf.append( "§" ); break;
- case 'ø': buf.append( "ø" ); break;
- case 'ç': buf.append( "ç" ); break;
- case '¤': buf.append( "¤" ); break;
- case 'ª': buf.append( "ª" ); break;
- case 'Ç': buf.append( "Ç" ); break;
- case 'Ã': buf.append( "Ã" ); break;
- case 'Â': buf.append( "Â" ); break;
- case 'Æ': buf.append( "Æ" ); break;
- case '©': buf.append( "©" ); break;
- case '®': buf.append( "®" ); break;
- case '¥': buf.append( "¥" ); break;
- case 'Þ': buf.append( "þ" ); break;
- case '¯': buf.append( "¯" ); break;
- case 'Ð': buf.append( "Ð" ); break;
- case 'º': buf.append( "º" ); break;
- case '¡': buf.append( "¡" ); break;
- case '£': buf.append( "£" ); break;
- case '±': buf.append( "±" ); break;
- case '¿': buf.append( "¿" ); break;
- case 'Ø': buf.append( "Ø" ); break;
- case 'Á': buf.append( "À" ); break;
- case 'À': buf.append( "Á" ); break;
- case 'É': buf.append( "È" ); break;
- case 'È': buf.append( "É" ); break;
- case 'ù': buf.append( "ú" ); break;
- case 'ñ': buf.append( "ñ" ); break;
- case 'Ñ': buf.append( "Ñ" ); break;
- case 'µ': buf.append( "µ" ); break;
- case 'Í': buf.append( "Ì" ); break;
- case 'Ì': buf.append( "Í" ); break;
- case 'í': buf.append( "ì" ); break;
- case 'ì': buf.append( "í" ); break;
- case 'î': buf.append( "î" ); break;
- case 'Î': buf.append( "Î" ); break;
- case 'ó': buf.append( "ó" ); break;
- case 'Ó': buf.append( "Ò" ); break;
- case 'ò': buf.append( "Î" ); break;
- case 'Ò': buf.append( "Ó" ); break;
- case 'ô': buf.append( "ô" ); break;
- case 'Ô': buf.append( "Ô" ); break;
- case 'õ': buf.append( "õ" ); break;
- case 'Õ': buf.append( "Õ" ); break;
- case 'ý': buf.append( "ý" ); break;
- case 'Ý': buf.append( "Ý" ); break;
- case 'û': buf.append( "û" ); break;
- case 'Û': buf.append( "Û" ); break;
- case 'ú': buf.append( "ù" ); break;
- case 'Ú': buf.append( "Ù" ); break;
- case 'Ù': buf.append( "Ú" ); break;
- case 'Ê': buf.append( "Ê" ); break;
- case 'ê': buf.append( "ê" ); break;
- case 'å': buf.append( "å" ); break;
- case 'Å': buf.append( "Å" ); break;
- case 'ë': buf.append( "ë" ); break;
- case 'Ë': buf.append( "Ë" ); break;
- case 'ÿ': buf.append( "ÿ" ); break;
- case 'ï': buf.append( "ï" ); break;
- case 'Ï': buf.append( "Ï" ); break;
- case '«': buf.append( "«" ); break;
- case '»': buf.append( "»" ); break;
- case '\'': buf.append( "´" ); break;
- case '\"': buf.append( """ ); break;
- //case '\u8211': buf.append( "–" ); break;
- //case '\u8212': buf.append( "—" ); break;
- //case '\u8220': buf.append( "“" ); break;
- //case '\u8221': buf.append( "”" ); break;
- //case '\u8222': buf.append( "„" ); break;
- //case '\"': buf.append( """ ); break;
- default: buf.append( s.charAt(i) );
- }
-
- }
- return buf.toString();
- }
-
-
- public static String decodeHTMLinTags(String s){
- StringBuffer buffer = new StringBuffer();
- boolean start = false;
- boolean stop = false;
- int startIndex = 0;
- int stopIndex = 0;
- int temp = 0;
-
- for(int i=0;i<s.length();i++){
- if(s.charAt(i)=='<'){
- start = true;
- startIndex = i;
- } else if(s.charAt(i)=='>'){
- stop = true;
- stopIndex = i;
-
- if(start && stop){
- buffer.append(s.substring(temp,startIndex));
- buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1)));
- i= temp= stopIndex+1;
- start= stop= false;
- }
- }
- }
- if(stopIndex>0){
- buffer.append(s.substring(stopIndex+1));
- return buffer.toString();
- } else {
- return s;
- }
- }
-
- public static String replaceQuot(String s) {
- StringBuffer buffer = new StringBuffer();
- for(int j = 0; j < s.length();j++){
- if(s.charAt(j)=='&'){
- if(s.indexOf( """,j) == j) {
- buffer.append( "\"" );
- j += 5;
- }//if
- } else {
- buffer.append(s.charAt(j));
- }//else
- }//for
- return buffer.toString();
- }
-
- /** wandelt Quotes in Sonderzeichen um
- */
- /**
- public static String decodeHtml(String s) {
- StringBuffer buf = new StringBuffer();
- for(int i=0;i < s.length(); i++ ) {
- if( s.indexOf( "ö", i ) == i ) {
- buf.append( "ö" ); i += 5;
- continue;
- }
- if( s.indexOf( "ä", i ) == i ) {
- buf.append( "ä" ); i += 5;
- continue;
- }
- if( s.indexOf( "ü", i ) == i ) {
- buf.append( "ü" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ö", i ) == i ) {
- buf.append( "Ö" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ä", i ) == i ) {
- buf.append( "Ä" ); i += 5;
- continue;
- }
- if( s.indexOf( "Ü", i ) == i ) {
- buf.append( "Ü" ); i += 5;
- continue;
- }
- if( s.indexOf( "ß", i ) == i ) {
- buf.append( "ß" ); i += 6;
- continue;
- }
- if( s.indexOf( """, i ) == i ) {
- buf.append( "\"" ); i += 5;
- continue;
- }
- buf.append( s.charAt(i) );
- }
- return buf.toString();
- }
- */
-
- /**
- * schnellere Variante der String.toLowerCase()-Routine
- *
- * @return String in Kleinbuchsten
- */
- public static String toLowerCase(String s) {
- int l = s.length();
- char[] a = new char[l];
- for (int i = 0; i < l; i++)
- a[i] = Character.toLowerCase(s.charAt(i));
- return new String(a);
- }
-
- /**
- * Findet <code>element</code> im String-Array <code>array</code>
- * @param array
- * @param element
- * @return Fundstelle als int oder -1
- */
- public static int indexOf(String[] array, String element) {
- if (array != null)
- for (int i = 0; i < array.length; i++)
- if (array[i].equals(element))
- return i;
- return -1;
- }
-
- /**
- * Testet auf Vorkommen von <code>element</code> in <code>array</code>
- * @param array String-Array
- * @param element
- * @return true wenn <code>element</code> vorkommt, sonst false
- */
- public static boolean contains(String[] array, String element) {
- return indexOf(array, element) >= 0;
- }
-
- /**
- * Ermittelt CRC-Prüfsumme von String <code>s</code>
- * @param s
- * @return CRC-Prüfsumme
- */
- public static int getCRC(String s) {
- int h = 0;
- char val[] = s.toCharArray();
- int len = val.length;
-
- for (int i = 0 ; i < len; i++) {
- h &= 0x7fffffff;
- h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
- }
-
- return (h << 8) | (len & 0xff);
- }
+ private static RE re_newline2br, re_brbr2p, re_mail, re_url, re_tags;
+
+ private StringUtil() { } // this avoids contruction
+
+ static {
+ try {
+ //precompile regex
+ re_newline2br = new RE("(\r?\n){1}");
+ re_brbr2p = new RE("(<br>\r?\n<br>){1,}");
+ re_mail = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)");
+ re_url = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
+ re_tags = new RE("<[^>]*>",RE.REG_ICASE);
+ }
+ catch (REException e){
+ System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
+ }
+ }
+
+
+ /**
+ * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
+ * @param theDate
+ * @return 8-ziffriger String (yyyymmdd)
+ */
+
+ public static final String date2webdbDate (GregorianCalendar theDate) {
+ StringBuffer webdbDate = new StringBuffer();
+ webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
+ webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
+ webdbDate.append(pad2(theDate.get(Calendar.DATE)));
+ return webdbDate.toString();
+ }
+
+ /**
+ * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
+ * @param theDate
+ * @return 12-ziffriger String (yyyymmdd)
+ */
+
+ public static final String date2webdbDateTime (GregorianCalendar theDate) {
+ StringBuffer webdbDate = new StringBuffer();
+ webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
+ webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
+ webdbDate.append(pad2(theDate.get(Calendar.DATE)));
+ webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
+ webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
+ return webdbDate.toString();
+ }
+
+ /**
+ * wandelt Calendar in dd.mm.yyyy / hh.mm um
+ * @param theDate
+ * @return String mit (dd.mm.yyyy / hh.mm um)
+ */
+ public static String date2readableDateTime (GregorianCalendar theDate) {
+ String readable = "";
+ int hour;
+ readable += pad2(theDate.get(Calendar.DATE));
+ readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
+ readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
+ hour = theDate.get(Calendar.HOUR);
+ if (theDate.get(Calendar.AM_PM) == Calendar.PM)
+ hour += 12;
+ readable += " / " + pad2(hour);
+ readable += ":" + pad2(theDate.get(Calendar.MINUTE));
+ return readable;
+ }
+
+ /**
+ * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
+ * getrennt ist.
+ *
+ * @param webdbDate
+ * @return String mit <code>/yyyy/mm/dd</code>
+ */
+ public static final String webdbDate2path (String webdbDate) {
+ StringBuffer path = new StringBuffer();
+ path.append("/").append(webdbDate.substring(0, 4));
+ path.append("/").append(webdbDate.substring(4, 6));
+ path.append("/");
+ //who did this?
+ //path.append("/").append(webdbDate.substring(6, 8));
+ return path.toString();
+ }
+
+ /**
+ * wandelt Calendar in dd.mm.yyyy um
+ *
+ * @param theDate
+ * @return String mit <code>dd.mm.yyyy</code>
+ */
+ public static final String webdbDate2readableDate (String webdbDate) {
+ String date = "";
+ date += webdbDate.substring(6, 8);
+ date += "." + webdbDate.substring(4, 6);
+ date += "." + webdbDate.substring(0, 4);
+ return date;
+ }
+
+
+ /**
+ * converts string from format: yyyy-mm-dd__hh:mm:ss.d
+ * to dd.mm.yyyy hh:mm
+ */
+ public static String dateToReadableDate(String date) {
+ StringBuffer returnDate = new StringBuffer();
+ if (date!=null) {
+
+ returnDate.append(date.substring(8,10)).append('.');
+ returnDate.append(date.substring(5,7)).append('.');
+ returnDate.append(date.substring(0,4)).append(' ');
+ returnDate.append(date.substring(11,16));
+ }
+ return returnDate.toString();
+ }
+
+ /**
+ * converts string from format: yyyy-mm-dd__hh:mm:ss.d
+ * to yyyy
+ */
+ public static String dateToYear (String date) {
+ StringBuffer returnDate = new StringBuffer();
+ if (date!=null) {
+
+ returnDate.append(date.substring(0,4));
+ }
+ return returnDate.toString();
+ }
+
+ /**
+ * converts string from format: yyyy-mm-dd__hh:mm:ss.d
+ * to [m]m
+ */
+ public static String dateToMonth (String date) {
+ StringBuffer returnDate = new StringBuffer();
+ if (date!=null) {
+ if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
+ else returnDate.append(date.substring(6,7));
+ }
+ return returnDate.toString();
+ }
+
+ /**
+ * converts string from format: yyyy-mm-dd__hh:mm:ss.d
+ * to [d]d
+ */
+ public static String dateToDayOfMonth (String date) {
+ StringBuffer returnDate = new StringBuffer();
+ if (date!=null) {
+ if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
+ else returnDate.append(date.substring(9,10));
+ }
+ return returnDate.toString();
+ }
+
+ /**
+ * converts string from format: yyyy-mm-dd__hh:mm:ss.d
+ * to hh:mm
+ */
+ public static String dateToTime (String date) {
+ StringBuffer returnDate = new StringBuffer();
+ if (date!=null) {
+ returnDate.append(date.substring(11,16));
+ }
+ return returnDate.toString();
+ }
/**
- * Liefert Default-Wert def zurück, wenn String <code>s</code>
- * kein Integer ist.
- *
- * @param s
- * @param def
- * @return geparster int aus s oder def
- */
- public static int parseInt(String s, int def) {
- if (s == null) return def;
- try {
- return Integer.parseInt(s);
- } catch (NumberFormatException e) {
- return def;
- }
- }
-
- /**
- * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
- * @param s
- * @param def
- * @return geparster float oder def
- */
- public static float parseFloat(String s, float def) {
- if (s == null) return def;
- try {
- return new Float(s).floatValue();
- } catch (NumberFormatException e) {
- return def;
- }
- }
-
- /**
- * Findet Ende eines Satzes in String <code>text</code>
- * @param text
- * @param startIndex
- * @return index des Satzendes, oder -1
- */
- public static int findEndOfSentence(String text, int startIndex) {
- while (true) {
- int i = text.indexOf('.', startIndex);
- if (i < 0) return -1;
- if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
- (i+1 >= text.length()
- || text.charAt(i+1) == ' '
- || text.charAt(i+1) == '\n'
- || text.charAt(i+1) == '\t'))
- return i+1;
- startIndex = i+1;
- }
- }
-
- /**
- * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
- * @param text
- * @param startIndex
- * @return Index des Wortendes, oder -1
- */
- public static int findEndOfWord(String text, int startIndex) {
- int i = text.indexOf(' ', startIndex),
- j = text.indexOf('\n', startIndex);
- if (i < 0) i = text.length();
- if (j < 0) j = text.length();
- return Math.min(i, j);
- }
-
- /**
- * This routine makes html links (href) out of text browseable urls
- * @param text
- * @return Konvertierter String
- */
- public static String makeLinks(String text) {
- int i = 0;
- StringBuffer buf = new StringBuffer(text.length());
- while (true) {
- int j = text.indexOf("http://", i);
- if (j < 0) {
- buf.append(text.substring(i));
- break;
- } else {
- buf.append(text.substring(i, j));
- int k = findEndOfWord(text,j+7);
- String url="";
- if (k<0) url = text.substring(j);
- else url = text.substring(j,k);
-
- buf.append("<a href=\042"+url+"\042>"+url+"</a>");
- //System.out.println("url mark: " + url);
- i = j+url.length();
- }
- }
- return buf.toString();
-
- }
-
-
- /**
- * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
- * in den html-tag <p>
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String convertNewline2P(String haystack) {
- try {
- RE regex = new RE("(<br>\r?\n<br>){1,}");
- return regex.substituteAll(haystack,"\n</p><p>");
- } catch(REException ex){
- return null;
- }
- }
-
- /**
- * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
- * in den html-tag <br>
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String convertNewline2Break(String haystack) {
- try {
- RE regex = new RE("(\r?\n){1}");
- return regex.substituteAll(haystack,"$0<br>");
- } catch(REException ex){
- return null;
- }
- }
-
- /**
- * createMailLinks wandelt text im email-adressenformat
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createMailLinks(String haystack) {
- try {
- RE regex = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)");
- return regex.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
- } catch(REException ex){
- return null;
- }
- }
-
-
- /**
- * createMailLinks wandelt text im email-adressenformat
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
- try {
- RE regex = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+).([a-zA-Z0-9_.-]+)");
- return regex.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
- } catch(REException ex){
- return null;
- }
- }
-
-
- /**
- * createURLLinks wandelt text im url-format
- * in einen klickbaren link um
- * nur sinnvoll, wenn text nicht im html-format eingegeben
- */
- public static String createURLLinks(String haystack) {
- try {
- //dieser Ausdruck brauch dringend fachliche Beratung
- RE regex = new RE("((https://)|(http://)|(ftp://))+([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/([^ \t\r\n<>]+[^ \t\r\n.,<>])");
- return regex.substituteAll(haystack,"<a href=\"$0\">$0</a>");
- } catch(REException ex){
- return null;
- }
- }
-
- /**
- * this routine takes text in url format and makes
- * a clickaeble "<href>" link removing any "illegal" html tags
- * @param haystack, the url
- * @param title, the href link text
- * @param imagRoot, the place to find icons
- * @param extImage, the url of the icon to show next to the link
- * @return a String containing the url
- */
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
- try {
- //dieser Ausdruck brauch dringend fachliche Beratung
- RE regex = new RE("((https://)|(http://)|(ftp://))+([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>]+[^ \t\r\n.,<>])");
- if (title == null) {
- return regex.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
- } else {
- title = removeHTMLTags(title);
- return regex.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">"+title+"</a>");
- }
- } catch(REException ex){
- return null;
- }
- }
-
- /**
- * this routine takes text in url format and makes
- * a clickaeble "<href>" link removing any "illegal" html tags
- * @param haystack, the url
- * @param imageRoot, the place to find icons
- * @param extImage, the url of the icon to show next to the link
- * @param intImage, unused
- * @return a String containing the url
- */
- public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
- return createURLLinks(haystack, title, imageRoot, extImage);
- }
-
- /**
- * this routine takes text in url format and makes
- * an image link removing any "illegal" html tags
- * @param haystack, the url
- * @param title, the image alt text, can be null
- * @param height, height of the image
- * @param width, width of the image
- * @return a String containing the url
- */
- public static String createIMGLinks(String haystack, String title, String height,String width) {
- try {
- //dieser Ausdruck brauch dringend fachliche Beratung
- RE regex = new RE("((https://)|(http://)|(ftp://))+([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>]+[^ \t\r\n.,<>])");
- if (title != null) {
- title = removeHTMLTags(title);
- return regex.substituteAll(haystack,"<img src=\"$0\" width=\""+width+"\" height=\""+height+"\" alt=\""+title+"\"/> <br><i>"+title+"</i>");
- } else {
- return regex.substituteAll(haystack,"<img src=\"$0\" width=\""+width+"\" height=\""+height+"\" alt=\"\"/> ");
- }
- } catch(REException ex){
- return null;
- }
- }
-
-
-
- /**
- * deleteForbiddenTags
- * this method deletes all <script>, <body> and <head>-tags
- */
- public static String deleteForbiddenTags(String haystack) {
- try {
- RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
- regex = new RE("<head>(.*?)</head>");
- haystack = regex.substituteAll(haystack,"");
- regex = new RE("<[ \t\r\n/]*body(.*?)>");
- haystack = regex.substituteAll(haystack,"");
- return haystack;
- } catch(REException ex){
- return null;
- }
- }
-
- /**
- * this method deletes all html tags
+ * Splits the provided CSV text into a list. stolen wholesale from
+ * from Jakarta Turbine StrinUtils.java -mh
*
+ * @param text The CSV list of values to split apart.
+ * @param separator The separator character.
+ * @return The list of values.
*/
-
- public static String removeHTMLTags(String haystack){
-try {
- RE regex = new RE("<[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- return haystack;
- } catch(REException ex){
- return null;
- }
-
-
+ public static String[] split(String text, String separator)
+ {
+ StringTokenizer st = new StringTokenizer(text, separator);
+ String[] values = new String[st.countTokens()];
+ int pos = 0;
+ while (st.hasMoreTokens())
+ {
+ values[pos++] = st.nextToken();
+ }
+ return values;
}
/**
- * this method deletes all but the approved tags html tags
- * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
+ * Joins the elements of the provided array into a single string
+ * containing a list of CSV elements. Stolen wholesale from Jakarta
+ * Turbine StringUtils.java. -mh
+ *
+ * @param list The list of values to join together.
+ * @param separator The separator character.
+ * @return The CSV text.
*/
-
-
- public static String approveHTMLTags(String haystack){
- try {
- String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
- String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
- String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
-
- // kill all the bad tags that have attributes
- String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
- RE regex = new RE(s,RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the bad tags that are attributeless
- regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which have a javascript attribute like onLoad
- regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- // kill all the tags which include a url to an unacceptable protocol
- regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
- haystack = regex.substituteAll(haystack,"");
-
- return haystack;
- } catch(REException ex){
- ex.printStackTrace();
- return null;
- }
-
-
+ public static String join(String[] list, String separator)
+ {
+ StringBuffer csv = new StringBuffer();
+ for (int i = 0; i < list.length; i++)
+ {
+ if (i > 0)
+ {
+ csv.append(separator);
+ }
+ csv.append(list[i]);
+ }
+ return csv.toString();
}
- /**
- * createHTML ruft alle regex-methoden zum unwandeln eines nicht
- * htmlcodierten string auf und returnt einen htmlcodierten String
- */
- public static String createHTML(String content){
- content=convertNewline2Break(content);
- content=convertNewline2P(content);
- content=createMailLinks(content);
- content=createURLLinks(content);
- return content;
- }
-
- /**
- * createHTML ruft alle regex-methoden zum unwandeln eines nicht
- * htmlcodierten string auf und returnt einen htmlcodierten String
- */
- public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
- content=convertNewline2Break(content);
- content=convertNewline2P(content);
- content=createMailLinks(content,producerDocRoot,mailImage);
- content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
- return content;
- }
+ /**
+ * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
+ *
+ * @return gequoteter String
+ */
+ public static String quoteIfNecessary(String s) {
+ for (int i = 0; i < s.length(); i++)
+ if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
+ return quote(s, '"');
+ return s;
+ }
+
+ /**
+ * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
+ * "gefährliche" Zeichen innerhalb des Strings
+ * Quotes special SQL-characters in <code>s</code>
+ *
+ * @return geqoteter String
+ */
+ public static String quote(String s)
+ {
+ //String s2 = quote(s, '\'');
+
+ //Quickhack
+ //Because of '?-Bug in Postgresql-JDBC-Driver
+ StringBuffer temp = new StringBuffer();
+ for(int i=0;i<s.length();i++){
+ if(s.charAt(i)=='\''){
+ temp.append("´");
+ } else {
+ temp.append(s.charAt(i));
+ }
+ }
+ String s2 = temp.toString();
+ //Quickhack end
+
+ s2 = quote(s2, '\"');
+ return s2;
+ }
+
+ /**
+ * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
+ * "gefährliche" Zeichen innerhalb des Strings
+ *
+ * @param s String, der gequoted werden soll
+ * @param quoteChar zu quotendes Zeichen
+ * @return gequoteter String
+ */
+ public static String quote(String s, char quoteChar)
+ {
+ StringBuffer buf = new StringBuffer(s.length());
+ int pos = 0;
+ while (pos < s.length()) {
+ int i = s.indexOf(quoteChar, pos);
+ if (i < 0) i = s.length();
+ buf.append(s.substring(pos, i));
+ pos = i;
+ if (pos < s.length()) {
+ buf.append('\\');
+ buf.append(quoteChar);
+ pos++;
+ }
+ }
+ return buf.toString();
+ }
+
+ /**
+ * replaces dangerous characters in <code>s</code>
+ *
+ */
+
+ public static String unquote(String s)
+ {
+ char quoteChar='\'';
+ StringBuffer buf = new StringBuffer(s.length());
+ int pos = 0;
+ String searchString = "\\"+quoteChar;
+ while (pos < s.length()) {
+ int i = s.indexOf(searchString, pos);
+ if (i < 0) i = s.length();
+ buf.append(s.substring(pos, i));
+ pos = i+1;
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Wandelet String in byte[] um.
+ * @param s
+ * @return byte[] des String
+ */
+
+ public static byte[] stringToBytes(String s) {
+ String crlf = System.getProperty("line.separator");
+ if (!crlf.equals("\n"))
+ s = replace(s, "\n", crlf);
+ // byte[] buf = new byte[s.length()];
+ byte[] buf = s.getBytes();
+ return buf;
+ }
+
+ /**
+ * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
+ * @param s
+ * @param pattern
+ * @param substitute
+ * @return String mit den Ersetzungen
+ */
+ public static String replace(String s, String pattern, String substitute) {
+ int i = 0, pLen = pattern.length(), sLen = substitute.length();
+ StringBuffer buf = new StringBuffer(s.length());
+ while (true) {
+ int j = s.indexOf(pattern, i);
+ if (j < 0) {
+ buf.append(s.substring(i));
+ break;
+ } else {
+ buf.append(s.substring(i, j));
+ buf.append(substitute);
+ i = j+pLen;
+ }
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
+ * @param s
+ * @param pattern
+ * @param substitute
+ * @return String mit den Ersetzungen
+ */
+ public static String regexpReplace(String haystack, String pattern, String substitute) {
+ try {
+ RE regex = new RE(pattern);
+ return regex.substituteAll(haystack,substitute);
+ } catch(REException ex){
+ return null;
+ }
+ }
+
+
+
+
+ /**
+ * Fügt einen Separator an den Pfad an
+ * @param path
+ * @return Pfad mit Separator am Ende
+ */
+ public static final String addSeparator (String path) {
+ return path.length() == 0 || path.endsWith(File.separator) ? path : path
+ + File.separatorChar;
+ }
+
+ /**
+ * Fügt ein <code>/</code> ans ende des Strings and
+ * @param path
+ * @return Pfad mit <code>/</code> am Ende
+ */
+ public static final String addSlash (String path) {
+ return path.length() == 0 || path.endsWith("/") ? path : path + '/';
+ }
+
+ /**
+ * Löscht <code>/</code> am Ende des Strings, falls vorhanden
+ * @param path
+ * @return String ohne <code>/</code> am Ende
+ */
+ public static final String removeSlash (String path) {
+ return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
+ - 1) : path;
+ }
+
+ /**
+ * Checks to see if the path is absolute by looking for a leading file
+ * separater
+ * @param path
+ * @return
+ */
+ public static boolean isAbsolutePath (String path) {
+ return path.startsWith(File.separator);
+ }
+
+ /**
+ * Löscht Slash am Anfang des Strings
+ * @param path
+ * @return
+ */
+ public static String removeFirstSlash (String path) {
+ return path.startsWith("/") ? path.substring(1) : path;
+ }
+
+ /**
+ * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
+ * @return zwistellige Zahl
+ */
+ public static String pad2 (int number) {
+ return number < 10 ? "0" + number : String.valueOf(number);
+ }
+
+ /**
+ * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
+ *
+ * @return 3-stellige Zahl
+ */
+ public static String pad3 (int number) {
+ return number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
+ }
+
+ /**
+ * Konvertiert Unix-Linefeeds in Win-Linefeeds
+ * @param s
+ * @return Konvertierter String
+ */
+ public static String unixLineFeedsToWin(String s) {
+ int i = -1;
+ while (true) {
+ i = s.indexOf('\n', i+1);
+ if (i < 0) break;
+ if ((i == 0 || s.charAt(i-1) != '\r') &&
+ (i == s.length()-1 || s.charAt(i+1) != '\r')) {
+ s = s.substring(0, i)+'\r'+s.substring(i);
+ i++;
+ }
+ }
+ return s;
+ }
+
+
+ /**
+ * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen
+ * und Spaces werden zu Underscores
+ *
+ * @return gültige Url
+ */
+ public static String convert2url(String s) {
+ s = toLowerCase(s);
+ StringBuffer buf = new StringBuffer();
+ for(int i = 0; i < s.length(); i++ ) {
+ switch( s.charAt( i ) ) {
+ case 'ö':
+ buf.append( "oe" ); break;
+ case 'ä':
+ buf.append( "ae" ); break;
+ case 'ü':
+ buf.append( "ue" ); break;
+ case 'ã':
+ buf.append( "a" ); break;
+ case '´':
+ case '.':
+ buf.append( "_" ); break;
+ case ' ':
+ if( buf.charAt( buf.length() - 1 ) != '_' ) {
+ buf.append( "_" );
+ }
+ break;
+ default:
+ buf.append( s.charAt( i ) );
+ }
+ }
+ return buf.toString();
+ }
+
+ /**
+ * wandelt Sonderzeichen in Quotes um
+ *
+ * @return Kovertierter String
+ */
+ public static String encodeHtml(String s) {
+ StringBuffer buf = new StringBuffer();
+ for(int i=0;i < s.length(); i++ ) {
+
+ /** @todo looks inefficient, to ask for index of every char, in
+ * case of failure it runs to the end.*/
+ if (s.charAt(i)=='&') {
+ // convert html to xml-parsable representation
+ if( s.indexOf( "ö", i ) == i ) {
+ buf.append( "ö" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ä", i ) == i ) {
+ buf.append( "ä" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ü", i ) == i ) {
+ buf.append( "ü" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ö", i ) == i ) {
+ buf.append( "Ö" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ä", i ) == i ) {
+ buf.append( "Ä" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ü", i ) == i ) {
+ buf.append( "Ü" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ß", i ) == i ) {
+ buf.append( "ß" ); i += 6;
+ continue;
+ }
+
+ /** @todo should only escape outside of tags */
+
+ if( s.indexOf( """, i ) == i ) {
+ buf.append( "ß" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "–", i ) == i ) {
+ buf.append( "–" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( "—", i ) == i ) {
+ buf.append( "—" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( "“", i ) == i ) {
+ buf.append( "“" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( "”", i ) == i ) {
+ buf.append( "”" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( "„", i ) == i ) {
+ buf.append( "„" ); i += 6;
+ continue;
+ }
+
+ //looks pretty stupid
+ if( s.indexOf( "<", i ) == i ) {
+ buf.append( "<" ); i += 3;
+ continue;
+ }
+ if( s.indexOf( ">", i ) == i ) {
+ buf.append( ">" ); i += 3;
+ continue;
+ }
+ if( s.indexOf( "´", i ) == i ) {
+ buf.append( "´" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( " ", i ) == i ) {
+ buf.append( " " ); i += 5;
+ continue;
+ }
+ //has to be the last
+ //if( s.indexOf( "&", i ) == i ) {
+ // buf.append( "&" ); i += 0;
+ // continue;
+ //}
+ }
+ // convert umlauts an other special charakters
+ switch( s.charAt(i) ) {
+ case 'ö': buf.append( "ö" ); break;
+ case 'ä': buf.append( "ä" ); break;
+ case 'ü': buf.append( "ü" ); break;
+ case 'Ö': buf.append( "Ö" ); break;
+ case 'Ä': buf.append( "Ä" ); break;
+ case 'Ü': buf.append( "Ü" ); break;
+ case 'ß': buf.append( "ß" ); break;
+ case 'é': buf.append( "é" ); break;
+ case 'è': buf.append( "è" ); break;
+ case 'á': buf.append( "á" ); break;
+ case 'à': buf.append( "à" ); break;
+ case 'â': buf.append( "â" ); break;
+ case 'ã': buf.append( "ã" ); break;
+ case '¬': buf.append( "¬" ); break;
+ case '¹': buf.append( "¹" ); break;
+ case '²': buf.append( "²" ); break;
+ case '³': buf.append( "³" ); break;
+ case '¼': buf.append( "¼" ); break;
+ case '½': buf.append( "½" ); break;
+ case '¾': buf.append( "¾" ); break;
+ case '¶': buf.append( "¶" ); break;
+ case 'æ': buf.append( "æ" ); break;
+ case 'ð': buf.append( "ð" ); break;
+ case '|': buf.append( "¦" ); break;
+ case '·': buf.append( "·" ); break;
+ case '°': buf.append( "°" ); break;
+ case '§': buf.append( "§" ); break;
+ case 'ø': buf.append( "ø" ); break;
+ case 'ç': buf.append( "ç" ); break;
+ case '¤': buf.append( "¤" ); break;
+ case 'ª': buf.append( "ª" ); break;
+ case 'Ç': buf.append( "Ç" ); break;
+ case 'Ã': buf.append( "Ã" ); break;
+ case 'Â': buf.append( "Â" ); break;
+ case 'Æ': buf.append( "Æ" ); break;
+ case '©': buf.append( "©" ); break;
+ case '®': buf.append( "®" ); break;
+ case '¥': buf.append( "¥" ); break;
+ case 'Þ': buf.append( "þ" ); break;
+ case '¯': buf.append( "¯" ); break;
+ case 'Ð': buf.append( "Ð" ); break;
+ case 'º': buf.append( "º" ); break;
+ case '¡': buf.append( "¡" ); break;
+ case '£': buf.append( "£" ); break;
+ case '±': buf.append( "±" ); break;
+ case '¿': buf.append( "¿" ); break;
+ case 'Ø': buf.append( "Ø" ); break;
+ case 'Á': buf.append( "À" ); break;
+ case 'À': buf.append( "Á" ); break;
+ case 'É': buf.append( "È" ); break;
+ case 'È': buf.append( "É" ); break;
+ case 'ù': buf.append( "ú" ); break;
+ case 'ñ': buf.append( "ñ" ); break;
+ case 'Ñ': buf.append( "Ñ" ); break;
+ case 'µ': buf.append( "µ" ); break;
+ case 'Í': buf.append( "Ì" ); break;
+ case 'Ì': buf.append( "Í" ); break;
+ case 'í': buf.append( "ì" ); break;
+ case 'ì': buf.append( "í" ); break;
+ case 'î': buf.append( "î" ); break;
+ case 'Î': buf.append( "Î" ); break;
+ case 'ó': buf.append( "ó" ); break;
+ case 'Ó': buf.append( "Ò" ); break;
+ case 'ò': buf.append( "Î" ); break;
+ case 'Ò': buf.append( "Ó" ); break;
+ case 'ô': buf.append( "ô" ); break;
+ case 'Ô': buf.append( "Ô" ); break;
+ case 'õ': buf.append( "õ" ); break;
+ case 'Õ': buf.append( "Õ" ); break;
+ case 'ý': buf.append( "ý" ); break;
+ case 'Ý': buf.append( "Ý" ); break;
+ case 'û': buf.append( "û" ); break;
+ case 'Û': buf.append( "Û" ); break;
+ case 'ú': buf.append( "ù" ); break;
+ case 'Ú': buf.append( "Ù" ); break;
+ case 'Ù': buf.append( "Ú" ); break;
+ case 'Ê': buf.append( "Ê" ); break;
+ case 'ê': buf.append( "ê" ); break;
+ case 'å': buf.append( "å" ); break;
+ case 'Å': buf.append( "Å" ); break;
+ case 'ë': buf.append( "ë" ); break;
+ case 'Ë': buf.append( "Ë" ); break;
+ case 'ÿ': buf.append( "ÿ" ); break;
+ case 'ï': buf.append( "ï" ); break;
+ case 'Ï': buf.append( "Ï" ); break;
+ case '«': buf.append( "«" ); break;
+ case '»': buf.append( "»" ); break;
+ case '\'': buf.append( "´" ); break;
+ case '\"': buf.append( """ ); break;
+ //case '\u8211': buf.append( "–" ); break;
+ //case '\u8212': buf.append( "—" ); break;
+ //case '\u8220': buf.append( "“" ); break;
+ //case '\u8221': buf.append( "”" ); break;
+ //case '\u8222': buf.append( "„" ); break;
+ //case '\"': buf.append( """ ); break;
+ default: buf.append( s.charAt(i) );
+ }
+
+ }
+ return buf.toString();
+ }
+
+
+ public static String decodeHTMLinTags(String s){
+ StringBuffer buffer = new StringBuffer();
+ boolean start = false;
+ boolean stop = false;
+ int startIndex = 0;
+ int stopIndex = 0;
+ int temp = 0;
+
+ for(int i=0;i<s.length();i++){
+ if(s.charAt(i)=='<'){
+ start = true;
+ startIndex = i;
+ } else if(s.charAt(i)=='>'){
+ stop = true;
+ stopIndex = i;
+
+ if(start && stop){
+ buffer.append(s.substring(temp,startIndex));
+ buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1)));
+ i= temp= stopIndex+1;
+ start= stop= false;
+ }
+ }
+ }
+ if(stopIndex>0){
+ buffer.append(s.substring(stopIndex+1));
+ return buffer.toString();
+ } else {
+ return s;
+ }
+ }
+
+ public static String replaceQuot(String s) {
+ StringBuffer buffer = new StringBuffer();
+ for(int j = 0; j < s.length();j++){
+ if(s.charAt(j)=='&'){
+ if(s.indexOf( """,j) == j) {
+ buffer.append( "\"" );
+ j += 5;
+ }//if
+ } else {
+ buffer.append(s.charAt(j));
+ }//else
+ }//for
+ return buffer.toString();
+ }
+
+ /** wandelt Quotes in Sonderzeichen um
+ */
+ /**
+ public static String decodeHtml(String s) {
+ StringBuffer buf = new StringBuffer();
+ for(int i=0;i < s.length(); i++ ) {
+ if( s.indexOf( "ö", i ) == i ) {
+ buf.append( "ö" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ä", i ) == i ) {
+ buf.append( "ä" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ü", i ) == i ) {
+ buf.append( "ü" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ö", i ) == i ) {
+ buf.append( "Ö" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ä", i ) == i ) {
+ buf.append( "Ä" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "Ü", i ) == i ) {
+ buf.append( "Ü" ); i += 5;
+ continue;
+ }
+ if( s.indexOf( "ß", i ) == i ) {
+ buf.append( "ß" ); i += 6;
+ continue;
+ }
+ if( s.indexOf( """, i ) == i ) {
+ buf.append( "\"" ); i += 5;
+ continue;
+ }
+ buf.append( s.charAt(i) );
+ }
+ return buf.toString();
+ }
+ */
+
+ /**
+ * schnellere Variante der String.toLowerCase()-Routine
+ *
+ * @return String in Kleinbuchsten
+ */
+ public static String toLowerCase(String s) {
+ int l = s.length();
+ char[] a = new char[l];
+ for (int i = 0; i < l; i++)
+ a[i] = Character.toLowerCase(s.charAt(i));
+ return new String(a);
+ }
+
+ /**
+ * Findet <code>element</code> im String-Array <code>array</code>
+ * @param array
+ * @param element
+ * @return Fundstelle als int oder -1
+ */
+ public static int indexOf(String[] array, String element) {
+ if (array != null)
+ for (int i = 0; i < array.length; i++)
+ if (array[i].equals(element))
+ return i;
+ return -1;
+ }
+
+ /**
+ * Testet auf Vorkommen von <code>element</code> in <code>array</code>
+ * @param array String-Array
+ * @param element
+ * @return true wenn <code>element</code> vorkommt, sonst false
+ */
+ public static boolean contains(String[] array, String element) {
+ return indexOf(array, element) >= 0;
+ }
+
+ /**
+ * Ermittelt CRC-Prüfsumme von String <code>s</code>
+ * @param s
+ * @return CRC-Prüfsumme
+ */
+ public static int getCRC(String s) {
+ int h = 0;
+ char val[] = s.toCharArray();
+ int len = val.length;
+
+ for (int i = 0 ; i < len; i++) {
+ h &= 0x7fffffff;
+ h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
+ }
+
+ return (h << 8) | (len & 0xff);
+ }
+
+ /**
+ * Liefert Default-Wert def zurück, wenn String <code>s</code>
+ * kein Integer ist.
+ *
+ * @param s
+ * @param def
+ * @return geparster int aus s oder def
+ */
+ public static int parseInt(String s, int def) {
+ if (s == null) return def;
+ try {
+ return Integer.parseInt(s);
+ } catch (NumberFormatException e) {
+ return def;
+ }
+ }
+
+ /**
+ * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
+ * @param s
+ * @param def
+ * @return geparster float oder def
+ */
+ public static float parseFloat(String s, float def) {
+ if (s == null) return def;
+ try {
+ return new Float(s).floatValue();
+ } catch (NumberFormatException e) {
+ return def;
+ }
+ }
+
+ /**
+ * Findet Ende eines Satzes in String <code>text</code>
+ * @param text
+ * @param startIndex
+ * @return index des Satzendes, oder -1
+ */
+ public static int findEndOfSentence(String text, int startIndex) {
+ while (true) {
+ int i = text.indexOf('.', startIndex);
+ if (i < 0) return -1;
+ if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
+ (i+1 >= text.length()
+ || text.charAt(i+1) == ' '
+ || text.charAt(i+1) == '\n'
+ || text.charAt(i+1) == '\t'))
+ return i+1;
+ startIndex = i+1;
+ }
+ }
+
+ /**
+ * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
+ * @param text
+ * @param startIndex
+ * @return Index des Wortendes, oder -1
+ */
+ public static int findEndOfWord(String text, int startIndex) {
+ int i = text.indexOf(' ', startIndex),
+ j = text.indexOf('\n', startIndex);
+ if (i < 0) i = text.length();
+ if (j < 0) j = text.length();
+ return Math.min(i, j);
+ }
+
+
+ /**
+ * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
+ * in den html-tag <p>
+ * nur sinnvoll, wenn text nicht im html-format eingegeben
+ */
+ public static String convertNewline2P(String haystack) {
+ return re_brbr2p.substituteAll(haystack,"\n</p><p>");
+ }
+
+ /**
+ * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
+ * in den html-tag <br>
+ * nur sinnvoll, wenn text nicht im html-format eingegeben
+ */
+ public static String convertNewline2Break(String haystack) {
+ return re_newline2br.substituteAll(haystack,"$0<br>");
+ }
+
+ /**
+ * createMailLinks wandelt text im email-adressenformat
+ * in einen klickbaren link um
+ * nur sinnvoll, wenn text nicht im html-format eingegeben
+ */
+ public static String createMailLinks(String haystack) {
+ return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
+ }
+
+
+ /**
+ * createMailLinks wandelt text im email-adressenformat
+ * in einen klickbaren link um
+ * nur sinnvoll, wenn text nicht im html-format eingegeben
+ */
+ public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
+ return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
+ }
+
+
+ /**
+ * createURLLinks wandelt text im url-format
+ * in einen klickbaren link um
+ * nur sinnvoll, wenn text nicht im html-format eingegeben
+ */
+ public static String createURLLinks(String haystack) {
+ return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
+ }
+
+ /**
+ * this routine takes text in url format and makes
+ * a clickaeble "<href>" link removing any "illegal" html tags
+ * @param haystack, the url
+ * @param title, the href link text
+ * @param imagRoot, the place to find icons
+ * @param extImage, the url of the icon to show next to the link
+ * @return a String containing the url
+ */
+ public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
+ if (title == null) {
+ return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
+ } else {
+ title = removeHTMLTags(title);
+ return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">"+title+"</a>");
+ }
+ }
+
+ /**
+ * this routine takes text in url format and makes
+ * a clickaeble "<href>" link removing any "illegal" html tags
+ * @param haystack, the url
+ * @param imageRoot, the place to find icons
+ * @param extImage, the url of the icon to show next to the link
+ * @param intImage, unused
+ * @return a String containing the url
+ */
+ public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
+ return createURLLinks(haystack, title, imageRoot, extImage);
+ }
+
+ /**
+ * this routine takes text in url format and makes
+ * an image link removing any "illegal" html tags
+ * @param haystack, the url
+ * @param title, the image alt text, can be null
+ * @param height, height of the image
+ * @param width, width of the image
+ * @return a String containing the url
+ */
+ public static String createIMGLinks(String haystack, String title,
+ String height,String width) {
+ String wh="";
+ if ( (height != null) && (width != null) )
+ {
+ wh = "width=\""+width+"\" height=\""+height+"\"";
+ }
+ if (title != null) {
+ title = removeHTMLTags(title);
+ return re_url.substituteAll(haystack,
+ "<img hspace=\"10\" vspace=\"6\" "+
+ "align=\"left\" src=\"$0\" "+wh+
+ " alt=\""+title+"\"/> <br><i>"+
+ title+"</i>");
+ } else {
+ return re_url.substituteAll(haystack,
+ "<img hspace=\"10\" vspace=\"6\" "+
+ "align=\"left\" src=\"$0\" "+wh+
+ " alt=\"\"/> ");
+ }
+ }
+
+
+ /**
+ * deleteForbiddenTags
+ * this method deletes all <script>, <body> and <head>-tags
+ */
+ public static final String deleteForbiddenTags(String haystack) {
+ try {
+ RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
+ haystack = regex.substituteAll(haystack,"");
+ regex = new RE("<head>(.*?)</head>");
+ haystack = regex.substituteAll(haystack,"");
+ regex = new RE("<[ \t\r\n/]*body(.*?)>");
+ haystack = regex.substituteAll(haystack,"");
+ return haystack;
+ } catch(REException ex){
+ return null;
+ }
+ }
+
+ /**
+ * this method deletes all html tags
+ */
+ public static final String removeHTMLTags(String haystack){
+ return re_tags.substituteAll(haystack,"");
+ }
+
+
+ /**
+ * this method deletes all but the approved tags html tags
+ * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
+ */
+ public static String approveHTMLTags(String haystack){
+ try {
+ String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
+ String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
+ String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
+
+ // kill all the bad tags that have attributes
+ String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
+ RE regex = new RE(s,RE.REG_ICASE);
+ haystack = regex.substituteAll(haystack,"");
+
+ // kill all the bad tags that are attributeless
+ regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
+ haystack = regex.substituteAll(haystack,"");
+
+ // kill all the tags which have a javascript attribute like onLoad
+ regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
+ haystack = regex.substituteAll(haystack,"");
+
+ // kill all the tags which include a url to an unacceptable protocol
+ regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
+ haystack = regex.substituteAll(haystack,"");
+
+ return haystack;
+ } catch(REException ex){
+ ex.printStackTrace();
+ return null;
+ }
+ }
+
+
+ /**
+ * createHTML ruft alle regex-methoden zum unwandeln eines nicht
+ * htmlcodierten string auf und returnt einen htmlcodierten String
+ */
+ public static String createHTML(String content){
+ content=convertNewline2Break(content);
+ content=convertNewline2P(content);
+ content=createMailLinks(content);
+ content=createURLLinks(content);
+ return content;
+ }
+
+
+ /**
+ * createHTML ruft alle regex-methoden zum unwandeln eines nicht
+ * htmlcodierten string auf und returnt einen htmlcodierten String
+ */
+ public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
+ content=convertNewline2Break(content);
+ content=convertNewline2P(content);
+ content=createMailLinks(content,producerDocRoot,mailImage);
+ content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
+ return content;
+ }
}
public class WebdbImage
{
- // imageTypes
- public final static int WEBDB_JPG=0;
- public final static int WEBDB_GIF=1;
-
// default values for scaling
private int maxIconSize=120;
private int maxImageSize=640;
private byte[] iconData;
private byte[] imageData;
- private int imageType;
private int iconWidth;
private int iconHeight;
// constructor
- public WebdbImage(byte[] image, int type)
+ public WebdbImage(byte[] image)
throws IOException
{
- imageType=type;
planarImage = JAI.create("stream",new ByteArraySeekableStream(image));
scaleImage();
}
- public WebdbImage(byte[] image, int type, int iconMax)
+ public WebdbImage(byte[] image, int iconMax)
throws IOException
{
- imageType=type;
maxIconSize=iconMax;
planarImage = JAI.create("stream",new ByteArraySeekableStream(image));
scaleImage();
}
- public WebdbImage(byte[] image, int type, int iconMax, int imageMax)
+ public WebdbImage(byte[] image, int iconMax, int imageMax)
throws IOException
{
- imageType=type;
maxIconSize=iconMax;
maxImageSize=imageMax;
planarImage = JAI.create("stream",new ByteArraySeekableStream(image));
public byte[] getImage() {
if (imageData==null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-
- switch (imageType) {
- case WEBDB_JPG:
- JAI.create("encode", planarImage, outStream, "JPEG", null);break;
- case WEBDB_GIF:
- JAI.create("encode", planarImage, outStream, "JPEG", null);break;
- default:
- System.err.println("unknown image format: " + imageType);
- }
-
+ // @todo the choice of PNG or JPEG should be made configurable
+ JAI.create("encode", planarImage, outStream, "PNG", null);
imageData = outStream.toByteArray();
}
return imageData;
InterpolationBilinear interp = new InterpolationBilinear();
PlanarImage temp = JAI.create("scale", planarImage, scale, scale, 0.0F, 0.0F, interp);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- /** @todo gif */
- switch (imageType) {
- case WEBDB_JPG:
- JAI.create("encode", temp, outStream, "JPEG", null);break;
- case WEBDB_GIF:
- JAI.create("encode", temp, outStream, "JPEG", null);break;
- default:
- System.err.println("unknown image format: " + imageType);
- }
+ // @todo the choice of PNG or JPEG should be made configurable
+ JAI.create("encode", temp, outStream, "PNG", null);
iconData = outStream.toByteArray();
iconWidth=temp.getWidth();
iconHeight=temp.getHeight();
--- /dev/null
+package mir.module;
+
+import java.lang.*;
+
+/*
+ * ServletModuleException -
+ * wird vom ServletModule geschmissen</b>
+ *
+ *
+ * @version 5.7.199
+ * @author RK
+ */
+
+public final class ModuleUserException extends Exception
+{
+ public ModuleUserException(String msg) {
+ super(msg);
+ }
+}
+
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
+import javax.servlet.UnavailableException;
import java.io.File;
import java.util.Locale;
import java.util.HashMap;
import mir.misc.StringUtil;
import mir.misc.MirConfig;
import mir.misc.Logfile;
+import mir.storage.StorageObjectException;
/**
* Title: Mir
/**
* the configration
*/
- protected boolean getConfig(HttpServletRequest req) {
+ protected boolean getConfig(HttpServletRequest req)
+ throws UnavailableException {
String RealPath = super.getServletContext().getRealPath("/");
String Uri = req.getRequestURI();
// init config
MirConfig.initConfig(RealPath, RootUri, Name, getInitParameter("Config"));
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getPropWithHome(Name+".Logfile"));
theLog.printInfo(Name + " started.");
theLog.printInfo("Path is: " + MirConfig.getProp("Home"));
theLog.printInfo("Root URI is: " + MirConfig.getProp("RootUri"));
theLog.printInfo("Lang is: " + MirConfig.getProp("StandardLanguage"));
+ try {
+ MirConfig.initDbPool();
+ } catch ( StorageObjectException e) {
+ throw new UnavailableException(
+ "Could not initialize database pool. -- "
+ + e.toString(), 0);
+ }
+ super.getServletContext().setAttribute("mir.confed", new Boolean(true));
return true;
}
* @param res Http-Response, die vom Dispatcher durchgereicht wird
*/
public void insert(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleException {
+ throws ServletModuleException, ServletModuleUserException {
try {
HashMap withValues = getIntersectingValues(req, mainModule.getStorageObject());
String id = mainModule.add(withValues);
// theLog.printDebugInfo("--trying to deliver..."+id);
list(req,res);
//deliver(req, res, mainModule.getById(id), templateObjektString);
+ } catch (Exception e) {
+ throw new ServletModuleException(e.toString());
}
- catch (Exception e) { throw new ServletModuleException(e.toString());}
}
/**
*/
public final class ServletModuleDispatch {
- static Logfile theLog;
+ private static Logfile theLog;
+ private static final Class[] SIGNATURE =
+ { HttpServletRequest.class, HttpServletResponse.class };
- static {
- theLog = Logfile.getInstance("ServletModuleDispatch");
- }
- /**
- * privater Konstruktor, um versehentliche Instantiierung zu verhindern
- */
- private ServletModuleDispatch () {
- }
+ static {
+ theLog = Logfile.getInstance("/tmp/smod.dispatch");
+ }
- /**
- * Die Dispatch-Routine ruft das von dem Hauptservlet kommende ServletModule
- * mit dem per HttpServletRequest angegebenen Paramter <code>do</code> auf.
- * Ist kein Parameter angegeben, so wird versucht, in die <code>defaultAction</code>
- * des ServletModules zu springen.
- *
- * @param req Http-Request, das vom Dispatcher an die Methode des
- * ServletModules durchgereicht wird
- * @param res Http-Response, die vom Dispatcher an die Methode des
- * ServletModules durchgereicht wird
- * @param sMod ServletModule, an das dispatched wird.
- * @param mod Name des Modules als String (für Logfile)
- */
+ /**
+ * privater Konstruktor, um versehentliche Instantiierung zu verhindern
+ */
+ private ServletModuleDispatch () {
+ }
- public static void dispatch(ServletModule sMod, HttpServletRequest req,
- HttpServletResponse res) throws ServletModuleException
- {
- //sMod.predeliver(req,res);
+ /**
+ * Die Dispatch-Routine ruft das von dem Hauptservlet kommende ServletModule
+ * mit dem per HttpServletRequest angegebenen Paramter <code>do</code> auf.
+ * Ist kein Parameter angegeben, so wird versucht, in die <code>defaultAction</code>
+ * des ServletModules zu springen.
+ *
+ * @param req Http-Request, das vom Dispatcher an die Methode des
+ * ServletModules durchgereicht wird
+ * @param res Http-Response, die vom Dispatcher an die Methode des
+ * ServletModules durchgereicht wird
+ * @param sMod ServletModule, an das dispatched wird.
+ * @param mod Name des Modules als String (für Logfile)
+ */
- String doParam = req.getParameter("do");
- theLog.printInfo("SerletModuleDispatch: " + sMod.toString() + " with method " + doParam);
- if (doParam == null) {
- if (sMod.defaultAction() != null) doParam = sMod.defaultAction();
- else throw new ServletModuleException("no parameter do supplied!");
- }
+ public static void dispatch(ServletModule sMod, HttpServletRequest req,
+ HttpServletResponse res) throws ServletModuleException, ServletModuleUserException
+ {
+ //sMod.predeliver(req,res);
- Class[] params= { HttpServletRequest.class, HttpServletResponse.class};
+ String doParam = req.getParameter("do");
+ theLog.printInfo("SerletModuleDispatch: " + sMod.toString() + " with method " + doParam);
+ if (doParam == null) {
+ if (sMod.defaultAction() != null) doParam = sMod.defaultAction();
+ else throw new ServletModuleException("no parameter do supplied!");
+ }
- try {
- Method method = sMod.getClass().getMethod(doParam,params);
- if (method != null) {
- method.invoke(sMod,new Object[] {req,res} );
- return;
- }
- else theLog.printDebugInfo("method lookup unsuccesful");
- }
- catch ( NoSuchMethodException e) { throw new ServletModuleException("no such method!" + e.toString());}
- catch ( SecurityException e) { throw new ServletModuleException("method not allowed!" + e.toString());}
- catch ( InvocationTargetException e) {e.printStackTrace();throw new ServletModuleException("target method exception!" + e.getTargetException().toString());}
- catch ( IllegalAccessException e) { throw new ServletModuleException("illegal method not allowed!" + e.toString());}
-// catch ( Exception e ) { throw new ServletModuleException(e.toString()); }
+ try {
+ Method method = sMod.getClass().getMethod(doParam,SIGNATURE);
+ if (method != null) {
+ method.invoke(sMod,new Object[] {req,res} );
+ return;
+ }
+ else theLog.printDebugInfo("method lookup unsuccesful");
+ }
+ catch ( NoSuchMethodException e) { throw new ServletModuleException("no such method!" + e.toString());}
+ catch ( SecurityException e) { throw new ServletModuleException("method not allowed!" + e.toString());}
+ catch ( InvocationTargetException e) {
+ if (e.getTargetException().getClass().getName().equals("mir.servlet.ServletModuleUserException")) {
+ throw new ServletModuleUserException(((ServletModuleUserException)e.getTargetException()).getMsg());
+ } else {
+ e.printStackTrace();
+ throw new ServletModuleException(e.getTargetException().toString());
+ }
+ }
+ catch ( IllegalAccessException e) { throw new ServletModuleException("illegal method not allowed!" + e.toString());}
- throw new ServletModuleException("delivery failed! -- ");
- }
+ //hopefully we don't get here ...
+ throw new ServletModuleException("delivery failed! -- ");
+ }
}
import mir.storage.*;
import mir.entity.*;
-import com.javaexchange.dbConnectionBroker.*;
/*
* ServletModuleShow -
* liefert HTML fuer Show
// instances in AbstractEntity
// eingelesene confs
// datenbankverbindungen fuer brokers
- getSimpleInfo(res.getWriter(),getConfs());
+ //getSimpleInfo(res.getWriter(),getConfs());
PrintWriter out = res.getWriter();
out.println(getInstancesInfo());
- out.println(getInstancesConfInfo());
}
catch (Exception e) {
public String getInstancesInfo(){
return "<table><tr><td>Momentan instanzierte EntityObjekte = </td><td>" + getInstances()+"</td></tr></table>\n";
}
- public String getInstancesConfInfo(){
- return "<table><tr><td>Momentan instanzierte BrokerObjekte = </td><td>" + getConfBrokerCnt()+"</td></tr></table>\n";
- }
-
protected HashMap getConfs(){
return Configuration.getConfs();
}
- protected int getBrokerUseCnt(DbConnectionBroker broker){
- return broker.getUseCount();
- }
- protected int getConfBrokerCnt(){
- return MirConfig.getBrokerInstances();
- }
- protected int getBrokerSize(DbConnectionBroker broker){
- return broker.getSize();
- }
- public String getBrokerInfo(DbConnectionBroker broker){
- return "<tr><td>Connections im pool = </td><td>"+ broker.getSize() + "</td></tr>\n"+
- "<tr><td>Connection die gerade benutzt werden = </td><td>" + broker.getUseCount()+"</td></tr>\n";
- }
- public void getSimpleInfo(Writer out,HashMap confs) throws IOException{
- String key;
- DbConnectionBroker broker = null;
- out.write(getInstancesInfo());
- out.write(getInstancesConfInfo());
- Set set = confs.keySet();
- Iterator it = set.iterator();
- for (int i=0;i<set.size();i++){
- key=(String)it.next();
- out.write("<table><tr><td>Konfiguration : </td><td>" + confs.get(key)+ "</td></tr>\n" );
- broker=MirConfig.getBrokerInfo();
- //broker=(DbConnectionBroker) ((HashMap)confs.get(key)).get("Pool.broker");
- if(broker!=null) out.write(getBrokerInfo(broker));
- else
- out.write("<tr><td>Broker nicht initializiert</td><td></td></tr>\n");
- out.write("</table>\n");
- }
- }
}
--- /dev/null
+package mir.servlet;
+
+import java.lang.*;
+
+/*
+ * ServletModuleException -
+ * wird vom ServletModule geschmissen</b>
+ *
+ *
+ * @version 28.6.199
+ * @author RK
+ */
+
+public final class ServletModuleUserException extends Exception
+{
+ String msg;
+
+ public ServletModuleUserException(String msg) {
+ super(msg);
+ this.msg = msg;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+}
+
import java.io.*;
import java.util.*;
import freemarker.template.*;
-import com.javaexchange.dbConnectionBroker.*;
import mir.storage.StorageObject;
import mir.entity.*;
import mir.misc.*;
+import com.codestudio.sql.*;
+import com.codestudio.util.*;
/**
*/
public class Database implements StorageObject {
- protected DbConnectionBroker myBroker;
- protected String theTable;
- protected String theCoreTable=null;
- protected String thePKeyName="id";
- protected int thePKeyType;
- protected boolean evaluatedMetaData=false;
- protected ArrayList metadataFields,metadataLabels,metadataNotNullFields;
- protected int[] metadataTypes;
- protected Class theEntityClass;
- protected StorageObject myselfDatabase;
- protected HashMap cache;
- protected SimpleList popupCache=null;
- protected boolean hasPopupCache = false;
- protected SimpleHash hashCache=null;
- protected boolean hasTimestamp=true;
- private String database_driver;
- private String database_url;
- private int defaultLimit;
- protected DatabaseAdaptor theAdaptor;
- protected Logfile theLog;
- protected Connection con;
-
- /**
- * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
- * Aus diesem file werden <code>Database.Logfile</code>,
- * <code>Database.Username</code>,<code>Database.Password</code>,
- * <code>Database.Host</code> und <code>Database.Adaptor</code>
- * ausgelesen und ein Broker für die Verbindugen zur Datenbank
- * erzeugt.
- *
- * @param String confFilename Dateiname der Konfigurationsdatei
- */
- public Database() {
- //theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
- theLog = Logfile.getInstance(this.getClass().getName());
- String database_username=DatabaseConfig.getProp("Database.Username");
- String database_password=DatabaseConfig.getProp("Database.Password");
- String database_host=DatabaseConfig.getProp("Database.Host");
- String theAdaptorName=DatabaseConfig.getProp("Database.Adaptor");
- try {
- theEntityClass = Class.forName("mir.entity.GenericEntity");
- theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
- defaultLimit = Integer.parseInt(DatabaseConfig.getProp("Database.Limit"));
- database_driver=theAdaptor.getDriver();
- database_url=theAdaptor.getURL(database_username,database_password,database_host);
- theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
- DatabaseConfig.addBroker(database_driver,database_url);
- myBroker=DatabaseConfig.getBroker();
- }
- catch (Exception e){
- theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
- }
- }
-
- /**
- * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
- * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
- * wird eine mir.entity.GenericEntity erzeugt.
- *
- * @return Class-Objekt der Entity
- */
- public java.lang.Class getEntityClass () {
- return theEntityClass;
- }
-
- /**
- * Liefert die Standardbeschränkung von select-Statements zurück, also
- * wieviel Datensätze per Default selektiert werden.
- *
- * @return Standard-Anzahl der Datensätze
- */
- public int getLimit () {
- return defaultLimit;
- }
-
- /**
- * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
- * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
- * @return Name des Primary-Keys
- */
- public String getIdName () {
- return thePKeyName;
- }
-
- /**
- * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
- *
- * @return Name der Tabelle
- */
- public String getTableName () {
- return theTable;
- }
-
- /*
- * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
- * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
- * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
- * the Table
- */
-
- public String getCoreTable(){
- if (theCoreTable!=null) return theCoreTable;
- else return theTable;
- }
-
- /**
- * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
- * @return int-Array mit den Typen der Felder
- * @exception StorageObjectException
- */
- public int[] getTypes () throws StorageObjectException {
- if (metadataTypes == null)
- get_meta_data();
- return metadataTypes;
- }
-
- /**
- * Liefert eine Liste der Labels der Tabellenfelder
- * @return ArrayListe mit Labeln
- * @exception StorageObjectException
- */
- public ArrayList getLabels () throws StorageObjectException {
- if (metadataLabels == null)
- get_meta_data();
- return metadataLabels;
- }
-
- /**
- * Liefert eine Liste der Felder der Tabelle
- * @return ArrayList mit Feldern
- * @exception StorageObjectException
- */
- public ArrayList getFields () throws StorageObjectException {
- if (metadataFields == null)
- get_meta_data();
- return metadataFields;
- }
-
-
- /*
- * Gets value out of ResultSet according to type and converts to String
- * @param inValue Wert aus ResultSet.
- * @param aType Datenbanktyp.
- * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
- * dann /unsupported value/
- */
- private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
- String outValue = null;
- if (rs != null) {
- try {
- switch (aType) {
- case java.sql.Types.BIT:
- outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
- break;
- case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
- int out = rs.getInt(valueIndex);
- if (!rs.wasNull())
- outValue = new Integer(out).toString();
- break;
- case java.sql.Types.NUMERIC:
- long outl = rs.getLong(valueIndex);
- if (!rs.wasNull())
- outValue = new Long(outl).toString();
- break;
- case java.sql.Types.REAL:
- float tempf = rs.getFloat(valueIndex);
- if (!rs.wasNull()) {
- tempf *= 10;
- tempf += 0.5;
- int tempf_int = (int)tempf;
- tempf = (float)tempf_int;
- tempf /= 10;
- outValue = "" + tempf;
- outValue = outValue.replace('.', ',');
- }
- break;
- case java.sql.Types.DOUBLE:
- double tempd = rs.getDouble(valueIndex);
- if (!rs.wasNull()) {
- tempd *= 10;
- tempd += 0.5;
- int tempd_int = (int)tempd;
- tempd = (double)tempd_int;
- tempd /= 10;
- outValue = "" + tempd;
- outValue = outValue.replace('.', ',');
- }
- break;
- case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
- outValue = rs.getString(valueIndex);
- if (outValue != null)
- outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
- break;
- case java.sql.Types.LONGVARBINARY:
- outValue = rs.getString(valueIndex);
- if (outValue != null)
- outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
- break;
- case java.sql.Types.TIMESTAMP:
- Timestamp timestamp = (rs.getTimestamp(valueIndex));
- if (!rs.wasNull()) {
- outValue = timestamp.toString();
- }
- break;
- default:
- outValue = "<unsupported value>";
- theLog.printWarning("Unsupported Datatype: at " + valueIndex +
- " (" + aType + ")");
- }
- } catch (SQLException e) {
- throw new StorageObjectException("Could not get Value out of Resultset -- "
- + e.toString());
- }
- }
- return outValue;
- }
-
- /*
- * select-Operator um einen Datensatz zu bekommen.
- * @param id Primaerschluessel des Datensatzes.
- * @return liefert EntityObject des gefundenen Datensatzes oder null.
- */
- public Entity selectById(String id)
- throws StorageObjectException {
-
- if (id==null||id.equals(""))
- throw new StorageObjectException("id war null");
- if (cache != null && cache.containsKey(id))
- return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
-
- Statement stmt=null;Connection con=getPooledCon();
- Entity returnEntity=null;
- try {
- ResultSet rs;
- String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
- stmt = con.createStatement();
- rs = executeSql(stmt, selectSql);
- if (rs != null) {
- if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
- if (rs.next())
- returnEntity = makeEntityFromResultSet(rs);
- else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
- rs.close();
- } else {
- theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
- }
- } catch (SQLException sqe){
- throwSQLException(sqe,"selectById"); return null;
- } catch (NumberFormatException e) {
- theLog.printError("ID ist keine Zahl: " + id);
- } finally {
- freeConnection(con,stmt);
- }
-
- return returnEntity;
- }
-
- /**
- * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
- * @param key Datenbankfeld der Bedingung.
- * @param value Wert die der key anehmen muss.
- * @return EntityList mit den gematchten Entities
- */
-
- public EntityList selectByFieldValue(String aField, String aValue)
- throws StorageObjectException {
-
- return selectByFieldValue(aField, aValue, 0);
- }
-
- /**
- * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
- * @param key Datenbankfeld der Bedingung.
- * @param value Wert die der key anehmen muss.
- * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
- * @return EntityList mit den gematchten Entities
- */
-
- public EntityList selectByFieldValue(String aField, String aValue, int offset)
- throws StorageObjectException {
-
- return selectByWhereClause(aField + "=" + aValue, offset);
- }
-
-
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
- * Also offset wird der erste Datensatz genommen.
- *
- * @param wc where-Clause
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectException
- */
- public EntityList selectByWhereClause(String where)
- throws StorageObjectException {
-
- return selectByWhereClause(where, 0);
- }
-
-
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
- * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
- *
- * @param wc where-Clause
- * @param offset ab welchem Datensatz.
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectException
- */
- public EntityList selectByWhereClause(String whereClause, int offset)
- throws StorageObjectException {
-
- return selectByWhereClause(whereClause, null, offset);
- }
-
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
- * Also offset wird der erste Datensatz genommen.
- * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
- *
- * @param wc where-Clause
- * @param ob orderBy-Clause
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectException
- */
-
- public EntityList selectByWhereClause(String where, String order)
- throws StorageObjectException {
-
- return selectByWhereClause(where, order, 0);
- }
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
- * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
- *
- * @param wc where-Clause
- * @param ob orderBy-Clause
- * @param offset ab welchem Datensatz
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectException
- */
-
- public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
- throws StorageObjectException {
-
- return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
- }
-
-
- /**
- * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
- * @param wc where-Clause
- * @param ob orderBy-Clause
- * @param offset ab welchem Datensatz
- * @param limit wieviele Datensätze
- * @return EntityList mit den gematchten Entities
- * @exception StorageObjectException
- */
-
- public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
- throws StorageObjectException {
-
- // local
- EntityList theReturnList=null;
- Connection con=null;
- Statement stmt=null;
- ResultSet rs;
- int offsetCount = 0;
- int count=0;
-
-
- // build sql-statement
- if (wc != null && wc.length() == 0) {
- wc = null;
- }
- StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
- StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
- if (wc != null) {
- selectSql.append(" where ").append(wc);
- countSql.append(" where ").append(wc);
- }
- if (ob != null && !(ob.length() == 0)) {
- selectSql.append(" order by ").append(ob);
- }
- if (theAdaptor.hasLimit()) {
- if (limit > -1 && offset > -1) {
- selectSql.append(" limit ");
- if (theAdaptor.reverseLimit()) {
- selectSql.append(limit).append(",").append(offset);
- }
- else {
- selectSql.append(offset).append(",").append(limit);
- }
- }
- }
-
- // execute sql
- try {
- con = getPooledCon();
- stmt = con.createStatement();
- // counting rows
- if (theAdaptor.hasLimit()) {
- rs = executeSql(stmt, countSql.toString());
- if (rs != null) {
- if (rs.next())
- count = rs.getInt(1);
- rs.close();
- }
- else
- theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
- }
- // hier select
- rs = executeSql(stmt, selectSql.toString());
- if (rs != null) {
- theReturnList = new EntityList();
- if (evaluatedMetaData == false) {
- evalMetaData(rs.getMetaData());
- }
- Entity theResultEntity;
- while (rs.next()) {
- theResultEntity = makeEntityFromResultSet(rs);
- theReturnList.add(theResultEntity);
- offsetCount++;
- }
- rs.close();
- }
- // making entitylist
- if (!(theAdaptor.hasLimit()))
- count = offsetCount;
- if (theReturnList != null) {
- theReturnList.setCount(count);
- theReturnList.setOffset(offset);
- theReturnList.setWhere(wc);
- theReturnList.setOrder(ob);
- if (offset >= limit) {
- theReturnList.setPrevBatch(offset - limit);
- }
- if (offset + offsetCount < count) {
- theReturnList.setNextBatch(offset + limit);
- }
- }
- } catch (SQLException sqe) {
- throwSQLException(sqe, "selectByWhereClause");
- } finally {
- freeConnection(con, stmt);
- }
- return theReturnList;
- }
-
- /**
- * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
- *
- * @param rs Das ResultSetObjekt.
- * @return Entity Die Entity.
- */
-
- public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
- HashMap theResultHash = new HashMap();
- String theResult = null;
- int theType;
- Entity returnEntity = null;
- try {
- int size = metadataFields.size();
- for (int i = 0; i < size; i++) {
- // alle durchlaufen bis nix mehr da
- theType = metadataTypes[i];
- if (theType == java.sql.Types.LONGVARBINARY) {
- InputStream us = rs.getAsciiStream(i + 1);
- if (us != null) {
- InputStreamReader is = new InputStreamReader(us);
- char[] data = new char[32768];
- StringBuffer theResultString = new StringBuffer();
- int len;
- while ((len = is.read(data)) > 0) {
- theResultString.append(data, 0, len);
- }
- is.close();
- theResult = theResultString.toString();
- }
- else {
- theResult = null;
- }
- }
- else {
- theResult = getValueAsString(rs, (i + 1), theType);
- }
- if (theResult != null) {
- theResultHash.put(metadataFields.get(i), theResult);
- }
- }
- if (cache != null && theResultHash.containsKey(thePKeyName) && cache.containsKey((String)theResultHash.get(thePKeyName))) {
- //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
- returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
- }
- else {
- if (theEntityClass != null) {
- returnEntity = (Entity)theEntityClass.newInstance();
- returnEntity.setValues(theResultHash);
- returnEntity.setStorage(myselfDatabase);
- if (cache != null) {
- //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
- cache.put(returnEntity.getId(), returnEntity);
- }
- }
- else {
- throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
- }
- }
- } // try
- catch (IllegalAccessException e) {
- throwStorageObjectException("Kein Zugriff! -- " + e.toString());
- } catch (IOException e) {
- throwStorageObjectException("IOException! -- " + e.toString());
- } catch (InstantiationException e) {
- throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
- } catch (SQLException sqe) {
- throwSQLException(sqe, "makeEntityFromResultSet");
- return null;
- }
- return returnEntity;
- }
-
- /**
- * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
- * wird automatisch mit dem aktuellen Datum gefuellt.
- *
- * @param theEntity
- * @return der Wert des Primary-keys der eingefügten Entity
- */
- public String insert (Entity theEntity) throws StorageObjectException {
- String returnId = null;
- Connection con = null;
- PreparedStatement pstmt = null;
- //cache
- invalidatePopupCache();
- try {
- ArrayList streamedInput = theEntity.streamedInput();
- StringBuffer f = new StringBuffer();
- StringBuffer v = new StringBuffer();
- String aField, aValue;
- boolean firstField = true;
- // make sql-string
- for (int i = 0; i < getFields().size(); i++) {
- aField = (String)getFields().get(i);
- if (!aField.equals(thePKeyName)) {
- aValue = null;
- // sonderfaelle
- if (aField.equals("webdb_create")) {
- aValue = "NOW()";
- }
- else {
- if (streamedInput != null && streamedInput.contains(aField)) {
- aValue = "?";
- }
- else {
- if (theEntity.hasValueForField(aField)) {
- aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
- + "'";
- }
- }
- }
- // wenn Wert gegeben, dann einbauen
- if (aValue != null) {
- if (firstField == false) {
- f.append(",");
- v.append(",");
- }
- else {
- firstField = false;
- }
- f.append(aField);
- v.append(aValue);
- }
- }
- } // end for
- // insert into db
- StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
- String sql = sqlBuf.toString();
- theLog.printInfo("INSERT: " + sql);
- con = getPooledCon();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql);
- if (streamedInput != null) {
- for (int i = 0; i < streamedInput.size(); i++) {
- String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
- pstmt.setBytes(i + 1, inputString.getBytes());
- }
- }
- int ret = pstmt.executeUpdate();
- if(ret == 0){
- //insert failed
- return null;
- }
- pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
- ResultSet rs = pstmt.executeQuery();
- rs.next();
- returnId = rs.getString(1);
- theEntity.setId(returnId);
- } catch (SQLException sqe) {
- throwSQLException(sqe, "insert");
- } finally {
- try {
- con.setAutoCommit(true);
- } catch (Exception e) {
- ;
- }
- freeConnection(con, pstmt);
- }
- return returnId;
- }
-
- /**
- * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
- * wird automatisch mit dem aktuellen Datum gefuellt.
- *
- * @param theEntity
- */
- public void update (Entity theEntity) throws StorageObjectException {
- Connection con = null;
- PreparedStatement pstmt = null;
- ArrayList streamedInput = theEntity.streamedInput();
- String id = theEntity.getId();
- String aField;
- StringBuffer fv = new StringBuffer();
- boolean firstField = true;
- //cache
- invalidatePopupCache();
- // build sql statement
- for (int i = 0; i < getFields().size(); i++) {
- aField = (String)metadataFields.get(i);
- // only normal cases
- if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
- if (theEntity.hasValueForField(aField)) {
- if (firstField == false) {
- fv.append(", ");
- }
- else {
- firstField = false;
- }
- fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
- }
- }
- }
- StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
- // exceptions
- if (metadataFields.contains("webdb_lastchange")) {
- sql.append(",webdb_lastchange=NOW()");
- }
- if (streamedInput != null) {
- for (int i = 0; i < streamedInput.size(); i++) {
- sql.append(",").append(streamedInput.get(i)).append("=?");
- }
- }
- sql.append(" where id=").append(id);
- theLog.printInfo("UPDATE: " + sql);
- // execute sql
- try {
- con = getPooledCon();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql.toString());
- if (streamedInput != null) {
- for (int i = 0; i < streamedInput.size(); i++) {
- String inputString = theEntity.getValue((String)streamedInput.get(i));
- pstmt.setBytes(i + 1, inputString.getBytes());
- }
- }
- pstmt.executeUpdate();
- } catch (SQLException sqe) {
- throwSQLException(sqe, "update");
- } finally {
- try {
- con.setAutoCommit(true);
- } catch (Exception e) {
- ;
- }
- freeConnection(con, pstmt);
- }
- }
-
- /*
- * delete-Operator
- * @param id des zu loeschenden Datensatzes
- * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
- */
- public boolean delete (String id) throws StorageObjectException {
- Statement stmt = null;
- Connection con = null;
- String sql;
- int res = 0;
- // loeschen des caches
- invalidatePopupCache();
- sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
- "'";
- theLog.printInfo("DELETE " + sql);
- try {
- con = getPooledCon();
- stmt = con.createStatement();
- res = stmt.executeUpdate(sql);
- } catch (SQLException sqe) {
- throwSQLException(sqe, "delete");
- } finally {
- freeConnection(con, stmt);
- }
- if (cache != null) {
- theLog.printInfo("CACHE: deleted " + id);
- cache.remove(id);
- }
- return (res > 0) ? true : false;
- }
-
- /* noch nicht implementiert.
- * @return immer false
- */
- public boolean delete (EntityList theEntityList) {
- invalidatePopupCache();
- return false;
- }
-
- /**
- * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
- * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
- * @return null
- */
- public SimpleList getPopupData () {
- return null;
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
- */
- public SimpleList getPopupData (String name, boolean hasNullValue) {
- return getPopupData(name, hasNullValue, null);
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @param where Schraenkt die Selektion der Datensaetze ein.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
- */
- public SimpleList getPopupData (String name, boolean hasNullValue, String where) {
- return getPopupData(name, hasNullValue, where, null);
- }
-
- /**
- * Holt Daten fuer Popups.
- * @param name Name des Feldes.
- * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
- * @param where Schraenkt die Selektion der Datensaetze ein.
- * @param order Gibt ein Feld als Sortierkriterium an.
- * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
- */
- public SimpleList getPopupData (String name, boolean hasNullValue, String where,
- String order) {
- // caching
- if (hasPopupCache && popupCache != null)
- return popupCache;
- SimpleList simpleList = null;
- Connection con = null;
- Statement stmt = null;
- // build sql
- StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
- if (where != null && !(where.length() == 0))
- sql.append(" where ").append(where);
- sql.append(" order by ");
- if (order != null && !(order.length() == 0))
- sql.append(order);
- else
- sql.append(name);
- // execute sql
- try {
- con = getPooledCon();
- stmt = con.createStatement();
- ResultSet rs = executeSql(stmt, sql.toString());
- if (rs != null) {
- if (evaluatedMetaData == false)
- get_meta_data();
- simpleList = new SimpleList();
- SimpleHash popupDict;
- if (hasNullValue) {
- popupDict = new SimpleHash();
- popupDict.put("key", "");
- popupDict.put("value", "--");
- simpleList.add(popupDict);
- }
- while (rs.next()) {
- popupDict = new SimpleHash();
- popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
- popupDict.put("value", rs.getString(2));
- simpleList.add(popupDict);
- }
- rs.close();
- }
- } catch (Exception e) {
- theLog.printDebugInfo(e.toString());
- } finally {
- freeConnection(con, stmt);
- }
- if (hasPopupCache) {
- popupCache = simpleList;
- }
- return simpleList;
- }
-
- /**
- * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
- * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
- * Tabellen Verwendung finden.
- * @return SimpleHash mit den Tabellezeilen.
- */
- public SimpleHash getHashData () {
- if (hashCache == null) {
- try {
- hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
- -1));
- } catch (StorageObjectException e) {
- theLog.printDebugInfo(e.toString());
- }
- }
- return hashCache;
- }
-
- /* invalidates the popupCache
- */
- protected void invalidatePopupCache () {
-
- /** @todo invalidates toooo much */
- popupCache = null;
- hashCache = null;
- }
-
- /**
- * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
- * @param stmt Statemnt
- * @param sql Sql-String
- * @return ResultSet
- * @exception StorageObjectException
- */
- public ResultSet executeSql (Statement stmt, String sql)
- throws StorageObjectException, SQLException
- {
- ResultSet rs;
- long startTime = (new java.util.Date()).getTime();
- try {
- rs = stmt.executeQuery(sql);
- theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
- + sql);
- }
- catch (SQLException e)
- {
- theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
- + sql);
- throw e;
- }
-
- return rs;
- }
-
- /**
- * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
- * getimed und geloggt.
- * @param stmt PreparedStatement mit der SQL-Anweisung
- * @return Liefert ResultSet des Statements zurueck.
- * @exception StorageObjectException, SQLException
- */
- public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
- SQLException {
-
- long startTime = (new java.util.Date()).getTime();
- ResultSet rs = stmt.executeQuery();
- theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
- return rs;
- }
-
- /**
- * returns the number of rows in the table
- */
- public int getSize(String where)
- throws SQLException,StorageObjectException
- {
- long startTime = (new java.util.Date()).getTime();
- String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
- //theLog.printDebugInfo("trying: "+ sql);
- Connection con = null;
- Statement stmt = null;
- int result = 0;
-
- try {
- con = getPooledCon();
- stmt = con.createStatement();
- ResultSet rs = executeSql(stmt,sql);
- while(rs.next()){
- result = rs.getInt(1);
- }
- } catch (SQLException e) {
- theLog.printError(e.toString());
- } finally {
- freeConnection(con,stmt);
- }
- theLog.printInfo(theTable + " has "+ result +" rows where " + where);
- theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
- return result;
- }
-
- public int executeUpdate(Statement stmt, String sql)
- throws StorageObjectException, SQLException
- {
- int rs;
- long startTime = (new java.util.Date()).getTime();
- try
- {
- rs = stmt.executeUpdate(sql);
- theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
- }
- catch (SQLException e)
- {
- theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
- + sql);
- throw e;
- }
- return rs;
- }
-
- public int executeUpdate(String sql)
- throws StorageObjectException, SQLException
- {
- int result=-1;
- long startTime = (new java.util.Date()).getTime();
- Connection con=null;PreparedStatement pstmt=null;
- try {
- con=getPooledCon();
- pstmt = con.prepareStatement(sql);
- result = pstmt.executeUpdate();
- }
- catch (Exception e) {theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());}
- finally { freeConnection(con,pstmt); }
- theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
- return result;
- }
-
- /**
- * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
- * @param md ResultSetMetaData
- * @exception StorageObjectException
- */
- private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
- this.evaluatedMetaData = true;
- this.metadataFields = new ArrayList();
- this.metadataLabels = new ArrayList();
- this.metadataNotNullFields = new ArrayList();
- try {
- int numFields = md.getColumnCount();
- this.metadataTypes = new int[numFields];
- String aField;
- int aType;
- for (int i = 1; i <= numFields; i++) {
- aField = md.getColumnName(i);
- metadataFields.add(aField);
- metadataLabels.add(md.getColumnLabel(i));
- aType = md.getColumnType(i);
- metadataTypes[i - 1] = aType;
- if (aField.equals(thePKeyName)) {
- thePKeyType = aType;
- }
- if (md.isNullable(i) == md.columnNullable) {
- metadataNotNullFields.add(aField);
- }
- }
- } catch (SQLException e) {
- throwSQLException(e, "evalMetaData");
- }
- }
-
- /**
- * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
- * um die alle Columns und Typen einer Tabelle zu ermitteln.
- */
- private void get_meta_data () throws StorageObjectException {
- Connection con = null;
- PreparedStatement pstmt = null;
- String sql = "select * from " + theTable + " where 0=1";
- try {
- con = getPooledCon();
- pstmt = con.prepareStatement(sql);
- theLog.printInfo("METADATA: " + sql);
- ResultSet rs = pstmt.executeQuery();
- evalMetaData(rs.getMetaData());
- rs.close();
- } catch (SQLException e) {
- throwSQLException(e, "get_meta_data");
- } finally {
- freeConnection(con, pstmt);
- }
- }
-
- /**
- * Datenbankverbindung wird geschlossen
- */
- public void disconnectPool () {
- try {
- myBroker.destroy(100);
- } catch (SQLException sqe) {
- ;
- }
- }
-
- /**
- * Returns Connection-Object out of the PoolBroker.
- *
- * @return Connection Object.
- */
- public Connection getPooledCon () throws StorageObjectException {
- if (myBroker != null) {
- Connection con = myBroker.getConnection();
- if (con != null)
- return con;
- }
- throw new StorageObjectException("No connection to database!");
- }
-
- /**
- * Connection und StatementObjekt werden geschlossen und an den Connectionpool
- * zurückgeben
- * @param con Connection zur Datenbank
- * @param stmt Statement-Objekt
- */
- public void freeConnection (Connection con, Statement stmt) {
- try {
- if (stmt != null)
- stmt.close();
- } catch (SQLException e1) {
- theLog.printDebugInfo(e1.toString());
- }
- if (con != null)
- myBroker.freeConnection(con);
- else
- theLog.printDebugInfo("Con was null!");
- }
-
- /**
- * Wertet SQLException aus und wirft dannach eine StorageObjectException
- * @param sqe SQLException
- * @param wo Funktonsname, in der die SQLException geworfen wurde
- * @exception StorageObjectException
- */
- protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
- String state = "";
- String message = "";
- int vendor = 0;
- if (sqe != null) {
- state = sqe.getSQLState();
- message = sqe.getMessage();
- vendor = sqe.getErrorCode();
- }
- theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
- + wo);
- throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
- sqe.toString());
- }
-
- /**
- * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
- * @param message Nachricht mit dem Fehler
- * @exception StorageObjectException
- */
- void throwStorageObjectException (String message) throws StorageObjectException {
- theLog.printError(message);
- throw new StorageObjectException(message);
- }
+ protected String theTable;
+ protected String theCoreTable=null;
+ protected String thePKeyName="id";
+ protected int thePKeyType;
+ protected boolean evaluatedMetaData=false;
+ protected ArrayList metadataFields,metadataLabels,
+ metadataNotNullFields;
+ protected int[] metadataTypes;
+ protected Class theEntityClass;
+ protected StorageObject myselfDatabase;
+
+ /** @todo DatabaseCache will soon be replaced by
+ * ObjectStore. Points to interweave Database with
+ * ObjectStore are marked "todo: OS:" below */
+ protected DatabaseCache cache;
+
+ protected SimpleList popupCache=null;
+ protected boolean hasPopupCache = false;
+ protected SimpleHash hashCache=null;
+ protected boolean hasTimestamp=true;
+ private String database_driver;
+ private String database_url;
+ private int defaultLimit;
+ protected DatabaseAdaptor theAdaptor;
+ protected Logfile theLog;
+ protected static final SimpleHash POPUP_EMTYLINE=new SimpleHash();
+
+ static {
+ // always same object saves a little space
+ POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
+
+ /** @todo OS: init ObjectStore*/
+ }
+
+ /**
+ * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
+ * Aus diesem file werden <code>Database.Logfile</code>,
+ * <code>Database.Username</code>,<code>Database.Password</code>,
+ * <code>Database.Host</code> und <code>Database.Adaptor</code>
+ * ausgelesen und ein Broker für die Verbindugen zur Datenbank
+ * erzeugt.
+ *
+ * @param String confFilename Dateiname der Konfigurationsdatei
+ */
+ public Database() throws StorageObjectException {
+ theLog = Logfile.getInstance(MirConfig.getProp("Home")+
+ MirConfig.getProp("Database.Logfile"));
+ String theAdaptorName=MirConfig.getProp("Database.Adaptor");
+ defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
+ try {
+ theEntityClass = Class.forName("mir.entity.GenericEntity");
+ theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
+ } catch (Exception e){
+ theLog.printError("Error in Database() constructor with "+
+ theAdaptorName + " -- " +e.toString());
+ throw new StorageObjectException("Error in Database() constructor with "
+ +e.toString());
+ }
+ /*String database_username=MirConfig.getProp("Database.Username");
+ String database_password=MirConfig.getProp("Database.Password");
+ String database_host=MirConfig.getProp("Database.Host");
+ try {
+ database_driver=theAdaptor.getDriver();
+ database_url=theAdaptor.getURL(database_username,database_password,
+ database_host);
+ theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
+ database_url );
+ MirConfig.addBroker(database_driver,database_url);
+ //myBroker=MirConfig.getBroker();
+ }*/
+ }
+
+ /**
+ * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
+ * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
+ * wird eine mir.entity.GenericEntity erzeugt.
+ *
+ * @return Class-Objekt der Entity
+ */
+ public java.lang.Class getEntityClass () {
+ return theEntityClass;
+ }
+
+ /**
+ * Liefert die Standardbeschränkung von select-Statements zurück, also
+ * wieviel Datensätze per Default selektiert werden.
+ *
+ * @return Standard-Anzahl der Datensätze
+ */
+ public int getLimit () {
+ return defaultLimit;
+ }
+
+ /**
+ * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
+ * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
+ * @return Name des Primary-Keys
+ */
+ public String getIdName () {
+ return thePKeyName;
+ }
+
+ /**
+ * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
+ *
+ * @return Name der Tabelle
+ */
+ public String getTableName () {
+ return theTable;
+ }
+
+ /*
+ * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
+ * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
+ * wird.
+ * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
+ * the Table
+ */
+
+ public String getCoreTable(){
+ if (theCoreTable!=null) return theCoreTable;
+ else return theTable;
+ }
+
+ /**
+ * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
+ * @return int-Array mit den Typen der Felder
+ * @exception StorageObjectException
+ */
+ public int[] getTypes () throws StorageObjectException {
+ if (metadataTypes == null)
+ get_meta_data();
+ return metadataTypes;
+ }
+
+ /**
+ * Liefert eine Liste der Labels der Tabellenfelder
+ * @return ArrayListe mit Labeln
+ * @exception StorageObjectException
+ */
+ public ArrayList getLabels () throws StorageObjectException {
+ if (metadataLabels == null)
+ get_meta_data();
+ return metadataLabels;
+ }
+
+ /**
+ * Liefert eine Liste der Felder der Tabelle
+ * @return ArrayList mit Feldern
+ * @exception StorageObjectException
+ */
+ public ArrayList getFields () throws StorageObjectException {
+ if (metadataFields == null)
+ get_meta_data();
+ return metadataFields;
+ }
+
+
+ /*
+ * Gets value out of ResultSet according to type and converts to String
+ * @param inValue Wert aus ResultSet.
+ * @param aType Datenbanktyp.
+ * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
+ * dann /unsupported value/
+ */
+ private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
+ String outValue = null;
+ if (rs != null) {
+ try {
+ switch (aType) {
+ case java.sql.Types.BIT:
+ outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
+ break;
+ case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
+ int out = rs.getInt(valueIndex);
+ if (!rs.wasNull())
+ outValue = new Integer(out).toString();
+ break;
+ case java.sql.Types.NUMERIC:
+ /** @todo Numeric can be float or double depending upon
+ * metadata.getScale() / especially with oracle */
+ long outl = rs.getLong(valueIndex);
+ if (!rs.wasNull())
+ outValue = new Long(outl).toString();
+ break;
+ case java.sql.Types.REAL:
+ float tempf = rs.getFloat(valueIndex);
+ if (!rs.wasNull()) {
+ tempf *= 10;
+ tempf += 0.5;
+ int tempf_int = (int)tempf;
+ tempf = (float)tempf_int;
+ tempf /= 10;
+ outValue = "" + tempf;
+ outValue = outValue.replace('.', ',');
+ }
+ break;
+ case java.sql.Types.DOUBLE:
+ double tempd = rs.getDouble(valueIndex);
+ if (!rs.wasNull()) {
+ tempd *= 10;
+ tempd += 0.5;
+ int tempd_int = (int)tempd;
+ tempd = (double)tempd_int;
+ tempd /= 10;
+ outValue = "" + tempd;
+ outValue = outValue.replace('.', ',');
+ }
+ break;
+ case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
+ outValue = rs.getString(valueIndex);
+ //if (outValue != null)
+ //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
+ break;
+ case java.sql.Types.LONGVARBINARY:
+ outValue = rs.getString(valueIndex);
+ //if (outValue != null)
+ //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
+ break;
+ case java.sql.Types.TIMESTAMP:
+ Timestamp timestamp = (rs.getTimestamp(valueIndex));
+ if (!rs.wasNull()) {
+ outValue = timestamp.toString();
+ }
+ break;
+ default:
+ outValue = "<unsupported value>";
+ theLog.printWarning("Unsupported Datatype: at " + valueIndex +
+ " (" + aType + ")");
+ }
+ } catch (SQLException e) {
+ throw new StorageObjectException("Could not get Value out of Resultset -- "
+ + e.toString());
+ }
+ }
+ return outValue;
+ }
+
+ /*
+ * select-Operator um einen Datensatz zu bekommen.
+ * @param id Primaerschluessel des Datensatzes.
+ * @return liefert EntityObject des gefundenen Datensatzes oder null.
+ */
+ public Entity selectById(String id)
+ throws StorageObjectException {
+
+ if (id==null||id.equals(""))
+ throw new StorageObjectException("id war null");
+
+ /** @todo OS: build StoreIdenfier and check ObjectStore for StoreIdentifier */
+ if (cache != null && (cache.containsKey(id) > -1))
+ return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
+
+ Statement stmt=null;Connection con=getPooledCon();
+ Entity returnEntity=null;
+ try {
+ ResultSet rs;
+ /** @todo better prepared statement */
+ String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
+ stmt = con.createStatement();
+ rs = executeSql(stmt, selectSql);
+ if (rs != null) {
+ if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
+ if (rs.next())
+ returnEntity = makeEntityFromResultSet(rs);
+ else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
+ rs.close();
+ }
+ else {
+ theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
+ }
+ }
+ catch (SQLException sqe){
+ throwSQLException(sqe,"selectById"); return null;
+ }
+ catch (NumberFormatException e) {
+ theLog.printError("ID ist keine Zahl: " + id);
+ }
+ finally { freeConnection(con,stmt); }
+
+ /** @todo OS: Entity should be saved in ostore */
+ return returnEntity;
+ }
+
+
+ /**
+ * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
+ * @param key Datenbankfeld der Bedingung.
+ * @param value Wert die der key anehmen muss.
+ * @return EntityList mit den gematchten Entities
+ */
+ public EntityList selectByFieldValue(String aField, String aValue)
+ throws StorageObjectException
+ {
+ return selectByFieldValue(aField, aValue, 0);
+ }
+
+ /**
+ * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
+ * @param key Datenbankfeld der Bedingung.
+ * @param value Wert die der key anehmen muss.
+ * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
+ * @return EntityList mit den gematchten Entities
+ */
+ public EntityList selectByFieldValue(String aField, String aValue, int offset)
+ throws StorageObjectException
+ {
+ return selectByWhereClause(aField + "=" + aValue, offset);
+ }
+
+
+ /**
+ * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
+ * Also offset wird der erste Datensatz genommen.
+ *
+ * @param wc where-Clause
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+ public EntityList selectByWhereClause(String where)
+ throws StorageObjectException
+ {
+ return selectByWhereClause(where, 0);
+ }
+
+
+ /**
+ * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+ *
+ * @param wc where-Clause
+ * @param offset ab welchem Datensatz.
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+ public EntityList selectByWhereClause(String whereClause, int offset)
+ throws StorageObjectException
+ {
+ return selectByWhereClause(whereClause, null, offset);
+ }
+
+
+ /**
+ * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
+ * Also offset wird der erste Datensatz genommen.
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+ *
+ * @param wc where-Clause
+ * @param ob orderBy-Clause
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+
+ public EntityList selectByWhereClause(String where, String order)
+ throws StorageObjectException {
+ return selectByWhereClause(where, order, 0);
+ }
+
+
+ /**
+ * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
+ * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
+ *
+ * @param wc where-Clause
+ * @param ob orderBy-Clause
+ * @param offset ab welchem Datensatz
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+
+ public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
+ throws StorageObjectException {
+ return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
+ }
+
+
+ /**
+ * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
+ * @param wc where-Clause
+ * @param ob orderBy-Clause
+ * @param offset ab welchem Datensatz
+ * @param limit wieviele Datensätze
+ * @return EntityList mit den gematchten Entities
+ * @exception StorageObjectException
+ */
+
+ public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
+ throws StorageObjectException {
+
+ // local
+ EntityList theReturnList=null;
+ Connection con=null;
+ Statement stmt=null;
+ ResultSet rs;
+ int offsetCount = 0, count=0;
+
+ // build sql-statement
+
+ /** @todo count sql string should only be assembled if we really count
+ * see below at the end of method //rk */
+
+ if (wc != null && wc.length() == 0) {
+ wc = null;
+ }
+ StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
+ StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
+ if (wc != null) {
+ selectSql.append(" where ").append(wc);
+ countSql.append(" where ").append(wc);
+ }
+ if (ob != null && !(ob.length() == 0)) {
+ selectSql.append(" order by ").append(ob);
+ }
+ if (theAdaptor.hasLimit()) {
+ if (limit > -1 && offset > -1) {
+ selectSql.append(" limit ");
+ if (theAdaptor.reverseLimit()) {
+ selectSql.append(limit).append(",").append(offset);
+ }
+ else {
+ selectSql.append(offset).append(",").append(limit);
+ }
+ }
+ }
+
+ /** @todo OS: make StoreIdentifier and ask Ostore*/
+
+ // execute sql
+ try {
+ con = getPooledCon();
+ stmt = con.createStatement();
+
+ // selecting...
+ rs = executeSql(stmt, selectSql.toString());
+ if (rs != null) {
+ if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
+
+ theReturnList = new EntityList();
+ Entity theResultEntity;
+ while (rs.next()) {
+ theResultEntity = makeEntityFromResultSet(rs);
+ theReturnList.add(theResultEntity);
+ offsetCount++;
+ }
+ rs.close();
+ }
+
+ // making entitylist infos
+ if (!(theAdaptor.hasLimit())) count = offsetCount;
+
+ if (theReturnList != null) {
+ // now we decide if we have to know an overall count...
+ count=offsetCount;
+ if (limit > -1 && offset > -1) {
+ if (offsetCount==limit) {
+ /** @todo counting should be deffered to entitylist
+ * getSize() should be used */
+ rs = executeSql(stmt, countSql.toString());
+ if (rs != null) {
+ if ( rs.next() ) count = rs.getInt(1);
+ rs.close();
+ }
+ else theLog.printError("Could not count: " + countSql);
+ }
+ }
+ theReturnList.setCount(count);
+ theReturnList.setOffset(offset);
+ theReturnList.setWhere(wc);
+ theReturnList.setOrder(ob);
+ if (offset >= limit) {
+ theReturnList.setPrevBatch(offset - limit);
+ }
+ if (offset + offsetCount < count) {
+ theReturnList.setNextBatch(offset + limit);
+ }
+ }
+ }
+ catch (SQLException sqe) {
+ throwSQLException(sqe, "selectByWhereClause");
+ }
+ finally {
+ freeConnection(con, stmt);
+ }
+
+ return theReturnList;
+ }
+
+
+ /**
+ * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
+ *
+ * @param rs Das ResultSetObjekt.
+ * @return Entity Die Entity.
+ */
+ private Entity makeEntityFromResultSet (ResultSet rs)
+ throws StorageObjectException
+ {
+ /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
+ HashMap theResultHash = new HashMap();
+ String theResult = null;
+ int theType;
+ Entity returnEntity = null;
+ try {
+ int size = metadataFields.size();
+ for (int i = 0; i < size; i++) {
+ // alle durchlaufen bis nix mehr da
+ theType = metadataTypes[i];
+ if (theType == java.sql.Types.LONGVARBINARY) {
+ InputStream us = rs.getAsciiStream(i + 1);
+ if (us != null) {
+ InputStreamReader is = new InputStreamReader(us);
+ char[] data = new char[32768];
+ StringBuffer theResultString = new StringBuffer();
+ int len;
+ while ((len = is.read(data)) > 0) {
+ theResultString.append(data, 0, len);
+ }
+ is.close();
+ theResult = theResultString.toString();
+ }
+ else {
+ theResult = null;
+ }
+ }
+ else {
+ theResult = getValueAsString(rs, (i + 1), theType);
+ }
+ if (theResult != null) {
+ theResultHash.put(metadataFields.get(i), theResult);
+ }
+ }
+
+ /** @todo why fetching all data (above) and then consulting the
+ * cache? we should fetch pkeyname first // rk */
+ if (cache != null && theResultHash.containsKey(thePKeyName) &&
+ (cache.containsKey((String)theResultHash.get(thePKeyName)) > -1)) {
+ returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
+ } else {
+ if (theEntityClass != null) {
+ returnEntity = (Entity)theEntityClass.newInstance();
+ returnEntity.setValues(theResultHash);
+ returnEntity.setStorage(myselfDatabase);
+ if (cache != null) {
+ //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
+ /** @todo put element into ObjectStore */
+ cache.put(returnEntity.getId(), returnEntity);
+ }
+ } else {
+ throwStorageObjectException("Internal Error: theEntityClass not set!");
+ }
+ }
+ } catch (IllegalAccessException e) {
+ throwStorageObjectException("Kein Zugriff! -- " + e.toString());
+ } catch (IOException e) {
+ throwStorageObjectException("IOException! -- " + e.toString());
+ } catch (InstantiationException e) {
+ throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
+ } catch (SQLException sqe) {
+ throwSQLException(sqe, "makeEntityFromResultSet");
+ return null;
+ }
+ return returnEntity;
+ }
+
+ /**
+ * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
+ * wird automatisch mit dem aktuellen Datum gefuellt.
+ *
+ * @param theEntity
+ * @return der Wert des Primary-keys der eingefügten Entity
+ */
+ public String insert (Entity theEntity) throws StorageObjectException {
+ String returnId = null;
+ Connection con = null;
+ PreparedStatement pstmt = null;
+ //cache
+ invalidatePopupCache();
+ /** @todo OS: if Entity is StorableObject, invalidate in ObjectStore
+ * careful: Entity has no id yet! */
+ try {
+ ArrayList streamedInput = theEntity.streamedInput();
+ StringBuffer f = new StringBuffer();
+ StringBuffer v = new StringBuffer();
+ String aField, aValue;
+ boolean firstField = true;
+ // make sql-string
+ for (int i = 0; i < getFields().size(); i++) {
+ aField = (String)getFields().get(i);
+ if (!aField.equals(thePKeyName)) {
+ aValue = null;
+ // sonderfaelle
+ if (aField.equals("webdb_create")) {
+ aValue = "NOW()";
+ }
+ else {
+ if (streamedInput != null && streamedInput.contains(aField)) {
+ aValue = "?";
+ }
+ else {
+ if (theEntity.hasValueForField(aField)) {
+ aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
+ + "'";
+ }
+ }
+ }
+ // wenn Wert gegeben, dann einbauen
+ if (aValue != null) {
+ if (firstField == false) {
+ f.append(",");
+ v.append(",");
+ }
+ else {
+ firstField = false;
+ }
+ f.append(aField);
+ v.append(aValue);
+ }
+ }
+ } // end for
+ // insert into db
+ StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
+ String sql = sqlBuf.toString();
+ theLog.printInfo("INSERT: " + sql);
+ con = getPooledCon();
+ con.setAutoCommit(false);
+ pstmt = con.prepareStatement(sql);
+ if (streamedInput != null) {
+ for (int i = 0; i < streamedInput.size(); i++) {
+ String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
+ pstmt.setBytes(i + 1, inputString.getBytes());
+ }
+ }
+ int ret = pstmt.executeUpdate();
+ if(ret == 0){
+ //insert failed
+ return null;
+ }
+ pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
+ ResultSet rs = pstmt.executeQuery();
+ rs.next();
+ returnId = rs.getString(1);
+ theEntity.setId(returnId);
+ } catch (SQLException sqe) {
+ throwSQLException(sqe, "insert");
+ } finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ ;
+ }
+ freeConnection(con, pstmt);
+ }
+ return returnId;
+ }
+
+ /**
+ * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
+ * wird automatisch mit dem aktuellen Datum gefuellt.
+ *
+ * @param theEntity
+ */
+ public void update (Entity theEntity) throws StorageObjectException {
+ Connection con = null;
+ /** @todo this is stupid: why do we prepare statement, when we
+ * throw it away afterwards. should be regular statement
+ * update/insert could better be one routine called save()
+ * that chooses to either insert or update depending if we
+ * have a primary key in the entity. i don't know if we
+ * still need the streamed input fields. // rk */
+ /** @todo extension: check if Entity did change, otherwise we don't need */
+ /** @todo OS: invalidate in Ostore if Entity is StorableObject */
+ PreparedStatement pstmt = null;
+ ArrayList streamedInput = theEntity.streamedInput();
+ String id = theEntity.getId();
+ String aField;
+ StringBuffer fv = new StringBuffer();
+ boolean firstField = true;
+ //cache
+ invalidatePopupCache();
+ // build sql statement
+ for (int i = 0; i < getFields().size(); i++) {
+ aField = (String)metadataFields.get(i);
+ // only normal cases
+ if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
+ aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
+ if (theEntity.hasValueForField(aField)) {
+ if (firstField == false) {
+ fv.append(", ");
+ }
+ else {
+ firstField = false;
+ }
+ fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
+ }
+ }
+ }
+ StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
+ // exceptions
+ if (metadataFields.contains("webdb_lastchange")) {
+ sql.append(",webdb_lastchange=NOW()");
+ }
+ if (streamedInput != null) {
+ for (int i = 0; i < streamedInput.size(); i++) {
+ sql.append(",").append(streamedInput.get(i)).append("=?");
+ }
+ }
+ sql.append(" where id=").append(id);
+ theLog.printInfo("UPDATE: " + sql);
+ // execute sql
+ try {
+ con = getPooledCon();
+ con.setAutoCommit(false);
+ pstmt = con.prepareStatement(sql.toString());
+ if (streamedInput != null) {
+ for (int i = 0; i < streamedInput.size(); i++) {
+ String inputString = theEntity.getValue((String)streamedInput.get(i));
+ pstmt.setBytes(i + 1, inputString.getBytes());
+ }
+ }
+ pstmt.executeUpdate();
+ } catch (SQLException sqe) {
+ throwSQLException(sqe, "update");
+ } finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ ;
+ }
+ freeConnection(con, pstmt);
+ }
+ }
+
+ /*
+ * delete-Operator
+ * @param id des zu loeschenden Datensatzes
+ * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
+ */
+ public boolean delete (String id) throws StorageObjectException {
+ Statement stmt = null;
+ Connection con = null;
+ String sql;
+ int res = 0;
+ // loeschen des caches
+ invalidatePopupCache();
+ /** @todo OS: invalidate if StorableObject */
+ /** @todo could be prepared Statement */
+ sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
+ "'";
+ theLog.printInfo("DELETE " + sql);
+ try {
+ con = getPooledCon();
+ stmt = con.createStatement();
+ res = stmt.executeUpdate(sql);
+ } catch (SQLException sqe) {
+ throwSQLException(sqe, "delete");
+ } finally {
+ freeConnection(con, stmt);
+ }
+ /** @todo should take place before we delete */
+ if (cache != null) {
+ theLog.printInfo("CACHE: deleted " + id);
+ cache.remove(id);
+ }
+ return (res > 0) ? true : false;
+ }
+
+ /* noch nicht implementiert.
+ * @return immer false
+ */
+ public boolean delete (EntityList theEntityList) {
+ invalidatePopupCache();
+ return false;
+ }
+
+ /**
+ * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
+ * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
+ * @return null
+ */
+ public SimpleList getPopupData () throws StorageObjectException {
+ return null;
+ }
+
+ /**
+ * Holt Daten fuer Popups.
+ * @param name Name des Feldes.
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
+ */
+ public SimpleList getPopupData (String name, boolean hasNullValue)
+ throws StorageObjectException {
+ return getPopupData(name, hasNullValue, null);
+ }
+
+ /**
+ * Holt Daten fuer Popups.
+ * @param name Name des Feldes.
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
+ * @param where Schraenkt die Selektion der Datensaetze ein.
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
+ */
+ public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
+ return getPopupData(name, hasNullValue, where, null);
+ }
+
+ /**
+ * Holt Daten fuer Popups.
+ * @param name Name des Feldes.
+ * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
+ * @param where Schraenkt die Selektion der Datensaetze ein.
+ * @param order Gibt ein Feld als Sortierkriterium an.
+ * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
+ */
+ public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
+ // caching
+ if (hasPopupCache && popupCache != null)
+ return popupCache;
+ SimpleList simpleList = null;
+ Connection con = null;
+ Statement stmt = null;
+ // build sql
+ StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
+ .append(",").append(name).append(" from ")
+ .append(theTable);
+ if (where != null && !(where.length() == 0))
+ sql.append(" where ").append(where);
+ sql.append(" order by ");
+ if (order != null && !(order.length() == 0))
+ sql.append(order);
+ else
+ sql.append(name);
+ // execute sql
+ try {
+ con = getPooledCon();
+ } catch (Exception e) {
+ throw new StorageObjectException(e.toString());
+ }
+ try {
+ stmt = con.createStatement();
+ ResultSet rs = executeSql(stmt, sql.toString());
+
+ if (rs != null) {
+ if (!evaluatedMetaData) get_meta_data();
+ simpleList = new SimpleList();
+ // if popup has null-selector
+ if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
+
+ SimpleHash popupDict;
+ while (rs.next()) {
+ popupDict = new SimpleHash();
+ popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
+ popupDict.put("value", rs.getString(2));
+ simpleList.add(popupDict);
+ }
+ rs.close();
+ }
+ } catch (Exception e) {
+ theLog.printError("getPopupData: "+e.toString());
+ throw new StorageObjectException(e.toString());
+ } finally {
+ freeConnection(con, stmt);
+ }
+
+ if (hasPopupCache) popupCache = simpleList;
+ return simpleList;
+ }
+
+ /**
+ * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
+ * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
+ * Tabellen Verwendung finden.
+ * @return SimpleHash mit den Tabellezeilen.
+ */
+ public SimpleHash getHashData () {
+ /** @todo dangerous! this should have a flag to be enabled, otherwise
+ * very big Hashes could be returned */
+ if (hashCache == null) {
+ try {
+ hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
+ -1));
+ } catch (StorageObjectException e) {
+ theLog.printDebugInfo(e.toString());
+ }
+ }
+ return hashCache;
+ }
+
+ /* invalidates the popupCache
+ */
+ protected void invalidatePopupCache () {
+ /** @todo invalidates toooo much */
+ popupCache = null;
+ hashCache = null;
+ }
+
+ /**
+ * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
+ * @param stmt Statemnt
+ * @param sql Sql-String
+ * @return ResultSet
+ * @exception StorageObjectException
+ */
+ public ResultSet executeSql (Statement stmt, String sql)
+ throws StorageObjectException, SQLException
+ {
+ long startTime = System.currentTimeMillis();
+ ResultSet rs;
+ try {
+ rs = stmt.executeQuery(sql);
+ theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
+ + sql);
+ }
+ catch (SQLException e)
+ {
+ theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
+ - startTime) + "ms. for: "+ sql);
+ throw e;
+ }
+
+ return rs;
+ }
+
+ /**
+ * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
+ * getimed und geloggt.
+ * @param stmt PreparedStatement mit der SQL-Anweisung
+ * @return Liefert ResultSet des Statements zurueck.
+ * @exception StorageObjectException, SQLException
+ */
+ public ResultSet executeSql (PreparedStatement stmt)
+ throws StorageObjectException, SQLException {
+
+ long startTime = (new java.util.Date()).getTime();
+ ResultSet rs = stmt.executeQuery();
+ theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
+ return rs;
+ }
+
+ /**
+ * returns the number of rows in the table
+ */
+ public int getSize(String where)
+ throws SQLException,StorageObjectException
+ {
+ long startTime = System.currentTimeMillis();
+ String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
+ Connection con = null;
+ Statement stmt = null;
+ int result = 0;
+
+ try {
+ con = getPooledCon();
+ stmt = con.createStatement();
+ ResultSet rs = executeSql(stmt,sql);
+ while(rs.next()){
+ result = rs.getInt(1);
+ }
+ } catch (SQLException e) {
+ theLog.printError(e.toString());
+ } finally {
+ freeConnection(con,stmt);
+ }
+ //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
+ theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
+ + sql);
+ return result;
+ }
+
+ public int executeUpdate(Statement stmt, String sql)
+ throws StorageObjectException, SQLException
+ {
+ int rs;
+ long startTime = (new java.util.Date()).getTime();
+ try
+ {
+ rs = stmt.executeUpdate(sql);
+ theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
+ + sql);
+ }
+ catch (SQLException e)
+ {
+ theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
+ - startTime) + "ms. for: "+ sql);
+ throw e;
+ }
+ return rs;
+ }
+
+ public int executeUpdate(String sql)
+ throws StorageObjectException, SQLException
+ {
+ int result=-1;
+ long startTime = (new java.util.Date()).getTime();
+ Connection con=null;PreparedStatement pstmt=null;
+ try {
+ con=getPooledCon();
+ pstmt = con.prepareStatement(sql);
+ result = pstmt.executeUpdate();
+ }
+ catch (Exception e) {
+ theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
+ throw new StorageObjectException("executeUpdate failed: "+e.toString());
+ }
+ finally { freeConnection(con,pstmt); }
+ theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
+ + sql);
+ return result;
+ }
+
+ /**
+ * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
+ * @param md ResultSetMetaData
+ * @exception StorageObjectException
+ */
+ private void evalMetaData (ResultSetMetaData md)
+ throws StorageObjectException {
+
+ this.evaluatedMetaData = true;
+ this.metadataFields = new ArrayList();
+ this.metadataLabels = new ArrayList();
+ this.metadataNotNullFields = new ArrayList();
+ try {
+ int numFields = md.getColumnCount();
+ this.metadataTypes = new int[numFields];
+ String aField;
+ int aType;
+ for (int i = 1; i <= numFields; i++) {
+ aField = md.getColumnName(i);
+ metadataFields.add(aField);
+ metadataLabels.add(md.getColumnLabel(i));
+ aType = md.getColumnType(i);
+ metadataTypes[i - 1] = aType;
+ if (aField.equals(thePKeyName)) {
+ thePKeyType = aType;
+ }
+ if (md.isNullable(i) == md.columnNullable) {
+ metadataNotNullFields.add(aField);
+ }
+ }
+ } catch (SQLException e) {
+ throwSQLException(e, "evalMetaData");
+ }
+ }
+
+ /**
+ * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
+ * um die alle Columns und Typen einer Tabelle zu ermitteln.
+ */
+ private void get_meta_data () throws StorageObjectException {
+ Connection con = null;
+ PreparedStatement pstmt = null;
+ String sql = "select * from " + theTable + " where 0=1";
+ try {
+ con = getPooledCon();
+ pstmt = con.prepareStatement(sql);
+ theLog.printInfo("METADATA: " + sql);
+ ResultSet rs = pstmt.executeQuery();
+ evalMetaData(rs.getMetaData());
+ rs.close();
+ } catch (SQLException e) {
+ throwSQLException(e, "get_meta_data");
+ } finally {
+ freeConnection(con, pstmt);
+ }
+ }
+
+
+ public Connection getPooledCon() throws StorageObjectException {
+ /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
+ try{
+ Class.forName("com.codestudio.sql.PoolMan").newInstance();
+ } catch (Exception e){
+ throw new StorageObjectException("Could not find the PoolMan Driver"
+ +e.toString());
+ }*/
+ Connection con = null;
+ try{
+ con = SQLManager.getInstance().requestConnection();
+ } catch(SQLException e){
+ theLog.printError("could not connect to the database "+e.toString());
+ System.err.println("could not connect to the database "+e.toString());
+ throw new StorageObjectException("Could not connect to the database"+
+ e.toString());
+ }
+ return con;
+ }
+
+ public void freeConnection (Connection con, Statement stmt)
+ throws StorageObjectException {
+ SQLManager.getInstance().closeStatement(stmt);
+ SQLManager.getInstance().returnConnection(con);
+ }
+
+ /**
+ * Wertet SQLException aus und wirft dannach eine StorageObjectException
+ * @param sqe SQLException
+ * @param wo Funktonsname, in der die SQLException geworfen wurde
+ * @exception StorageObjectException
+ */
+ protected void throwSQLException (SQLException sqe, String wo)
+ throws StorageObjectException {
+ String state = "";
+ String message = "";
+ int vendor = 0;
+ if (sqe != null) {
+ state = sqe.getSQLState();
+ message = sqe.getMessage();
+ vendor = sqe.getErrorCode();
+ }
+ theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
+ + wo);
+ throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
+ sqe.toString());
+ }
+
+ protected void _throwStorageObjectException (Exception e, String wo)
+ throws StorageObjectException {
+ if (e != null) {
+ theLog.printError(e.toString()+ wo);
+ throw new StorageObjectException(wo + e.toString());
+ } else {
+ theLog.printError(wo);
+ throw new StorageObjectException(wo);
+ }
+
+ }
+
+ /**
+ * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
+ * eine StorageObjectException
+ * @param message Nachricht mit dem Fehler
+ * @exception StorageObjectException
+ */
+ void throwStorageObjectException (String message)
+ throws StorageObjectException {
+ _throwStorageObjectException(null, message);
+ }
+
}
public final class DatabaseAdaptorPostgresql implements DatabaseAdaptor{
-// private static String url = "jdbc:postgresql://localhost:5432/mir";
-// just testing
-
- private static String url = "jdbc:postgresql://localhost:5432/mir_unstable";
- private static String driver = "org.postgresql.Driver";
-
public String getDriver() {
- return driver;
+ return MirConfig.getProp("Adaptor.PostgreSQL.Driver");
}
public String getURL(String user, String pass, String host) {
- return url;
- }
-
- public static void setUrl(String u) throws Exception {
- if (!url.startsWith("jdbc:"))
- throw new Exception("Database Adaptor URL must begin with: \"jdbc:\"");
- url = u;
- }
-
- public static void setDriver(String d) {
- driver = d;
+ return MirConfig.getProp("Adaptor.PostgreSQL.URL");
}
public boolean hasLimit() {
--- /dev/null
+package mir.storage;
+
+import java.util.*;
+
+public class DatabaseCache {
+ private final ArrayList _cache;
+ private int _counter;
+ private final int _max;
+
+ public DatabaseCache(int i_max){
+ _counter = 0;
+ _max = i_max;
+ _cache = new ArrayList(_max);
+ }
+
+ public DatabaseCache(){
+ _counter = -1;
+ _max = 100;
+ _cache = new ArrayList(_max);
+ }
+
+ public synchronized void put(String key, Object value){
+ if(_counter >=_max){
+ _cache.remove(0);
+ _cache.trimToSize();
+ _counter --;
+ System.out.println("put: remove " + _counter);
+ }
+ _cache.add(new Entry(key,value));
+ _counter ++;
+ System.out.println("put: put " + _counter);
+ }
+
+ public synchronized void clear(){
+ _cache.clear();
+ }
+
+ public int containsKey(String key){
+ for(int i = 0; i<_cache.size(); i++){
+ if( _cache.get(i)!=null && ((Entry)_cache.get(i)).getKey().equals(key) )
+ return i;
+ }
+ return -1;
+ }
+
+ public int containsValue(Object o){
+ for(int i = 0; i<_cache.size(); i++){
+ if( _cache.get(i)!=null && ((Entry)_cache.get(i)).getValue().equals(o) )
+ return i;
+ }
+ return -1;
+ }
+
+ public Object get(String key){
+ for(int i = 0; i<_cache.size(); i++){
+ if( _cache.get(i) != null &&
+ ((Entry)_cache.get(i)).getKey(key) != null &&
+ ((Entry)_cache.get(i)).getKey(key).equals(key) ) {
+ System.out.println("test2: "+((Entry)_cache.get(i)).getKey(key));
+ return ((Entry)_cache.get(i)).getValue();
+ }
+ }
+ return null;
+ }
+
+ public synchronized boolean remove(String key){
+ int i = containsKey(key);
+ if(i==-1){
+ return false;
+ }
+ _cache.remove(i);
+ _cache.trimToSize();
+ _counter --;
+ return true;
+ }
+
+ public int size(){
+ return _counter;
+ }
+
+ private class Entry {
+ private String _key;
+ private Object _value;
+
+ public Entry(String i_key, Object i_value){
+ _key = i_key;
+ _value = i_value;
+ }
+
+ public void put(String i_key, Object i_value){
+ _key = i_key;
+ _value = i_value;
+ }
+
+ public Object getValue(String i_key){
+ if(i_key.equals(_key)){
+ return _value;
+ } else {
+ return null;
+ }
+ }
+
+ public Object getValue(){
+ return _value;
+ }
+
+ public String getKey(Object i_o){
+ if(i_o.equals(_value)){
+ return _key;
+ } else {
+ return null;
+ }
+ }
+
+ public String getKey(){
+ return _key;
+ }
+ }//Entry
+
+}
+
+
+++ /dev/null
-
-package mir.storage;
-
-import java.util.*;
-import java.lang.*;
-import com.javaexchange.dbConnectionBroker.*;
-
-/**
- * Title: Mir
- * Description: Class that allows access to all Database Config values
- * Copyright: Copyright (c) 2001
- * Company: Indymedia
- * @author mh <heckmann@hbe.ca>
- * @version 0.1
- */
-
-
-public class DatabaseConfig {
-
- private static HashMap configHash;
- private static HashMap brokerHash;
- private static int instances=0;
-
- static {
- configHash = new HashMap();
- brokerHash = new HashMap();
- configHash.put("Database.Host", "localhost");
- configHash.put("Database.Adaptor", "mir.storage.DatabaseAdaptorPostgresql");
- configHash.put("Database.Limit", "20");
- configHash.put("Database.poolMin", "1");
- configHash.put("Database.poolMax", "10");
- configHash.put("Database.poolLog", "/tmp/pool.log");
- configHash.put("Database.poolResetTime", "1.0");
-
- // just for testing
- configHash.put("Database.Username", "postgres");
- configHash.put("Database.Password", "");
- }
-
- public static void setUsername(String user) {
- configHash.put("Database.Username", user);
- }
-
- public static void setPassword(String pass) {
- configHash.put("Database.Password", pass);
- }
-
- public static void setHost(String host) {
- configHash.put("Database.Host", host);
- }
-
- public static void setAdaptor(String adaptor) {
- configHash.put("Database.Adaptor", adaptor);
- }
-
- public static void setDefaultLimit(int limit) {
- configHash.put("Database.Limit", Integer.toString(limit));
- }
-
- public static void setPoolMin(int min) {
- configHash.put("Database.poolMin", Integer.toString(min));
- }
-
- public static void setPoolMax(int max) {
- configHash.put("Database.poolMax", Integer.toString(max));
- }
-
- public static void setPoolResetTime(float t) {
- configHash.put("Database.poolResetTime", Float.toString(t));
- }
-
- public static void setPoolLog(String l) {
- configHash.put("Database.poolLog", l);
- }
-
- /**
- * Returns the property asked for by pulling it out a HashMap
- * @param a String containing the property name (key)
- * @return a String containing the prop. value
- */
- public static String getProp(String propName) {
- return (String)configHash.get(propName);
- }
-
- public static void addBroker(String driver, String URL){
-
- String username,passwd,min,max,log,reset;
-
- if(!brokerHash.containsKey("Pool.broker")){
- username=getProp("Database.Username");
- passwd=getProp("Database.Password");
- min=getProp("Database.poolMin");
- max=getProp("Database.poolMax");
- log= getProp("Database.poolLog");
- reset=getProp("Database.poolResetTime");
-
- try{
- System.err.println("-- making Broker for -"
- +driver+" - " +URL
- + " log " + log + " user "
- + username + " pass: " + passwd);
-
- DbConnectionBroker br = new DbConnectionBroker(driver,URL,username,passwd,(new Integer(min)).intValue(),
- (new Integer(max)).intValue(),log,(new Float(reset)).floatValue());
- if (br!=null){
- instances++;
- brokerHash.put("Pool.broker",br);
- } else {
- throw new Exception();
- }
- } catch(Exception e){
- System.err.println("Der ConnectionBroker konnte nicht initializiert werden"+ e.toString());e.printStackTrace();
- }
- } // end if
- }
-
- /**
- * Liefert DBConnectionBroker einer Configuration zurueck
- * @param confFilename
- * @return DBConnectionBroker
- */
- public static DbConnectionBroker getBroker() {
- DbConnectionBroker broker=null;
- broker=(DbConnectionBroker)brokerHash.get("Pool.broker");
- if (broker==null) {
- System.err.println("Konnte kein ConnectionPoolBroker initialisiert werden");
- }
- return broker;
- }
-
- /**
- * Liefert Anzahl der Instantiierten DBConnectionBroker zurueck
- * @return
- */
- public static int getBrokerInstances() {
- return instances;
- }
-
- public static DbConnectionBroker getBrokerInfo(){
- return (DbConnectionBroker)brokerHash.get("Pool.broker");
- }
-
- /**
- * Finalize method
- */
- public void finalize(){
- instances --;
- try {
- super.finalize();
- } catch (Throwable t) {}
- }
-
-}
* @param con
* @param stmt
*/
- abstract public void freeConnection(Connection con, Statement stmt);
+ abstract public void freeConnection(Connection con, Statement stmt)
+ throws StorageObjectException;
* Dokumentation siehe Database.java
* @return
*/
- abstract public SimpleList getPopupData ();
+ abstract public SimpleList getPopupData () throws StorageObjectException;
abstract public int executeUpdate(Statement a, String sql) throws StorageObjectException, SQLException ;
abstract public int executeUpdate(String sql) throws StorageObjectException, SQLException ;
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: ObjectStore for StorableObjects
+ * Description: ObjectStore holds a Map of @see StoreContainer for all possible
+ * @see StoreIdentifier.
+ *
+ * @see StorageIdentifier - identitfies one object in the ObjectStore
+ * i.e. in its apropriate bucket. It holds a unique identifier
+ * of a StorableObject and a reference on the StorableObject.
+ *
+ * @see StoreContainer - "Buckets" to store different types of Objects
+ * in one Container. These buckets are cofigurable via
+ * config.properties.
+ *
+ * @see StoreContainerType - is a signature for all StoreContainer
+ * and StoreIdentifier.
+ *
+ * @see StorableObjects - Interface Object have to implement to
+ * be handled by the ObjectStore
+ *
+ * @see ServletStoreInfo - Maintenance Servlet for ObjectStore.
+ * Displays information about current content of the
+ * ObjectStore.
+ *
+ *
+ * Copyright: Copyright (c) 2002
+ * Company: indy
+ * @author rk
+ * @version 1.0
+ */
+
+import java.util.*;
+import mir.misc.Logfile;
+
+public class ObjectStore {
+
+ private final static ObjectStore INSTANCE=new ObjectStore();
+ private final static HashMap containerMap=new HashMap(); // StoreContainerType/StoreContainer
+ private final static Class storableObjectInterface=StorableObject.class;
+ private static Logfile storeLog;
+ private static long storeHit=0,storeMiss=0;
+
+ private ObjectStore() {
+ }
+ public static ObjectStore getInstance() { return INSTANCE; }
+
+
+ /**
+ * Method: use
+ * Description: The ObjectStore tries to find the @see StoreIdentifier sid
+ * and returns the stored Object.
+ *
+ * @return StorableObject is null when no StorableObject for the
+ * StoreIdentifier sid is found.
+ */
+ public StorableObject use(StoreIdentifier sid) {
+ if (sid!=null ) {
+ StorableObject storeObject=null;
+ StoreContainer stoc = getStoreContainerForSid( sid );
+ if (stoc!=null) storeObject=stoc.use(sid);
+ else System.out.println("Warning: container not found for: " + sid.toString());
+ if (storeObject!=null) storeHit++;
+ return storeObject;
+ }
+ storeMiss++; return null;
+
+ }
+
+ /**
+ * Method: add
+ * Description: A StoreIdentifier is added to the ObjectStore, if it
+ * contains a reference to a @see StorableObject.
+ */
+ public void add(StoreIdentifier sid) {
+ if ( sid!=null && sid.hasReference() ) {
+ // find the right StoreContainer for sid
+ StoreContainer stoc = getStoreContainerForSid(sid);
+ if (stoc==null) {
+ // we have to make new StoreContainer
+ StoreContainerType stocType = sid.getStoreContainerType();
+ stoc = new StoreContainer(stocType);
+ containerMap.put(stocType, stoc);
+ }
+ stoc.add(sid);
+ }
+ }
+
+ /**
+ * Method: toString()
+ * Description: Displays statistical information about the ObjectStore.
+ * Further information is gathered from all @see StoreContainer
+ *
+ * @return String
+ */
+ public String toString() {
+
+ float hitRatio=0;
+ long divisor=storeHit+storeMiss;
+ if (divisor>0) hitRatio=(float)storeHit/(float)divisor;
+ hitRatio*=100;
+
+ StringBuffer sb = new StringBuffer("Mir-ObjectStore v_");
+ sb.append(version()).append("\n");
+ sb.append("ObjectStore overall hits/misses/ratio: ").append(storeHit);
+ sb.append("/").append(storeMiss).append("/").append(hitRatio);
+ sb.append("%\nCurrently ").append(containerMap.size());
+ sb.append(" StoreContainer in use - listing information:\n");
+
+ // ask container for information
+ StoreContainer currentStoc;
+ for(Iterator it=containerMap.keySet().iterator();it.hasNext();) {
+ currentStoc=(StoreContainer)containerMap.get(it.next());
+ sb.append(currentStoc.toString());
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Method: invalidate(StorableObject sto)
+ * Description: ObjectStore is notified of change of a @see StorableObject
+ * sto and invalidates all relevant cache entries.
+ */
+
+ public void invalidate(StoreIdentifier sid) {
+ // propagate invalidation to StoreContainer
+ if (sid!=null) {
+ StoreContainer stoc = getStoreContainerForSid(sid);
+ stoc.invalidate(sid);
+ }
+ }
+
+ /**
+ * Method: invalidate(StoreContainerType)
+ * Description: serves to invalidate a whole StoreContainer
+ *
+ * @return
+ */
+ public void invalidate(StoreContainerType stoc_type) {
+ if ( stoc_type != null ) {
+ StoreContainer stoc = getStoreContainerForStocType(stoc_type);
+ if ( stoc!=null )
+ stoc.invalidate();
+ }
+
+ }
+
+ // internal methods for StoreContainer managment
+
+ /**
+ * Method: getStoreContainerForSid
+ * Description: private method to find the right @see StoreContainer for
+ * the @see StoreIdentifier sid.
+ *
+ * @return StoreContainer is null when no Container is found.
+ */
+ private StoreContainer getStoreContainerForSid(StoreIdentifier sid){
+ // find apropriate container for a specific sid
+ if (sid!=null) {
+ StoreContainerType stoc_type = sid.getStoreContainerType();
+ return getStoreContainerForStocType(stoc_type);
+ }
+ return null;
+ }
+
+ private StoreContainer getStoreContainerForStocType(StoreContainerType stoc_type) {
+ if ( stoc_type!=null && containerMap.containsKey(stoc_type) )
+ return (StoreContainer)containerMap.get(stoc_type);
+ return null;
+ }
+
+ /**
+ * Method: implementsStorableObject
+ * Description: internall helper method to find out if a class implements
+ * interface StorableObject.
+ *
+ * @return true if yes, otherwise no.
+ */
+ private final static boolean implementsStorableObject(Class aClass) {
+ if (aClass!=null) {
+ Class[] interfaces = aClass.getInterfaces();
+ if (interfaces.length>0) {
+ for (int i=0;i<interfaces.length;i++) {
+ if (interfaces[i]==storableObjectInterface) return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
+ private boolean has(StoreIdentifier sid) {
+ StoreContainer stoc = getStoreContainerForSid( sid );
+ return ( stoc != null && stoc.has(sid) ) ? true:false;
+ }
+
+
+ /**
+ * Method: version()
+ * Description: returns ObjectStore version as String
+ *
+ * @return String
+ */
+ private String version() { return "00.d5";}
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: ServletStoreInfo
+ * Description: Servlet displays information about the Object store.
+ *
+ * Copyright: Copyright (c) 2002
+ * Company:
+ * @author
+ * @version 1.0
+ */
+
+import java.io.*;
+import javax.servlet.http.*;
+import javax.servlet.*;
+
+public class ServletStoreInfo extends HttpServlet {
+
+ ObjectStore ostore = ObjectStore.getInstance();
+
+ /** @todo servlet displays infos for ObjectStore
+ * additionally some task could be controlled: gc, and change of
+ * size of the @see StoreContainer in use.
+ */
+
+ public void doGet(HttpServletRequest req, HttpServletResponse res)
+ throws ServletException, IOException
+ {
+ doPost(req,res);
+ }
+
+ public void doPost(HttpServletRequest req, HttpServletResponse res)
+ throws ServletException, UnavailableException, IOException
+ {
+ PrintWriter out = res.getWriter();
+ out.println("<html><head><title>ObjectStore></title></head><body><pre>\n");
+ out.println(ostore.toString());
+ out.println("\n</pre></body></html>");
+ out.close();
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: Interface StorableObject
+ * Description: Interface all Objects need to implement to be storable in the
+ * ObjectStore.
+ * Copyright: Copyright (c) 2002
+ * Company: indy
+ * @author rk
+ * @version 1.0
+ */
+
+import java.util.*;
+
+public interface StorableObject {
+
+ /**
+ * Method getStoreIdentifier() forces StorableObjects to return a StoreIdentifier.
+ * if an Object implements this, it can be stored in ObjectStore. The ObjectStore.
+ * @see StoreIdentifier for a description of values needed for implementing
+ * getStoreIdentifier()
+ *
+ * @return StoreIdentifier
+ *
+ */
+ abstract StoreIdentifier getStoreIdentifier();
+
+ /**
+ * Method: notifyOnReleaseSet()
+ * Description: Contains a Set of @see StoreIdentifier which are invalidated
+ * on update/insert/delete of this StorableObject.
+ *
+ * @return Set of StoreIdentifier.
+ */
+ abstract Set getNotifyOnReleaseSet();
+
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: StoreContainer
+ *
+ * Description: This is the bucket object for one type of StorableObjects,
+ * mainy a linked list of StoreIdenfiers. On use or creation
+ * an object stored in StoreIdentifier is put to head of the
+ * list. if maximum size of the list is reached, the
+ * StoreIdentifier at the end of the list is released.
+ *
+ * Copyright: Copyright (c) 2002
+ * Company: indy
+ * @author //rk
+ * @version 1.0
+ */
+
+import java.util.*;
+import mir.misc.Logfile;
+
+public class StoreContainer {
+
+ private final static int DEFAULT_SIZE=10;
+ private static Logfile storeLog;
+ private static int uniqueCounter=10000;
+
+ private LinkedList container;
+ private StoreContainerType stocType;
+ private int maxSize=DEFAULT_SIZE;
+ private int uniqueId;
+ private int addCount=0,removeCount=0,storeOutCount;
+ private int hitCount=0,missCount=0;
+
+ private StoreContainer() {};
+
+ public StoreContainer(StoreContainerType stoc_type) {
+ this.uniqueId=++uniqueCounter;
+ this.stocType=stoc_type;
+ this.container=new LinkedList();
+ }
+
+ public StoreContainer(StoreContainerType stoc_type, int maxSize) {
+ this();
+ this.maxSize=maxSize;
+ }
+
+ public synchronized StorableObject use(StoreIdentifier sid) {
+ int hit = container.indexOf(sid);
+ if (hit>0) {
+ StoreIdentifier hitSid = (StoreIdentifier)container.get(hit);
+ if ( hitSid!=null ) {
+ hitCount++;
+ return hitSid.use();
+ }
+ }
+ missCount++;
+ return null;
+ }
+
+ public boolean has(StoreIdentifier sid) {
+ return container.contains(sid);
+ }
+
+ public void add(StoreIdentifier sid) {
+ if ( sid != null && sid.hasReference() ) {
+ if ( has(sid) ) {
+ moveToHead(sid);
+ System.err.println("OBJECTStore: tried to add sid " + sid.toString() +
+ " that was already in store.");
+ }
+ else {
+ container.addFirst(sid);
+ shrinkIfNecessary();
+ addCount++;
+ }
+ }
+ }
+
+ /**
+ * Method: invalidate(StorableObject sto)
+ * Description: finds @see StorableObject, propagates invalidation to
+ * @see StoreIdentifier and removes StoreIdentifier from
+ * list.
+ */
+ public synchronized void invalidate(StoreIdentifier search_sid) {
+ if (search_sid!=null) {
+ int hit = container.indexOf(search_sid);
+ if (hit >0 ) {
+ StoreIdentifier sid = (StoreIdentifier)container.get(hit);
+ container.remove(sid);
+ sid.invalidate();
+ removeCount++;
+ }
+ }
+ }
+
+ public synchronized void invalidate() {
+ StoreIdentifier sid;
+ while (container.size() > 0) {
+ sid=(StoreIdentifier)container.getLast();
+ container.removeLast();
+ sid.invalidate();
+ }
+ }
+
+ /**
+ * Method: setSize
+ * Description: readjusts StoreContainer size to value.
+ *
+ */
+ public void setSize(int size) {
+ if (size <0) return;
+ shrinkToSize(size);
+ this.maxSize=size;
+ }
+
+ private void shrinkIfNecessary() { shrinkToSize(maxSize); }
+
+ private void shrinkToSize(int size) {
+ if ( size < container.size() ) {
+ // shrink
+ while (size < container.size() ) {
+ StoreIdentifier sid = (StoreIdentifier)container.getLast();
+ container.remove(sid);
+ sid.release();
+ storeOutCount++;
+ }
+ }
+ }
+
+ private synchronized void moveToHead(StoreIdentifier sid) {
+ if ( sid!=null ) {
+ container.remove(sid);
+ container.addFirst(sid);
+ }
+ }
+
+ /**
+ * Method: toString()
+ * Description: gives out statistical Information, viewable via
+ * @see ServletStoreInfo.
+ *
+ * @return String
+ */
+ public String toString() {
+ float hitRatio=0;
+ long divisor=hitCount+missCount;
+ if (divisor>0) hitRatio=(float)hitCount/(float)divisor;
+ hitRatio*=100;
+
+ StringBuffer sb = new StringBuffer("StoreContainer id: ");
+ sb.append(uniqueId).append(" for ");
+ sb.append(stocType.toString()).append("\n [current/maximum size: ");
+ sb.append(container.size()).append("/").append(maxSize);
+ sb.append("]\n [added/stored out/removed: ").append(addCount).append("/");
+ sb.append(storeOutCount).append("/").append(removeCount).append("]\n [hit/miss/ratio: ");
+ sb.append(hitCount).append("/").append(missCount).append("/");
+ sb.append(hitRatio).append("%]\n");
+
+ /** @todo list members ? */
+ return sb.toString();
+ }
+
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: StoreContainerType
+ *
+ * Description: StoreContainerTypes are uniqe Objects and are generated
+ * via @see valueOf(Class stocClass, int stocType).
+ * For every combination of stocClass and stocType there is
+ * only one Object instantiated.
+ *
+ * Copyright: Copyright (c) 2002
+ * Company: indy
+ *
+ * @author rk
+ * @version 1.0
+ */
+
+import java.util.HashMap;
+import mir.misc.Logfile;
+
+public class StoreContainerType {
+
+ public final static int STOC_TYPE_UNKNOWN=-1;
+ public final static int STOC_TYPE_ENTITY=0;
+ public final static int STOC_TYPE_ENTITYLIST=1;
+ public final static int STOC_TYPE_MAX=STOC_TYPE_ENTITYLIST;
+
+ private static HashMap[] uniqueTypes=new HashMap[STOC_TYPE_MAX+1];
+ private static Logfile storeLog;
+ private Class stocClass=null;
+ private int stocType=STOC_TYPE_UNKNOWN;
+
+ static {
+ uniqueTypes[STOC_TYPE_ENTITY]= new HashMap();
+ uniqueTypes[STOC_TYPE_ENTITYLIST]=new HashMap();
+
+ }
+
+ private StoreContainerType() {}
+
+ private StoreContainerType(Class stocClass, int stocType) {
+ this.stocClass=stocClass;
+ this.stocType=stocType;
+ }
+
+ public static StoreContainerType valueOf(Class stoc_class, int stoc_type) {
+ StoreContainerType returnStocType=null;
+ if (stoc_type>=0 && stoc_type <= STOC_TYPE_MAX) {
+ HashMap current = uniqueTypes[stoc_type];
+ if ( current.containsKey(stoc_class) )
+ returnStocType=(StoreContainerType)current.get(stoc_class);
+ else {
+ returnStocType=new StoreContainerType(stoc_class,stoc_type);
+ current.put(stoc_class,returnStocType);
+ }
+ }
+ return returnStocType;
+ }
+
+ public int getStocType() { return stocType; }
+ public Class getStocClass() { return stocClass; }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer(this.stocClass.toString());
+ sb.append("@").append(stringForStoreType(stocType));
+ return sb.toString();
+ }
+
+ private static String stringForStoreType(int stocType) {
+ switch(stocType) {
+ case STOC_TYPE_ENTITY: return "ENTITY";
+ case STOC_TYPE_ENTITYLIST: return "ENTITYLIST";
+ default: return "UNKNOWN";
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store;
+
+/**
+ * Title: Class StoreIdentifier
+ * Description: StoreIdentifier has two functions.
+ * A) StoreIdenfier holds a reference to a @see StorableObject
+ * or B) StoreIdentifier is used too search for a @see StorableObject
+ * in the @see StoreContainer that matches its
+ *
+ * Copyright: Copyright (c) 2002
+ * Company: indy
+ * @author rk
+ * @version 1.0
+ */
+import java.util.*;
+import mir.misc.Logfile;
+
+public class StoreIdentifier {
+
+ /** @todo check if invalidating already to avoid deadlocks
+ * what about concurrency? */
+
+ private static Logfile storeLog;
+ private static ObjectStore o_store = ObjectStore.getInstance();
+
+ private StoreContainerType stocType=null;
+ private StorableObject reference=null;
+ private String uniqueIdentifier=null; // id for Entity & sql for EntityList
+ private long timesUsed;
+ private boolean invalidating=false;
+
+ /** @todo initialize logfile */
+
+ private StoreIdentifier() {}
+
+ public StoreIdentifier(StorableObject reference, int storeType, String uniqueIdentifier) {
+ this(reference.getClass(), uniqueIdentifier);
+ this.reference=reference;
+ }
+
+ public StoreIdentifier(Class theClass, String uniqueIdentifier) {
+ this(theClass, StoreContainerType.STOC_TYPE_ENTITY,uniqueIdentifier);
+ }
+
+ public StoreIdentifier(Class theClass, int storeType, String uniqueIdentifier) {
+ this.uniqueIdentifier=uniqueIdentifier;
+ this.stocType = StoreContainerType.valueOf(theClass, storeType);
+ }
+ /**
+ * Method: ivalidate
+ * Description:
+ *
+ * @return
+ */
+ public void invalidate() {
+ System.out.println("Invalidating: " + toString());
+ // avoid deadlock due to propagation.
+ if (!invalidating) {
+ invalidating=true;
+ if ( stocType!=null &&
+ stocType.getStocType()==StoreContainerType.STOC_TYPE_ENTITY )
+ {
+ System.out.println("Propagating invalidation to EntityList for " + toString());
+ // we should invalidate related ENTITY_LIST
+ StoreContainerType entityListStocType =
+ StoreContainerType.valueOf( stocType.getStocClass(),
+ StoreContainerType.STOC_TYPE_ENTITYLIST );
+ o_store.invalidate(entityListStocType);
+ }
+
+ // propagate invalidation to Set
+ Set set = reference.getNotifyOnReleaseSet();
+ if (set!=null) {
+ for (Iterator it = set.iterator(); it.hasNext(); ) {
+ Object o = it.next();
+ if ( o instanceof StoreIdentifier ) {
+ System.out.println("Propagating invalidation to StoreIdentifier: " + o.toString());
+ // propagate invalidation to a specific StoreIdentifier in cache
+ o_store.invalidate((StoreIdentifier)o);
+ } else if ( o instanceof StoreContainerType ) {
+ System.out.println("Propagating invalidation to StoreContainer: " + o.toString());
+ // propagate invalidation to a whole StoreContainer
+ o_store.invalidate((StoreContainerType)o);
+ }
+
+ }
+ }
+ release();
+ }
+ }
+
+ public void release() {
+ this.reference=null;
+ this.uniqueIdentifier=null;
+ this.stocType=null;
+ }
+
+ public StorableObject use() {
+ timesUsed++;
+ return reference;
+ }
+
+ /**
+ * Method equals for comparison between two identifier
+ *
+ * @return true if yes otherwise false
+ *
+ */
+ public boolean equals(Object sid) {
+ if ( !(sid instanceof StoreIdentifier) ) return false;
+ if ( ((StoreIdentifier)sid).getStoreContainerType()==stocType &&
+ ((StoreIdentifier)sid).getUniqueIdentifier().equals(uniqueIdentifier) )
+ return true;
+ return false;
+ }
+
+ public StoreContainerType getStoreContainerType() { return stocType; }
+ public String getUniqueIdentifier() { return uniqueIdentifier; }
+ public boolean hasReference() { return (reference==null) ? false:true; }
+
+ public String toString() {
+ StringBuffer id = new StringBuffer(uniqueIdentifier);
+ id.append("@storetype: ").append(stocType.toString());
+ if (reference != null) id.append(" ("+timesUsed).append(") times used.");
+ return id.toString();
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store.test;
+
+/**
+ * Title:
+ * Description:
+ * Copyright: Copyright (c) 2002
+ * Company:
+ * @author
+ * @version 1.0
+ */
+
+import java.util.*;
+import mir.storage.store.*;
+
+public class EntityC1 implements StorableObject {
+
+ String id;
+
+ public EntityC1(String id) {
+ this.id=id;
+ }
+
+ public StoreIdentifier getStoreIdentifier() {
+ return new StoreIdentifier(this, StoreContainerType.STOC_TYPE_ENTITY,id);
+ }
+
+ public Set getNotifyOnReleaseSet() {
+ HashSet notifiees = new HashSet();
+ // simulating a relation from EntityC1 to EntityC2/Entitylist
+ notifiees.add(StoreContainerType.valueOf( EntityC2.class,
+ StoreContainerType.STOC_TYPE_ENTITYLIST));
+ // simulates a relation to EntityC2 with uniqueIdentifier "1"
+ notifiees.add(new StoreIdentifier(EntityC2.class,"1"));
+ notifiees.add(new StoreIdentifier(EntityC2.class,"18"));
+ return (Set)notifiees;
+ }
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store.test;
+
+/**
+ * Title:
+ * Description:
+ * Copyright: Copyright (c) 2002
+ * Company:
+ * @author
+ * @version 1.0
+ */
+
+import java.util.*;
+import mir.storage.store.*;
+
+public class EntityC2 implements StorableObject {
+
+ String id;
+
+ public EntityC2(String id) {
+ this.id=id;
+ }
+
+ public StoreIdentifier getStoreIdentifier() {
+ return new StoreIdentifier(this, StoreContainerType.STOC_TYPE_ENTITY,id);
+ }
+
+ public Set getNotifyOnReleaseSet() {
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store.test;
+
+/**
+ * Title:
+ * Description:
+ * Copyright: Copyright (c) 2002
+ * Company:
+ * @author
+ * @version 1.0
+ */
+
+import java.util.*;
+import mir.storage.store.*;
+
+public class EntityC3 implements StorableObject {
+
+ String id;
+
+ public EntityC3(String id) {
+ this.id=id;
+ }
+
+ public StoreIdentifier getStoreIdentifier() {
+ return new StoreIdentifier(this, StoreContainerType.STOC_TYPE_ENTITY,id);
+ }
+
+ public Set getNotifyOnReleaseSet() {
+ return null;
+ }
+}
\ No newline at end of file
--- /dev/null
+package mir.storage.store.test;
+
+/**
+ * Title:
+ * Description:
+ * Copyright: Copyright (c) 2002
+ * Company:
+ * @author
+ * @version 1.0
+ */
+
+import mir.storage.store.*;
+
+public class TestStore {
+
+ private static ObjectStore o_store = ObjectStore.getInstance();
+
+ public TestStore() {
+
+ }
+
+ public static void main(String[] args) {
+ long startTime = System.currentTimeMillis();
+ System.out.println("Starting testrun on ObjectStore...");
+ TestStore testStore1 = new TestStore();
+ testStore1.startTest();
+ System.out.println("Finished testrun on ObjectStore. ("
+ + (System.currentTimeMillis() - startTime) + " ms)");
+ }
+
+ public void startTest() {
+
+ EntityC1 c1 = new EntityC1("1");
+ o_store.add(c1.getStoreIdentifier());
+ EntityC1 c12 = new EntityC1("2");
+ o_store.add(c12.getStoreIdentifier());
+ o_store.add(c12.getStoreIdentifier()); // should not be added as it's there already
+
+ EntityC2 c2;
+ for (int i=0; i<20; i++) {
+ c2 = new EntityC2(""+i);
+ o_store.add(c2.getStoreIdentifier());
+ } // should contain only 10
+
+ // test cycle: search in store
+
+ StorableObject reference; StoreIdentifier search_sid;
+
+ // search for EntityC1
+ search_sid=new StoreIdentifier(EntityC1.class,"1");
+ reference=o_store.use(search_sid);
+ if (reference==null)
+ System.out.println("--- should have found" + search_sid.toString());
+
+ search_sid=new StoreIdentifier(EntityC1.class,"A");
+ reference=o_store.use(search_sid);
+ if (reference!=null)
+ System.out.println("--- should not have found" + search_sid.toString());
+
+ search_sid=new StoreIdentifier(EntityC3.class,"1");
+ reference=o_store.use(search_sid);
+ if (reference!=null)
+ System.out.println("--- should not have found" + search_sid.toString());
+
+ // test cycle: invalidation */
+ search_sid=new StoreIdentifier(EntityC1.class,"1");
+ o_store.invalidate(search_sid);
+
+ System.out.println(o_store.toString());
+ /** @todo compare values of store and state failed if values are not
+ * right*/
+
+
+
+ }
+}
\ No newline at end of file
--- /dev/null
+package mircoders.entity;
+
+import java.lang.*;
+import java.io.*;
+import java.util.*;
+import java.sql.*;
+
+/*
+ * kind of hack for postgres non-standard LargeObjects that Poolman
+ * doesn't know about. see all the casting, LargeObj stuff in getIcon, getAudio
+ * at some point when postgres has normal BLOB support, this should go.
+ */
+import org.postgresql.Connection;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
+
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+/**
+ * This class handles storage of audio data and meta data
+ *
+ * @author mh
+ * @version 11.11.2000
+ */
+
+
+public class EntityAudio extends EntityUploadedMedia
+{
+ public EntityAudio()
+ {
+ super();
+ }
+
+ public EntityAudio(StorageObject theStorage) {
+ this();
+ setStorage(theStorage);
+ }
+
+ //
+ // methods
+
+
+
+ public byte[] getAudio() throws StorageObjectException
+ {
+ theLog.printDebugInfo("--getaudio started");
+ java.sql.Connection con=null;Statement stmt=null;
+ byte[] data=null;
+
+ try {
+ con = theStorageObject.getPooledCon();
+ con.setAutoCommit(false);
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
+ stmt = con.createStatement();
+ ResultSet rs = theStorageObject.executeSql(stmt,
+ "select audio_data from audio where id="+getId());
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+ if(rs!=null) {
+ if (rs.next()) {
+ LargeObject lob = lom.open(rs.getInt(1));
+ data = lob.read(lob.size());
+ lob.close();
+ //data = rs.getBytes(1);
+ }
+ rs.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError("EntityAudio -- getAudio failed"+e.toString());
+ throwStorageObjectException(e, "EntityAudio -- getAudio failed: ");
+ }
+ finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError(
+ "EntityAudio -- getAudio reseting transaction mode failed"
+ +e.toString());
+ }
+ theStorageObject.freeConnection(con,stmt);
+ }
+
+ return data;
+ }
+
+ public void setAudio(byte[] uploadData)
+ throws StorageObjectException {
+
+ if (uploadData!=null) {
+ java.sql.Connection con=null;PreparedStatement pstmt=null;
+ try {
+
+ if (uploadData!=null) {
+ con = theStorageObject.getPooledCon();
+ con.setAutoCommit(false);
+ theLog.printDebugInfo("setaudio :: trying to insert audio");
+
+ // setting values
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+ int oid = lom.create();
+ LargeObject lob = lom.open(oid);
+ lob.write(uploadData);
+ lob.close();
+ String sql = "update images set"
+ +" audio_data="+oid
+ +" where id="+getId();
+ theLog.printDebugInfo("setaudio :: updating: "+ sql);
+ pstmt = con.prepareStatement(sql);
+ //pstmt.setBytes(1, imageData);
+ //pstmt.setBytes(2, iconData);
+ pstmt.executeUpdate();
+ sql="update content set is_produced='0' where to_media="+getId();
+ pstmt = con.prepareStatement(sql);
+ pstmt.executeUpdate();
+ }
+ }
+ catch (Exception e) {
+ throwStorageObjectException(e,"setaudio ::failed: ");
+ }
+ finally {
+ try { if (con!=null) con.setAutoCommit(true); } catch (Exception e) {;}
+ theStorageObject.freeConnection(con,pstmt); }
+ }
+ }
+
+
+ public void update() throws StorageObjectException {
+ super.update();
+ try {
+ theStorageObject.executeUpdate("update content set is_produced='0' where to_media="+getId());
+ } catch (SQLException e) {
+ throwStorageObjectException(e, "EntityAudio :: update :: failed!! ");
+ }
+ }
+
+ public void setValues(HashMap theStringValues)
+ {
+ if (theStringValues != null) {
+ if (!theStringValues.containsKey("is_published"))
+ theStringValues.put("is_published","0");
+ }
+ super.setValues(theStringValues);
+ }
+
+}
import java.util.*;
import java.sql.*;
-import freemarker.template.*;
-
import mir.entity.*;
import mir.misc.*;
import mir.storage.*;
public class EntityBreaking extends Entity
{
- private static int instances;
-
- public EntityBreaking() { super(); instances++; }
+ public EntityBreaking() { super(); }
public EntityBreaking(StorageObject theStorage) { this(); setStorage(theStorage); }
- public void finalize() {
- instances--;
- super.finalize();
- }
-
}
public class EntityComment extends Entity
{
- private static int instances;
public EntityComment()
{
super();
- instances++;
}
public EntityComment(StorageObject theStorage) {
public void setValues(HashMap theStringValues)
{
if (theStringValues != null) {
- if (!theStringValues.containsKey("is_published"))
+ if (!theStringValues.containsKey("is_published")) {
theStringValues.put("is_published","0");
- if (theStringValues.containsKey("main_url"))
- if (((String)theStringValues.get("main_url")).equalsIgnoreCase("http://")) {
- theStringValues.remove("main_url");
- } else if (!((String)theStringValues.get("main_url")).startsWith("http://")){
- theStringValues.put("main_url","http://"+((String)theStringValues.get("main_url")));
- }
+ }
+
+ if (theStringValues.containsKey("main_url")){
+ if (((String)theStringValues.get("main_url")).equalsIgnoreCase("http://")) {
+ theStringValues.remove("main_url");
+ } else if ((!((String)theStringValues.get("main_url")).startsWith("http://"))
+ && ((String)theStringValues.get("main_url")).length()>0){
+ theStringValues.put("main_url","http://"+((String)theStringValues.get("main_url")));
+ }
+ }
+
}
super.setValues(theStringValues);
}
+ /**
+ * overridden method getValue to include formatted date into every
+ * entityContent
+ */
+
+ public String getValue(String field)
+ {
+ String returnField = null;
+ if (field!=null)
+ {
+ if (field.equals("date_formatted"))
+ {
+ if (hasValueForField("date"))
+ returnField = StringUtil.webdbDate2readableDate(getValue("date"));
+ }
+ else if (field.equals("description_parsed")) {
+ /** @todo the config stuff should be moved to StringUtil */
+ String extLinkName = MirConfig.getProp("Producer.ExtLinkName");
+ String intLinkName = MirConfig.getProp("Producer.IntLinkName");
+ String mailLinkName = MirConfig.getProp("Producer.MailLinkName");
+ String imageRoot = MirConfig.getProp("Producer.ImageRoot");
+ returnField = StringUtil.createHTML(getValue("description"),imageRoot,mailLinkName,extLinkName,intLinkName);
+ }
+ else
+ return super.getValue(field);
+ }
+ return returnField;
+ }
+
- public void finalize() {
- instances--;
- super.finalize();
- }
}
import java.io.*;
import java.util.*;
import java.sql.*;
+import java.lang.reflect.*;
import freemarker.template.*;
import mir.entity.*;
import mir.misc.*;
+import mir.media.*;
import mir.storage.*;
import mircoders.storage.*;
public class EntityContent extends Entity
{
- private static int instances;
+ String mirconf_extLinkName = MirConfig.getProp("Producer.ExtLinkName");
+ String mirconf_intLinkName = MirConfig.getProp("Producer.IntLinkName");
+ String mirconf_mailLinkName = MirConfig.getProp("Producer.MailLinkName");
+ String mirconf_imageRoot = MirConfig.getProp("Producer.ImageRoot");
+
+ //this should always be transient i.e it can never be stored in the db
+ //or ObjectStore. (so the ObjectStore should only be caching what comes
+ //directly out of the DB. @todo confirm this with rk. -mh
+ HashMap _entCache = new HashMap();
+ Boolean _hasMedia = null;
// constructors
public EntityContent()
{
super();
- instances++;
//content_data is now filed-type "text"
//streamedInput = new ArrayList();
//streamedInput.add("content_data");
setStorage(theStorage);
}
- public void finalize() {
- instances--;
- super.finalize();
- }
-
//
// methods
* set is_produced flag for the article
*/
- public void setProduced(boolean yesno)
+ public void setProduced(boolean yesno) throws StorageObjectException
{
- Connection con=null;Statement stmt=null;
String value = (yesno) ? "1":"0";
- String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
+ 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 (StorageObjectException e) {
- theLog.printDebugInfo(e.toString() + "\n -- set produced failed");
+ throwStorageObjectException(e, "\n -- set produced failed");
} catch (SQLException e) {
- theLog.printDebugInfo(e.toString() + "\n -- set produced failed");
+ throwStorageObjectException(e, "\n -- set produced failed");
} finally {
theStorageObject.freeConnection(con,stmt);
}
* make openposting to newswire
*/
- public void newswire()
+ public void newswire() throws StorageObjectException
{
String sql = "update content set to_article_type='1', is_produced='0' where id='" + getId()+"'";
try {
theStorageObject.executeUpdate(sql);
} catch (StorageObjectException e) {
- theLog.printError(e.toString() + "newswire failed");
+ throwStorageObjectException(e, "\n -- newswire failed");
} catch (SQLException e) {
- theLog.printError(e.toString() + "newswire failed");
+ throwStorageObjectException(e, "\n -- newswire failed");
}
}
/**
* dettach from media
*/
-
- public void dettach(String cid,String mid)
+ public void dettach(String cid,String mid) throws StorageObjectException
{
if (mid!=null){
try{
DatabaseContentToMedia.getInstance().delete(cid,mid);
} catch (Exception e){
- theLog.printError("failed to get instance");
+ throwStorageObjectException(e, "\n -- failed to get instance");
}
//set Content to unproduced
setProduced(false);
* attach to media
*/
- public void attach(String mid)
+ public void attach(String mid) throws StorageObjectException
{
if (mid!=null) {
//write media-id mid and content-id in table content_x_media
try{
DatabaseContentToMedia.getInstance().addMedia(getId(),mid);
} catch(StorageObjectException e){
- theLog.printError("attach: could not get the instance");
+ throwStorageObjectException(e, "attach: could not get the instance");
}
//set Content to unproduced
setProduced(false);
public String getValue(String field)
{
- if (field!=null && field.equals("date_formatted"))
+ String returnField = null;
+ if (field!=null)
{
- if (hasValueForField("date"))
- return StringUtil.webdbDate2readableDate(getValue("date"));
- else return null;
- }
- else
- return super.getValue(field);
+ if (field.equals("date_formatted"))
+ {
+ if (hasValueForField("date"))
+ returnField = StringUtil.webdbDate2readableDate(getValue("date"));
+ }
+ else if (field.equals("description_parsed"))
+ returnField = getDescriptionParsed();
+ else if (field.equals("content_data_parsed"))
+ returnField = getContentDataParsed();
+ else
+ return super.getValue(field);
+ }
+ return returnField;
}
+ public TemplateModel get(java.lang.String key) throws TemplateModelException
+ {
+ if (key!=null) {
+ if (_entCache.containsKey(key)) {
+ return (TemplateModel)_entCache.get(key);
+ }
+ if (key.equals("to_comments")) {
+ try {
+ _entCache.put(key, getComments());
+ return (TemplateModel)_entCache.get(key);
+ } catch (Exception ex) {
+ theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ if (key.equals("to_media_images")) {
+ try {
+ _entCache.put(key, getImagesForContent());
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getImagesForContent: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ if (key.equals("to_media_audio")) {
+ try {
+ _entCache.put(key, getAudioForContent());
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getAudioForContent: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ if (key.equals("to_media_video")) {
+ try {
+ _entCache.put(key, getVideoForContent());
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getVideoForContent: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ if (key.equals("to_media_other")) {
+ try {
+ _entCache.put(key, getOtherMediaForContent());
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getOtherMediaForContent: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ else if (key.equals("to_media_icon")) {
+ try {
+ _entCache.put(key, getUploadedMediaForNewswire());
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ else if (key.equals("to_topics")) {
+ try {
+ _entCache.put(key,
+ DatabaseContentToTopics.getInstance().getTopics(this));
+ return (TemplateModel)_entCache.get(key);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
+ throw new TemplateModelException(ex.toString());
+ }
+ }
+ else {
+ return new SimpleScalar(getValue(key));
+ }
+
+ }
+ return null;
+ }
+
+
+
+
/**
* overridden method setValues to patch creator_main_url
*/
super.setValues(theStringValues);
}
- /**
- * return the content_data as string
- * is obsolete, because content_data is now sql-type text
- public String getContentData()
- {
- Connection con=null;Statement stmt=null;
- byte[] content_data=null;
+ private String getContentDataParsed() {
+ String returnField = getValue("content_data");
+ if (returnField!=null & returnField.length()>0 ) {
+ returnField=StringUtil.deleteForbiddenTags(returnField);
+ //create http-links and email-links
+ if (getValue("is_html").equals("0")) {
+ returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
+ mirconf_mailLinkName,mirconf_extLinkName,
+ mirconf_intLinkName);
+ }
+ returnField = StringUtil.decodeHTMLinTags(returnField);
+ }
+ return returnField;
+ }
- try {
- con = theStorageObject.getPooledCon();
- con.setAutoCommit(false);
- stmt = con.createStatement();
- ResultSet rs = theStorageObject.executeSql(stmt,"select content_data from content where id="+getId());
- if(rs!=null) {
- if (rs.next()) {
- content_data = rs.getBytes(1);
- }
- rs.close();
- }
- }
- catch (Exception e) {theLog.printError("EntityContent :: getContent failed! "+e.toString());}
- finally {
- try {con.setAutoCommit(true); } catch (Exception e) {;}
- theStorageObject.freeConnection(con,stmt); }
- return StringUtil.encodeHtml(StringUtil.unquote( new String(content_data) ));
- }
-*/
+ private String getDescriptionParsed() {
+ String returnField = getValue("description");
+ if (returnField != null && returnField.length()>0) {
+ returnField = StringUtil.deleteForbiddenTags(returnField);
+ if (getValue("is_html").equals("0")) {
+ returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
+ mirconf_mailLinkName,mirconf_extLinkName,
+ mirconf_intLinkName);
+ }
+ returnField = StringUtil.decodeHTMLinTags(returnField);
+ }
+ return returnField;
+ }
/**
* fetches all the comments belonging to an article
*
* @return freemarker.template.SimpleList
*/
- public SimpleList getComments() {
+ private EntityList getComments() throws StorageObjectException {
return ((DatabaseContent)theStorageObject).getComments(this);
}
+ // @todo this needs to optimized. expensive SQL
+ private SimpleHash getUploadedMediaForNewswire()
+ throws StorageObjectException, TemplateModelException
+ {
+ // fetching/setting the images
+ // return to_media_icons
+ String tinyIcon = null, iconAlt = null;
+ MirMedia mediaHandler = null;
+ EntityUploadedMedia uploadedMedia;
+ Entity mediaType;
+ SimpleHash returnHash = new SimpleHash();
+
+ EntityList upMediaEntityList =
+ DatabaseContentToMedia.getInstance().getUploadedMedia(this);
+ if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
+
+ for (int n=0; n < upMediaEntityList.size();n++) {
+ uploadedMedia = (EntityUploadedMedia)upMediaEntityList.elementAt(n);
+ mediaType = uploadedMedia.getMediaType();
+ try {
+ mediaHandler = MediaHelper.getHandler( mediaType );
+ } catch (MirMediaException ex) {
+ throw new TemplateModelException(ex.toString());
+ }
+ //the "best" media type to show
+ if (mediaHandler.isVideo()) {
+ tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
+ iconAlt = "Video";
+ break;
+ } else if (mediaHandler.isAudio()) {
+ tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
+ iconAlt = "Audio";
+ } else if (tinyIcon == null && !mediaHandler.isImage()) {
+ tinyIcon = mediaHandler.getTinyIcon();
+ iconAlt = mediaHandler.getIconAlt();
+ }
+ }
+ //it only has image(s)
+ if (tinyIcon == null) {
+ tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
+ iconAlt = "Image";
+ }
+ // uploadedMedia Entity list is empty.
+ // we only have text
+ } else {
+ tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
+ iconAlt = "Text";
+ }
+ returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
+ returnHash.put("icon_alt", iconAlt);
+ return returnHash;
+ }
+
+ private boolean hasMedia() throws StorageObjectException
+ {
+ if (_hasMedia == null) {
+ _hasMedia =
+ new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
+ }
+ return _hasMedia.booleanValue();
+ }
+
+ //######## @todo all of the following getBlahForContent should have
+ // and optimized version where LIMIT=1 sql for list view.
+ private EntityList getImagesForContent()
+ throws StorageObjectException, TemplateModelException
+ {
+ if (hasMedia())
+ return DatabaseContentToMedia.getInstance().getImages(this);
+ else
+ return null;
+ }
+
+ private EntityList getAudioForContent()
+ throws StorageObjectException, TemplateModelException
+ {
+ if (hasMedia())
+ return DatabaseContentToMedia.getInstance().getAudio(this) ;
+ else
+ return null;
+ }
+
+ private EntityList getVideoForContent()
+ throws StorageObjectException, TemplateModelException
+ {
+ if (hasMedia())
+ return DatabaseContentToMedia.getInstance().getVideo(this) ;
+ else
+ return null;
+ }
+
+ private EntityList getOtherMediaForContent()
+ throws StorageObjectException, TemplateModelException
+ {
+ if (hasMedia())
+ return DatabaseContentToMedia.getInstance().getOther(this);
+ else
+ return null;
+ }
}
public class EntityFeature extends Entity
{
- private static int instances;
-
public EntityFeature()
{
- super();
- instances++;
+ super();
}
public EntityFeature(StorageObject theStorage) {
this();
- setStorage(theStorage);
+ setStorage(theStorage);
}
public void update() throws StorageObjectException{
dbContent.setUnproduced("to_feature="+getId());
}
- public void finalize() {
- instances--;
- super.finalize();
- }
}
import java.util.*;
import java.sql.*;
+/*
+ * kind of hack for postgres non-standard LargeObjects that Poolman
+ * doesn't know about. see all the casting, LargeObj stuff in getIcon, getImage
+ * at some point when postgres has normal BLOB support, this should go.
+ */
+import org.postgresql.Connection;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
+
import mir.entity.*;
import mir.misc.*;
import mir.storage.*;
*/
-public class EntityImages extends Entity
+public class EntityImages extends EntityUploadedMedia
{
- private static int instances;
-
public EntityImages()
{
super();
- instances++;
}
public EntityImages(StorageObject theStorage) {
- public byte[] getImage()
+ public byte[] getImage() throws StorageObjectException
{
theLog.printDebugInfo("--getimage started");
- Connection con=null;Statement stmt=null;
+ java.sql.Connection con=null;Statement stmt=null;
byte[] img_data=null;
try {
con = theStorageObject.getPooledCon();
con.setAutoCommit(false);
- stmt = con.createStatement();
- ResultSet rs = theStorageObject.executeSql(stmt,"select image_data from images where id="+getId());
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
+ stmt = con.createStatement();
+ ResultSet rs = theStorageObject.executeSql(stmt,
+ "select image_data from images where id="+getId());
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
if(rs!=null) {
- if (rs.next()) {
- img_data = rs.getBytes(1);
- }
- rs.close();
+ if (rs.next()) {
+ LargeObject lob = lom.open(rs.getInt(1));
+ img_data = lob.read(lob.size());
+ System.err.println("LOB IMG SIZE: "+lob.size());
+ lob.close();
+ System.err.println("res set img NOT NULL2");
+ //img_data = rs.getBytes(1);
+ }
+ rs.close();
}
- }
- catch (Exception e) {theLog.printDebugInfo("-- getImage gescheitert: "+e.toString());}
- finally {
- try {con.setAutoCommit(true); } catch (Exception e) {;}
- theStorageObject.freeConnection(con,stmt); }
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError("EntityImages -- getImage failed"+e.toString());
+ throwStorageObjectException(e, "EntityImages -- getImage failed: ");
+ }
+ finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError(
+ "EntityImages -- getImage reseting transaction mode failed"
+ +e.toString());
+ }
+ theStorageObject.freeConnection(con,stmt);
+ }
return img_data;
}
- public void setImage(byte[] uploadData, String imageType)
- {
- int type = 0;
-
- //hack -mh
- if (imageType.equals("1"))
- type = 1;
- //end hack
+ public void setImage(byte[] uploadData)
+ throws StorageObjectException {
if (uploadData!=null) {
- Connection con=null;PreparedStatement pstmt=null;
+ java.sql.Connection con=null;PreparedStatement pstmt=null;
try {
theLog.printDebugInfo("settimage :: making internal representation of image");
- WebdbImage webdbImage= new WebdbImage(uploadData,type);
+ WebdbImage webdbImage= new WebdbImage(uploadData);
theLog.printDebugInfo("settimage :: made internal representation of image");
byte[] imageData = webdbImage.getImage();
theLog.printDebugInfo("settimage :: getImage");
theLog.printDebugInfo("settimage :: trying to insert image");
// setting values
- String sql = "update images set img_height='"+webdbImage.getImageHeight() +
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+ int oidImage = lom.create();
+ int oidIcon = lom.create();
+ LargeObject lobImage = lom.open(oidImage);
+ LargeObject lobIcon = lom.open(oidIcon);
+ lobImage.write(imageData);
+ lobIcon.write(iconData);
+ lobImage.close();
+ lobIcon.close();
+ String sql = "update images set img_height='"
+ +webdbImage.getImageHeight() +
"',img_width='" + webdbImage.getImageWidth() +
"',icon_height='" + webdbImage.getIconHeight() +
- "',icon_width='" + webdbImage.getIconWidth() + "', image_data=?, icon_data=? where id="+getId();
+ "',icon_width='" + webdbImage.getIconWidth()
+ + "', image_data="+oidImage+", icon_data="+oidIcon
+ +" where id="+getId();
theLog.printDebugInfo("settimage :: updating sizes: "+ sql);
pstmt = con.prepareStatement(sql);
- pstmt.setBytes(1, imageData);
- pstmt.setBytes(2, iconData);
+ //pstmt.setBytes(1, imageData);
+ //pstmt.setBytes(2, iconData);
pstmt.executeUpdate();
sql="update content set is_produced='0' where to_media="+getId();
pstmt = con.prepareStatement(sql);
pstmt.executeUpdate();
}
}
- catch (Exception e) {theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());}
+ catch (Exception e) {throwStorageObjectException(e, "settimage :: setImage gescheitert: ");}
finally {
- try {con.setAutoCommit(true); } catch (Exception e) {;}
+ try { if (con!=null) con.setAutoCommit(true); } catch (Exception e) {;}
theStorageObject.freeConnection(con,pstmt); }
}
}
try {
theStorageObject.executeUpdate("update content set is_produced='0' where to_media="+getId());
} catch (SQLException e) {
- theLog.printError("EntityImages :: update :: failed!! "+ e.toString());
+ throwStorageObjectException(e, "EntityImages :: update :: failed!! ");
}
}
super.setValues(theStringValues);
}
- public byte[] getIcon()
+ public byte[] getIcon() throws StorageObjectException
{
- Connection con=null;Statement stmt=null;
+ java.sql.Connection con=null;Statement stmt=null;
byte[] img_data=null;
try {
con = theStorageObject.getPooledCon();
con.setAutoCommit(false);
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
stmt = con.createStatement();
- ResultSet rs = theStorageObject.executeSql(stmt,"select icon_data from images where id="+getId());
+ ResultSet rs = theStorageObject.executeSql(stmt,
+ "select icon_data from images where id="+getId());
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
if(rs!=null) {
+ System.err.println("res set NOT NULL");
if (rs.next()) {
- img_data = rs.getBytes(1);
+ LargeObject lob = lom.open(rs.getInt(1));
+ img_data = lob.read(lob.size());
+ System.err.println("LOB SIZE: "+lob.size());
+ lob.close();
+ System.err.println("res set NOT NULL2");
+ //img_data = rs.getBytes(1);
+ System.err.println("res set NOT NULL3");
}
- rs.close();
+ rs.close();
}
- }
- catch (Exception e) {theLog.printDebugInfo("-- getIcon gescheitert: "+e.toString());}
- finally {
- try {con.setAutoCommit(true); } catch (Exception e) {;}
- theStorageObject.freeConnection(con,stmt); }
-
- return img_data;
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError("EntityImages -- getIcon failed"+e.toString());
+ throwStorageObjectException(e, "EntityImages -- getIcon failed:");
+ } finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError(
+ "EntityImages -- getIcon reseting transaction mode failed"
+ +e.toString());
+ }
+ theStorageObject.freeConnection(con,stmt);
+ }
+
+ return img_data;
}
- public void finalize() {
- instances--;
- super.finalize();
- }
-
}
public class EntityLinksImcs extends Entity
{
- private static int instances;
public EntityLinksImcs(){
super();
- instances++;
}
public EntityLinksImcs(StorageObject theStorage)
setStorage(theStorage);
}
- public void finalize() {
- instances--;
- super.finalize();
- }
}
public class EntityMedia extends Entity
{
- private static int instances;
public EntityMedia(){
super();
- instances++;
}
public EntityMedia(StorageObject theStorage)
*
* @return mir.entity.Entity
*/
- public Entity getMediaType() {
- return ((DatabaseMedia)theStorageObject).getMediaType(this);
- }
+ public Entity getMediaType() throws StorageObjectException {
+ try {
+ return ((DatabaseMedia)theStorageObject).getMediaType(this);
+ } catch (StorageObjectException e) {
+ throw new StorageObjectException("getMediaType(): "+e.toString());
+ }
- public void finalize() {
- instances--;
- super.finalize();
- }
+ }
}
--- /dev/null
+package mircoders.entity;
+
+import java.lang.*;
+import java.io.*;
+import java.util.*;
+import java.sql.*;
+
+/*
+ * kind of hack for postgres non-standard LargeObjects that Poolman
+ * doesn't know about. see all the casting, LargeObj stuff in getIcon, getOther
+ * at some point when postgres has normal BLOB support, this should go.
+ */
+import org.postgresql.Connection;
+import org.postgresql.largeobject.LargeObject;
+import org.postgresql.largeobject.LargeObjectManager;
+
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+/**
+ * This class handles storage of other data and meta data
+ *
+ * @author mh
+ * @version 11.11.2000
+ */
+
+
+public class EntityOther extends EntityUploadedMedia
+{
+ public EntityOther()
+ {
+ super();
+ }
+
+ public EntityOther(StorageObject theStorage) {
+ this();
+ setStorage(theStorage);
+ }
+
+ //
+ // methods
+
+
+
+ public byte[] getOther() throws StorageObjectException
+ {
+ theLog.printDebugInfo("--getother started");
+ java.sql.Connection con=null;Statement stmt=null;
+ byte[] img_data=null;
+
+ try {
+ con = theStorageObject.getPooledCon();
+ con.setAutoCommit(false);
+ LargeObjectManager lom;
+ java.sql.Connection jCon;
+ stmt = con.createStatement();
+ ResultSet rs = theStorageObject.executeSql(stmt,
+ "select other_data from other where id="+getId());
+ jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
+ .getNativeConnection();
+ lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI();
+ if(rs!=null) {
+ if (rs.next()) {
+ LargeObject lob = lom.open(rs.getInt(1));
+ img_data = lob.read(lob.size());
+ lob.close();
+ //img_data = rs.getBytes(1);
+ }
+ rs.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError("EntityOther -- getOther failed"+e.toString());
+ throwStorageObjectException(e, "EntityOther -- getOther failed: ");
+ }
+ finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printError(
+ "EntityOther -- getOther reseting transaction mode failed"
+ +e.toString());
+ }
+ theStorageObject.freeConnection(con,stmt);
+ }
+
+ return img_data;
+ }
+
+ public void setOther(byte[] otherData, String otherType)
+ throws StorageObjectException {
+
+ if (otherData!=null) {
+ java.sql.Connection con=null;PreparedStatement pstmt=null;
+ try {
+
+ theLog.printDebugInfo("settother :: making internal representation of other");
+ theLog.printDebugInfo("settother :: made internal representation of other");
+ theLog.printDebugInfo("settother :: getOther");
+
+ if ( otherData!=null) {
+ con = theStorageObject.getPooledCon();
+ con.setAutoCommit(false);
+ theLog.printDebugInfo("settother :: trying to insert other");
+
+ // setting values
+ pstmt.setBytes(1, otherData);
+ String sql="update content set is_produced='0' where to_media="+getId();
+ pstmt = con.prepareStatement(sql);
+ pstmt.executeUpdate();
+ }
+ }
+ catch (Exception e) {throwStorageObjectException(e, "settother :: setOther gescheitert: ");}
+ finally {
+ try { if (con!=null) con.setAutoCommit(true); } catch (Exception e) {;}
+ theStorageObject.freeConnection(con,pstmt); }
+ }
+ }
+
+ public void update() throws StorageObjectException {
+ super.update();
+ try {
+ theStorageObject.executeUpdate("update content set is_produced='0' where to_media="+getId());
+ } catch (SQLException e) {
+ throwStorageObjectException(e, "EntityOther :: update :: failed!! ");
+ }
+ }
+
+ public void setValues(HashMap theStringValues)
+ {
+ if (theStringValues != null) {
+ if (!theStringValues.containsKey("is_published"))
+ theStringValues.put("is_published","0");
+ }
+ super.setValues(theStringValues);
+ }
+
+}
*/
-public class EntityTopics extends Entity
+public class EntityTopics extends Entity
{
- private static int instances;
-
public EntityTopics(){
super();
- instances++;
}
public EntityTopics(StorageObject theStorage)
dbContent.setUnproduced("to_topic="+getId());
}
- public void finalize() {
- instances--;
- super.finalize();
- }
}
import java.util.*;
import java.sql.*;
+import freemarker.template.*;
+
import mir.entity.*;
import mir.misc.*;
import mir.storage.*;
+import mir.media.*;
import mircoders.storage.*;
/**
public class EntityUploadedMedia extends Entity
{
- private static int instances;
+
public EntityUploadedMedia(){
super();
- instances++;
}
public EntityUploadedMedia(StorageObject theStorage)
super.setValues(theStringValues);
}
+
/**
* fetches the MediaType entry assiciated w/ this media
*
* @return mir.entity.Entity
*/
- public Entity getMediaType() {
- return ((DatabaseUploadedMedia)theStorageObject).getMediaType(this);
+ public Entity getMediaType() throws StorageObjectException {
+ Entity ent = null;
+ try {
+ ent = DatabaseUploadedMedia.getInstance().getMediaType(this);
+ } catch (StorageObjectException e) {
+ throwStorageObjectException(e, "get MediaType failed -- ");
+ }
+ return ent;
}
+ public String getValue(String key)
+ {
+ String returnValue=null;
+
+ if (key!=null) {
+ if (key.equals("url"))
+ returnValue=getUrl();
+ else if (key.equals("list"))
+ returnValue=getListView();
+ else
+ returnValue=super.getValue(key);
+ }
+ return returnValue;
+ }
+
+ public TemplateModel get(java.lang.String key) throws TemplateModelException
+ {
+ return new SimpleScalar(getValue(key));
+ }
+
+ private String getUrl()
+ {
+ MirMedia mediaHandler=null;
+ Entity mediaType=null;
+
+ try {
+ mediaType = getMediaType();
+ mediaHandler = MediaHelper.getHandler( mediaType );
+ return mediaHandler.getURL(this, mediaType);
+ } catch (Exception ex) {
+ theLog.printWarning("-- getUrl: could not fetch data "
+ + this.getClass().toString()+" "+ ex.toString());
+ }
+ return null;
+ }
+ private String getListView()
+ {
+ MirMedia mediaHandler=null;
+ Entity mediaType=null;
- public void finalize() {
- instances--;
- super.finalize();
+ try {
+ mediaType = getMediaType();
+ mediaHandler = MediaHelper.getHandler( mediaType );
+ return mediaHandler.getListView(this, mediaType);
+ } catch (Exception ex) {
+ theLog.printWarning("-- getUrl: could not fetch data "
+ + this.getClass().toString()+" "+ ex.toString());
+ }
+ return null;
}
+
+
}
public class EntityUsers extends Entity
{
- private static int instances;
public EntityUsers()
{
super();
- instances++;
}
public EntityUsers(StorageObject theStorage) {
setStorage(theStorage);
}
- public void finalize() {
- instances--;
- super.finalize();
- }
-
// Methods
public boolean isAdmin()
*/
-public class EntityVideo extends Entity
+public class EntityVideo extends EntityUploadedMedia
{
- private static int instances;
public EntityVideo()
{
super();
- instances++;
}
public EntityVideo(StorageObject theStorage) {
//
// methods
- public byte[] getVideoData()
+ public byte[] getVideoData() throws StorageObjectException
{
Connection con=null;Statement stmt=null;
return video_data;
}
- public void setVideoData(byte[] uploadData)
+ public void setVideoData(byte[] uploadData) throws StorageObjectException
{
if (uploadData!=null) {
Connection con=null;PreparedStatement pstmt=null;
super.setValues(theStringValues);
}
-
- public void finalize() {
- instances--;
- super.finalize();
- }
-
}
if (!logDir.exists()) {
logDir.mkdir();
}
- logger = Logfile.getInstance("Inputlog");
+ logger = Logfile.getInstance(args[0] + "LOG/xml.log");
XmlInputParser xmlInputParser = new XmlInputParser();
//get the config-file
/* Commented out for now since it seems unused and need more
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+/**
+ * Handles audio media, like mp3 and maybe it could also handle some other.
+ * It is MediaHandlerGeneric with different icons.
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MirMedia
+ * @author mh <heckmann@hbe.ca>
+ * @version 24.09.2001
+ */
+
+public class MediaHandlerAudio extends MediaHandlerGeneric implements MirMedia
+{
+
+ private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
+ private static String bigIcon = MirConfig.getProp("Producer.Icon.BigAudio");
+
+ public String getTinyIcon()
+ {
+ return tinyIcon;
+ }
+
+ public String getBigIcon()
+ {
+ return bigIcon;
+ }
+
+ public String getIconAlt()
+ {
+ return "Audio";
+ }
+
+ public boolean isAudio()
+ {
+ return true;
+ }
+}
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+/**
+ * This is the Generic MediaHandler. It stores the media data on
+ * the filesystem and keeps basic metadata (size, type...) in the
+ * DB. Usually only representation needs to be overridden.
+ * See the MediaHandlerAudio class to see an example of how one
+ * could override it.
+ * <p>
+ * Most media handlers should override this class.
+ * <p>
+ * In theory, it could be used to handle miscellaneous media that
+ * we don't have entered in the media_type table, (like RTF documents,
+ * PS, PDF, etc..)
+ * <p>
+ * Of course it implements the MirMedia interface.
+ *
+ * @see mir.media.MirMedia
+ * @author mh <heckmann@hbe.ca>
+ * @version 24.09.2001
+ */
+
+public class MediaHandlerGeneric implements MirMedia
+{
+
+ protected String imageHost = MirConfig.getProp("Producer.Image.Host");
+ protected String imageRoot = MirConfig.getProp("Producer.ImageRoot");
+ protected Logfile theLog = Logfile.getInstance(MirConfig.getProp("Home")+"log/media.log");
+ public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt )
+ throws MirMediaException {
+
+ String ext = mediaTypeEnt.getValue("name");
+ String dir = MirConfig.getProp("Producer.Media.Path");
+ String mediaHost = MirConfig.getProp("Producer.Media.Host");
+ String mediaFname = ent.getId()+"."+ext;
+ String date = ent.getValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ Integer size = new Integer(uploadedData.length);
+ try {
+ FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData);
+ //if(FileUtil.write(dir+"/"+mediaFname, uploadedData)) {
+ //were done with the data, dereference.
+ uploadedData=null;
+
+ ent.setValueForProperty("is_produced", "1");
+ ent.setValueForProperty("icon_is_produced", "1");
+ ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
+ //ent.setValueForProperty("publish_path", mediaFname);
+ ent.setValueForProperty("publish_server", mediaHost);
+ ent.setValueForProperty("size", size.toString());
+ ent.update();
+ } catch (Exception e) {
+ theLog.printError(e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return true;
+ }
+
+ //a method that will probably never get used..
+ private byte[] getFile (String fileName)
+ throws MirMediaException {
+
+ long size = FileUtil.getSize(fileName);
+ if (size < 0) return null;
+
+ byte[] container = new byte[(int)size];
+
+ try {
+ FileUtil.read(fileName, container);
+ } catch (Exception e) {
+ theLog.printError(e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return container;
+ }
+
+ public byte[] get (Entity ent, Entity mediaTypeEnt) {
+ return null;
+ }
+
+ public byte[] getIcon (Entity ent) {
+ return null;
+ }
+
+ public String getStoragePath()
+ {
+ return MirConfig.getProp("Producer.Media.Path");
+ }
+
+ public String getIconStoragePath()
+ {
+ return MirConfig.getProp("Producer.Image.IconPath");
+ }
+
+ public String getPublishHost()
+ {
+ return MirConfig.getProp("Producer.Media.Host");
+ }
+
+ public String getTinyIcon()
+ {
+ return MirConfig.getProp("Producer.Icon.TinyText");
+ }
+
+ public String getBigIcon()
+ {
+ return MirConfig.getProp("Producer.Icon.BigText");
+ }
+
+ public String getIconAlt()
+ {
+ return "Generic media";
+ }
+
+ public String getURL(Entity ent, Entity mediaTypeEnt)
+ {
+ String stringSize = ent.getValue("size");
+ if (stringSize == null)
+ return null;
+ int size = Integer.parseInt(stringSize, 10)/1024;
+ String title = ent.getValue("title")+
+ " - "+mediaTypeEnt.getValue("name")+" "+
+ size+" KB";
+ return StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+
+ ent.getValue("publish_path"), title, imageRoot, getBigIcon());
+ }
+
+ public String getListView(Entity ent, Entity mediaTypeEnt)
+ {
+ //String title = ent.getValue("title")+
+ // " - "+mediaTypeEnt.getValue("name")+" "+
+ // ent.getValue("size")+" Bytes";
+ return StringUtil.createIMGLinks(imageHost+
+ getBigIcon(), null, null, null);
+ }
+
+ public boolean isVideo()
+ {
+ return false;
+ }
+
+ public boolean isAudio()
+ {
+ return false;
+ }
+
+ public boolean isImage()
+ {
+ return false;
+ }
+
+}
+
+
+
--- /dev/null
+
+package mircoders.media;
+
+import java.lang.*;
+import java.io.*;
+import java.util.*;
+import java.lang.reflect.*;
+
+import mir.media.*;
+import mir.misc.*;
+import mir.entity.*;
+import mir.storage.StorageObjectException;
+import mircoders.entity.EntityImages;
+
+/**
+ * This class handles saving, fetching creating representations
+ * for all images. The image content is stored in the DB. The content is
+ * written out to a file at the ProducerImages level.
+ * Remember that Handlers for specific image types, Gif, Jpeg, etc..
+ * should override it.
+ * It implements the MirMedia interface.
+ * <p>
+ * slowly starting to look better, a next step would be to have the
+ * representation stuff (WebdbImage) happen here.
+ * -mh 01.03.2002
+ *
+ * @see mir.media.MirMedia
+ * @author mh
+ * @version 24.09.2001
+ */
+
+
+public class MediaHandlerImages implements MirMedia
+{
+ private Logfile theLog = Logfile.getInstance(MirConfig.getProp("Home")+
+ "log/media.log");
+
+ public byte[] get(Entity ent, Entity mediaTypeEnt)
+ throws MirMediaException
+ {
+ byte[] image_data = null;
+
+ try {
+ image_data = ((EntityImages)ent).getImage();
+ } catch ( StorageObjectException e) {
+ theLog.printDebugInfo("MediaHandlerImages.get: "+e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+
+ return image_data;
+ }
+
+ public boolean set(byte[] uploadData, Entity ent, Entity mediaTypeEnt)
+ throws MirMediaException {
+
+ try {
+ ((EntityImages)ent).setImage(uploadData);
+ } catch ( StorageObjectException e) {
+ theLog.printDebugInfo("MediaHandlerImages.set: "+e.toString());
+ throw new MirMediaException(e.toString());
+ }
+ //deref. -mh
+ uploadData=null;
+
+ return true;
+ }
+
+ public byte[] getIcon(Entity ent) throws MirMediaException
+ {
+ byte[] icon_data = null;
+
+ try {
+ icon_data = ((EntityImages)ent).getIcon();
+ } catch ( StorageObjectException e) {
+ theLog.printDebugInfo("MediaHandlerImages.getIcon: "+e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return icon_data;
+ }
+
+ public String getURL(Entity ent, Entity mediaTypeEnt)
+ {
+ String title = ent.getValue("title");
+ return StringUtil.createIMGLinks(ent.getValue("publish_server")+
+ ent.getValue("publish_path"), title, ent.getValue("img_height"),
+ ent.getValue("img_width"));
+ }
+
+ public String getListView(Entity ent, Entity mediaTypeEnt)
+ {
+ //String title = ent.getValue("title");
+ return StringUtil.createIMGLinks( MirConfig.getProp("Producer.ProductionHost")+
+ ent.getValue("icon_path"), null, ent.getValue("icon_height"),
+ ent.getValue("icon_width"));
+ }
+
+ public String getStoragePath()
+ {
+ return MirConfig.getProp("Producer.Image.Path");
+ }
+
+ public String getIconStoragePath()
+ {
+ return MirConfig.getProp("Producer.Image.IconPath");
+ }
+
+ public String getPublishHost()
+ {
+ return MirConfig.getProp("Producer.Image.Host");
+ }
+
+ public String getTinyIcon ()
+ {
+ return MirConfig.getProp("Producer.Icon.TinyImage");
+ }
+
+ public String getBigIcon ()
+ {
+ return MirConfig.getProp("Producer.Icon.BigImage");
+ }
+
+ public String getIconAlt ()
+ {
+ return "Image";
+ }
+
+ public boolean isVideo ()
+ {
+ return false;
+ }
+
+ public boolean isAudio ()
+ {
+ return false;
+ }
+
+ public boolean isImage ()
+ {
+ return true;
+ }
+
+}
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+/**
+ * Please note: this media handler produces
+ * 3 media files, the raw .mp3, a .m3u which is
+ * contains the URL for the mp3 and a .pls which
+ * contains the URL to the mp3 in shoutcast playlist
+ * format. What's important is that the web server (of
+ * the media host) must recognize the .m3u and .pls file
+ * extensions and send the proper "audio/x-mpegurl"
+ * and "audio/x-scpls" mime-types respectively.
+ * If the web server is apache, it's easy, just
+ * add:
+ *
+ * audio/x-mpegurl m3u
+ * audio/x-scpl pls
+ *
+ * to the file pointed to by the "TypesConfig"
+ * command in your apache config file. Or add
+ * and equivalent AddType command to your httpd.conf.
+ * Of course this assumes that the mod_mime is loaded.
+ *
+ * If the web server is not apache, then your on your own.
+ *
+ * @see mir.media.MirMedia
+ * @author mh <heckmann@hbe.ca>
+ * @version 01.12.2001
+ */
+
+public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia
+{
+
+ public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt )
+ throws MirMediaException {
+
+ String ext = mediaTypeEnt.getValue("name");
+ String dir = MirConfig.getProp("Producer.Media.Path");
+ String mediaHost = MirConfig.getProp("Producer.Media.Host");
+ String date = ent.getValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String baseName = ent.getId();
+ String mediaFname = baseName+"."+ext;
+ String mp3Pointer = mediaHost+datePath+mediaFname;
+ String mpegURLFile = baseName+".m3u";
+ String playlistFile = baseName+".pls";
+ Integer size = new Integer(uploadedData.length);
+ try {
+ FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData);
+ //FileUtil.write(dir+"/"+mediaFname, uploadedData);
+ //were done with the data, dereference.
+ uploadedData=null;
+
+ //write the "meta" files
+ //first the .m3u since it only contains one line
+ FileUtil.write(dir+"/"+datePath+"/"+mpegURLFile,mp3Pointer.getBytes());
+ //now the .pls file
+ FileUtil.write(dir+"/"+datePath+"/"+playlistFile,mp3Pointer.getBytes());
+ ent.setValueForProperty("is_produced", "1");
+ ent.setValueForProperty("icon_is_produced", "1");
+ ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
+ //ent.setValueForProperty("publish_path", mediaFname);
+ ent.setValueForProperty("publish_server", mediaHost);
+ ent.setValueForProperty("size", size.toString());
+ ent.update();
+ } catch (Exception e) {
+ theLog.printError(e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return true;
+ }
+
+ public String getURL(Entity ent, Entity mediaTypeEnt)
+ {
+ String stringSize = ent.getValue("size");
+ if (stringSize == null)
+ return null;
+ int size = Integer.parseInt(stringSize, 10)/1024;
+ String rawTitle = ent.getValue("title")+
+ " - "+mediaTypeEnt.getValue("name")+" "+
+ size+" KB "+"download";
+ String m3uTitle = ent.getValue("title")+
+ " - "+mediaTypeEnt.getValue("name")+" "+
+ "streaming URL";
+ String plsTitle = ent.getValue("title")+
+ " - "+mediaTypeEnt.getValue("name")+" "+
+ "playlist URL";
+
+ String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), ".mp3$","");
+
+ String m3uURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+basePath+".m3u", m3uTitle, imageRoot, getBigIcon());
+ String plsURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+basePath+".pls", plsTitle, imageRoot, getBigIcon());
+ String rawURL = StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+ent.getValue("publish_path"), rawTitle, imageRoot, getBigIcon());
+
+ return m3uURL+"\n<p>"+plsURL+"\n<p>"+rawURL;
+
+ }
+
+}
+
+
+
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+
+/**
+ * Handles real audio. like MediaHandlerAudio, except it manages the ram file, too.
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MirMedia
+ * @author john <john@manifestor.org>
+ * @version 11.10.2001
+ */
+
+
+public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia
+{
+
+ public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt )
+ throws MirMediaException {
+ String ext = mediaTypeEnt.getValue("name");
+ String dir = MirConfig.getProp("Producer.Media.Path");
+ String rtspDir = MirConfig.getProp("Producer.RealMedia.Path");
+ String mediaHost = MirConfig.getProp("Producer.Media.Host");
+ String rtspMediaHost = MirConfig.getProp("Producer.RealMedia.Host");
+
+ String date = ent.getValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String mediaFname = ent.getId()+"."+ext;
+ String realMediaPointer = rtspMediaHost+datePath+mediaFname;
+ String realMediaFile = ent.getId()+".ram";
+ Integer size = new Integer(uploadedData.length);
+ try {
+ FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData);
+ //FileUtil.write(rtspDir+"/"+mediaFname, uploadedData);
+ //were done with the data, dereference.
+ uploadedData=null;
+
+ //write a ram file
+ FileUtil.write(dir+"/"+datePath+"/"+realMediaFile,realMediaPointer.getBytes());
+ ent.setValueForProperty("is_produced", "1");
+ ent.setValueForProperty("icon_is_produced", "1");
+ ent.setValueForProperty("publish_path",datePath+"/"+realMediaFile);
+ //ent.setValueForProperty("publish_path", realMediaFile);
+ ent.setValueForProperty("publish_server", mediaHost);
+ ent.setValueForProperty("size", size.toString());
+ ent.update();
+ } catch (Exception e) {
+ theLog.printError(e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return true;
+ }
+
+}
+
+
+
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+
+/**
+ * Handles real video. like MediaHandlerAudio, except it manages the ram file, too.
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MirMedia
+ * @author john <john@manifestor.org>
+ * @version 11.10.2001
+ */
+
+
+public class MediaHandlerRealVideo extends MediaHandlerGeneric implements MirMedia
+{
+
+ private String imageHost = MirConfig.getProp("Producer.Image.Host");
+ private static String imageRoot = MirConfig.getProp("Producer.ImageRoot");
+ private Logfile theLog = Logfile.getInstance(MirConfig.getProp("Home")+"log/media.log");
+
+ public boolean set (byte[] uploadedData, Entity ent, Entity mediaTypeEnt )
+ throws MirMediaException {
+
+ String ext = mediaTypeEnt.getValue("name");
+ String dir = MirConfig.getProp("Producer.Media.Path");
+ String rtspDir = MirConfig.getProp("Producer.RealMedia.Path");
+ String mediaHost = MirConfig.getProp("Producer.Media.Host");
+ String rtspMediaHost = MirConfig.getProp("Producer.RealMedia.Host");
+
+ String mediaFname = ent.getId()+"."+ext;
+ String RealMediaPointer = rtspMediaHost+mediaFname;
+ String RealMediaFile = ent.getId()+".ram";
+ String date = ent.getValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ Integer size = new Integer(uploadedData.length);
+ try {
+ FileUtil.write(dir+"/"+datePath+"/"+mediaFname, uploadedData);
+ //FileUtil.write(rtspDir+"/"+mediaFname, uploadedData);
+ //were done with the data, dereference.
+ uploadedData=null;
+
+ //write an rm file
+ FileUtil.write(dir+"/"+RealMediaFile,RealMediaPointer.getBytes());
+ ent.setValueForProperty("is_produced", "1");
+ ent.setValueForProperty("icon_is_produced", "1");
+ ent.setValueForProperty("publish_path",datePath+"/"+mediaFname);
+ //ent.setValueForProperty("publish_path", RealMediaFile);
+ ent.setValueForProperty("publish_server", mediaHost);
+ ent.setValueForProperty("size", size.toString());
+ ent.update();
+ } catch (Exception e) {
+ theLog.printError(e.toString());
+ throw new MirMediaException(e.toString());
+ }
+
+ return true;
+ }
+
+
+
+
+
+ public String getPublishHost()
+ {
+ return MirConfig.getProp("Producer.Media.Host");
+ }
+
+
+
+ public String getURL(Entity ent, Entity mediaTypeEnt)
+ {
+ int size = Integer.parseInt(ent.getValue("size"), 10)/1024;
+ String title = ent.getValue("title")+
+ " - "+mediaTypeEnt.getValue("name")+" "+
+ size+" KB";
+ return StringUtil.createURLLinks(ent.getValue("publish_server")+"/"+
+ ent.getValue("publish_path"), title, imageRoot, getBigIcon());
+ }
+
+
+ private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
+ private static String bigIcon = MirConfig.getProp("Producer.Icon.BigVideo");
+
+ public String getTinyIcon()
+ {
+ return tinyIcon;
+ }
+
+ public String getBigIcon()
+ {
+ return bigIcon;
+ }
+
+ public String getIconAlt()
+ {
+ return "Video";
+ }
+
+ public boolean isVideo()
+ {
+ return true;
+ }
+
+}
+
+
+
--- /dev/null
+/*
+ * put your module comment here
+ */
+
+
+package mircoders.media;
+
+import java.util.*;
+
+import mir.media.*;
+import mir.entity.*;
+import mir.misc.*;
+import mir.storage.*;
+
+
+/**
+ * Handles video media, like mpeg, av, and qt
+ * It is like MediaHandlerAudio with different icons.
+ * It is MediaHandlerGeneric with different icons.
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MirMedia
+ * @author john <john@manifestor.org>
+ * @version 11.10.2001
+ */
+
+public class MediaHandlerVideo extends MediaHandlerGeneric implements MirMedia
+{
+
+ private static String tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
+ private static String bigIcon = MirConfig.getProp("Producer.Icon.BigVideo");
+
+ public String getTinyIcon()
+ {
+ return tinyIcon;
+ }
+
+ public String getBigIcon()
+ {
+ return bigIcon;
+ }
+
+ public String getIconAlt()
+ {
+ return "Video";
+ }
+
+ public boolean isVideo()
+ {
+ return true;
+ }
+}
public ModuleBreaking (StorageObject theStorage)
{
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Breaking.Logfile"));
if (theStorage == null) theLog.printWarning("ModuleBreaking -- StorageObject was null!");
this.theStorage = theStorage;
}
// Methoden
-
+ public EntityList getBreakingNews() {
+ EntityList returnList = null;
+ try {
+ returnList = getByWhereClause(null,"webdb_create desc",0,5);
+ }
+ catch (Exception ex) {
+ theLog.printWarning("--getBreakingNews(): could not fetch Breaking News" + ex.toString());
+ }
+ return returnList;
+ }
}
// Contructor
public ModuleComment(StorageObject theStorage)
{
- //if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Comment.Logfile"));
- //if (theStorage == null) theLog.printWarning("StorageObject was null!");
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Comment.Logfile"));
+ if (theStorage == null) theLog.printWarning("StorageObject was null!");
this.theStorage = theStorage;
}
// Methoden
- public SimpleList getCommentAsSimpleList() {
- return ((DatabaseComment)theStorage).getPopupData();
+ public SimpleList getCommentAsSimpleList() throws ModuleException {
+ try {
+ return ((DatabaseComment)theStorage).getPopupData();
+ } catch (StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
/**
public ModuleContent() {
super();
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Content.Logfile"));
}
public ModuleContent(StorageObject theStorage) {
this.theStorage = theStorage;
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Content.Logfile"));
}
//
// methoden, um an ContentEntities zu kommen
+ public EntityList getFeatures(int offset, int limit) throws ModuleException
+ {
+ return getContent("is_published=true AND to_article_type=2", "date desc, webdb_create desc",
+ offset, limit);
+ }
+
+ public EntityList getNewsWire(int offset, int limit) throws ModuleException
+ {
+ return getContent("is_published=true AND to_article_type = 1",
+ "date desc, webdb_create desc",offset,limit);
+ }
+
+ public EntityList getStartArticle() throws ModuleException
+ {
+ EntityList returnList = getContent("is_published=true AND to_article_type=4",
+ "date desc, webdb_create desc",0,1);
+ //if no startspecial exists
+ if (returnList==null || returnList.size()==0)
+ returnList = getContent("is_published=true AND to_article_type=3",
+ "date desc, webdb_create desc",0,1);
+
+ return returnList;
+ }
public EntityList getContent(HashMap searchValues, boolean concat, int offset, EntityUsers user)
throws ModuleException {
this.theStorage = theStorage;
if (theLog == null)
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Feature.Logfile"));
}
- public SimpleList getSchwerpunktAsSimpleList() {
- return ((DatabaseFeature)theStorage).getPopupData();
+ public SimpleList getSchwerpunktAsSimpleList()
+ throws ModuleException {
+ try {
+ return ((DatabaseFeature)theStorage).getPopupData();
+ } catch (StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
}
public ModuleImages(StorageObject theStorage) {
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home")+MirConfig.getProp("Module.Bilder.Logfile"));
if (theStorage == null) theLog.printWarning("StorageObject was null!");
this.theStorage = theStorage;
// Methoden
- public SimpleList getBilderAsSimpleList() {
+ public SimpleList getBilderAsSimpleList()
+ throws ModuleException {
// String sql = "select id, name from Bilder order by name";
- return ((DatabaseImages)theStorage).getPopupData();
+ try {
+ return ((DatabaseImages)theStorage).getPopupData();
+ } catch (StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
}
// Kontruktor
public ModuleLanguage (StorageObject theStorage) {
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Language.Logfile"));
if (theStorage == null) theLog.printWarning("ModuleLanguage -- StorageObject was null!");
this.theStorage = theStorage;
public ModuleLinksImcs(StorageObject theStorage) {
this.theStorage = theStorage;
if (theLog == null)
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.LinksImcs.Logfile"));
}
public SimpleHash getLinksImcsAsSimpleHash() {
public ModuleMediafolder(StorageObject theStorage)
{
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Mediafolder.Logfile"));
if (theStorage == null) theLog.printWarning("StorageObject was null!");
this.theStorage = theStorage;
}
// Methoden
- public SimpleList getPopupData() {
- return ((DatabaseMediafolder)theStorage).getPopupData();
+ public SimpleList getPopupData() throws ModuleException {
+ try {
+ return ((DatabaseMediafolder)theStorage).getPopupData();
+ } catch (Exception e) {
+ throw new ModuleException(e.toString());
+ }
}
public ModuleMessage (StorageObject theStorage)
{
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Messages.Logfile"));
if (theStorage == null) theLog.printWarning("ModuleMessage -- StorageObject was null!");
this.theStorage = theStorage;
this.theStorage = theStorage;
if (theLog == null)
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Schwerpunkt.Logfile"));
}
- public SimpleList getSchwerpunktAsSimpleList() {
- return ((DatabaseFeature)theStorage).getPopupData();
+ public SimpleList getSchwerpunktAsSimpleList()
+ throws ModuleException {
+ try {
+ return ((DatabaseFeature)theStorage).getPopupData();
+ } catch (StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
}
public ModuleTopics(StorageObject theStorage) {
this.theStorage = theStorage;
if (theLog == null)
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Themen.Logfile"));
}
- public SimpleList getTopicsAsSimpleList() {
- return ((DatabaseTopics)theStorage).getPopupData();
+ public SimpleList getTopicsAsSimpleList() throws ModuleException {
+ try {
+ return ((DatabaseTopics)theStorage).getPopupData();
+ } catch(StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
+ }
+
+
+ /**
+ * Method getTopicList
+ *
+ * @return SimpleList of all Topics sorted by title
+ *
+ */
+ public EntityList getTopicsList()
+ {
+ EntityList returnList=null;
+ try {
+ returnList=getByWhereClause("","title",-1);
+ }
+ catch (Exception e)
+ {
+ theLog.printWarning("--getTopicsList: topics could not be fetched");
+ }
+ return returnList;
}
}
public ModuleUploadedMedia(StorageObject theStorage) {
this.theStorage = theStorage;
if (theLog == null)
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Themen.Logfile"));
}
- public SimpleList getUploadedMediaAsSimpleList() {
- return ((DatabaseUploadedMedia)theStorage).getPopupData();
+ public SimpleList getUploadedMediaAsSimpleList()
+ throws ModuleException {
+ try {
+ return ((DatabaseUploadedMedia)theStorage).getPopupData();
+ } catch (StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
}
public ModuleUsers(StorageObject theStorage)
{
- if (theLog == null) theLog = Logfile.getInstance(this.getClass().getName());
+ if (theLog == null) theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Module.Users.Logfile"));
if (theStorage == null) theLog.printWarning("StorageObject was null!");
this.theStorage = theStorage;
}
}
- public SimpleList getUsersAsSimpleList() {
+ public SimpleList getUsersAsSimpleList() throws ModuleException {
// String sql = "select id, name from Users order by name";
- return ((DatabaseUsers)theStorage).getPopupData();
+ try {
+ return ((DatabaseUsers)theStorage).getPopupData();
+ } catch(StorageObjectException e) {
+ throw new ModuleException(e.toString());
+ }
}
}
abstract public class Producer {
- protected static String producerDocRoot = MirConfig.getProp("Producer.DocRoot");
- protected static String producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
- protected static String producerProductionHost = MirConfig.getProp("Producer.ProductionHost");
- protected static String producerOpenAction = MirConfig.getProp("Producer.OpenAction");;
- protected static Logfile theLog = Logfile.getInstance("Producer");
- protected static ModuleTopics topicsModule;
+ protected static String producerDocRoot = MirConfig.getProp("Producer.DocRoot");
+ protected static String producerStorageRoot = MirConfig.getProp("Producer.StorageRoot");
+ protected static String producerProductionHost = MirConfig.getProp("Producer.ProductionHost");
+ protected static String producerOpenAction = MirConfig.getProp("Producer.OpenAction");;
+
+ /** @todo same as in HTMLTemplateProcessor, this should be dynamically set */
+ protected static String actionRoot = MirConfig.getProp("RootUri") + "/servlet/Mir";
+
+ protected static Logfile theLog = Logfile.getInstance(MirConfig.getProp("Home") + "/" + MirConfig.getProp("Producer.Logfile"));
+ protected static ModuleTopics topicsModule;
protected static ModuleLinksImcs linksImcsModule;
- protected static ModuleSchwerpunkt schwerpunktModule;
- protected static ModuleFeature featureModule;
- protected static ModuleContent contentModule;
- protected static ModuleImages imageModule;
- protected static ModuleUploadedMedia uploadedMediaModule;
+ protected static ModuleSchwerpunkt schwerpunktModule;
+ protected static ModuleFeature featureModule;
+ protected static ModuleContent contentModule;
+ protected static ModuleImages imageModule;
+ protected static ModuleUploadedMedia uploadedMediaModule;
static {
// init
try {
- contentModule = new ModuleContent(DatabaseContent.getInstance());
- topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
+
+ contentModule = new ModuleContent(DatabaseContent.getInstance());
+ topicsModule = new ModuleTopics(DatabaseTopics.getInstance());
linksImcsModule = new ModuleLinksImcs(DatabaseLinksImcs.getInstance());
- schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance());
- featureModule = new ModuleFeature(DatabaseFeature.getInstance());
- imageModule = new ModuleImages(DatabaseImages.getInstance());
- uploadedMediaModule = new ModuleUploadedMedia(DatabaseImages.getInstance());
- } catch(StorageObjectException e) {;}
+ schwerpunktModule = new ModuleSchwerpunkt(DatabaseFeature.getInstance());
+ featureModule = new ModuleFeature(DatabaseFeature.getInstance());
+ imageModule = new ModuleImages(DatabaseImages.getInstance());
+ uploadedMediaModule = new ModuleUploadedMedia(DatabaseImages.getInstance());
+
+ }
+ catch(StorageObjectException e)
+ {
+ System.err.println("*** failed to initialize Producer " + e.toString());
+ }
}
public void handle(PrintWriter htmlout, EntityUsers user)
outputFile.close();
outStream.close();
- printHTML(htmlout, "Produced <a href=\"" + producerProductionHost+ filename + "\">" + filename + "</a>");
+ printHTML(htmlout, "Produced <a href=\"" + producerProductionHost+
+ filename + "\">" + filename + "</a>");
//theLog.printInfo("Produced: " + producerStorageRoot + filename);
- //theLog.printDebugInfo("free mem:" + java.lang.Runtime.getRuntime().freeMemory());
+ //theLog.printDebugInfo("free mem:" + java.lang.Runtime.getRuntime().freeMemory());
//theLog.printDebugInfo("total mem:" + java.lang.Runtime.getRuntime().totalMemory());
return true;
/**
* logging
*/
+
+ public void logHTMLFinish(PrintWriter htmlout,String moduleName, int pageCount, long startTime, long endTime) {
+ // timing and message to browser
+ long overall = endTime - startTime;
+ int pagesPerMinute=0; float perMinute = (float)overall/(float)60000;
+ if (perMinute >0) pagesPerMinute = (int) ((float)pageCount / perMinute);
+
+ logHTML(htmlout, "Producer."+moduleName+" finished producing: " +
+ overall + " ms for "+ pageCount+" Pages = " +pagesPerMinute + " pages/min");
+ logHTML(htmlout, "Back to <a href=\""+actionRoot+"\">Admin-Startage</a>");
+ }
+
public void logHTML(PrintWriter out, String s) {
_print(out, s, true);
}
// handle all
public void handle(PrintWriter htmlout, EntityUsers user, boolean force,boolean sync)
- throws StorageObjectException, ModuleException {
+ {
printHTML(htmlout, "Producer.All: started");
long sessionConnectTime = 0;
long startTime = (new java.util.Date()).getTime();
- new ProducerImages().handle(htmlout, user, force,sync);
- new ProducerStartPage().handle(htmlout, user, force,sync);
- new ProducerContent().handle(htmlout, user, force,sync);
- new ProducerOpenPosting().handle(htmlout, user, force,sync);
- new ProducerTopics().handle(htmlout, user, force,sync);
- new ProducerNavigation().handle(htmlout, user, force,sync);
+
+ try {
+ //new ProducerImages().handle(htmlout, user, force,sync);
+ new ProducerMedia().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.Media continuing "+ e.toString());
+ }
+ try {
+ new ProducerStartPage().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.StartPage continuing "+ e.toString());
+ }
+ try {
+ new ProducerContent().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.Content continuing "+ e.toString());
+ }
+ try {
+ new ProducerOpenPosting().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.OpenPosting continuing "+ e.toString());
+ }
+ try {
+ new ProducerTopics().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.Topics continuing "+ e.toString());
+ }
+ try {
+ new ProducerNavigation().handle(htmlout, user, force,sync);
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.All <font color=\"red\">ERROR:</font>"
+ +" in Producer.Navigation continuing "+ e.toString());
+ }
// Finish
sessionConnectTime = new java.util.Date().getTime() - startTime;
long sessionConnectTime = 0;
long startTime = (new java.util.Date()).getTime();
EntityContent currentContent;
+ HashMap currentContentValues;
//get all new unproduced content-entities
String whereClause="is_produced='0' && to_article_type>0";
while (entityList != null) {
for(int i=0;i<entityList.size();i++) {
currentContent = (EntityContent)entityList.elementAt(i);
+ currentContentValues = currentContent.getValues();
EntityList topicEntityList = DatabaseContentToTopics.getInstance().getTopics(currentContent);
SimpleHash topicHash = HTMLTemplateProcessor.makeSimpleHash(topicEntityList);
import java.io.*;
import java.lang.*;
-import java.lang.reflect.*;
import java.util.*;
import freemarker.template.*;
import mir.misc.*;
-import mir.media.*;
import mir.storage.*;
import mir.module.*;
import mir.entity.*;
public class ProducerContent extends Producer {
- public static void main(String argv[]){
- /**
- * Why are we reloading the config here?
- * Can someone please explain this?
- * Hope I didn't break anything
- * -mh. <heckmann@hbe.ca>
- */
- //Configuration.initConfig("config");
- System.out.println(MirConfig.getProp("Producer.DocRoot"));
-
- try {
- new ProducerContent().handle(new PrintWriter(System.out), null, false,false);
- } catch(Exception e) {
- System.err.println(e.toString());
- }
- }
-
-
-
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
- throws StorageObjectException, ModuleException {
-
- handle(htmlout,user,force,sync,null);
- }
-
-
-
-
-
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync, String id)
- throws StorageObjectException, ModuleException {
-
- String contentTemplate = MirConfig.getProp("Producer.Content.Template");
- int contentBatchsize = Integer.parseInt(MirConfig.getProp("Producer.Content.Batchsize"));
- String extLinkName = MirConfig.getProp("Producer.ExtLinkName");
- String intLinkName = MirConfig.getProp("Producer.IntLinkName");
- String mailLinkName = MirConfig.getProp("Producer.MailLinkName");
- String imageRoot = MirConfig.getProp("Producer.ImageRoot");
-
- long sessionConnectTime = 0;
- long startTime = (new java.util.Date()).getTime();
- String whereClause = " ";
- String orderBy = " ";
- String htmlFileName = null;
- String currentMediaId;
- EntityContent currentContent;
- EntityList batchEntityList;
- SimpleHash imageHash = new SimpleHash();
- EntityUsers userEntity=null;
- Entity mediaType;
- Entity upMedia;
- SimpleHash upMediaSimpleHash;
- Class mediaHandlerClass;
- Class mediaStorageClass;
- String mediaStorageName;
- String mediaHandlerName=null;
- MirMedia mediaHandler=null;
- Database mediaStorage=null;
-
-
-
- // production of the content-pages
- orderBy="date desc, webdb_lastchange desc";
- if(force==true){
- whereClause="is_published='1'";
- // if true: produces a single content item
- if(id !=null){
- whereClause += " AND id="+id;
- }
- batchEntityList = contentModule.getContent(whereClause, orderBy, 0, contentBatchsize, userEntity);
- } else {
- whereClause="is_produced='0' AND is_published='1'";
- //if true produces a single contentitem
- if(id !=null){
- whereClause += " AND id="+id;
- }
- batchEntityList = contentModule.getContent(whereClause, orderBy, 0, contentBatchsize, userEntity);
- }
-
- while (batchEntityList != null) {
- for(int i=0;i<batchEntityList.size();i++) {
- currentContent = (EntityContent)batchEntityList.elementAt(i);
- HashMap currentContentValues = currentContent.getValues();
- String date = (String)currentContent.getValue("date");
- String year = date.substring(0,4);
- String month = date.substring(4,6);
-
- htmlFileName = producerDocRoot
- + "/" + year + "/" + month + "/" + currentContent.getValue("id") + ".shtml";
-
- currentContentValues.put("content_data",StringUtil.deleteForbiddenTags((String)currentContentValues.get("content_data")));
- currentContentValues.put("description",StringUtil.deleteForbiddenTags((String)currentContentValues.get("description")));
-
-
- //create http-links and email-links
- if (currentContentValues.get("is_html").equals("0")) {
- String temp = (String)currentContentValues.get("content_data");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.createHTML(temp,imageRoot,mailLinkName,extLinkName,intLinkName);
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContentValues.put("content_data",temp);
- }
- temp = (String)currentContentValues.get("description");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.createHTML(temp,imageRoot,mailLinkName,extLinkName,intLinkName);
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContentValues.put("description",temp);
- }
- } else {
- String temp = (String)currentContentValues.get("content_data");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContentValues.put("content_data",temp);
- }
- temp = (String)currentContentValues.get("description");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContentValues.put("description",temp);
- }
- }
-
- //create the freemarker-model
- SimpleHash mergeData = HTMLTemplateProcessor.makeSimpleHash(currentContentValues);
-
- // get the uploaded media
- EntityList currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (currentMediaList!=null && currentMediaList.getCount()>=1) {
- SimpleList mediaList = new SimpleList();
- for (int n=0; n < currentMediaList.size();n++) {
- upMedia = currentMediaList.elementAt(n);
- upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
- mediaType = ((EntityMedia)upMedia).getMediaType();
- //in case it's a non-existant to_media_type entry..
- if (mediaType != null) {
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaStorageName = mediaType.getValue("tablename");
- mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- Method m = mediaStorageClass.getMethod("getInstance", null);
- mediaStorage = (Database)m.invoke(null, null);
- //we most likely need further info
- upMedia = mediaStorage.selectById(upMedia.getId());
- } catch (Exception e) {
- theLog.printError("ProducerStartpage:problem in reflection: "+mediaHandlerName);
- } //end catch
- upMediaSimpleHash.put("url", mediaHandler.getURL(upMedia, mediaType));
- upMediaSimpleHash.put("type",mediaType.getValue("classname"));
- mediaList.add(upMediaSimpleHash);
- } //end if media_type != null
- } //end for
- mergeData.put("to_media", mediaList);
- } //end if currentMediaList != null
-
- // get the comments for the article
- // and html-ize them
- SimpleList commentList = currentContent.getComments();
- try{
- if(commentList.isEmpty()==false){
- while(commentList.hasNext()){
- SimpleHash comment = (SimpleHash)commentList.next();
- SimpleScalar commentText = (SimpleScalar)comment.get("description");
- comment.put("description",new SimpleScalar(StringUtil.createHTML(commentText.getAsString(),imageRoot,mailLinkName,extLinkName,intLinkName)));
- }
- }
- } catch(Exception e){}
- mergeData.put("comments", commentList);
-
- // get the topics of this article
- mergeData.put("topics",HTMLTemplateProcessor.makeSimpleList(DatabaseContentToTopics.getInstance().getTopics(currentContent)));
-
- //produce html
- boolean retVal = produce(contentTemplate, htmlFileName, mergeData, htmlout);
- sessionConnectTime = new java.util.Date().getTime() - startTime;
- if (retVal == true && !"1".equals(currentContent.getValue("is_produced")))
- currentContent.setProduced(true);
- }//while
-
- if (batchEntityList.hasNextBatch()){
- batchEntityList = contentModule.getContent(whereClause, orderBy, batchEntityList.getNextBatch(),contentBatchsize, userEntity);
- } else {
- batchEntityList=null;
- }
- }
-
- // timing an message to browser
- sessionConnectTime = new java.util.Date().getTime() - startTime;
- logHTML(htmlout, "Producer.Content finished: " + sessionConnectTime + " ms.");
- }
+ private String contentTemplate=MirConfig.getProp("Producer.Content.Template");
+
+ public static void main(String argv[]){
+ /**
+ * Why are we reloading the config here?
+ * Can someone please explain this?
+ * Hope I didn't break anything
+ * -mh. <heckmann@hbe.ca>
+ *
+ * This is the entry point for standalone production. The code
+ * is then running in a new virtual machine, e.g. when called
+ * from cron-script. In that case the config has to be initliased.
+ * Don't know if is ok that way //rk
+ *
+ * ok, i figured that out a few months ago.. -mh
+ *
+ */
+ //Configuration.initConfig("config");
+ System.out.println(MirConfig.getProp("Producer.DocRoot"));
+
+ try {
+ new ProducerContent().handle(new PrintWriter(System.out), null,
+ false,false);
+ } catch(Exception e) {
+ System.err.println(e.toString());
+ }
+ }
+
+
+
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force,
+ boolean sync)
+ throws StorageObjectException, ModuleException {
+
+ handle(htmlout,user,force,sync,null);
+ }
+
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force,
+ boolean sync, String id) throws StorageObjectException,
+ ModuleException
+ {
+
+ long startTime = System.currentTimeMillis();
+ int pageCount=0;
+
+ String whereClause = " ";
+ String orderBy = " ";
+ String htmlFileName = null;
+ EntityContent currentContent;
+ EntityList batchEntityList;
+ EntityUsers userEntity=null;
+
+ int contentBatchsize =
+ Integer.parseInt(MirConfig.getProp("Producer.Content.Batchsize"));
+ // production of the content-pages
+
+ /** @todo this should be moved to ModuleContent */
+ orderBy="date desc, webdb_lastchange desc";
+ if(force==true){
+ whereClause="is_published='1'";
+ // if true: produces a single content item
+ if(id !=null){
+ whereClause += " AND id="+id;
+ // I think this avoids a select count(*)...
+ contentBatchsize=-1;
+ }
+ batchEntityList = contentModule.getContent(whereClause, orderBy, 0,
+ contentBatchsize, userEntity);
+ } else {
+ whereClause="is_produced='0' AND is_published='1'";
+ //if true produces a single contentitem
+ if(id !=null){
+ whereClause += " AND id="+id;
+ // this avoids a select count(*)...
+ contentBatchsize=-1;
+ }
+ batchEntityList = contentModule.getContent(whereClause, orderBy, 0,
+ contentBatchsize, userEntity);
+ }
+
+ while (batchEntityList!=null) {
+ for(int i=0;i<batchEntityList.size();i++) {
+ currentContent = (EntityContent)batchEntityList.elementAt(i);
+
+ try {
+
+ SimpleHash mergeData=new SimpleHash();
+ mergeData.put("content", currentContent);
+
+ /** @todo this should be assembled in entity */
+ String date = currentContent.getValue("date");
+ String year = date.substring(0,4);
+ String month = date.substring(4,6);
+ htmlFileName = producerDocRoot + "/" + year + "/" + month + "/" +
+ currentContent.getValue("id") + ".shtml";
+
+ //produce html
+ boolean retVal = produce(contentTemplate, htmlFileName, mergeData, htmlout);
+ if ( retVal ) currentContent.setProduced(true);
+
+ }
+ catch(Exception e)
+ {
+ String errorText = "Producer.Content <font color=red>ERROR</font> while producing content ID:"
+ + currentContent.getId()+", skipping it :: "+e.toString();
+ logHTML(htmlout, errorText);
+ theLog.printError(errorText);
+ }
+ pageCount++;
+ }//for
+ // if next batch get it...
+ if (batchEntityList.hasNextBatch()){
+ //batchEntityList = contentModule.getByWhereClause(whereClause,
+ // null, batchEntityList.getNextBatch(),
+ // contentBatchsize);
+ batchEntityList = contentModule.getContent(whereClause, orderBy,
+ batchEntityList.getNextBatch(),
+ contentBatchsize, userEntity);
+ } else {
+ batchEntityList=null;
+ }
+
+ }
+
+
+
+ logHTMLFinish(htmlout, "Content", pageCount, startTime, System.currentTimeMillis());
+
+ /** @todo why no syncing here? */
+
+ }
}
public class ProducerFeature extends ProducerList {
-
- public void setAdditional(String key, TemplateModel value) {
- additional.put(key,value);
- }
-
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
throws StorageObjectException, ModuleException {
orderBy="date desc";
listTemplate = MirConfig.getProp("Producer.FeatureList.Template");
boolean first=true;
whereClause="is_published!=true AND to_article_type=0 AND id IN (";
for(int i=0; i < featureEntityList.size(); i++){
- if(first==false) {
- whereClause += ",";
- }
- EntityTopics currentTopic = (EntityTopics)featureEntityList.elementAt(i);
- EntityList contentEntityList = DatabaseContentToTopics.getInstance().getContent(currentTopic);
- whereClause += currentTopic.getId();
- fileDesc = currentTopic.getValue("filename").trim();
- setAdditional("topic",currentTopic);
+ try {
+ EntityTopics currentTopic = (EntityTopics)featureEntityList.elementAt(i);
+ EntityList contentEntityList = DatabaseContentToTopics.getInstance().getContent(currentTopic);
+ if(first==false) {
+ whereClause += ",";
+ }
+ whereClause += currentTopic.getId();
+ fileDesc = currentTopic.getValue("filename").trim();
+ setAdditional("topic",currentTopic);
+ } catch (Exception e) {
+ logHTML(htmlout, "problem with feature skipping");
+ }
first = false;
}
handleIt(htmlout,user,force);
}
- public static void main(String argv[]){
- try {
- new ProducerOpenPosting().handle(new PrintWriter(System.out), null,false, false);
- } catch(Exception e) {
- System.err.println(e.toString());
- }
- }
-}
\ No newline at end of file
+ public static void main(String argv[]){
+ try {
+ new ProducerOpenPosting().handle(new PrintWriter(System.out), null,false, false);
+ } catch(Exception e) {
+ System.err.println(e.toString());
+ }
+ }
+}
public static void main(String argv[]){
try {
- new ProducerContent().handle(new PrintWriter(System.out), null, false,false);
+ new ProducerContent().handle(new PrintWriter(System.out), null,
+ false,false);
} catch(Exception e) { System.err.println(e.toString()); }
}
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force,
+ boolean sync)
throws StorageObjectException, ModuleException {
handle(htmlout,user,force,sync,null);
}
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync, String id)
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force,
+ boolean sync, String id)
throws StorageObjectException, ModuleException
{
long sessionConnectTime = 0;
String productionPath;
EntityImages currentImage;
EntityList batchEntityList;
+ String orderBy = "date desc, webdb_lastchange desc";
- int contentBatchsize = Integer.parseInt(MirConfig.getProp("Producer.Content.Batchsize"));
- String imageHost = MirConfig.getProp("Producer.Image.Host");
- String imagePath = MirConfig.getProp("Producer.Image.Path");
- String iconPath = MirConfig.getProp("Producer.Image.IconPath");
+ int contentBatchsize = Integer.parseInt(MirConfig.getProp(
+ "Producer.Content.Batchsize"));
+ String imageHost = MirConfig.getProp("Producer.Image.Host");
+ String imagePath = MirConfig.getProp("Producer.Image.Path");
+ String iconPath = MirConfig.getProp("Producer.Image.IconPath");
// get batch of non-produced images, that are to be published
whereClause="is_published='1'";
whereClause += " and id="+id;
if (force==false) whereClause += " and icon_is_produced='0'";
- batchEntityList = imageModule.getByWhereClause(whereClause, null, 0, contentBatchsize);
+ batchEntityList = imageModule.getByWhereClause(whereClause, orderBy, 0,
+ contentBatchsize);
theLog.printDebugInfo("whereclause: " + whereClause);
theLog.printDebugInfo("trying image: " + i);
currentImage = (EntityImages)batchEntityList.elementAt(i);
+ try {
// make filenames
String date = currentImage.getValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
- iconFilename = producerDocRoot + iconPath + StringUtil.webdbDate2path(date) +
- currentImage.getId() + (( currentImage.getValue("to_img_type").equals("0") ) ? ".jpg":".gif");
+ iconFilename=producerDocRoot + iconPath + datePath +
+ currentImage.getId() +
+ ((currentImage.getValue("to_img_type").equals("0"))
+ ? ".jpg":".gif");
- imageFilename = currentImage.getId() + (( currentImage.getValue("to_img_type").equals("0") ) ? ".jpg":".gif");
+ imageFilename=datePath + currentImage.getId() +
+ ((currentImage.getValue("to_img_type").equals("0"))
+ ? ".jpg":".gif");
productionPath = imagePath + "/" + imageFilename ;
currentImage.setValueForProperty("icon_path",iconFilename);
- //currentImage.setValueForProperty("publish_path","imc/germany/" + imageFilename);
- currentImage.setValueForProperty("publish_path",imageFilename);
+ currentImage.setValueForProperty("publish_path",imageFilename);
currentImage.setValueForProperty("publish_server", imageHost);
- if (currentImage.getValue("icon_data")!= null && currentImage.getValue("image_data")!= null) {
+ if (currentImage.getValue("icon_data")!= null &&
+ currentImage.getValue("image_data")!= null) {
// make icon
- boolean iconProduced = produceFile(iconFilename, currentImage.getIcon(), htmlout, true);
- logHTML(htmlout,"icon : " + iconFilename + (( iconProduced==true )? " succeded":" <font color=\"Red\" failed!</font>"));
+ boolean iconProduced = produceFile(iconFilename,
+ currentImage.getIcon(),
+ htmlout, true);
+ logHTML(htmlout,"icon : "+iconFilename+((
+ iconProduced==true )?
+ " succeded":" <font color=\"Red\" failed!</font>"));
// make image
- boolean imageProduced = produceFile(productionPath, currentImage.getImage(), htmlout, false);
- logHTML(htmlout,"image: " + productionPath + ((imageProduced==true)?" succeded":" <font color=\"Red\" failed!</font>"));
+ boolean imageProduced = produceFile(productionPath,
+ currentImage.getImage(),
+ htmlout, false);
+ logHTML(htmlout,"image: "+productionPath +
+ ((imageProduced==true)?
+ " succeded":" <font color=\"Red\" failed!</font>"));
// update image-data
if (iconProduced && imageProduced) {
- currentImage.setValueForProperty("icon_is_produced", "1");
+ currentImage.setValueForProperty("icon_is_produced",
+ "1");
currentImage.update();
}
}
- }
+ } catch (Exception e) {
+ logHTML(htmlout, "Producer.Images ERROR with: image ID "+
+ currentImage.getId() +
+ " <font color=\"Red\"> failed!</font>");
+ }
+ }//end for
// if next batch get it...
if (batchEntityList.hasNextBatch()){
- batchEntityList = imageModule.getByWhereClause(whereClause, null, batchEntityList.getNextBatch(),contentBatchsize);
+ batchEntityList = imageModule.getByWhereClause(whereClause,
+ orderBy, batchEntityList.getNextBatch(),
+ contentBatchsize);
} else {
batchEntityList=null;
}
}
// Finish
sessionConnectTime = new java.util.Date().getTime() - startTime;
- logHTML(htmlout, "Producer.Images finished: " + sessionConnectTime + " ms.");
+ logHTML(htmlout, "Producer.Images finished: " + sessionConnectTime +
+ " ms.");
}
-}
\ No newline at end of file
+}
public String orderBy;
public String fileDesc;
protected HashMap additional = new HashMap();
- Entity mediaType;
- Entity upMedia;
- SimpleHash upMediaSimpleHash;
- Class mediaHandlerClass;
- Class mediaStorageClass;
- String mediaStorageName;
- String mediaHandlerName=null;
- MirMedia mediaHandler=null;
- Database mediaStorage=null;
handleIt(htmlout,user,force);
}
+ /** @todo this should return the number of pages produced! */
public void handleIt(PrintWriter htmlout, EntityUsers user, boolean force)
throws StorageObjectException, ModuleException {
//now produce the pages
if (list!=null || force==true) {
SimpleHash mergeData = HTMLTemplateProcessor.makeSimpleHashWithEntitylistInfos(list);
- //first we try to get the images
-
- if(list!=null){
- for (int k=0; k < list.size();k++) {
- currentContent = (EntityContent)list.elementAt(k);
- //images to content
- EntityList currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (currentMediaList!=null && currentMediaList.getCount()>=1) {
- SimpleList mediaListAudio = new SimpleList();
- SimpleList mediaListImages = new SimpleList();
- SimpleList mediaListVideo = new SimpleList();
- SimpleList mediaListOther = new SimpleList();
- //SimpleHash allMediaSimpleHash = new SimpleHash();
- for (int n=0; n < currentMediaList.size();n++) {
- upMedia = currentMediaList.elementAt(n);
- upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
- mediaType = ((EntityMedia)upMedia).getMediaType();
- //must be a non-existant to_media_type entry..
- if (mediaType != null) {
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaStorageName = mediaType.getValue("tablename");
- mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- Method m = mediaStorageClass.getMethod("getInstance", null);
- mediaStorage = (Database)m.invoke(null, null);
- //we most likely need further info
- upMedia = mediaStorage.selectById(upMedia.getId());
- } catch (Exception e) {
- theLog.printError("ProducerList: problem in reflection: "+mediaHandlerName);
- } //end catch
- upMediaSimpleHash.put("url", mediaHandler.getListView(upMedia, mediaType));
- if (upMedia.getValue("is_published") == "1") {
- if (mediaHandler.isImage()) {
- mediaListImages.add(upMediaSimpleHash);
- } else if (mediaHandler.isAudio()) {
- mediaListAudio.add(upMediaSimpleHash);
- } else if (mediaHandler.isVideo()) {
- mediaListVideo.add(upMediaSimpleHash);
- } else {
- mediaListOther.add(upMediaSimpleHash);
- }
- } //end if is_published
- } //end if media_type != null
- } //end for
- try{
- SimpleList contentList = (SimpleList)mergeData.get("contentlist");
- SimpleHash contentHash = (SimpleHash)contentList.get(k);
- contentHash.put("to_media_audio", mediaListAudio);
- contentHash.put("to_media_images", mediaListImages);
- contentHash.put("to_media_video", mediaListVideo);
- contentHash.put("to_media_other", mediaListOther);
- } catch (Exception e){}
- } //end if currentMediaList != null
-
- //content to html
- if(currentContent.getValue("is_html").equals("0")){
- String temp = (String)currentContent.getValue("description");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.createHTML(temp);
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContent.setValueForProperty("description",temp);
- }
- } else {
- String temp = (String)currentContent.getValue("description");
- if(temp!=null && temp.length()>0){
- temp = StringUtil.decodeHTMLinTags(temp);
- currentContent.setValueForProperty("description",temp);
- }
- }
- }
- }
- SimpleList itemList = HTMLTemplateProcessor.makeSimpleList(list);
//process hashmap additional and add to mergedata
if (additional != null) {
Set set = additional.keySet();
logHTML(htmlout, "Producer.List finished: " + sessionConnectTime + " ms.");
} //end handle
- abstract public void setAdditional(String key, TemplateModel value);
+ public void setAdditional(String key, TemplateModel value) {
+ additional.put(key,value);
+ }
+
}
import mir.entity.*;
import mir.media.*;
+import mircoders.media.*;
import mircoders.entity.*;
import mircoders.storage.*;
import mir.storage.*;
boolean mediaProduced = false;
String whereClause;
String mediaHost;
+ String id2=null;
String iconPath;
String mediaPath;
String iconFilename;
Entity currentMedia;
EntityList batchEntityList;
- int contentBatchsize = Integer.parseInt(MirConfig.getProp("Producer.Content.Batchsize"));
+ int contentBatchsize = Integer.parseInt(MirConfig.getProp("Producer.Content.Batchsize"));
// get batch of non-produced medias, that are to be published
whereClause="is_published='1'";
Entity currentMediaType = DatabaseUploadedMedia.getInstance().getMediaType(currentMedia);
String mediaHandlerName = currentMediaType.getValue("classname");
- Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- MirMedia currentMediaHandler = (MirMedia)mediaHandlerClass.newInstance();
-
+ Class mediaHandlerClass = Class.forName("mircoders.media.MediaHandler"+mediaHandlerName);
+ MirMedia currentMediaHandler = (MirMedia)mediaHandlerClass.newInstance();
+
String date = currentMedia.getValue("date");
String datePath = StringUtil.webdbDate2path(date);
// do icon
- if (currentMedia.getValue("icon_is_produced") != "1") {
+ if (!currentMedia.getValue("icon_is_produced").equals("1")) {
iconPath = currentMediaHandler.getIconStoragePath();
iconFilename = producerDocRoot+iconPath+datePath+
currentMedia.getId()+"."+currentMediaType.getValue("name");
iconProduced = produceFile(iconFilename, currentMediaHandler.getIcon(currentMedia), htmlout, true);
if(iconProduced) {
currentMedia.setValueForProperty("icon_path",iconFilename);
- logHTML(htmlout,"icon : " + iconFilename + (( iconProduced==true )? " succeded":" <font color=\"Red\" failed!</font>"));
+ logHTML(htmlout,"icon : " + iconFilename + (( iconProduced==true )? " succeded":" <font color=\"Red\"> failed!</font>"));
}
} else {
iconProduced = true;
}
-
+
//now produce the media content
mediaHost = currentMediaHandler.getPublishHost();
mediaPath = currentMediaHandler.getStoragePath();
+ id2 = currentMedia.getId();
mediaFilename = currentMedia.getId()+"."+currentMediaType.getValue("name");
//hack: make this a config option. -mh
- //productionPath = mediaPath+datePath+"/"+ mediaFilename ;
- productionPath = mediaPath+"/"+mediaFilename ;
+ productionPath = mediaPath+datePath+"/"+ mediaFilename ;
+ //productionPath = mediaPath+"/"+mediaFilename ;
//hack: see above. -mh.
- //currentMedia.setValueForProperty("publish_path",datePath+"/"+mediaFilename);
- currentMedia.setValueForProperty("publish_path",mediaFilename);
+ currentMedia.setValueForProperty("publish_path",datePath+"/"+mediaFilename);
+ //currentMedia.setValueForProperty("publish_path",mediaFilename);
currentMedia.setValueForProperty("publish_server", mediaHost);
+ theLog.printError("ABOUT OT FILE"+id2);
mediaProduced = produceFile(productionPath, currentMediaHandler.get(currentMedia, currentMediaType), htmlout, false);
- logHTML(htmlout,"media: " + productionPath + ((mediaProduced==true)?" succeded":" <font color=\"Red\" failed!</font>"));
+ logHTML(htmlout,"media: " + productionPath + ((mediaProduced==true)?" succeded":" <font color=\"Red\"> failed!</font>"));
// update media-data
if (iconProduced && mediaProduced) {
currentMedia.setValueForProperty("is_produced", "1");
currentMedia.update();
}
-
+ } catch (MirMediaException e) {
+ theLog.printError("media exception: "+id+e.toString());
+ logHTML(htmlout, "problem with media id: "
+ +id+" <font color=\"Red\"> failed!</font>: "
+ +e.toString());
} catch (Exception e) {
- theLog.printError("failed in reflection: "+e);
+ theLog.printError("failed in reflection: "+id+e.toString());
+ logHTML(htmlout, "reflection problem in media id: "
+ +id+" <font color=\"Red\"> failed!</font>: "
+ +e.toString());
}
}
public void handle(PrintWriter htmlout, EntityUsers user, boolean forced, boolean sync)
throws mir.module.ModuleException, mir.storage.StorageObjectException {
- printHTML(htmlout, "Producer.Navigation: started");
+ printHTML(htmlout, "Producer.Navigation: started");
long sessionConnectTime = 0;
long startTime = (new java.util.Date()).getTime();
EntityList entityList;
SimpleHash naviPageModel;
- // get the topiclist
- entityList = topicsModule.getByWhereClause("","title",-1);
- SimpleList topicList = HTMLTemplateProcessor.makeSimpleList(entityList);
+ // get the imclinks
+ entityList = linksImcsModule.getByWhereClause("", "sortpriority, title", -1);
+ SimpleList imcList = HTMLTemplateProcessor.makeSimpleList(entityList);
- // get the imclinks
- entityList = linksImcsModule.getByWhereClause("", "sortpriority, title", -1);
- SimpleList imcList = HTMLTemplateProcessor.makeSimpleList(entityList);
-
- EntityList theParentList = linksImcsModule.getByWhereClause("to_parent_id=NULL", "sortpriority, title", -1);
- SimpleList parentList = HTMLTemplateProcessor.makeSimpleList(theParentList);
+ EntityList theParentList = linksImcsModule.getByWhereClause("to_parent_id=NULL", "sortpriority, title", -1);
+ SimpleList parentList = HTMLTemplateProcessor.makeSimpleList(theParentList);
// put the informations into the navipagemodel
naviPageModel = new SimpleHash();
- naviPageModel.put("topics", topicList);
- naviPageModel.put("imclist", imcList);
- naviPageModel.put("parentlist", parentList);
+ naviPageModel.put("topics", topicsModule.getTopicsList());
+ naviPageModel.put("imclist", imcList);
+ naviPageModel.put("parentlist", parentList);
htmlFileName = producerDocRoot + "/navigation.inc";
}
}
-}
\ No newline at end of file
+}
public class ProducerOpenPosting extends ProducerList {
- public void setAdditional(String key, TemplateModel value) {
- additional.put(key,value);
- }
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
- throws StorageObjectException, ModuleException {
+ public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
+ throws StorageObjectException, ModuleException
+ {
listTemplate = MirConfig.getProp("Producer.OpenPosting.Template");
whereClause="is_published='1'";
orderBy="date desc, webdb_create desc";
fileDesc="open";
- EntityList topicsEntityList = topicsModule.getByWhereClause("","title", -1);
- SimpleList topicsList = HTMLTemplateProcessor.makeSimpleList(topicsEntityList);
- SimpleScalar title = new SimpleScalar();
- title.setValue("Open-Posting");
- setAdditional("topicslist",topicsList);
- setAdditional("title",title);
-
+ setAdditional("topicslist",topicsModule.getTopicsList());
+ setAdditional("title",new SimpleScalar("Open-Posting"));
handleIt(htmlout,user,force);
}
- public static void main(String argv[]){
- try {
- new ProducerOpenPosting().handle(new PrintWriter(System.out), null,false, false);
- } catch(Exception e) {
- System.err.println(e.toString());
- }
- }
-}
\ No newline at end of file
+
+ public static void main(String argv[]){
+ try {
+ new ProducerOpenPosting().handle(new PrintWriter(System.out), null,false, false);
+ } catch(Exception e) {
+ System.err.println(e.toString());
+ }
+ }
+
+}
package mircoders.producer;
import java.io.*;
-import java.lang.*;
-import java.lang.reflect.*;
import java.util.*;
import freemarker.template.*;
+import mir.entity.*;
import mir.misc.*;
-import mir.media.*;
-import mir.storage.*;
import mir.module.*;
-import mir.entity.*;
-
+import mir.storage.*;
import mircoders.module.*;
import mircoders.storage.*;
import mircoders.entity.*;
private static String startPageTemplate = MirConfig.getProp("Producer.StartPage.Template");
private static int itemsPerPage = Integer.parseInt(MirConfig.getProp("Producer.StartPage.Items"));
private static int newsPerPage = Integer.parseInt(MirConfig.getProp("Producer.StartPage.Newswire"));
- Entity mediaType;
- Entity upMedia;
- SimpleHash upMediaSimpleHash;
- Class mediaHandlerClass;
- Class mediaStorageClass;
- String mediaStorageName;
-
-
public static void main(String argv[]){
try {
public void handle(PrintWriter htmlout, EntityUsers user, boolean force,boolean sync)
throws StorageObjectException, ModuleException
{
+ long startTime = System.currentTimeMillis();
printHTML(htmlout, "Producer.StartPage: started");
+ SimpleHash startPageModel = new SimpleHash();
- String extLinkName = MirConfig.getProp("Producer.ExtLinkName");
- String intLinkName = MirConfig.getProp("Producer.IntLinkName");
- String mailLinkName = MirConfig.getProp("Producer.MailLinkName");
- String imageRoot = MirConfig.getProp("Producer.ImageRoot");
-
- long sessionConnectTime = 0;
- long startTime = (new java.util.Date()).getTime();
- String nowWebdbDate = StringUtil.date2webdbDate(new GregorianCalendar());
- String whereClause;
- String orderBy;
- FileWriter outputFile;
- String htmlFileName;
- EntityContent currentContent;
- EntityList entityList;
- SimpleHash startPageModel;
- SimpleList contentList;
- String currentMediaId;
- EntityList upMediaEntityList;
- EntityList imageEntityList;
- EntityList currentMediaList;
- Entity mediaType;
- EntityMedia uploadedMedia;
- Class mediaHandlerClass=null;
- MirMedia mediaHandler=null;
- String mediaHandlerName=null;
- Database mediaStorage=null;
- String tinyIcon;
- String iconAlt;
- Logfile theLog = Logfile.getInstance(this.getClass().getName());
-
- SimpleList mediaList;
- SimpleHash contentHash;
-
- // get the topiclist
- entityList = topicsModule.getByWhereClause("","title",-1);
- SimpleList topicList = HTMLTemplateProcessor.makeSimpleList(entityList);
-
- // get the imclinks
- entityList = linksImcsModule.getByWhereClause("", "sortpriority, title", -1);
- SimpleList imcList = HTMLTemplateProcessor.makeSimpleList(entityList);
-
- EntityList theParentList = linksImcsModule.getByWhereClause("to_parent_id=NULL", "sortpriority, title", -1);
- SimpleList parentList = HTMLTemplateProcessor.makeSimpleList(theParentList);
-
- // get the newswire
- whereClause="is_published=true AND to_article_type = 1";
- entityList = contentModule.getContent(whereClause,"date desc, webdb_create desc",0,newsPerPage);
- SimpleList newsWireList = HTMLTemplateProcessor.makeSimpleList(entityList);
- for (int i=0; i < entityList.size();i++) {
- currentContent = (EntityContent)entityList.elementAt(i);
- //fetching/setting the images
- upMediaEntityList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
- tinyIcon = null;
- iconAlt = null;
- mediaHandler = null;
- mediaHandlerName = null;
- for (int n=0; n < upMediaEntityList.size();n++) {
- uploadedMedia = (EntityMedia)upMediaEntityList.elementAt(n);
- mediaType = uploadedMedia.getMediaType();
-
- //must of had a non-existant to_media_type entry..
- //let's save our ass.
- if (mediaType != null) {
- /*
- * grrr. why doesn't getId return an int! if It
- * did I could just compare the value of getId and
- * pick the biggest one. or is there
- * another way around this that I am missing?
- * can we make getIdasInt() or can we just have
- * another getId() that returns an Int and the VM
- * will handle it transparantly? -mh
- */
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- } catch (Exception e) {
- theLog.printError("ProducerStartpage:problem in reflection: "+mediaHandlerName);
- }
-
- //the "best" media type to show
- if (mediaHandler.isVideo()) {
- tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
- iconAlt = "Video";
- break;
- } else if (mediaHandler.isAudio()) {
- tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
- iconAlt = "Audio";
- } else if (tinyIcon == null && !mediaHandler.isImage()) {
- tinyIcon = mediaHandler.getTinyIcon();
- iconAlt = mediaHandler.getIconAlt();
- }
- }
- }
- //it only has image(s)
- if (tinyIcon == null) {
- tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
- iconAlt = "Image";
- }
-
- // uploadedMedia Entity list is empty.
- // we only have text
- } else {
- tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
- iconAlt = "Text";
- }
-
- try{
- //mediaList = HTMLTemplateProcessor.makeSimpleList(upMediaEntityList);
- contentHash = (SimpleHash)newsWireList.get(i);
- contentHash.put("tiny_icon", imageRoot+"/"+tinyIcon);
- contentHash.put("icon_alt", iconAlt);
- } catch (Exception e){}
- }
-
- // get the startarticle and the related images
- whereClause="is_published=true AND to_article_type=4";
- entityList = contentModule.getContent(whereClause,"date desc, webdb_create desc",0,1);
- //if no startspecial exists
- if (entityList==null || entityList.size()==0){
- whereClause="is_published=true AND to_article_type=3";
- entityList = contentModule.getContent(whereClause,"date desc, webdb_create desc",0,1);
- }
- SimpleList startItemList = HTMLTemplateProcessor.makeSimpleList(entityList);
- for (int k=0; k < entityList.size();k++) {
- currentContent = (EntityContent)entityList.elementAt(k);
- //media to content
- currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (currentMediaList!=null && currentMediaList.getCount()>=1) {
- SimpleList mediaListAudio = new SimpleList();
- SimpleList mediaListImages = new SimpleList();
- SimpleList mediaListVideo = new SimpleList();
- SimpleList mediaListOther = new SimpleList();
- for (int n=0; n < currentMediaList.size();n++) {
- upMedia = currentMediaList.elementAt(n);
- upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
- mediaType = ((EntityMedia)upMedia).getMediaType();
- //must be a non-existant to_media_type entry..
- if (mediaType != null) {
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaStorageName = mediaType.getValue("tablename");
- mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- Method m = mediaStorageClass.getMethod("getInstance", null);
- mediaStorage = (Database)m.invoke(null, null);
- //we most likely need further info
- upMedia = mediaStorage.selectById(upMedia.getId());
- } catch (Exception e) {
- theLog.printError("ProducerList: problem in reflection: "+mediaHandlerName);
- } //end catch
- upMediaSimpleHash.put("url", mediaHandler.getListView(upMedia, mediaType));
- if (upMedia.getValue("is_published") == "1") {
- if (mediaHandler.isImage()) {
- mediaListImages.add(upMediaSimpleHash);
- } else if (mediaHandler.isAudio()) {
- mediaListAudio.add(upMediaSimpleHash);
- } else if (mediaHandler.isVideo()) {
- mediaListVideo.add(upMediaSimpleHash);
- } else {
- mediaListOther.add(upMediaSimpleHash);
- }
- } //end if is_published
- } //end if media_type != null
- } //end for
- try{
- contentHash = (SimpleHash)startItemList.get(k);
- contentHash.put("to_media_audio", mediaListAudio);
- contentHash.put("to_media_images", mediaListImages);
- contentHash.put("to_media_video", mediaListVideo);
- contentHash.put("to_media_other", mediaListOther);
- } catch (Exception e){}
- } //end if currentMediaList != null
- } //enf for featurueList.size..
-
- // get the breaking news
- // only the first 5
- // todo: the number of breaking_news items have to be configurable
+ // breaking news
ModuleBreaking breakingModule = new ModuleBreaking(DatabaseBreaking.getInstance());
- entityList = breakingModule.getByWhereClause(null,"webdb_create desc",0,5);
- SimpleList breakingList = HTMLTemplateProcessor.makeSimpleList(entityList);
-
- // get the articles
- whereClause="is_published=true AND to_article_type=2";
- orderBy="date desc, webdb_create desc";
- entityList = contentModule.getContent(whereClause, orderBy, 0, itemsPerPage);
- SimpleList featureList = HTMLTemplateProcessor.makeSimpleList(entityList);
- for (int k=0; k < entityList.size();k++) {
- currentContent = (EntityContent)entityList.elementAt(k);
- //media to content
- currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (currentMediaList!=null && currentMediaList.getCount()>=1) {
- SimpleList mediaListAudio = new SimpleList();
- SimpleList mediaListImages = new SimpleList();
- SimpleList mediaListVideo = new SimpleList();
- SimpleList mediaListOther = new SimpleList();
- for (int n=0; n < currentMediaList.size();n++) {
- upMedia = currentMediaList.elementAt(n);
- upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
- mediaType = ((EntityMedia)upMedia).getMediaType();
- //must be a non-existant to_media_type entry..
- if (mediaType != null) {
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaStorageName = mediaType.getValue("tablename");
- mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- Method m = mediaStorageClass.getMethod("getInstance", null);
- mediaStorage = (Database)m.invoke(null, null);
- //we most likely need further info
- upMedia = mediaStorage.selectById(upMedia.getId());
- } catch (Exception e) {
- theLog.printError("ProducerList: problem in reflection: "+mediaHandlerName);
- } //end catch
- upMediaSimpleHash.put("url", mediaHandler.getListView(upMedia, mediaType));
-
- // he marc, shouldn't this be .equals("1") ?
- if (upMedia.getValue("is_published") == "1") {
- if (mediaHandler.isImage()) {
- mediaListImages.add(upMediaSimpleHash);
- } else if (mediaHandler.isAudio()) {
- mediaListAudio.add(upMediaSimpleHash);
- } else if (mediaHandler.isVideo()) {
- mediaListVideo.add(upMediaSimpleHash);
- } else {
- mediaListOther.add(upMediaSimpleHash);
- }
- } //end if is_published
- } //end if media_type != null
- } //end for
- try{
- contentHash = (SimpleHash)featureList.get(k);
- contentHash.put("to_media_audio", mediaListAudio);
- contentHash.put("to_media_images", mediaListImages);
- contentHash.put("to_media_video", mediaListVideo);
- contentHash.put("to_media_other", mediaListOther);
- } catch (Exception e){}
- } //end if currentMediaList != null
- } //enf for featurueList.size..
-
- // Zusaetzlich Informationen
- startPageModel = new SimpleHash();
- startPageModel.put("breakingnews", breakingList);
- startPageModel.put("topics", topicList);
- startPageModel.put("imclist", imcList);
- startPageModel.put("parentlist", parentList);
- startPageModel.put("newswire", newsWireList);
- startPageModel.put("startspecial", startItemList);
- startPageModel.put("features", featureList);
+ startPageModel.put("breakingnews", breakingModule.getBreakingNews());
+ startPageModel.put("topics", topicsModule.getTopicsList());
+ startPageModel.put("newswire", contentModule.getNewsWire(0,newsPerPage));
+ startPageModel.put("startspecial", contentModule.getStartArticle());
+ startPageModel.put("features", contentModule.getFeatures(0,itemsPerPage));
- htmlFileName = producerDocRoot + "/index.shtml";
+ /** @todo switch to compressed */
+ produce(startPageTemplate, producerDocRoot + "/index.shtml", startPageModel, htmlout);
- produce(startPageTemplate, htmlFileName, startPageModel, htmlout);
+ // finished
+ logHTMLFinish(htmlout, "Startpage", 1, startTime, System.currentTimeMillis());
- // Finish
- sessionConnectTime = new java.util.Date().getTime() - startTime;
- logHTML(htmlout, "Producer.Startseite finished: " + sessionConnectTime + " ms.");
if(sync==true){
+ logHTML(htmlout, "Producer.Startpage: rsyncing...");
Helper.rsync();
- logHTML(htmlout, "Producer.Startseite: rsync done");
+ logHTML(htmlout, "Producer.Startpage: rsync done");
}
}
}
String tinyIcon;
String iconAlt;
- public void setAdditional(String key, TemplateModel value) {
- additional.put(key,value);
- }
-
public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync, String id)
throws StorageObjectException, ModuleException {
where=id;
}
public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
- throws StorageObjectException, ModuleException {
+ throws StorageObjectException, ModuleException
+ {
+ long startTime = System.currentTimeMillis();
+ int pageCount =0;
+ logHTML(htmlout, "Producer.Topics: started");
- orderBy="date desc, webdb_create desc";
+ /** @todo should be done in static */
listTemplate = MirConfig.getProp("Producer.TopicList.Template");
+ orderBy="date desc, webdb_create desc";
EntityList topicsEntityList;
if(where==null){
topicsEntityList = topicsModule.getByWhereClause("","title", -1);
} else {
topicsEntityList = topicsModule.getByWhereClause(where,"title", -1);
}
- SimpleList topicsList = HTMLTemplateProcessor.makeSimpleList(topicsEntityList);
for(int i=0; i < topicsEntityList.size(); i++){
EntityTopics currentTopic = (EntityTopics)topicsEntityList.elementAt(i);
+
+ try {
EntityList contentEntityList = DatabaseContentToTopics.getInstance().getContent(currentTopic);
String whereClauseSpecial=null;
EntityContent currentContent;
if(entityList != null && entityList.size()==1){
currentContent = (EntityContent)entityList.elementAt(0);
- SimpleHash specialHash = HTMLTemplateProcessor.makeSimpleHash(currentContent);
-
- currentMediaList = DatabaseContentToMedia.getInstance().getUploadedMedia(currentContent);
- if (currentMediaList!=null && currentMediaList.getCount()>=1) {
- SimpleList mediaListAudio = new SimpleList();
- SimpleList mediaListImages = new SimpleList();
- SimpleList mediaListVideo = new SimpleList();
- SimpleList mediaListOther = new SimpleList();
- for (int n=0; n < currentMediaList.size();n++) {
- upMedia = currentMediaList.elementAt(n);
- upMediaSimpleHash = HTMLTemplateProcessor.makeSimpleHash(upMedia);
- mediaType = ((EntityMedia)upMedia).getMediaType();
- //must be a non-existant to_media_type entry..
- if (mediaType != null) {
- try {
- mediaHandlerName = mediaType.getValue("classname");
- mediaStorageName = mediaType.getValue("tablename");
- mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- Method m = mediaStorageClass.getMethod("getInstance", null);
- mediaStorage = (Database)m.invoke(null, null);
- //we most likely need further info
- upMedia = mediaStorage.selectById(upMedia.getId());
- } catch (Exception e) {
- theLog.printError("ProducerList: problem in reflection: "+mediaHandlerName);
- } //end catch
- upMediaSimpleHash.put("url", mediaHandler.getListView(upMedia, mediaType));
- if (upMedia.getValue("is_published") == "1") {
- if (mediaHandler.isImage()) {
- mediaListImages.add(upMediaSimpleHash);
- } else if (mediaHandler.isAudio()) {
- mediaListAudio.add(upMediaSimpleHash);
- } else if (mediaHandler.isVideo()) {
- mediaListVideo.add(upMediaSimpleHash);
- } else {
- mediaListOther.add(upMediaSimpleHash);
- }
- } //end if is_published
- } //end if media_type != null
- } //end for
- try{
- specialHash.put("to_media_audio", mediaListAudio);
- specialHash.put("to_media_images", mediaListImages);
- specialHash.put("to_media_video", mediaListVideo);
- specialHash.put("to_media_other", mediaListOther);
- } catch (Exception e){}
- } //end if currentMediaList != null
- setAdditional("special",specialHash);
+ try {
+ setAdditional("special",currentContent);
+ } catch (Exception e) {
+ theLog.printError("ProducerTopics: problem with start special media: "+currentContent.getId()+" "+e.toString()+" <font color=\"red\">skipping</font>");
+ logHTML(htmlout,"ProducerTopics: problem with start special media: "+currentContent.getId()+" "+e.toString());
+ }
}
//set the list of topics
- setAdditional("topicslist",topicsList);
+ setAdditional("topicslist",topicsEntityList);
handleIt(htmlout,user,force);
+ pageCount++;
+ }
+ } catch (Exception e) {
+ theLog.printError("ProducerTopics: problem with start special media: "
+ +e.toString()+" <font color=\"red\">skipping</font>");
+ logHTML(htmlout,"ProducerTopics: problem with topic id: "
+ +currentTopic.getId()+ "<font color=\"red\">skipping</font>");
}
}
+ logHTMLFinish(htmlout, "Topics", pageCount, startTime, System.currentTimeMillis());
}
public static void main(String argv[]){
+++ /dev/null
-package mircoders.producer;
-
-import java.io.*;
-import java.lang.*;
-import java.util.*;
-
-import freemarker.template.*;
-
-import mir.misc.*;
-import mir.storage.*;
-import mir.module.*;
-import mir.entity.*;
-
-import mircoders.module.*;
-import mircoders.storage.*;
-import mircoders.entity.*;
-
-
-public class ProducerWap extends Producer {
-
- static String wapTemplate;
- static int itemsPerPage;
- static int newsPerPage;
-
- // Initialierung
- static {
- wapTemplate = MirConfig.getProp("Producer.Wap.Template");
- itemsPerPage = Integer.parseInt(MirConfig.getProp("Producer.Wap.Items"));
- }
-
- public static void main(String argv[]){
- try {
- // do we need the following? -mh <heckmann@hbe.ca>
- //Configuration.initConfig(argv[0]);
- new ProducerWap().handle(new PrintWriter(System.out), null);
- } catch(Exception e) {
- System.err.println(e.toString());
- }
- }
-
- public void handle(PrintWriter htmlout, EntityUsers user, boolean force, boolean sync)
- throws StorageObjectException, ModuleException
- {
- printHTML(htmlout, "Producer.StartPage: started");
-
- long sessionConnectTime = 0;
- long startTime = (new java.util.Date()).getTime();
- String nowWebdbDate = StringUtil.date2webdbDate(new GregorianCalendar());
- String whereClause;
- String orderBy;
- FileWriter outputFile;
- String xmlFileName;
- String wmlFileName;
- EntityContent currentContent;
- EntityList entityList;
- SimpleHash wapPageModel;
- SimpleList contentList;
- String currentMediaId;
- SimpleHash imageHash = new SimpleHash();
-
-
- // get the breaking news
- // only the first 5
- ModuleBreaking breakingModule = new ModuleBreaking(DatabaseBreaking.getInstance());
- entityList = breakingModule.getByWhereClause(null,"webdb_create desc",0,itemsPerPage);
- SimpleList breakingList = HTMLTemplateProcessor.makeSimpleList(entityList);
-
-
-
- // Zusaetzlich Informationen
- wapPageModel = new SimpleHash();
- wapPageModel.put("breaking", breakingList);
-
- xmlFileName = producerDocRoot + "/wap/index.xml";
- wmlFileName = producerDocRoot + "/wap/index.wml";
-
- produce(wapTemplate, xmlFileName, wapPageModel, new LineFilterWriter(htmlout));
-
- XmlSaxonStyler styler = XmlSaxonStyler.getInstance();
- // clear XSL-Cache
- // XslStyleCache.clear();
-
- try {
- InputStream is = new FileInputStream(producerStorageRoot+xmlFileName);
- OutputStream os = new FileOutputStream(producerStorageRoot+wmlFileName);
- String contentXsl = MirConfig.getProp("Home") + "templates/" + MirConfig.getProp("Xsl.Wap");
- logHTML(htmlout,"using style " + contentXsl);
- styler.style(contentXsl,is,os);
- is.close();
- os.close();
- logHTML(htmlout,"styling done.");
- logHTML(htmlout, "html erstellt: <a href=\"" + producerProductionHost+ wmlFileName + "\">" + wmlFileName + "</a>");
- } catch (FileNotFoundException e) {
- System.err.println(e.toString());
- } catch (IOException e) {
- System.err.println(e.toString());
- } catch (org.xml.sax.SAXException e) {
- logHTML(htmlout,e.toString());
- System.err.println(e.toString());
- }
-
- // Finish
- sessionConnectTime = new java.util.Date().getTime() - startTime;
- logHTML(htmlout, "Producer.Startseite finished: " + sessionConnectTime + " ms.");
- }
-}
-
private ServletModuleBreaking() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Breaking.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Breaking.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Breaking.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Breaking.ConfirmTemplate");
catch (IOException e) {throw new ServletModuleException(e.toString());}
catch (Exception e) {throw new ServletModuleException(e.toString());}
}
-
-
-
- // test: deriving entity from freemarker.template.TemplateHashModel
- //////////////////////////////////////////////////////////////////////////////
-
- public void edit(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleException {
- try {
- theLog.printDebugInfo("getting a breaking news");
- String idParam = req.getParameter("id");
- deliver(req, res, (TemplateModelRoot)mainModule.getById(idParam), templateObjektString);
- } catch(ModuleException e) {
- throw new ServletModuleException(e.toString());
- }
- }
}
public static ServletModule getInstance() { return instance; }
private ServletModuleComment() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Comment.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Comment.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Comment.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Comment.ConfirmTemplate");
if (query_text!=null || query_is_published!=null ) {
EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue());
- if (theList!=null) {
+ if (theList!=null && theList.size()>0) {
//make articleHash for comment
StringBuffer buf= new StringBuffer("id in (");boolean first=true;
private ServletModuleContent() {
try {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Content.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Content.ListTemplate");
templateOpString = MirConfig.getProp("ServletModule.Content.OpTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Content.ObjektTemplate");
mergeData.put("is_published", "1");
String now = StringUtil.date2webdbDate(new GregorianCalendar());
mergeData.put("date", new SimpleScalar(now));
+ try {
mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
+ } catch (ModuleException e) {
+ theLog.printError("themenPopupData could not be fetched.");
+ }
try {
mergeData.put("articletypePopupData", DatabaseArticleType.getInstance().getPopupData());
} catch (Exception e) {
} catch (Exception e) {
theLog.printError("language-popup could not be fetched.");
}
+ try {
mergeData.put("schwerpunktPopupData", schwerpunktModule.getSchwerpunktAsSimpleList());
+ } catch (ModuleException e) {
+ theLog.printError("schwerpunktPopupData could not be fetched.");
+ }
mergeData.put("login_user", user);
deliver(req, res, mergeData, templateObjektString);
}
catch(ModuleException e) {
theLog.printError("smod content :: attach :: could not get entityContent");
}
+ catch(StorageObjectException e) {
+ theLog.printError("smod content :: attach :: could not get entityContent");
+ }
+
_showObject(idParam, req, res);
}
catch(ModuleException e) {
theLog.printError("smod content :: dettach :: could not get entityContent");
}
+ catch(StorageObjectException e) {
+ theLog.printError("smod content :: dettach :: could not get entityContent");
+ }
+
_showObject(cidParam, req, res);
}
catch(ModuleException e) {
theLog.printError("smod content :: newswire :: could not get entityContent");
}
+ catch(StorageObjectException e) {
+ theLog.printError("smod content :: dettach :: could not get entityContent");
+ }
+
list(req, res);
}
* can we make getIdasInt() or can we just have
* another getId() that returns an Int and the VM
* will handle it transparantly? -mh
- */
+ */
try {
mediaHandlerName = mediaType.getValue("classname");
mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
private ServletModuleImages() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Bilder.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Bilder.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Bilder.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Bilder.ConfirmTemplate");
EntityImages entImage = (EntityImages)mainModule.getById(id);
if (imageData!=null && fileName!=null) {
- String fileType = "-1";
-
- //the where clause to find the media_type entry
+ //the where clause to find the media_type entry
//from the content-type.
- //we use the media type entry to lookup the
+ //we use the media type entry to lookup the
//media Handler/Storage classes
String wc = " mime_type='"+contentType+"'";
EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
- String mediaTypeId = null;
+ String mediaTypeId = null;
String mediaStorageName = null;
String mediaHandlerName = null;
-
+
//if we found an entry matching the
//content-type int the table.
if (mediaTypesList.size() > 0) {
mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
parameters.put("to_media_type",mediaTypeId);
-
+
//load the classes via reflection
String MediaId;
try {
//were done with mpReq at this point, dereference it. as it contains
//mucho mem. -mh 01.10.2001
mpReq=null;
-
+
if(mediaId!=null){
new ProducerMedia().handle(null, null, false, false, mediaId);
}
- } catch (Exception e) {
- theLog.printError("setting uploaded_media failed: "+e.toString());
+ } catch (Exception e) {
+ theLog.printError("setting uploaded_media failed: "+e.toString());
} //end try-catch
- if (fileType != "-1")
- entImage.setImage(imageData, fileType);
- else
- theLog.printError("Wrong file uploaded!");
+ entImage.setImage(imageData);
}
_edit(id, req, res);
}
try {
WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
HashMap parameters = mp.getParameters();
- MpRequest mpReq = (MpRequest)mp.requestList.get(0);
- byte[] imageData=mpReq.getMedia();
- String fileName=mpReq.getFilename();
- String contentType=mpReq.getContentType();
+ //MpRequest mpReq = (MpRequest)mp.requestList.get(0);
+ //byte[] imageData=mpReq.getMedia();
+ //String fileName=mpReq.getFilename();
+ //String contentType=mpReq.getContentType();
EntityUsers user = _getUser(req);
parameters.put("to_publisher", user.getId());
parameters.put("is_published","0");
String id = mainModule.set(parameters);
- EntityImages entImage = (EntityImages)mainModule.getById(id);
-
- if (imageData!=null && fileName!=null) {
- String fileType = "-1";
- if (contentType.equals("image/jpeg")) fileType="0";
- if (contentType.equals("image/gif")) fileType="1";
- if (fileType != "-1")
- entImage.setImage(imageData, fileType);
- else
- theLog.printError("Wrong file uploaded!");
- }
+ theLog.printError("Image ID"+id);
_edit(id, req, res);
}
catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
String fileName=mpReq.getFilename();
String contentType=mpReq.getContentType();
- String fileType = "-1";
- if (contentType.equals("image/jpeg")) fileType="0";
- if (contentType.equals("image/gif")) fileType="1";
- if (fileType != "-1") {
- EntityImages entImage = (EntityImages)mainModule.getById(idParam);
- entImage.setImage(imageData, fileType);
- }
- else
- theLog.printError("Wrong file uploaded!");
+ EntityImages entImage = (EntityImages)mainModule.getById(idParam);
+ entImage.setImage(imageData);
}
catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
+ catch (StorageObjectException e) { throw new ServletModuleException("upload -- storageobjectexception " + e.toString());}
}
else // keine id
throw new ServletModuleException("Keine id angegeben");
public static ServletModule getInstance() { return instance; }
private ServletModuleLanguage() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Language.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Language.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Language.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Language.ConfirmTemplate");
private ServletModuleLinksImcs() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.LinksImcs.Logfile"));
templateListString = MirConfig.getProp("ServletModule.LinksImcs.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.LinksImcs.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.LinksImcs.ConfirmTemplate");
private static ServletModuleMediafolder instance = new ServletModuleMediafolder();
private ServletModuleMediafolder() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Mediafolder.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Mediafolder.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Mediafolder.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Mediafolder.ConfirmTemplate");
public static ServletModule getInstance() { return instance; }
private ServletModuleMessage() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Messages.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Messages.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Messages.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Messages.ConfirmTemplate");
public class ServletModuleOpenIndy extends ServletModule
{
- private ModuleContent contentModule;
- private ModuleImages imageModule;
- private ModuleTopics themenModule;
-
- //config values
- private static String commentFormTemplate = "open/comment.template";
- private static String commentFormDoneTemplate = "open/comment_done.template";
- private static String commentFormDupeTemplate = "open/comment_dupe.template";
- private static String postingFormTemplate = "open/posting.template";
- private static String postingFormDoneTemplate = "open/posting_done.template";
- private static String postingFormDupeTemplate = "open/posting_dupe.template";
- private static boolean directOp = true;
+
+ private String commentFormTemplate, commentFormDoneTemplate,
+ commentFormDupeTemplate;
+ private String postingFormTemplate, postingFormDoneTemplate,
+ postingFormDupeTemplate;
+ private ModuleContent contentModule;
+ private ModuleImages imageModule;
+ private ModuleTopics themenModule;
+ private String directOp ="yes";
// Singelton / Kontruktor
private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
public static ServletModule getInstance() { return instance; }
- public static void setDirectOp(boolean v) {
- directOp=v;
- }
-
-// public static setCommentFormTemplate(String template) throws {
- // if
-
private ServletModuleOpenIndy() {
try {
- theLog = Logfile.getInstance(this.getClass().getName());
- //commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
- //commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
- //commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
- //postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
- //postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
- //postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
- //directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
+ commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
+ commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
+ commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
+ postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
+ postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
+ postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
+ directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
mainModule = new ModuleComment(DatabaseComment.getInstance());
contentModule = new ModuleContent(DatabaseContent.getInstance());
themenModule = new ModuleTopics(DatabaseTopics.getInstance());
* Method for delivering the form-Page for open posting
*/
- public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
- {
+ public void addposting(HttpServletRequest req, HttpServletResponse res)
+ throws ServletModuleException {
SimpleHash mergeData = new SimpleHash();
String numOfMedia = req.getParameter("medianum");
if(numOfMedia==null||numOfMedia.equals("")){
}
mergeData.put("medianum",numOfMedia);
mergeData.put("mediafields",mediaFields);
- mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
/** @todo popups missing */
try{
- mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
+ SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
+ mergeData.put("languagePopUpData", popUpData );
+ mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
} catch (Exception e) {
- theLog.printError("languagePopUpData failed");
- }
+ theLog.printError("languagePopUpData or getTopicslist failed "
+ +e.toString());
+ throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
+ }
+
deliver(req, res, mergeData, postingFormTemplate);
}
*/
public void insposting(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleException
+ throws ServletModuleException, ServletModuleUserException
{
SimpleHash mergeData = new SimpleHash();
boolean setMedia=false;
+ boolean setTopic = false;
try {
WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
HashMap withValues = mp.getParameters();
+
+ if ((((String)withValues.get("title")).length() == 0) ||
+ (((String)withValues.get("description")).length() == 0) ||
+ (((String)withValues.get("content_data")).length() == 0))
+ throw new ServletModuleUserException("Missing field");
// call the routines that escape html
withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
withValues.put("is_produced", "0");
- // op-articles are immediatly published
- withValues.put("is_published","1");
+ // op-articles are not immediatly published
+ // we don't know that all is good yet (media, title is present, etc..)
+ withValues.put("is_published","0");
// if op direct article-type == newswire
- if (directOp) withValues.put("to_article_type","1");
+ if (directOp.equals("yes")) withValues.put("to_article_type","1");
// owner is openposting user
withValues.put("to_publisher","1");
theLog.printDebugInfo("id: "+cid);
//insert was not successfull
if(cid==null){
- //How do we know that it was not succesful cause of a
+ //How do we know that it was not succesful cause of a
//dupe, what if it failed cause of "No space left on device"?
//Or is there something I am missing? Wouldn't it be better
//to have an explicit dupe check and then insert? I have no
}
String[] to_topicsArr = mp.getParameterValues("to_topic");
- if (to_topicsArr != null && to_topicsArr.length > 0) {
+
+ if (to_topicsArr != null && to_topicsArr.length > 0) {
try{
DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
- theLog.printError("setting content_x_topic success");
+ setTopic = true;
} catch (Exception e) {
theLog.printError("setting content_x_topic failed");
+ contentModule.deleteById(cid);
+ throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
} //end try
} //end if
//sends us. (the "Oreilly method")
String contentType = mpReq.getContentType();
- theLog.printError("FROM BROWSER: "+contentType);
+ theLog.printInfo("FROM BROWSER: "+contentType);
//if the client browser sent us unknown (text/plain is default)
//or if we got application/octet-stream, it's possible that
//the browser is in error, better check against the file extension
- if (contentType.equals("text/plain") ||
+ if (contentType.equals("text/plain") ||
contentType.equals("application/octet-stream")) {
- /**
+ /**
* This is just a temporary way to get the content-type via
* the .extension , we could maybe use a magic method, by looking
* at the header (first few bytes) of the file. (like the file(1)
* command).
- * The Oreilly method relies on the content-type that the client
+ * The Oreilly method relies on the content-type that the client
* browser sends and that sometimes is application-octet stream with
* broken/mis-configured browsers.
- *
- * The map file should be Mir/content-types.properties, it's the
- * default Sun Java file with some additional entries that it did
- * not have. So if you support a new media type you have to make
+ *
+ * The map file should be Mir/content-types.properties, it's the
+ * default Sun Java file with some additional entries that it did
+ * not have. So if you support a new media type you have to make
* sure that it is in this file -mh
*/
contentType = FileUtil.guessContentTypeFromName(fileName);
- theLog.printError("tYPE: "+contentType);
if (contentType==null)
contentType = "text/plain"; // rfc1867 says this is the default
}
HashMap mediaValues = new HashMap();
- theLog.printError("CONTENT TYPE IS: "+contentType);
+ theLog.printInfo("CONTENT TYPE IS: "+contentType);
- if (contentType.equals("text/plain") ||
+ if (contentType.equals("text/plain") ||
contentType.equals("application/octet-stream")) {
- throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
+ throw new ServletModuleUserException("One or more files of unrecognized types");
}
String mediaTitle=(String)withValues.get("media_title"+i);
mediaValues.put("to_publisher", "1"); // op user
mediaValues.put("to_media_folder", "7"); // op media_folder
mediaValues.put("is_produced", "0");
- mediaValues.put("is_published","1");
+ mediaValues.put("is_published","0");
//the where clause to find the media_type entry
//from the content-type.
- //we use the media type entry to lookup the
+ //we use the media type entry to lookup the
//media Handler/Storage classes
- String wc = " mime_type='"+contentType+"'";
+ //String wc = " mime_type = '"+contentType+"'";
- EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
+ // @todo this should probably be moved to DatabaseMediaType -mh
+ String[] cTypeSplit = StringUtil.split(contentType, "/");
+ String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
+
+ DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
+ EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
String mediaTypeId = null;
- String mediaStorageName = null;
- String mediaHandlerName = null;
+ MirMedia mediaHandler;
+ Database mediaStorage;
//if we found an entry matching the
//content-type int the table.
if (mediaTypesList.size() > 0) {
+ Entity mediaType = null;
+
+ // find out if we an exact content-type match if so take it.
+ // otherwise just use the first one.
+ // @todo this should probably be moved to DatabaseMediaType -mh
+ for(int j=0;j<mediaTypesList.size();j++) {
+ if(contentType.equals(
+ mediaTypesList.elementAt(j).getValue("mime_type")))
+ mediaType = mediaTypesList.elementAt(j);
+ }
+
+ if( mediaType == null )
+ mediaType = mediaTypesList.elementAt(0);
+
//get the class names from the media_type table.
- mediaTypeId = mediaTypesList.elementAt(0).getId();
- mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
- mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
+ mediaTypeId = mediaType.getId();
+ try {
+ // ############### @todo: merge these and the getURL call into one
+ // getURL helper call that just takes the Entity as a parameter
+ // along with media_type
+ mediaHandler = MediaHelper.getHandler(mediaType);
+ mediaStorage = MediaHelper.getStorage(mediaType,
+ "mircoders.storage.Database");
+ } catch (MirMediaException e) {
+ theLog.printError("getting media handler failed: "+e.toString());
+ contentModule.deleteById(cid);
+ throw new ServletModuleException("getting media handler failed: "
+ +e.toString());
+ }
+
mediaValues.put("to_media_type",mediaTypeId);
-
+
//load the classes via reflection
String MediaId;
+ Entity mediaEnt = null;
try {
- Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
- Method m = mediaStorageClass.getMethod("getInstance", null);
- Database mediaStorage = (Database)m.invoke(null, null);
- Entity mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
- mediaEnt.setStorage(mediaStorage);
- mediaEnt.setValues(mediaValues);
- mediaId = mediaEnt.insert();
-
- Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
- MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
- //save and store the media data/metadata
- mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
-
- //were done with mpReq at this point, dereference it.
- //as it contains mucho mem. -mh 01.10.2001
- mpReq=null;
-
- if(mediaId!=null){
- new ProducerMedia().handle(null, null, false, false, mediaId);
- }
- } catch (Exception e) {
- theLog.printError("setting uploaded_media failed: "+e.toString());
- } //end try-catch
+ mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
+ mediaEnt.setStorage(mediaStorage);
+ mediaEnt.setValues(mediaValues);
+ mediaId = mediaEnt.insert();
+
+ //save and store the media data/metadata
+ mediaHandler.set(mpReq.getMedia(), mediaEnt,
+ mediaType);
+
+ //were done with mpReq at this point, dereference it.
+ //as it contains mucho mem. -mh 01.10.2001
+ mpReq=null;
- //we got this far, associate the media to the article
- try{
- DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
- theLog.printError("setting content_x_media success");
+ //we got this far, associate the media to the article
+ mediaEnt.setValueForProperty("is_published","1");
+ mediaEnt.update();
+ new ProducerMedia().handle(null,null,false,false,mediaId);
+ DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
} catch (Exception e) {
- theLog.printError("setting content_x_media failed");
+ theLog.printError("setting media failed: "+e.toString());
+ contentModule.deleteById(cid);
+ throw new ServletModuleException("setting media failed: "+e.toString());
}
} else {
- theLog.printDebugInfo("Wrong file uploaded!: " + fileName);
- throw new ServletModuleException("ModuleException: One or more files of unrecognized types");
+ contentModule.deleteById(cid);
+ theLog.printDebugInfo("Wrong file type uploaded!: " + fileName);
+ throw new ServletModuleUserException("One or more files of unrecognized types");
} // end if-else mediaTypesList.size() > 0
} //end for Iterator...
+ //if we're here all is ok...
+ EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
+ contentEnt.setValueForProperty("is_published","1");
+ contentEnt.update();
+
+
//dereference mp. -mh
mp=null;
// producing new page
new ProducerContent().handle(null, null, false, false,cid);
//if direct op producing startpage
- if (directOp) new ProducerStartPage().handle(null,null);
+ if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
+ //produce the topicPages if set
+ //should be more intelligent
+ //if(setTopic==true) new ProducerTopics().handle(null,null);
+
// sync the server
//should be configureable
int exitValue = Helper.rsync();
catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
deliver(req, res, mergeData, postingFormDoneTemplate);
- //System.gc();
}
}
public static ServletModule getInstance() { return instance; }
private ServletModuleProducer() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Producer.Logfile"));
defaultAction="produce";
}
public static ServletModule getInstance() { return instance; }
private ServletModuleSchwerpunkt() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Schwerpunkt.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Schwerpunkt.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Schwerpunkt.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Schwerpunkt.ConfirmTemplate");
public static ServletModule getInstance() { return instance; }
private ServletModuleTopics() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Themen.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Themen.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Themen.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Themen.ConfirmTemplate");
public static ServletModule getInstance() { return instance; }
private ServletModuleUsers() {
- theLog = Logfile.getInstance(this.getClass().getName());
+ theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Users.Logfile"));
templateListString = MirConfig.getProp("ServletModule.Users.ListTemplate");
templateObjektString = MirConfig.getProp("ServletModule.Users.ObjektTemplate");
templateConfirmString = MirConfig.getProp("ServletModule.Users.ConfirmTemplate");
String idParam = req.getParameter("id");
if (idParam == null) throw new ServletModuleException("Falscher Aufruf: (id) nicht angegeben");
try {
+ //theLog.printInfo("Showing User with id: " + idParam);
deliver(req, res, mainModule.getById(idParam), templateObjektString);
}
catch (ModuleException e) { throw new ServletModuleException(e.toString());}
this.theTable="article_type";
}
- public SimpleList getPopupData() { return getPopupData("name",false); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("name",false); }
}
--- /dev/null
+package mircoders.storage;
+
+import java.lang.*;
+import java.sql.*;
+import java.io.*;
+import java.util.*;
+
+import freemarker.template.*;
+
+import mir.storage.*;
+import mir.entity.*;
+import mir.misc.*;
+
+/**
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
+ *
+ *
+ */
+
+public class DatabaseAudio extends Database implements StorageObject{
+
+ private static DatabaseAudio instance;
+ private static SimpleList publisherPopupData;
+
+ public static DatabaseAudio getInstance() throws StorageObjectException
+ {
+ if (instance == null) {
+ instance = new DatabaseAudio();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseAudio() throws StorageObjectException
+ {
+ super();
+ this.hasTimestamp = true;
+ this.theTable="audio";
+ this.theCoreTable="media";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityAudio");
+ }
+ catch (Exception e) { throw new StorageObjectException(e.toString()); }
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("title",true);
+ }
+
+ public void update(Entity theEntity) throws StorageObjectException
+ {
+ 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 StorageObjectException
+ {
+ 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
+
+}
public class DatabaseBreaking extends Database implements StorageObject{
- private static DatabaseBreaking instance;
-
- public static DatabaseBreaking getInstance() throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseBreaking();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseBreaking() throws StorageObjectException
- {
- super();
- this.cache = new HashMap();
- this.theTable="breaking";
- try {
- this.theEntityClass = Class.forName("mircoders.entity.EntityBreaking");
- }
- catch (Exception e) { throw new StorageObjectException(e.toString()); }
- }
+ private static DatabaseBreaking instance;
+
+ public static DatabaseBreaking getInstance() throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseBreaking();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseBreaking() throws StorageObjectException
+ {
+ super();
+ //this.cache = new DatabaseCache(4);
+ this.theTable="breaking";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityBreaking");
+ }
+ catch (Exception e) { throw new StorageObjectException(e.toString()); }
+ }
}
{
super();
this.hasTimestamp = false;
- this.cache = new HashMap();
+ ////this.cache = new HashMap();
this.theTable="comment";
try {
this.theEntityClass = Class.forName("mircoders.entity.EntityComment");
catch (Exception e) { throw new StorageObjectException(e.toString()); }
}
- public SimpleList getPopupData() { return getPopupData("title",true); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("title",true); }
public boolean deleteByContentId(String id)
throws StorageObjectException {
super();
this.theTable="content";
this.theCoreTable="media";
+
relationComments = new EntityRelation("id", "to_media", DatabaseComment.getInstance(), EntityRelation.TO_MANY);
relationFeature = new EntityRelation("id", "to_feature", DatabaseFeature.getInstance(), EntityRelation.TO_ONE);
try { this.theEntityClass = Class.forName("mircoders.entity.EntityContent"); }
* sets the database flag is_produced to unproduced
*/
- public void setUnproduced(String where)
+ public void setUnproduced(String where) throws StorageObjectException
{
Connection con=null;Statement stmt=null;
String sql = "update content set is_produced='0' where " + where;
stmt = con.createStatement();
executeUpdate(stmt,sql);
}
- catch (Exception e) {theLog.printDebugInfo("-- set unproduced failed");}
+ catch (Exception e) {_throwStorageObjectException(e, "-- set unproduced failed");}
finally { freeConnection(con,stmt);}
}
* returns the comments that belong to the article (via entityrelation)
* where db-flag is_published is true
*/
- public SimpleList getComments(EntityContent entC) {
- SimpleList comments=null;
- try {
- comments = relationComments.getManyAsSimpleList(entC,"webdb_create","is_published='1'");
- }
- catch (StorageObjectException e) {
- theLog.printError("DatabaseComments :: failed to get comments");
- }
- return comments;
+ public EntityList getComments(EntityContent entC) throws StorageObjectException {
+ return relationComments.getMany(entC,"webdb_create","is_published='1'");
}
/**
* returns the features that belong to the article (via entityrelation)
*/
- public SimpleList getFeature(EntityContent entC) {
- SimpleList feature=null;
- try {
- feature = relationFeature.getManyAsSimpleList(entC);
- }
- catch (StorageObjectException e) {
- theLog.printError("DatabaseComments :: failed to get features");
- }
- return feature;
+ public EntityList getFeature(EntityContent entC) throws StorageObjectException {
+ return relationFeature.getMany(entC);
}
- public boolean delete(String id)
- throws StorageObjectException {
+ public boolean delete(String id) throws StorageObjectException
+ {
DatabaseComment.getInstance().deleteByContentId(id);
super.delete(id);
return true;
this.hasTimestamp = false;
this.theTable="content_x_media";
}
-
+
/**
* get all the media-files belonging to a content entity
*
*/
- public EntityList getMedia(EntityContent content) {
+ public EntityList getMedia(EntityContent content)
+ throws StorageObjectException {
EntityList returnList=null;
if (content != null) {
// get all to_topic from media_x_topic
returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,-1);
} catch (Exception e) {
theLog.printDebugInfo("-- get media failed " + e.toString());
+ throw new StorageObjectException("-- get media failed " + e.toString());
+ }
+ }
+ return returnList;
+ }
+
+ public boolean hasMedia(EntityContent content)
+ throws StorageObjectException {
+ String wc = "content_id="+content.getId();
+ if( content != null) {
+ try {
+ if(selectByWhereClause(wc,-1).size() == 0)
+ return false;
+ else
+ return true;
+ } catch (Exception e) {
+ theLog.printError("-- hasMedia failed " + e.toString());
+ throw new StorageObjectException("-- hasMedia failed " + e.toString());
+ }
+ } else {
+ theLog.printError("-- hasMedia failed: content is NULL");
+ throw new StorageObjectException("-- hasMedia failed: content is NULL");
+ }
+ }
+
+
+
+
+ /**
+ * get all the audio belonging to a content entity
+ *
+ */
+ public EntityList getAudio(EntityContent content)
+ throws StorageObjectException {
+ EntityList returnList=null;
+ if (content != null) {
+ // get all to_topic from media_x_topic
+ String id = content.getId();
+ //this is not supported by mysql
+ String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")";
+
+ try {
+ returnList = DatabaseAudio.getInstance().selectByWhereClause(subselect,-1);
+ } catch (Exception e) {
+ theLog.printDebugInfo("-- get audio failed " + e.toString());
+ throw new StorageObjectException("-- get audio failed " + e.toString());
+ }
+ }
+ return returnList;
+ }
+
+ /**
+ * get all the video belonging to a content entity
+ *
+ */
+ public EntityList getVideo(EntityContent content)
+ throws StorageObjectException {
+ EntityList returnList=null;
+ if (content != null) {
+ // get all to_topic from media_x_topic
+ String id = content.getId();
+ //this is not supported by mysql
+ String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")";
+
+ try {
+ returnList = DatabaseVideo.getInstance().selectByWhereClause(subselect,-1);
+ } catch (Exception e) {
+ theLog.printDebugInfo("-- get video failed " + e.toString());
+ throw new StorageObjectException("-- get video failed " + e.toString());
}
}
return returnList;
}
-
+
/**
* get all the images belonging to a content entity
*
*/
- public EntityList getImages(EntityContent content) {
+ public EntityList getImages(EntityContent content)
+ throws StorageObjectException {
EntityList returnList=null;
if (content != null) {
// get all to_topic from media_x_topic
returnList = DatabaseImages.getInstance().selectByWhereClause(subselect,-1);
} catch (Exception e) {
theLog.printDebugInfo("-- get images failed " + e.toString());
+ throw new StorageObjectException("-- get images failed " + e.toString());
}
}
return returnList;
/**
- * get all the uploaded Media belonging to a content entity
+ * get all the uploaded/other Media belonging to a content entity
*
*/
- public EntityList getUploadedMedia(EntityContent content) {
+ public EntityList getOther(EntityContent content)
+ throws StorageObjectException
+ {
+ /** @todo this should only fetch published media / rk */
+
EntityList returnList=null;
if (content != null) {
// get all to_topic from media_x_topic
String id = content.getId();
//this is not supported by mysql
- String subselect = "id in (select media_id from " + theTable + " where content_id=" + id+")";
+ String subselect = "id in (select media_id from " + theTable +
+ " where content_id=" + id+")";
try {
- returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,-1);
+ returnList = DatabaseOther.getInstance().selectByWhereClause(subselect,
+ "id");
+ } catch (Exception e) {
+ e.printStackTrace();
+ theLog.printDebugInfo("-- get Other failed " + e.toString());
+ throw new StorageObjectException("-- get Other failed "
+ + e.toString());
+ }
+ }
+ return returnList;
+ }
+
+ /**
+ * get all the uploaded/other Media belonging to a content entity
+ *
+ */
+ public EntityList getUploadedMedia(EntityContent content)
+ throws StorageObjectException
+ {
+ /** @todo this should only fetch published media / rk */
+
+ EntityList returnList=null;
+ if (content != null) {
+ // get all to_topic from media_x_topic
+ String id = content.getId();
+ //this is not supported by mysql
+ String subselect = "id in (select media_id from " + theTable +
+ " where content_id=" + id+")";
+
+ try {
+ returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause(subselect,
+ "id");
} catch (Exception e) {
+ e.printStackTrace();
theLog.printDebugInfo("-- get uploadedMedia failed " + e.toString());
+ throw new StorageObjectException("-- get uploadedMedia failed "
+ + e.toString());
}
}
return returnList;
}
- public void setMedia(String contentId, String[] mediaId) {
+ public void setMedia(String contentId, String[] mediaId)
+ throws StorageObjectException {
if (contentId == null){
return;
}
}
//first delete all row with content_id=contentId
String sql = "delete from "+ theTable +" where content_id=" + contentId;
-
+
Connection con=null;Statement stmt=null;
try {
con = getPooledCon();
ResultSet rs = executeSql(stmt,sql);
} catch (Exception e) {
theLog.printDebugInfo("-- set media failed -- delete");
+ throw new StorageObjectException("-- set media failed -- delete"+e.toString());
} finally {
freeConnection(con,stmt);
}
-
+
//now insert
//first delete all row with content_id=contentId
for (int i=0;i<mediaId.length;i++) {
int rs = executeUpdate(stmt,sql);
} catch (Exception e) {
theLog.printDebugInfo("-- set topics failed -- insert");
+ throw new StorageObjectException("-- set topics failed -- insert "+e.toString());
} finally {
freeConnection(con,stmt);
}
}
}
- public void addMedia(String contentId, String mediaId) {
+ public void addMedia(String contentId, String mediaId)
+ throws StorageObjectException {
if (contentId == null && mediaId == null) {
return;
}
-
+
Connection con=null;Statement stmt=null;
//now insert
-
+
String sql = "insert into "+ theTable +" (content_id,media_id) values ("
+ contentId + "," + mediaId + ")";
try {
int rs = executeUpdate(stmt,sql);
} catch (Exception e) {
theLog.printDebugInfo("-- add media failed -- insert");
+ throw new StorageObjectException("-- add media failed -- insert "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
}
-
- public void setMedia(String contentId, String mediaId) {
+
+ public void setMedia(String contentId, String mediaId)
+ throws StorageObjectException {
if (contentId == null && mediaId == null) {
return;
}
int rs = executeUpdate(stmt,sql);
} catch (Exception e) {
theLog.printDebugInfo("-- set media failed -- delete");
+ throw new StorageObjectException("-- set media failed -- delete "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
int rs = executeUpdate(stmt,sql);
} catch (Exception e) {
theLog.printDebugInfo("-- set media failed -- insert");
+ throw new StorageObjectException("-- set media failed -- insert "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
}
- public void deleteByContentId(String contentId) {
+ public void deleteByContentId(String contentId)
+ throws StorageObjectException {
if (contentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no content id");
return;
stmt = con.createStatement();
int rs = executeUpdate(stmt,sql);
} catch (Exception e) {
- //theLog.printDebugInfo("-- delete topics failed ");
+ theLog.printDebugInfo("-- delete by contentId failed ");
+ throw new StorageObjectException("-- delete by content id failed -- delete "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
}
- public void deleteByMediaId(String mediaId) {
+ public void deleteByMediaId(String mediaId)
+ throws StorageObjectException {
if (mediaId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
return;
theLog.printDebugInfo("-- delete media success ");
} catch (Exception e) {
theLog.printDebugInfo("-- delete media failed ");
+ throw new StorageObjectException("-- delete by media id failed -- "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
}
-
- public void delete(String contentId, String mediaId) {
+
+ public void delete(String contentId, String mediaId)
+ throws StorageObjectException {
if (mediaId == null || contentId==null) {
theLog.printDebugInfo("-- delete media failed -- missing parameter");
return;
theLog.printDebugInfo("-- delete content_x_media success ");
} catch (Exception e) {
theLog.printDebugInfo("-- delete content_x_media failed ");
+ throw new StorageObjectException("-- delete content_x_media failed -- "
+ +e.toString());
} finally {
freeConnection(con,stmt);
}
}
- public EntityList getContent(EntityMedia media) {
+ public EntityList getContent(EntityMedia media)
+ throws StorageObjectException {
EntityList returnList=null;
if (media != null) {
String id = media.getId();
returnList = DatabaseContent.getInstance().selectByWhereClause(mediaSelect,-1);
}
}
- catch (Exception e) {theLog.printDebugInfo("-- get content failed");}
+ catch (Exception e) {
+ theLog.printDebugInfo("-- get content failed");
+ throw new StorageObjectException("-- get content failed -- "
+ +e.toString());
+ }
finally { freeConnection(con,stmt);}
}
return returnList;
}
-
+
/**
* Returns a EntityList with all content-objects having a relation to a media
*/
-
-public EntityList getContent() {
+
+public EntityList getContent()
+ throws StorageObjectException {
EntityList returnList=null;
-
+
String select = "select distinct content_id from " + theTable;
// execute select statement
Connection con=null;Statement stmt=null;
returnList = DatabaseContent.getInstance().selectByWhereClause(mediaSelect,"webdb_lastchange desc");
}
}
- catch (Exception e) {theLog.printDebugInfo("-- get content failed");}
+ catch (Exception e) {
+ theLog.printDebugInfo("-- get content failed");
+ throw new StorageObjectException("-- get content failed -- "
+ +e.toString());
+ }
finally { freeConnection(con,stmt);}
return returnList;
* Returns a ArrayList of Integer-Objects from a content-id.
* @returns ArrayList
*/
- public ArrayList getTopicsOfContent(String contentId) {
+ public ArrayList getTopicsOfContent(String contentId)
+ throws StorageObjectException {
ArrayList returnList = new ArrayList();
if (contentId != null) {
String sql = "select topic_id from " + theTable + " where content_id=" + contentId;
/**
* Set new topics
*/
- public void setTopics(String contentId, String[] topicId) {
+ public void setTopics(String contentId, String[] topicId)
+ throws StorageObjectException {
if (contentId == null){
return;
}
return;
}
//first check which topics this article has
- ArrayList hasTopics = getTopicsOfContent(contentId);
- ArrayList toSet = new ArrayList();
- ArrayList toDelete = new ArrayList();
+ Collection hasTopics = getTopicsOfContent(contentId);
+ Collection toSet = new ArrayList();
+ Collection toDelete = new ArrayList();
if(hasTopics!=null && hasTopics.size()>0){
//now we check if there are new topics and copy them to an array.
}
} else {
//all the topics has to be set, so we copy all to the array
- toSet=(ArrayList)Arrays.asList(topicId);
+ for (int i = 0; i < topicId.length; i++){
+ toSet.add(topicId[i]);
+ }
}
//first delete all row with content_id=contentId
}
}
- public void deleteByContentId(String contentId) {
+ public void deleteByContentId(String contentId)
+ throws StorageObjectException {
if (contentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no content id");
return;
}
}
- public void deleteByTopicId(String topicId) {
+ public void deleteByTopicId(String topicId)
+ throws StorageObjectException {
if (topicId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
return;
}
- public EntityList getContent(EntityTopics topic) {
+ public EntityList getContent(EntityTopics topic)
+ throws StorageObjectException {
EntityList returnList=null;
if (topic != null) {
String id = topic.getId();
public class DatabaseFeature extends Database implements StorageObject{
- private static DatabaseFeature instance;
-
- public static DatabaseFeature getInstance() throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseFeature();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseFeature() throws StorageObjectException
- {
- super();
- this.cache = new HashMap();
- this.hasTimestamp = false;
- this.theTable="feature";
-
- try {
- this.theEntityClass = Class.forName("mircoders.entity.EntityFeature");
- }
- catch (Exception e) {
- throw new StorageObjectException(e.toString());
- }
- }
-
- public SimpleList getPopupData() {
- return getPopupData("title",true);
- }
+ private static DatabaseFeature instance;
+
+ public static DatabaseFeature getInstance() throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseFeature();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseFeature() throws StorageObjectException
+ {
+ super();
+ //this.cache = new DatabaseCache(10);
+ this.hasTimestamp = false;
+ this.theTable="feature";
+
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityFeature");
+ }
+ catch (Exception e) {
+ throw new StorageObjectException(e.toString());
+ }
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("title",true);
+ }
}
this.theTable="img_color";
}
- public SimpleList getPopupData() { return getPopupData("name",true); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("name",true); }
}
this.theTable="img_format";
}
- public SimpleList getPopupData() { return getPopupData("name",true); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("name",true); }
}
this.theTable="img_layout";
}
- public SimpleList getPopupData() { return getPopupData("name",true); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("name",true); }
}
this.theTable="img_type";
}
- public SimpleList getPopupData() { return getPopupData("name",true); }
+ public SimpleList getPopupData()
+ throws StorageObjectException { return getPopupData("name",true); }
}
catch (Exception e) { throw new StorageObjectException(e.toString()); }
}
- public SimpleList getPopupData() {
+ public SimpleList getPopupData() throws StorageObjectException {
return getPopupData("title",true);
}
this.theTable="language";
}
- public SimpleList getPopupData() { return getPopupData("name",false); }
+ public SimpleList getPopupData() throws StorageObjectException {
+ SimpleList pData = null;
+ try {
+ pData = getPopupData("name",false);
+ } catch (StorageObjectException e) {System.err.println("FF");}
+ return pData;
+ }
}
*
*/
public class DatabaseLinksImcs extends Database
- implements StorageObject {
- private static DatabaseLinksImcs instance;
+ implements StorageObject {
+ private static DatabaseLinksImcs instance;
- /**
- * put your documentation comment here
- * @return
- * @exception StorageObjectException
- */
- public static DatabaseLinksImcs getInstance () throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseLinksImcs();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
+ /**
+ * put your documentation comment here
+ * @return
+ * @exception StorageObjectException
+ */
+ public static DatabaseLinksImcs getInstance () throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseLinksImcs();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ /**
+ * put your documentation comment here
+ */
+ private DatabaseLinksImcs () throws StorageObjectException
+ {
+ super();
+ ////this.cache = new HashMap();
+ this.hasTimestamp = false;
+ this.theTable = "links_imcs";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityLinksImcs");
+ } catch (Exception e) {
+ throw new StorageObjectException(e.toString());
+ }
+ }
- /**
- * put your documentation comment here
- */
- private DatabaseLinksImcs () throws StorageObjectException
- {
- super();
- //this.cache = new HashMap();
- this.hasTimestamp = false;
- this.theTable = "links_imcs";
- try {
- this.theEntityClass = Class.forName("mircoders.entity.EntityLinksImcs");
- } catch (Exception e) {
- throw new StorageObjectException(e.toString());
- }
- }
+ /** @todo toooo much copy/paste in this class //rk */
- public String insert (Entity theEntity) throws StorageObjectException {
+ public String insert (Entity theEntity) throws StorageObjectException {
String returnId = "0";
Connection con = null;
PreparedStatement pstmt = null;
//cache
invalidatePopupCache();
try {
+ HashMap theEntityValues = theEntity.getValues();
ArrayList streamedInput = theEntity.streamedInput();
StringBuffer f = new StringBuffer();
StringBuffer v = new StringBuffer();
aValue = "?";
}
else {
- if (theEntity.hasValueForField(aField)) {
- if (aField.equals("to_parent_id")) {
- aValue = StringUtil.quote((String)theEntity.getValue(aField));
- } else {
- aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField)) + "'";
- }
+ if (theEntityValues.containsKey(aField)) {
+ if (aField.equals("to_parent_id")) {
+ aValue = StringUtil.quote((String)theEntityValues.get(aField));
+ } else {
+ aValue = "'" + StringUtil.quote((String)theEntityValues.get(aField)) + "'";
+ }
}
}
}
pstmt = con.prepareStatement(sql);
if (streamedInput != null) {
for (int i = 0; i < streamedInput.size(); i++) {
- String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
+ String inputString = (String)theEntityValues.get(streamedInput.get(i));
pstmt.setBytes(i + 1, inputString.getBytes());
}
}
return returnId;
}
- public void update (Entity theEntity) throws StorageObjectException {
- Connection con = null;
- PreparedStatement pstmt = null;
- ArrayList streamedInput = theEntity.streamedInput();
- String id = theEntity.getId();
- String aField;
- StringBuffer fv = new StringBuffer();
- boolean firstField = true;
- //cache
- invalidatePopupCache();
- // build sql statement
- for (int i = 0; i < getFields().size(); i++) {
- aField = (String)metadataFields.get(i);
- // only normal cases
- if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
- if (theEntity.hasValueForField(aField)) {
- if (firstField == false) {
- fv.append(", ");
- }
- else {
- firstField = false;
- }
- if (aField.equals("to_parent_id")) {
- fv.append(aField).append("=").append(StringUtil.quote(theEntity.getValue(aField)));
- } else {
- fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
- }
- }
- }
- }
- StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
- // exceptions
- if (metadataFields.contains("webdb_lastchange")) {
- sql.append(",webdb_lastchange=NOW()");
- }
- if (streamedInput != null) {
- for (int i = 0; i < streamedInput.size(); i++) {
- sql.append(",").append(streamedInput.get(i)).append("=?");
- }
- }
- sql.append(" where id=").append(id);
- theLog.printInfo("UPDATE: " + sql);
- // execute sql
- try {
- con = getPooledCon();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql.toString());
- if (streamedInput != null) {
- for (int i = 0; i < streamedInput.size(); i++) {
- String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
- pstmt.setBytes(i + 1, inputString.getBytes());
- }
- }
- pstmt.executeUpdate();
- } catch (SQLException sqe) {
- throwSQLException(sqe, "update");
- } finally {
- try {
- con.setAutoCommit(true);
- } catch (Exception e) {
- ;
- }
- freeConnection(con, pstmt);
- }
- }
-
- /**
- * put your documentation comment here
- * @return
- */
- public SimpleHash getHashData () {
- return getHashData();
- }
+ public void update (Entity theEntity) throws StorageObjectException {
+ Connection con = null;
+ PreparedStatement pstmt = null;
+ ArrayList streamedInput = theEntity.streamedInput();
+ HashMap theEntityValues = theEntity.getValues();
+ String id = theEntity.getId();
+ String aField;
+ StringBuffer fv = new StringBuffer();
+ boolean firstField = true;
+ //cache
+ invalidatePopupCache();
+ // build sql statement
+ for (int i = 0; i < getFields().size(); i++) {
+ aField = (String)metadataFields.get(i);
+ // only normal cases
+ if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
+ aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
+ if (theEntityValues.containsKey(aField)) {
+ if (firstField == false) {
+ fv.append(", ");
+ }
+ else {
+ firstField = false;
+ }
+ if (aField.equals("to_parent_id")) {
+ fv.append(aField).append("=").append(StringUtil.quote((String)theEntityValues.get(aField)));
+ } else {
+ fv.append(aField).append("='").append(StringUtil.quote((String)theEntityValues.get(aField))).append("'");
+ }
+ }
+ }
+ }
+ StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
+ // exceptions
+ if (metadataFields.contains("webdb_lastchange")) {
+ sql.append(",webdb_lastchange=NOW()");
+ }
+ if (streamedInput != null) {
+ for (int i = 0; i < streamedInput.size(); i++) {
+ sql.append(",").append(streamedInput.get(i)).append("=?");
+ }
+ }
+ sql.append(" where id=").append(id);
+ theLog.printInfo("UPDATE: " + sql);
+ // execute sql
+ try {
+ con = getPooledCon();
+ con.setAutoCommit(false);
+ pstmt = con.prepareStatement(sql.toString());
+ if (streamedInput != null) {
+ for (int i = 0; i < streamedInput.size(); i++) {
+ String inputString = (String)theEntityValues.get(streamedInput.get(i));
+ pstmt.setBytes(i + 1, inputString.getBytes());
+ }
+ }
+ pstmt.executeUpdate();
+ } catch (SQLException sqe) {
+ throwSQLException(sqe, "update");
+ } finally {
+ try {
+ con.setAutoCommit(true);
+ } catch (Exception e) {
+ ;
+ }
+ freeConnection(con, pstmt);
+ }
+ }
- public SimpleList getPopupData () {
- return getPopupData();
- }
}
private DatabaseMedia() throws StorageObjectException
{
super();
- this.cache = new HashMap();
+ //this.cache = new DatabaseCache(100);
this.hasTimestamp = false;
- this.theTable="media*";
- relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE);
+ this.theTable="media";
+ relationMediaType = new EntityRelation("to_media_type", "id",
+ DatabaseMediaType.getInstance(), EntityRelation.TO_ONE);
try {
this.theEntityClass = Class.forName("mircoders.entity.EntityMedia");
}
* returns the comments that belong to the article (via entityrelation)
* where db-flag is_published is true
*/
- public Entity getMediaType(Entity ent) {
+ public Entity getMediaType(Entity ent) throws StorageObjectException {
Entity type=null;
try {
type = relationMediaType.getOne(ent);
}
catch (StorageObjectException e) {
- theLog.printError("DatabaseUploadedMedia :: failed to get media_type");
+ theLog.printError("DatabaseMedia :: failed to get media_type");
+ throw new StorageObjectException("DatabaseMedia :"+e.toString());
}
return type;
}
{
super();
this.hasTimestamp = false;
- this.cache = new HashMap();
+ //this.cache = new DatabaseCache(20);
this.theTable="media_type";
try {
this.theEntityClass = Class.forName("mir.entity.GenericEntity");
public class DatabaseMediafolder extends Database implements StorageObject{
- private static DatabaseMediafolder instance;
-
- public static DatabaseMediafolder getInstance() throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseMediafolder();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseMediafolder() throws StorageObjectException
- {
- super();
- this.hasTimestamp = false;
- this.cache = new HashMap();
- this.theTable="media_folder";
- }
-
- public SimpleList getPopupData() {
- return getPopupData("name",true);
- }
+ private static DatabaseMediafolder instance;
+
+ public static DatabaseMediafolder getInstance() throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseMediafolder();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseMediafolder() throws StorageObjectException
+ {
+ super();
+ this.hasTimestamp = false;
+ //this.cache = new DatabaseCache(20);
+ this.theTable="media_folder";
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("name",true);
+ }
}
public class DatabaseMessages extends Database implements StorageObject{
- private static DatabaseMessages instance;
-
- public static DatabaseMessages getInstance() throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseMessages();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseMessages() throws StorageObjectException
- {
- super();
- this.cache = new HashMap();
- this.theTable="messages";
- }
+ private static DatabaseMessages instance;
+
+ public static DatabaseMessages getInstance() throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseMessages();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseMessages() throws StorageObjectException
+ {
+ super();
+ //this.cache = new DatabaseCache(10);
+ this.theTable="messages";
+ }
}
--- /dev/null
+package mircoders.storage;
+
+import java.lang.*;
+import java.sql.*;
+import java.io.*;
+import java.util.*;
+
+import freemarker.template.*;
+
+import mir.storage.*;
+import mir.entity.*;
+import mir.misc.*;
+
+/**
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
+ *
+ *
+ */
+
+public class DatabaseOther extends Database implements StorageObject{
+
+ private static DatabaseOther instance;
+ private static SimpleList publisherPopupData;
+
+ public static DatabaseOther getInstance() throws StorageObjectException
+ {
+ if (instance == null) {
+ instance = new DatabaseOther();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseOther() throws StorageObjectException
+ {
+ super();
+ this.hasTimestamp = true;
+ this.theTable="other_media";
+ this.theCoreTable="media";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityOther");
+ }
+ catch (Exception e) { throw new StorageObjectException(e.toString()); }
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("title",true);
+ }
+
+ public void update(Entity theEntity) throws StorageObjectException
+ {
+ 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 StorageObjectException
+ {
+ 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
+
+}
this.theTable="rights";
}
- public SimpleList getPopupData() { return getPopupData("name",true); }
+ public SimpleList getPopupData() throws StorageObjectException
+ { return getPopupData("name",true); }
}
public class DatabaseTopics extends Database implements StorageObject{
- private static DatabaseTopics instance;
-
- public static DatabaseTopics getInstance() throws StorageObjectException {
- if (instance == null) {
- instance = new DatabaseTopics();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseTopics() throws StorageObjectException
- {
+ private static DatabaseTopics instance;
+
+ public static DatabaseTopics getInstance() throws StorageObjectException {
+ if (instance == null) {
+ instance = new DatabaseTopics();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseTopics() throws StorageObjectException
+ {
super();
- this.cache = new HashMap();
- this.hasTimestamp = false;
- this.theTable="topic";
- try {
- this.theEntityClass = Class.forName("mircoders.entity.EntityTopics");
- }
- catch (Exception e) {
- throw new StorageObjectException(e.toString());
- }
-
- }
-
- public SimpleList getPopupData() {
- return getPopupData("title",true);
- }
+ //this.cache = new DatabaseCache(20);
+ this.hasTimestamp = false;
+ this.theTable="topic";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityTopics");
+ }
+ catch (Exception e) {
+ throw new StorageObjectException(e.toString());
+ }
+
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("title",true);
+ }
/**
- * returns the comments that belong to the article (via entityrelation)
+ * returns the media_type that belongs to the media item (via entityrelation)
* where db-flag is_published is true
*/
- public Entity getMediaType(Entity ent) {
+ public Entity getMediaType(Entity ent) throws StorageObjectException {
Entity type=null;
try {
type = relationMediaType.getOne(ent);
}
catch (StorageObjectException e) {
theLog.printError("DatabaseUploadedMedia :: failed to get media_type");
+ throw new StorageObjectException("DatabaseUploadedMedia :: failed to get media_type"+ e.toString());
}
return type;
}
}
}
- public SimpleList getPopupData() {
+ public SimpleList getPopupData() throws StorageObjectException {
return getPopupData("login",true);
}
}
--- /dev/null
+package mircoders.storage;
+
+import java.lang.*;
+import java.sql.*;
+import java.io.*;
+import java.util.*;
+
+import freemarker.template.*;
+
+import mir.storage.*;
+import mir.entity.*;
+import mir.misc.*;
+
+/**
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
+ *
+ *
+ */
+
+public class DatabaseVideo extends Database implements StorageObject{
+
+ private static DatabaseVideo instance;
+ private static SimpleList publisherPopupData;
+
+ public static DatabaseVideo getInstance() throws StorageObjectException
+ {
+ if (instance == null) {
+ instance = new DatabaseVideo();
+ instance.myselfDatabase = instance;
+ }
+ return instance;
+ }
+
+ private DatabaseVideo() throws StorageObjectException
+ {
+ super();
+ this.hasTimestamp = true;
+ this.theTable="video";
+ this.theCoreTable="media";
+ try {
+ this.theEntityClass = Class.forName("mircoders.entity.EntityVideo");
+ }
+ catch (Exception e) { throw new StorageObjectException(e.toString()); }
+ }
+
+ public SimpleList getPopupData() throws StorageObjectException {
+ return getPopupData("title",true);
+ }
+
+ public void update(Entity theEntity) throws StorageObjectException
+ {
+ 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 StorageObjectException
+ {
+ String date = theEntity.getValue("date");
+ if (date==null){
+ date = StringUtil.date2webdbDate(new GregorianCalendar());
+ theEntity.setValueForProperty("date",date);
+ }
+ return super.insert(theEntity);
+ }
+
+}
+++ /dev/null
-package mircoders.storage;
-
-import java.lang.*;
-import java.sql.*;
-import java.io.*;
-import java.util.*;
-
-import freemarker.template.*;
-
-import mir.storage.*;
-import mir.entity.*;
-import mir.misc.*;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseVideos extends Database implements StorageObject{
-
- private static DatabaseVideos instance;
- private static SimpleList publisherPopupData;
-
- public static DatabaseVideos getInstance() throws StorageObjectException
- {
- if (instance == null) {
- instance = new DatabaseVideos();
- instance.myselfDatabase = instance;
- }
- return instance;
- }
-
- private DatabaseVideos() throws StorageObjectException
- {
- super();
- this.hasTimestamp = true;
- this.theTable="videos";
- this.theCoreTable="media";
- try {
- this.theEntityClass = Class.forName("mircoders.entity.EntityVideo");
- }
- catch (Exception e) { throw new StorageObjectException(e.toString()); }
- }
-
- public SimpleList getPopupData() {
- return getPopupData("title",true);
- }
-
- public void update(Entity theEntity) throws StorageObjectException
- {
- 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 StorageObjectException
- {
- theEntity.setValueForProperty("to_media_type","3");
- String date = theEntity.getValue("date");
- if (date==null){
- date = StringUtil.date2webdbDate(new GregorianCalendar());
- theEntity.setValueForProperty("date",date);
- }
- return super.insert(theEntity);
- }
-
-}
<include "head.template">
-<form enctype="multipart/form-data" method="post" action="${actionRoot}?module=Images&<compress>do=
- <if new>insert<else>update</if></compress>&id=${id}">
+<form enctype="multipart/form-data" method="post" action="${actionRoot}?module=Images&do=<if new>insert<else>update</if>&id=${id}">
<if icon_data=="" || icon_data=="0">
<INPUT TYPE="file" NAME="mptest">
</if>
</tr>
<if contentlist>
<list contentlist as entry>
- <tr <compress><if grey=="1"><assign grey="0">bgcolor="#dddddd" <else><assign grey="1"> </if></compress>>
+ <tr <if grey=="1"><assign grey="0">bgcolor="#dddddd" <else><assign grey="1"> </if>>
<td>
<if entry.icon_data!="" && entry.icon_data!="0">
<a href="${actionRoot}?module=Images&do=showimg&id=${entry.id}" target="new">
</td>
</tr>
- <tr>
+ <tr>
<td align="right" bgcolor="#006600"><font color="#ffffff" face="Verdana, Arial, Helvetica, sans-serif" size="-1">
- <B>Text der Breaking News:</B></font></td>
+ <B>text:</B> (max. 5 lines / 250 characters)</font></td>
<td>
- <textarea cols="40" rows="2" name="text">${text}</textarea>
+ <textarea cols="50" rows="3" name="text" wrap=virtual>${text}</textarea>
</td>
</tr>
<if contentlist>
<list contentlist as entry>
- <tr <compress><if grey=="1"><assign grey="0">bgcolor="#dddddd" <else><assign grey="1"> </if></compress>>
+ <tr <transform compressWhitespace><if grey=="1"><assign grey="0">bgcolor="#dddddd" <else><assign grey="1"> </if></transform>>
<td>${entry.date}<br>
<if entry.is_published=="0"><font color="Brown">V</font><else>-</if>
</td>
<html>
-
-<head>
-<title>Indymedia Germany | Open Posting | ${now}</title>
-
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
-
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
-
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
-
- <link rel="stylesheet" href="mir.css" type="text/css">
-</head>
-
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" alink="#ffffff" vlink="#cc0033">
-
-<!-- ###### form ###### -->
+<head><title>indymedia.de | comment.commit</title></head>
+<body bgcolor="white" text="black" link="#006600" vlink="#009900" alink="red">
+
+<form action="${openAction}" method=post>
+<input type="hidden" name="do" value="inscomment">
- <form action="${openAction}" method=post>
- <input type="hidden" name="do" value="inscomment">
- <table width="99%" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee">
+<table width="100%" border="0" cellspacing="0" cellpadding="4" bgcolor="silver">
<tr>
- <td bgcolor="#cc0033" colspan="3">
- <font color="White"><b>Kommentierung eines Beiträgs bei Indymedia</b></font>
- </td>
+ <td bgcolor="#663399" colspan="3">
+ <font color="White"><b>Kommentierung eines Beiträgs bei Indymedia</b></font>
+ </td>
</tr>
- <!-- ###### info text ###### -->
<tr>
- <td bgcolor="#eeeeee" colspan="3">
- <font color="#000000">
- <br><br>
- Bitte respektiere die Meinungen anderer und bleibe beim
- <b>Thema des Artikels</b>, den Du kommentierst und versuche,
- <b>präzise</b> zu sein.
- <br><br>
- Indymedia ist grundsätzlich offen für alle Meinungen,
- es sei denn sie haben faschistische, rassistische,
- sexistische oder generell menschenverachtende Inhalte.
- Bedenke bei Deinem Kommentar, dass die Leute, die hier
- schreiben, nicht unbedingt einer Weltanschauung sind.
- Darum beurteile sie auch nicht danach. Indymedia ist
- für alle, die meinen, etwas zu sagen zu haben zu den
- politischen und sozialen Verhältnissen auf der Welt.
- Darum erwarten wir, dass Kommentar-SchreiberInnen
- grundsätzlich solidarisch auf andere Meinungen
- reagieren. Wir behalten uns vor, diffamierende
- Aburteilungen und Beschimpfungen zu löschen.
- <br><br>
- </font>
- </td>
+ <td bgcolor="#003300" colspan="3">
+ <p>
+ <font color="white"">
+ Hinweis: Dein Kommentar kann in jedem Stil und jeder Form sein, akademisch bis persönlich.<br>
+ Aber bitte bleibe beim <b>Thema des Artikels</b>, den Du kommentierst und versuche, <b>präzise</b> zu sein.
+ </font>
+ </p>
+
+ </td>
</tr>
- <!-- ###### header ##### -->
<tr>
- <td bgcolor="#cc0033" colspan="3">
- <font face="Helvetica, Arial" color="white" size=+2><b>Kommentierungsformular</b></font>
- </td>
+ <td bgcolor="#663399" colspan="3">
+ <font face="Helvetica, Arial" color="white" size=+2><b>Kommentierungsformular</b></font>
+ </td>
</tr>
- <!-- ###### titel ##### -->
<tr>
- <td>
- <b>Titel des Kommentars:</b></td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="title" size="45" maxlength="45"><br>
- <font size="-1" color="#333333">[ muss ausgefüllt werden ]</font>
- </td>
+ <td>
+ <b>Titel des Kommentars:</b>
+ </td>
+ <td colspan="2">
+ <input type="text" name="title" size="45" maxlength="45"> <font size="-1" color="#663399">(muss ausgefüllt werden)</font>
+ </td>
</tr>
- <!-- ###### creator ##### -->
<tr>
- <td>
- <b>Dein Name:</b>
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator" size="45" maxlength="45"><br>
- <font size="-1" color="#333333">[ muss ausgefüllt werden ]</font>
- </td>
+ <td>
+ <b>Dein Name:</b>
+ </td>
+ <td colspan="2">
+ <input type="text" name="creator" size="20" maxlength="45"> <font size="-1" color="#663399">(muss ausgefüllt werden)</font>
+ </td>
</tr>
- <!-- ###### email ##### -->
<tr>
- <td>
- Deine eMail-Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="email" size="45" maxlength="80"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
+ <td>
+ Deine eMail-Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="email" size="30" maxlength="80"> <font size="-1">(<i>optional</i>)</font>
+ </td>
</tr>
- <!-- ###### web ##### -->
<tr>
- <td>
- Deine Web Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="main_url" size="45" maxlength="160" value="http://"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
+ <td>
+ Deine Web Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="main_url" size="40" maxlength="160" value="http://"> <font size="-1">(<i>optional</i>)</font>
+ </td>
</tr>
- <!-- ###### phone ##### -->
<tr>
- <td>
- Deine Telefon-Nr.:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="phone" size="45" maxlength="80"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
+ <td>
+ Deine Telefon-Nr.:
+ </td>
+ <td colspan="2">
+ <input type="text" name="phone" size="30" maxlength="80"> <font size="-1">(<i>optional</i>)</font>
+ </td>
</tr>
- <!-- ###### adress ##### -->
<tr>
- <td>
- Deine Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="address" size="45" maxlength="160"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
+ <td>
+ Deine Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="address" size="40" maxlength="160"><font size="-1"> <i>(optional)</i></font>
+ </td>
</tr>
- <!-- ###### leguage ##### -->
<tr>
- <td>
- Die Sprache deines Kommentares:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <select name="to_language">
- <option value="0">de</option>
- <option value="1">en</option>
- </select>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
+ <td>
+ Die Sprache deines Kommentares:
+ </td>
+ <td colspan="2">
+ <select name="to_language">
+ <option value="0">de</option>
+ <option value="1">en</option>
+ </select>
+ <font size="-1"><i>(optional)</i></font>
+ </td>
</tr>
- <!-- ###### coment ##### -->
<tr>
- <td valign="top">
- <b>Dein Kommentar:</b>
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <textarea name="description" rows="20" cols="60" wrap=virtual></textarea><br><br>
- </td>
+ <td valign="top">
+ <b>Dein Kommentar:</b>
+ </td>
+ <td bgcolor="#003300" colspan="2">
+ <textarea name="description" rows="20" cols="60" wrap=virtual></textarea>
+ <br><br>
+ </td>
</tr>
- <!-- ###### submit ##### -->
<tr>
- <td>
- Bitte drücke den Verschicken-Knopf<b> nur einmal</b>!!!<br>
- In wenigen Minuten ist Dein Kommentar unter dem kommentierten
- Artikel. Manchmal kann es aber aufgrund technischer Probleme
- etwas dauern bis er erscheint.
- <br><br>
- Die <b>Moderationskriterien</b> kannst Du
- <a href="/static/moderation.html">hier nachlesen</a><br><br>
- </td>
- <td bgcolor="#dddddd" valign="top" align="center"><br>
- <input type="submit" value="Kommentar abschicken"><br>
- </td>
- <td bgcolor="#dddddd" valign="top" align="center"><br>
- <input type="reset" value="Formular löschen"><br>
- <input type="hidden" name="to_media" value="${aid}"><br>
- </td>
+ <td>
+ </td>
+ <td bgcolor="#663399" valign="top" align="center">
+ <br>
+ <input type="submit" value="Kommentar abschicken"><br>
+
+ </td>
+ <td bgcolor="#003300" valign="top" align="center">
+ <br>
+ <input type="reset" value="Formular löschen"><br>
+ <input type="hidden" name="to_media" value="${aid}">
+ <br>
+ </td>
</tr>
</table>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
- <head>
- <title>Indymedia Germany | Comment done | ${now}</title>
-
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
+<html>
+<head>
+ <title>indymedia.de | open posting</title>
+</head>
- <link rel="stylesheet" href="mir.css" type="text/css">
- </head>
+<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" alink="#ffffff" vlink="#cc0033">
- <table align="center" width="750" border="0" cellspacing="0" cellpadding="5" bgcolor="#eeeeee">
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <font color="#ffffff"><b>Immer ruhig mit den jungen Pferden!</b></font
- </td>
- </tr>
- <tr>
- <td bgcolor="#eeeeee">
- <font color="000000"><br><br>
- Du hast vermutlich den Reload-Button
- benutzt oder versucht, Deinen Kommentar noch einmal zu posten. Das ist aber
- unnötig. Die Tatsache, dass Du diesen Text liest, bedeutet, dass Dein
- Kommentar schon angekommen ist. Er wird gleich auf der Seite auftauchen. Versprochen.
- <center><em>Keine Panik!</em></center><br><br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <a href="javascript:history.go(-2)">
- <font color="#ffffff"><b>>> Zurück zum kommentierten Artikel</b></font></a>
- </td>
- </tr>
- </table>
+<table width="100%" border="0" cellspacing="0" cellpadding="10">
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <font color="White"><b>Dein Kommentar ist jetzt auf dem Weg zur WebSite!</b></font
+ </td>
+ </tr>
+ <tr>
+ <td bgcolor="003300">
+ <font color="White">
+ <br>
+ Er landet direkt in einem intelligenten Filter - und wenn er keine rassistischen, sexistischen oder faschistischen Inhalte oder Werbung enthält, wird er in Kürze auf http://www.germany.indymedia.org/newswire/ auftauchen.<br>
+ <br>
+ <center><em>Gedulde Dich einen Moment - Es lohnt sich!</em></center><br>
+ <br>
+ </font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück zum kommentierten Artikel</b></font></a>
+ </td>
+ </tr>
+</table>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
- <head>
- <title>Indymedia Germany | Comment done | ${now}</title>
-
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
+<html>
+<head>
+ <title>indymedia.de | open posting - Kommentar-Duplikat</title>
+</head>
- <link rel="stylesheet" href="mir.css" type="text/css">
- </head>
+<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" alink="#ffffff" vlink="#cc0033">
- <table align="center" width="750" border="0" cellspacing="0" cellpadding="5" bgcolor="#eeeeee">
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <font color="#ffffff"><b>Immer ruhig mit den jungen Pferden!</b></font
- </td>
- </tr>
- <tr>
- <td bgcolor="#eeeeee">
- <font color="000000"><br><br>
- Du hast vermutlich den Reload-Button
- benutzt oder versucht, Deinen Kommentar noch einmal zu posten. Das ist aber
- unnötig. Die Tatsache, dass Du diesen Text liest, bedeutet, dass Dein
- Kommentar schon angekommen ist. Er wird gleich auf der Seite auftauchen. Versprochen.
- <center><em>Keine Panik!</em></center><br><br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <a href="javascript:history.go(-2)">
- <font color="#ffffff"><b>>> Zurück zum kommentierten Artikel</b></font></a>
- </td>
- </tr>
- </table>
+<table width="100%" border="0" cellspacing="0" cellpadding="10">
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <font color="White"><b>
+ Immer ruhig mit den jungen Pferden!
+ </b></font
+ </td>
+ </tr>
+ <tr>
+ <td bgcolor="003300" width=70%>
+ <font color="White">
+ <br>
+ Du hast vermutlich den Reload-Button
+ benutzt oder versucht, Deinen Kommentar noch einmal zu posten. Das ist aber
+ unnötig. Die Tatsache, dass Du diesen Text liest, bedeutet, dass Dein
+ Kommentar schon angekommen ist. Er wird gleich auf der Seite auftauchen. Versprochen.
+ <br>
+ <center><em>Keine Panik</em></center><br>
+ <br>
+ </font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück zum kommentierten Artikel</b></font></a>
+ </td>
+ </tr>
+</table>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//DE">
<html>
<head>
-<title>Indymedia Germany | Open Posting | ${now}</title>
-
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
-
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
-
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
-
-<link rel="stylesheet" href="mir.css" type="text/css">
+ <title>indymedia.de | open posting</title>
+ <meta name="description" content="Indymedia Germany | Unabhängiges Medienzentrum">
+ <meta name="author" content="IMC Kollektiv">
+ <meta name="keywords" content="Freie Medien, Gegenöffentlichkeit">
+ <meta name="date" content="### Date ###Time">
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8559-1">
+ <meta name="robots" content="index">
+ <meta name="robots" content="follow">
+ <link rel=stylesheet type="text/css" href="${productionHost}/style/formate.css">
</head>
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" alink="#ffffff" vlink="#cc0033">
-
-<!-- ###### main table ###### -->
-
- <table width="99%" border="0" cellspacing="0" cellpadding="10" bgcolor="#eeeeee">
- <tr>
- <td align="center" bgcolor="#dddddd" colspan="3">
- <fontsize="+1">
- <b><a href="#form">Direkt zum Eingabeformular springen!</a></b>
- </font><br>
- </td>
- </tr>
- <tr>
- <td align="center" bgcolor="#cc0033" colspan="3"><br>
- <font size="+2" color="#ffffff" face="Helvetica, Arial">Veröffentliche Deinen Beitrag</font><br><br>
- </td>
- </tr>
- <tr>
- <td colspan="3" bgcolor="#ffffff">
- <h3><b>Kurze Anleitung zum Posten eines Beitrages in de.indymedia.org</b></h3>
-
-<!-- ###### text ###### -->
-
-<b>I</b>ndymedia ist ein basisdemokratischer Nachrichtenkanal.
-Wir arbeiten aus Liebe und aus Respekt gegenüber Menschen,
-die sich für eine bessere, lebenswertere Welt engagieren.
-Bei Indymedia kann grundsätzlich JedeR Texte, Videos, Audios oder Fotos
-zu politischen oder sozialen Themen veröffentlichen.
-<br><br>
-
-Indymedia will vor allem die Möglichkeit geben,
-subjektive Stellungnahmen verschiedenster Menschen
-'auf der Strasse' über politische Ereignisse oder aus
-der alltäglichen Lebenswelt zu veröffentlichen. Zudem
-ist Indymedia eine Plattform für Hintergrundberichte,
-die andere Hintergründe als kommerzielle Medien aufzeigen.
-<br><br>
+<body bgcolor="White" text="Black" link="white" vlink="white" alink="Red">
-Um indymedia als Plattform für eigene
-Berichterstattung zu konturieren, werden bestimmte
-Beiträge nicht auf die Startseite gestellt. Dazu gehören:
-<br><br>
-<ul>
-<li>
-Termine und Demoaufrufe [ Weil wir wissen, dass diese für die Mobilisierung
-sehr wichtig sind, verlinken wir zu verschiedenen Internetprojekten, auf
-denen Ihr gute Terminsammlungen findet ] Bei angelaufenen Kampagnen werden
-regelmäßig Termine und Aufrufe in die Mittelspalten-Texte als Links gesetzt.
-<br><br>
+<table width="99%" border="0" cellspacing="0" cellpadding="8" bgcolor="silver">
+ <tr>
+ <td align="center" bgcolor="#663399" colspan="3">
+ <font face="Helvetica, Arial"><a href="#form">Direkt zum Eingabeformular springen!</a></font>
+ <br>
+ </td>
+ </tr>
+ <tr>
+ <td align="center" colspan="3">
+ <br>
+ <font size="+2" face="Helvetica, Arial">Veröffentliche Deinen Beitrag</font><br><br>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3" bgcolor="white">
+ <h3>Kurze Anleitung zum Posten eines Beitrages in germany.indymedia</h3>
-<li>
-schon an anderen Stellen veröffentlichte Texte aus kommerziellen Medien
-kopierte Texte<br>
-[ hierbei sind Übersetzungen von Texten und Meldungen
-von hier kaum zugänglichen Medien eine Ausnahme ]
-<br><br>
+ <p><b>D</b>as Independent Media Center ist ein kollektiv geführtes Mediennetzwerk zur Produktion von radikalen, passionierten und durchaus auch subjektiven, persönlichen Stellungnahmen verschiedenster Menschen 'auf der Strasse', z.B. vor, während oder nach Kampagnen, polit. Ereignissen oder aus der alltäglichen Lebenswelt. Wir arbeiten aus Liebe und aus Respekt gegenüber Menschen, die sich für eine bessere, lebenswertere Welt engagieren, und deren Arbeit von den Medienkonzernen nicht oder nur verzerrt dargestellt wird.</p>
-<li>Gruppenstatements, Presseerklärungen, Diskussionspapiere, Massenmails
-<br>
+ <p>Indymedia ist ein demokratischer Nachrichtenkanal. Wir <b>wollen</b> Beiträge, Artikel, Meinungen und Infos aus der ganzen Welt veröffentlichen. Alle Beiträge werden sofort unzensiert veröffentlicht, sofern sie nicht in die im <b>Mission Statement</b> genannten Kategorien fallen. Allerdings erscheinen sie dann nicht gleich auf der Startseite, sondern auf einer eigenen Open-Posting-Seite. Dort werden sie von wechselnden Moderationsteams gegengelesen und
+ anschliessend auf den newswire der Starttseite weitergeleitet.<br>
+ Um diesen Ausschlussprozess so transparent wie möglich zu gestalten, können alle nicht veröffentlichten Beiträge per e-mail angefordert weren.</p>
-[auch hier geht es um die Zugänglichkeit von Texten. Beiträge von
-Gruppen, die schon auf zahlreichen anderen Internet-Seiten oder in
-Zeitschriften veröffentlicht wurden, werden nicht auf die Startseite
-gestellt, weil es nicht der Ansatz von indymedia ist alles
-irgendwie relevante auf der Seite zu versammeln, sondern eine
-Plattform für eigene Berichterstattung zu sein. Unter eigener
-Berichtserstattung verstehen wir allerdings Presseerklärungen
-von Kleingruppen oder Diskussionspapiere einzelner
-<br><br>
-<li>
-superkurze Meldungen:
-<br><br>
+ <p>Bitte benutze dieses Formular nur, um <b>neue</b> Beiträge und Ideen beizusteuern. Kommentare gehören zu dem jeweils diskutierten Beitrag. Wenn Du etwas zu einem Beitrag zu sagen hast, dann benutze dafür bitte die <b>Kommentar-Funktion</b> am Ende jedes Beitrags.</p>
-<li>
-reine Kommentare ohne Nachrichtenwert<br>
-[ Zusätzlich zu den selbstverfassten Beiträgen, gibt es bei indymedia
-noch die Möglichkeit über Artikel zu diskutieren.
-Das könnt Ihr unter dem jeweiligen Artikel - einfach auf
-"Kommentar eingeben" klicken ]
-<br><br>
+ <p>Unser Auffassung nach sollten Beiträge, die an diese Site geschickt werden, frei zur nicht-kommerziellen Wiederverwertung sein. Wenn Du nicht möchtest, dass das für Deinen Beitrag zutrifft, dann nenne Deine Konditionen in der Zusammenfassung.</p>
-<li>
-Beiträge von hierarchischen Gruppen und Parteien
-<br><br>
+ <p>Du kannst dieses Formular benutzen, um Deinen Artikel, Deinen Audio-Beitrag, Deinen Video-Beitrag oder Deine Fotos zu veröffentlichen. Bitte beschränke Dich auf Beiträge zu politischem oder sozialem Aktivismus. Wir (die Menschen, die diese Site organisieren) behalten uns vor, die Präsentation der zugeschickten Beiträge zu verändern. Weitere Informationen findest Du im <b>Mission Statement</b>.</p>
-<li>
-Außerdem gibt es Beiträge, die sofort in ein
-Müllarchiv kommen:
-<br><br>
-[1] Diskriminierender oder menschenverachtender Inhalt.
-<br><br>
-[2] Offensichtlicher Spam
+ <p>Nach dem Beiträge veröffentlicht wurden, können sie vom Kollektiv, das diese Site betreut, editiert, verlinkt oder sogar gelöscht werden.</p>
+ <br>
-</ul>
-
-<br><br>
-Was mit Eurem Beitrag passiert, lest Ihr am besten
-unter Grundsätze und Moderation nach. Hier eine kurze Zusammenfassung:
-<br><br>
-
-Alle Beiträge werden sofort unzensiert veröffentlicht.
-Allerdings erscheinen sie dann nicht gleich auf der
-Startseite, sondern auf der Open-Posting-Seite
-<a href="/open.shtml">alle Beiträge</a>
-alle Beiträge. Dort werden sie von Moderationskollektiven
-gegengelesen. Entsprechen sie den indymedia-Grundsätzen
-werden sie auf den newswire der Startseite weitergeleitet.
-In die Mittelspalte nehmen wir in der Regel Beiträge,
-die einen guten Überblick über ein aktuelles Thema geben.
-Diese Artikel werden von uns auch leicht redigiert:
-Wir korrigieren Rechtschreibfehler, versuchen unverständliche
-Stellen zu glätten und setzen Links hinein. Verlautbarungen,
-Texte, die keinen politischen oder sozialen Inhalt haben,
-reine Diskussionsbeiträge und Termine bleiben im Open Posting.
-Texte mit menschenverachtendem Inhalt oder Spam kommen ins
-Müllarchiv. Damit sind sie nicht mehr einsehbar. Wer
-sie trotzdem lesen will, kann sie per e-mail anfordern.
-Diese Moderationskriterien sind Resultat eines weltweiten
-Diskussionsprozesses über indymedia und werden ständig neu
-diskutiert und überarbeitet.
-<br><br>
-
-Urheberrecht: Unserer Auffassung nach sollten
-Beiträge, die an diese Site geschickt werden, frei zur
-nicht-kommerziellen Wiederverwertung sein. Wenn Du
-nicht möchtest, dass das für Deinen Beitrag zutrifft,
-dann nenne Deine Konditionen in der Zusammenfassung.
-<br><br>
-
- </td>
- </tr>
-
-
-<!-- ###### form ###### -->
- <tr>
- <td bgcolor="#cc0033" colspan="3">
- <center><font size="+2" face="Helvetica, Arial" color="#ffffff">
- <b>Veröffentlichungsformular</b>
- </font></center>
- </td>
- </tr>
+ <p><b>Zur Erinnerung:</b><p>
+ <ul>
+ <li>Bitte schicke <b>nur News-Artikel</b> und benutze zum Kommentieren von Artikeln das <b>Kommentierformular</b>, das Du unter jedem Artikel findest.
+ <li>Bitte schicke <b>nur eine Kopie</b> Deines Artikels - Bitte drücke den Verschicken-Knopf nur einmal</b>.
+ <li><b>Veröffentliche nur selbst erstellte Beiträge. (Keine Agenturmeldungen, Zeitungsartikel oder ähnliches!)</b>.
+ </ul>
+ </td>
+ </tr>
<form action="${openAction}?do=addposting" method="post">
- <tr>
- <td valign="top">
- Anzahl der Medien
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="medianum" value="${medianum}"> <input type="submit">
- </tr>
+ <tr>
+ <td>Anzahl der Medien</td>
+ <td colspan="2"><input type="text" name="medianum" value="${medianum}"> <input type="submit">
+ </tr>
</form>
<a name="form"></a>
<form enctype="multipart/form-data" action="${openAction}?do=insposting" method="post">
-
-<!-- ###### title ###### -->
- <tr>
- <td valign="top">
- Gib Deinem Beitrag einen <b>Titel</b>:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="title" size="65" maxlength="65" value=""><br>
- <font size="-1" color="#333333">[ muss ausgefüllt werden ]
- </font>
- </td>
- </tr>
-<!-- ###### topic ###### -->
- <tr>
- <td valign="top">
- <b>Thema</b> Von Deinem Beitrag:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <select name="to_topic" size="4" multiple>
- <list themenPopupData as t>
- <option value="${t.key}" <list to_topic as to><if (t.key == to)>selected</if></list>>${t.value}</option>
- </list>
- </select><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### creator ###### -->
- <tr>
- <td valign="top">
- <b>AutorIn</b> des Beitrags:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator" size="65" maxlength="45"><br>
- <font size="-1" color="#333333">[ muss ausgefüllt werden ]</font>
- </td>
- </tr>
-<!-- ###### abstract ###### -->
- <tr>
- <td valign="top">
- Eine kurze <b>Zusammenfassung</b> des Beitrags:</b>
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <textarea name="description" rows="12" cols="65" wrap=virtual></textarea><br>
- <font size="-1" color="#333333">[ nicht mehr als <b>15 Zeilen</b> ]</font>
- </td>
- </tr>
-<!-- ###### info ###### -->
- <tr>
- <td colspan="3">
- <font face="Helvetica, Arial" size=-1 color="#666666">
- Die Kontaktinformationen sind optional, aber ermöglichen,
- dass unser Publikum (z.B. auch JournalistInnen) Dich bezüglich
- Deines Beitrages erreichen können, was auch eine Weiterverwertung
- Deines Beitrages an anderen Stellen ermöglicht.
- </font>
- </td>
- </tr>
-<!-- ###### email ###### -->
- <tr>
- <td>
- Deine eMail-Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator_email" size="65" maxlength="80" value=""><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### web ###### -->
- <tr>
- <td>
- Deine Web Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator_main_url" size="65" maxlength="160" value="http://"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### adress ###### -->
- <tr>
- <td>
- Deine Adresse:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator_address" size="65" maxlength="160" value=""><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### phone ###### -->
- <tr>
- <td>
- Deine Telefon-Nr.:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="creator_phone" size="30" maxlength="30" value=""><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### lenguage ###### -->
- <tr>
- <td>
- Die Sprache deines Beitrages:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <select name="to_language">
- <list languagePopUpData as l>
- <option value="${l.key}">${l.value}</option>
- </list>
- </select><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### content ###### -->
- <tr>
- <td valign="top">
- ein <b>Artikel</b>:<br>
- Der Text, der Deinen Beitrag begleiten soll -
- wenn Du nur Text schicken willst, dann benutze auch dafür dieses Feld.
- </td>
- <td bgcolor="#dddddd" colspan="2">
- <textarea name="content_data" rows="20" cols="65" wrap="soft"></textarea>
- <br><br>
- </td>
- </tr>
-<!-- ###### multimedia ###### -->
- <tr>
- <td>
- Medien:
- </td>
- <td colspan="2">
- Hier kannst Du ein Medien zu Deinem Artikel hochladen<br>
- </td>
- </tr>
- <list mediafields as m>
- <tr>
- <td>Bild ${m}</td>
- <td colspan="2" bgcolor="#dddddd">
- <INPUT TYPE="file" NAME="media${m}"><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
-<!-- ###### media subtitle ###### -->
- <tr>
- <td>
- Medienunterschrift ${m}:
- </td>
- <td colspan="2" bgcolor="#dddddd">
- <input type="text" name="media_title${m}" size="65" maxlength="80" value=""><br>
- <font size="-1" color="#333333">[ optional ]</font>
- </td>
- </tr>
+ <tr>
+ <td bgcolor="#663399" colspan="3">
+ <center><font size="+2" face="Helvetica, Arial" color="white"><b>Veröffentlichungsformular</b></font></center>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top">
+ Gib Deinem Beitrag einen <b>Titel</b>:
+ </td>
+ <td colspan="2" bgcolor="#003300">
+ <input type="text" name="title" size="45" maxlength="45" value=""> <font size="-1" color="white"><br>(muss ausgefüllt werden)</font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top">
+ <b>Thema</b> Von Deinem Beitrag:
+ </td>
+ <td colspan="2">
+ <select name="to_topic" size="3" multiple>
+ <list themenPopupData as t>
+ <option value="${t.key}" <list to_topic as to><if (t.key == to)>selected</if></list>>${t.value}</option>
+ </list>
+ </select>
+ <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top">
+ <b>AutorIn</b> des Beitrags:
+ </td>
+ <td colspan="2" bgcolor="#003300">
+ <input type="text" name="creator" size="45" maxlength="45"> <font size="-1" color="white"><br>(muss ausgefüllt werden)</font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top">
+ Eine kurze <b>Zusammenfassung</b> des Beitrags:</b>
+ </td>
+ <td colspan="2" bgcolor="#003300">
+ <textarea name="description" rows="6" cols="45" wrap=virtual></textarea>
+ <font size="-1" color="white"><br>(nicht mehr als <b>5 Zeilen</b>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="3">
+ <font face="Helvetica, Arial" size=-1 color="#663399">
+ Die Kontaktinformationen sind optional, aber ermöglichen, dass unser Publikum (z.B. auch JournalistInnen) Dich bezüglich Deines Beitrages erreichen können, was auch eine Weiterverwertung Deines Beitrages an anderen Stellen ermöglicht.
+ </font>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ Deine eMail-Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="creator_email" size="45" maxlength="80" value=""> <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Deine Web Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="creator_main_url" size="45" maxlength="160" value="http://">
+ <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Deine Adresse:
+ </td>
+ <td colspan="2">
+ <input type="text" name="creator_address" size="45" maxlength="160" value=""> <font size="-1"> <i>(optional)</i></font>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Deine Telefon-Nr.:
+ </td>
+ <td colspan="2">
+ <input type="text" name="creator_phone" size="20" maxlength="20" value=""> <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Die Sprache deines Beitrages:
+ </td>
+ <td colspan="2">
+ <select name="to_language">
+ <list languagePopUpData as l>
+ <option value="${l.key}">${l.value}</option>
+ </list>
+ </select>
+ <font size="-1"><i>(optional)</i></font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top">
+ Dein <b>Artikel</b>:<br>
+ Der Text, der Deinen Beitrag begleiten soll - wenn Du nur Text schicken willst, dann benutze auch dafür dieses Feld.
+ </td>
+ <td bgcolor="#003300" colspan="2">
+ <textarea name="content_data" rows="20" cols="45" wrap="soft"></textarea>
+ <br><br>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ Medien:
+ </td>
+ <td colspan="2">
+ Hier kannst Du ein Medien zu Deinem Artikel hochladen (bislang nur jpg-Bilder)<br>
+ </td>
+ </tr>
+<list mediafields as m>
+ <tr>
+ <td>Bild ${m}</td>
+ <td colspan="2">
+ <INPUT TYPE="file" NAME="media${m}"> <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ Medienunterschrift ${m}:
+ </td>
+ <td colspan="2">
+ <input type="text" name="media_title${m}" size="40" maxlength="80" value=""> <font size="-1">(<i>optional</i>)</font>
+ </td>
+ </tr>
</list>
+ <tr>
+ <td><b </td>
+ <td bgcolor="#663399" valign="top" align="center"><br>
+ <input type="submit" value="Beitrag abschicken"><br>
+
+ </td>
+ <td bgcolor="#003300" valign="top" ge-aln="center">
+ <br>
+ <input type="reset" value="Formular löschen"><br>
+ </td>
+ </tr>
+</table>
-<!-- ###### info ###### -->
- <tr>
- <td>
- <br><br>
- <!-- ###### infotext ###### -->
- Bitte drücke den Verschicken-Knopf<b> nur einmal</b>!!!<br>
- In wenigen Minuten erscheind Dein Beitrag dann auf der
- <a href="/open.shtml">
- <b>"Open Posting"</b></a> - Seite.<br>
- Das ist nicht die Startseite.<br>
- Manchmal kann es aber aufgrund technischer Probleme
- etwas dauern bis er erscheint.
- <br><br>
- Die <b>Moderationskriterien</b> kannst Du
- <a href="/static/moderation.html"><b>hier nachlesen</b></a>
- <br><br>
- </td>
-
-<!-- ###### submit the form ###### -->
-
- <td bgcolor="#dddddd" valign="top" align="center"><br>
- <input type="submit" value="Beitrag abschicken"><br>
- </td>
- <td bgcolor="#dddddd" valign="top" align="center"><br>
- <input type="reset" value="Formular löschen"><br>
- </td>
- </tr>
-</table>
</body>
</html>
<html>
<head>
-<title>Indymedia Germany | Open Posting | ${now}</title>
-
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <title>indymedia.de | open posting</title>
+</head>
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
+<body bgcolor="White" text="Black" link="#006600" vlink="#009900" alink="Red">
+<table><tr>
+<td valign=top align=left>
+<font face="Helvetica, Arial" size=-1>
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
- <link rel="stylesheet" href="mir.css" type="text/css">
-</head>
+
+<table width="100%" border="0" cellspacing="0" cellpadding="4" bgcolor="#663399">
+ <tr>
+ <td align="center"><font color="White">Hurra, Du hast Deinen Artikel abgeschickt!</font></td>
+
+ </tr>
+ </table>
+<table border=1 cellspacing=0 width="100%">
+<tr>
+ <td bgcolor="003300"><font color="White">
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" vlink="#cc0033" alink="#ffffff">
+
+<br>
+Dein Artikel landet jetzt direkt in einem intelligenten Filter. Wenn Dein Artikel keine rassistischen, sexistischen oder faschistischen Inhalte hatte, und auch nicht ganz ohne Inhalt, also leer war, dann wird er in Kürze auf http://www.germany.indymedia.org/newswire/ auftauchen. <br><br>
+<center><EM>Gedulde Dich einen Moment! Es lohnt sich!</EM></center><br><br>
-<table width="750" align="center" border="0" cellspacing="0" cellpadding="5" bgcolor="#eeeeee">
- <tr>
- <td align="center" bgcolor="#cc0033">
- <font size="+2" color="#ffffff"><b>Hurra, Du hast Deinen Artikel abgeschickt!</b></font>
- </td>
- </tr>
- <tr>
- <td bgcolor="#eeeeee">
- <font color="#000000">
- <br>
- Dein Artikel landet in einigen Minuten auf der
- <a href="/open.shtml">"Open Posting"</a>
- - Seite. Das ist nicht die Startseite.
- Die Moderationskriterien kannst Du
- <a href="/static/moderation.html">hier lesen</a><br><br>
- <center><em><b>Gedulde Dich einen Moment! Es lohnt sich!</b></em></center><br><br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück</b></font></a>
- </td>
- </tr>
+</font>
+</td>
+</tr>
+<tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück</b></font></a>
+ </td>
+ </tr>
+</table>
</table>
-
</body>
-</html>
+</html>
\ No newline at end of file
<html>
<head>
-<title>Indymedia Germany | Open Posting | ${now}</title>
-
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
-
- <meta name="keywords" content=", freie medien, gegen&ouml;ffentlichkeit, indymedia, imc">
- <meta name="description" content="">
- <meta name="dc:title" content="">
- <meta name="dc:creator" content="">
- <meta name="dc:subject" content="">
- <meta name="dc:description" content="">
- <meta name="dc:publisher" content="indymedia collective">
- <meta name="dc:date" content="">
- <meta name="dc:language" content="de">
- <meta name="dc:coverage" content="">
- <meta name="dc:rights" content="http://de.indymedia.org/rights.html">
- <meta name="robots" href="http://de.indymedia.org/robots.txt">
- <meta http-equiv="expires" content="599">
-
- <script language="JavaScript">
- <!--
- function WM_netscapeCssFix() {
- if (document.WM.WM_netscapeCssFix.initWindowWidth != window.innerWidth ||
- document.WM.WM_netscapeCssFix.initWindowHeight != window.innerHeight) {
- document.location = document.location;
- }
- }
- function WM_netscapeCssFixCheckIn() {
- if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion)== 4)) {
- if (typeof document.WM == 'undefined'){
- document.WM = new Object;
- }
- if (typeof document.WM.WM_scaleFont == 'undefined') {
- document.WM.WM_netscapeCssFix = new Object;
- document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
- document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
- }
- window.onresize = WM_netscapeCssFix;
- }
- }
- WM_netscapeCssFixCheckIn()
- // -->
- </script>
- <link rel="stylesheet" href="mir.css" type="text/css">
+ <title>indymedia.de | open posting - Posting-Duplikat</title>
</head>
-<body marginwidth="0" marginheight="0" leftmargin="0" bgcolor="#eeeeee" link="#cc0033" vlink="#cc0033" alink="#ffffff">
+<body bgcolor="White" text="Black" link="white" vlink="#009900" alink="Red">
-<table width="750" align="center" border="0" cellspacing="0" cellpadding="5" bgcolor="#eeeeee">
- <tr>
- <td align="center" bgcolor="#cc0033">
- <font size="+2" color="#ffffff"><b>Immer ruhig mit den jungen Pferden!</b></font>
- </td>
- </tr>
- <tr>
- <td bgcolor="#eeeeee">
- <font color="#000000">
- <br>
- Du hast vermutlich den Reload-Button
- benutzt oder versucht, Deinen Artikel noch einmal zu posten. Das ist aber
- unnötig. Die Tatsache, dass Du diesen Text liest, bedeutet, dass Dein
- Posting schon angekommen ist. Er wird gleich auf der Seite auftauchen. Versprochen. <br>
- Technischer Hintergrund ist, daß de.indy über einen
- Proxy-Server läuft und der ist nicht immer minuten-aktuell.
- <center><em><b>Keine Panik!</b></em></center><br><br>
- </font>
- </td>
- </tr>
- <tr>
- <td valign="top" align="center" bgcolor="#cc0033">
- <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück</b></font></a>
- </td>
- </tr>
+<table width="100%" border="0" cellspacing="0" cellpadding="10">
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <font color="White"><b>
+ Immer ruhig mit den jungen Pferden!
+ </b></font
+ </td>
+ </tr>
+ <tr>
+ <td bgcolor="003300" width=70%>
+ <font color="White">
+ <br>
+ Du hast vermutlich den Reload-Button
+ benutzt oder versucht, Deinen Artikel noch einmal zu posten. Das ist aber
+ unnötig. Die Tatsache, dass Du diesen Text liest, bedeutet, dass Dein
+ Posting schon angekommen ist. Er wird gleich auf der Seite auftauchen. Versprochen.
+ <br>
+ Technischer Hintergrund ist, daß de.indy über einen
+ Proxy-Server läuft und der ist nicht immer minuten-aktuell.
+ <br>
+ <center><em>Keine Panik</em></center><br>
+ <br>
+ </font>
+ </td>
+ </tr>
+ <tr>
+ <td valign="top" align="center" bgcolor="#663399">
+ <a href="javascript:history.go(-2)"><font color="White"><b>>> Zurück</b></font></a>
+ </td>
+ </tr>
</table>
</body>
<html>
<head>
-<title>mir.indymedia.de: ${title}</title>
+<title>mir.indymedia.de: ${content.title}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="/style/mir.css" type="text/css">
- <list to_media as media>
-<meta name="keywords" content="${media["type"]}"></meta>
- </list>
+ <if content.to_media_images>
+ <meta name="keywords" content="images"></meta>
+ </if>
+ <if content.to_media_audio>
+ <meta name="keywords" content="audio"></meta>
+ </if>
+ <if content.to_media_video>
+ <meta name="keywords" content="video"></meta>
+ </if>
+ <if content.to_media_other>
+ <meta name="keywords" content="other"></meta>
+ </if>
</head>
<body bgcolor="#CCCCCC">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
- <h2>${title}</h2>
- <h4><i>${creator}, ${webdb_create_formatted}</i></h4>
- <p><b>${description}</b>
+ <h2>${content.title}</h2>
+ <h4><i>${content.creator}, ${content.webdb_create_formatted}</i></h4>
+ <p><b>${content.description}</b>
<!-- media -->
- <list to_media as media>
- <p>
- <if media && media["is_published"]=="1">
+ <list content.to_media_audio as media>
+ <p>
+ ${media["url"]}
+ </p>
+ </list>
+ <list content.to_media_video as media>
+ <p>
+ ${media["url"]}
+ </p>
+ </list>
+ <list content.to_media_other as media>
+ <p>
+ ${media["url"]}
+ </p>
+ </list>
+ <list content.to_media_images as media>
+ <p> I
${media["url"]}
- </if>
</p>
</list>
<!-- media -->
- <p>${content_data}</p>
- <if creator_main_url || creator_email>
+ <p>${content.content_data}</p>
+ <if content.creator_main_url || content.creator_email>
<table width="100%" bgcolor="#FFFFFF">
<tr>
<td>
<font size="-1">
- <if creator_email>
- <img src="/images/mail_small.gif" width="12" height="10" border="0" alt="-"> eMail: <a href="mailto:${creator_email}">${creator_email}</a><br>
+ <if content.creator_email>
+ <img src="/images/mail_small.gif" width="12" height="10" border="0" alt="-"> eMail: <a href="mailto:${content.creator_email}">${content.creator_email}</a><br>
</if>
- <if creator_main_url>
- <img src="/images/link_small.gif" width="12" height="10" border="0" alt=""> Homepage: <a href="${creator_main_url}" target="extern">${creator_main_url}</a><br>
+ <if content.creator_main_url>
+ <img src="/images/link_small.gif" width="12" height="10" border="0" alt=""> Homepage: <a href="${content.creator_main_url}" target="extern">${content.creator_main_url}</a><br>
</if>
</font>
</td>
</tr>
<tr><td> </td></tr>
<tr>
- <td><a href="${config.openaction}?do=addcomment&aid=${id}">
+ <td><a href="${config.openaction}?do=addcomment&aid=${content.id}">
Make a quick comment on this article</a>
</td>
</tr>
- <if comments>
- <list comments as c>
+ <if content.to_comments>
+ <list content.to_comments as c>
<tr>
<td>
<table width="100%" border="0" cellspacing="0" cellpadding="4">
<h3>${i.title}</h3>
<h4><i>${i.creator}, ${i.webdb_create_formatted}</i></h4>
<p>
- <if i.to_media_audio && i.to_media_audio[0]["is_published"]=="1">
- ${i.to_media_audio[0]["url"]}
- </if>
- <if i.to_media_video && i.to_media_video[0]["is_published"]=="1">
- ${i.to_media_video[0]["url"]}
- </if>
- <if i.to_media_other && i.to_media_other[0]["is_published"]=="1">
- ${i.to_media_other[0]["url"]}
- </if>
- <p>
- <if i.to_media_images && i.to_media_images[0]["is_published"]=="1">
- ${i.to_media_images[0]["url"]}
- </if>
+ <if i.to_media_audio >
+ ${i.to_media_audio[0]["list"]}
+ </if>
+ <if i.to_media_video >
+ ${i.to_media_video[0]["list"]}
+ </if>
+ <if i.to_media_other >
+ ${i.to_media_other[0]["list"]}
+ </if>
+ <p>
+ <if i.to_media_images >
+ ${i.to_media_images[0]["list"]}
+ </if>
${i.description}</p>
<p align="right">[<a href="${config.docroot}${i.publish_path}${i.id}.shtml">read</a>]</p>
</td>
<h4><i>${s.creator}, ${s.webdb_create_formatted}</i></h4>
<p>
<if s.to_media_audio && s.to_media_audio[0]["is_published"]=="1">
- ${s.to_media_audio[0]["url"]}
+ ${s.to_media_audio[0]["list"]}
</if>
<if s.to_media_video && s.to_media_video[0]["is_published"]=="1">
- ${s.to_media_video[0]["url"]}
+ ${s.to_media_video[0]["list"]}
</if>
<if s.to_media_other && s.to_media_other[0]["is_published"]=="1">
- ${s.to_media_other[0]["url"]}
+ ${s.to_media_other[0]["list"]}
</if>
<p>
<if s.to_media_images && s.to_media_images[0]["is_published"]=="1">
- ${s.to_media_images[0]["url"]}
+ ${s.to_media_images[0]["list"]}
</if>
${s.description} </p>
<p align="right">[<a href="${config.docroot}${s.publish_path}${s.id}.shtml">read</a>]</p>
<h4><i>${i.creator}, ${i.webdb_create_formatted}</i></h4>
<p>
<if i.to_media_audio && i.to_media_audio[0]["is_published"]=="1">
- ${i.to_media_audio[0]["url"]}
+ ${i.to_media_audio[0]["list"]}
</if>
<if i.to_media_video && i.to_media_video[0]["is_published"]=="1">
- ${i.to_media_video[0]["url"]}
+ ${i.to_media_video[0]["list"]}
</if>
<if i.to_media_other && i.to_media_other[0]["is_published"]=="1">
- ${i.to_media_other[0]["url"]}
+ ${i.to_media_other[0]["list"]}
</if>
<p>
<if i.to_media_images && i.to_media_images[0]["is_published"]=="1">
- ${i.to_media_images[0]["url"]}
+ ${i.to_media_images[0]["list"]}
</if>
${i.description} </p>
<p align="right">[<a href="${config.docroot}${i.publish_path}${i.id}.shtml">read</a>]</p>
<!-- newswire -->
<p>
<list newswire as n>
- <img alt=${n.icon_alt} border="0" height="10"
-src="${n.tiny_icon}" width="12">
+ <img alt=${n.to_media_icon["icon_alt"]} border="0" height="10"
+src="${n.to_media_icon["tiny_icon"]}" width="12">
<a href="${config.docroot}${n.publish_path}${n.id}.shtml"><b>${n.title}</b></a><br>
<font size="-2"><b></b>${n.webdb_create_formatted}</font><br>
<br>
<h4><i>${special.creator}, ${special.webdb_create_formatted}</i></h4>
<p>
<if special.to_media_audio && special.to_media_audio[0]["is_published"]=="1">
- ${special.to_media_audio[0]["url"]}
+ ${special.to_media_audio[0]["list"]}
</if>
<if special.to_media_video && special.to_media_video[0]["is_published"]=="1">
- ${special.to_media_video[0]["url"]}
+ ${special.to_media_video[0]["list"]}
</if>
<if special.to_media_other && special.to_media_other[0]["is_published"]=="1">
- ${special.to_media_other[0]["url"]}
+ ${special.to_media_other[0]["list"]}
</if>
<p>
<if special.to_media_images && special.to_media_images[0]["is_published"]=="1">
- ${special.to_media_images[0]["url"]}
+ ${special.to_media_images[0]["list"]}
</if>
${special.description} </p>
<p align="right">[<a href="${config.docroot}${special.publish_path}${special.id}.shtml">read</a>]</p>
<h4><i>${i.creator}, ${i.webdb_create_formatted}</i></h4>
<p>
<if i.to_media_audio && i.to_media_audio[0]["is_published"]=="1">
- ${i.to_media_audio[0]["url"]}
+ ${i.to_media_audio[0]["list"]}
</if>
<if i.to_media_video && i.to_media_video[0]["is_published"]=="1">
- ${i.to_media_video[0]["url"]}
+ ${i.to_media_video[0]["list"]}
</if>
<if i.to_media_other && i.to_media_other[0]["is_published"]=="1">
- ${i.to_media_other[0]["url"]}
+ ${i.to_media_other[0]["list"]}
</if>
<p>
<if i.to_media_images && i.to_media_images[0]["is_published"]=="1">
- ${i.to_media_images[0]["url"]}
+ ${i.to_media_images[0]["list"]}
</if>
${i.description}</p>
<p align="right">[<a href="${config.docroot}${i.publish_path}${i.id}.shtml">read</a>]</p>
--- /dev/null
+<html>
+<head>
+<title>indymedia.de | Fehlerhafte Eingabe</title>
+</head>
+<body>
+<include "head.template">
+<table width="100%" border="0" align="center">
+ <tr bgcolor="#006600">
+ <td>
+ <div align="center"><h2><font color="Pink">OOPS!</font></h2>
+ </div>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <p> Bei der Eingabe hat es folgende fehler gegeben:
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <p>
+ <p align="center"><font size="5" color="Red"><b> ${errorstring}</b></font>
+ <p>
+ <p>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <p align="center"><font face="Verdana, Arial, Helvetica, sans-serif" size="-1">Also, bitte druecken sie die zueruck taste und versuchen sie nochmal
+ </a></font>
+ <p>
+ </td>
+ </tr>
+</table>
+<include "foot.template">
+</body>
+</html>