+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.ArticleType"
- table="article_type"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">article_type_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="40"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * ArticleType.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * ArticleType
- * @author idefix
- * @version $Id: ArticleType.java,v 1.5 2003/08/18 18:22:24 idfx Exp $
- */
-public class ArticleType implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** default constructor */
- public ArticleType() {
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof ArticleType) ) return false;
- ArticleType castOther = (ArticleType) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Audio"
- table="audio"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="80"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="30"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="30"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sqltype="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
- <property
- name="iconIsProduced"
- type="boolean"
- column="icon_is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="iconPath"
- type="java.lang.String"
- column="icon_path"
- length="255"
- />
- <property
- name="kbits"
- type="short"
- column="kbits"
- length="2"
- />
- <!-- associations -->
- <many-to-one
- name="mediaType"
- class="mir.core.model.MediaType"
- column="to_media_type"
- />
- <many-to-one
- name="mediaFolder"
- class="mir.core.model.MediaFolder"
- column="to_media_folder"
- />
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Audio.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Audio
- * @author idefix
- * @version $Id: Audio.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class Audio extends UploadedMedia implements Serializable {
-
- /** nullable persistent field */
- private short kbits;
-
- /** default constructor */
- public Audio() {
- }
-
- public short getKbits() {
- return this.kbits;
- }
-
- public void setKbits(short kbits) {
- this.kbits = kbits;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.BreakingNewsItem"
- table="breaking"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">breaking_id_seq</param>
- </generator>
- </id>
- <property
- name="text"
- type="java.lang.String"
- column="text"
- not-null="true"
- length="255"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * BreakingNewsItem.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * BreakingNewsItem
- * @author idefix
- * @version $Id: BreakingNewsItem.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class BreakingNewsItem implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String text;
-
- /** persistent field */
- private java.util.Date webdbCreate;
-
- /** full constructor */
- public BreakingNewsItem(java.lang.String text, java.util.Date webdbCreate) {
- this.text = text;
- this.webdbCreate = webdbCreate;
- }
-
- /** default constructor */
- public BreakingNewsItem() {
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getText() {
- return this.text;
- }
-
- public void setText(java.lang.String text) {
- this.text = text;
- }
-
- public java.util.Date getWebdbCreate() {
- return this.webdbCreate;
- }
-
- public void setWebdbCreate(java.util.Date webdbCreate) {
- this.webdbCreate = webdbCreate;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof BreakingNewsItem) ) return false;
- BreakingNewsItem castOther = (BreakingNewsItem) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Comment"
- table="comment"
- proxy="mir.core.model.IComment"
->
- <id
- name="id"
- type="int"
- column="id"
- unsaved-value="0"
- >
- <generator class="sequence">
- <param name="sequence">comment_id_seq</param>
- </generator>
- </id>
-
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- not-null="true"
- length="80"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- not-null="true"
- sql-type="text"
- />
-
- <property
- name="mainUrl"
- type="java.lang.String"
- column="main_url"
- length="255"
- />
- <property
- name="email"
- type="java.lang.String"
- column="email"
- length="80"
- />
- <property
- name="address"
- type="java.lang.String"
- column="address"
- length="80"
- />
- <property
- name="phone"
- type="java.lang.String"
- column="phone"
- length="20"
- />
-
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
-
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
-
- <property
- name="checksum"
- type="int"
- column="checksum"
- length="4"
- />
-
- <property
- name="html"
- type="boolean"
- column="is_html"
- not-null="true"
- length="1"
- />
-
- <!-- associations -->
-
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
-
- <!-- dont know why but with Media it does not work -->
- <many-to-one
- name="media"
- class="mir.core.model.Content"
- column="to_media"
- />
-
- <many-to-one
- name="commentStatus"
- class="mir.core.model.CommentStatus"
- column="to_comment_status"
- />
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Comment.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Comment
- * @author idefix
- * @version $Id: Comment.java,v 1.4 2003/12/20 20:27:09 idfx Exp $
- */
-public class Comment implements Serializable, IComment {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String title;
-
- /** persistent field */
- private String creator;
-
- /** persistent field */
- private String description;
-
- /** nullable persistent field */
- private String mainUrl;
-
- /** nullable persistent field */
- private String email;
-
- /** nullable persistent field */
- private String address;
-
- /** nullable persistent field */
- private String phone;
-
- /** persistent field */
- private Date webdbCreate;
-
- /** persistent field */
- private boolean isPublished;
-
- /** persistent field */
- private Language language;
-
- /** persistent field */
- private Media media;
-
- /** nullable persistent field */
- private CommentStatus commentStatus;
-
- /** nullable persistent field */
- private int checksum;
-
- /** persistent field */
- private boolean isHtml;
-
- /** default constructor */
- public Comment() {
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getTitle() {
- return this.title;
- }
-
- public void setTitle(java.lang.String title) {
- this.title = title;
- }
-
- public java.lang.String getCreator() {
- return this.creator;
- }
-
- public void setCreator(java.lang.String creator) {
- this.creator = creator;
- }
-
- public java.lang.String getDescription() {
- return this.description;
- }
-
- public void setDescription(java.lang.String description) {
- this.description = description;
- }
-
- public java.lang.String getMainUrl() {
- return this.mainUrl;
- }
-
- public void setMainUrl(java.lang.String mainUrl) {
- this.mainUrl = mainUrl;
- }
-
- public java.lang.String getEmail() {
- return this.email;
- }
-
- public void setEmail(java.lang.String email) {
- this.email = email;
- }
-
- public java.lang.String getAddress() {
- return this.address;
- }
-
- public void setAddress(java.lang.String address) {
- this.address = address;
- }
-
- public java.lang.String getPhone() {
- return this.phone;
- }
-
- public void setPhone(java.lang.String phone) {
- this.phone = phone;
- }
-
- public java.util.Date getWebdbCreate() {
- return this.webdbCreate;
- }
-
- public void setWebdbCreate(java.util.Date webdbCreate) {
- this.webdbCreate = webdbCreate;
- }
-
- public boolean isPublished() {
- return this.isPublished;
- }
-
- public void setPublished(boolean isPublished) {
- this.isPublished = isPublished;
- }
-
- public int getChecksum() {
- return this.checksum;
- }
-
- public void setChecksum(int checksum) {
- this.checksum = checksum;
- }
-
- public boolean isHtml() {
- return this.isHtml;
- }
-
- public void setHtml(boolean isHtml) {
- this.isHtml = isHtml;
- }
- /**
- * @return
- */
- public CommentStatus getCommentStatus() {
- return commentStatus;
- }
-
- /**
- * @return
- */
- public Language getLanguage() {
- return language;
- }
-
- /**
- * @return
- */
- public Media getMedia() {
- return media;
- }
-
- /**
- * @param status
- */
- public void setCommentStatus(CommentStatus status) {
- commentStatus = status;
- }
-
- /**
- * @param language
- */
- public void setLanguage(Language language) {
- this.language = language;
- }
-
- /**
- * @param media
- */
- public void setMedia(Media media) {
- this.media = media;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
- public boolean equals(Object other) {
- if (!(other instanceof Comment))
- return false;
- Comment castOther = (Comment) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder().append(getId()).toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.CommentStatus"
- table="comment_status"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">comment_status_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="40"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * CommentStatus.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * CommentStatus
- * @author idefix
- * @version $Id: CommentStatus.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class CommentStatus implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** full constructor */
- public CommentStatus(java.lang.String name) {
- this.name = name;
- }
-
- /** default constructor */
- public CommentStatus() {
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof CommentStatus) ) return false;
- CommentStatus castOther = (CommentStatus) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Content"
- table="content"
- proxy="mir.core.model.IContent"
->
- <id
- name="id"
- type="int"
- column="id"
- unsaved-value="0"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
- <property
- name="html"
- type="boolean"
- column="is_html"
- not-null="true"
- length="1"
- />
- <property
- name="contentData"
- type="java.lang.String"
- column="content_data"
- sql-type="text"
- />
- <!-- associations -->
- <many-to-one
- name="articleType"
- class="mir.core.model.ArticleType"
- column="to_article_type"
- />
-
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
-
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
-
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
-
- <many-to-one name="parentContent"
- class="mir.core.model.Content"
- column="to_content"
- cascade="none"
- not-null="false"/>
-
- <set
- name="childContent"
- table="content"
- cascade="all"
- inverse="true"
- >
- <key
- column="to_content"
- />
- <one-to-many
- class="mir.core.model.Content"
- />
- </set>
-
- <set name="comments" table="comment" lazy="true">
- <key column="to_media"/>
- <one-to-many class="mir.core.model.Comment"/>
- </set>
-
- <set name="topics" table="content_x_topic" lazy="true">
- <key column="content_id"/>
- <many-to-many column="topic_id" class="mir.core.model.Topic"/>
- </set>
-
- <set name="attachedMedias" table="content_x_media" lazy="true">
- <key column="content_id"/>
- <many-to-many column="media_id" class="mir.core.model.Media"/>
- </set>
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Content.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Content
- * @author idefix
- * @version $Id: Content.java,v 1.5 2003/12/20 20:27:09 idfx Exp $
- */
-public class Content extends Media implements Serializable, IContent {
-
- /** persistent field */
- private boolean isHtml;
-
- /** nullable persistent field */
- private String contentData;
-
- /** persistent field */
- private ArticleType articleType;
-
- /** nullable persistent field */
- private Content parentContent;
-
- /** persistent field */
- private Set childContent;
-
- /** persistent field */
- private Set topics;
-
- /** persistent field */
- private Set attachedMedias;
-
- private Set comments;
-
- /** default constructor */
- public Content() {
- }
-
- public boolean isHtml() {
- return this.isHtml;
- }
-
- public boolean getHtml() {
- return isHtml();
- }
-
- public void setHtml(boolean isHtml) {
- this.isHtml = isHtml;
- }
-
- public java.lang.String getContentData() {
- return this.contentData;
- }
-
- public void setContentData(java.lang.String contentData) {
- this.contentData = contentData;
- }
-
- public ArticleType getArticleType() {
- return this.articleType;
- }
-
- public void setArticleType(ArticleType articleType) {
- this.articleType = articleType;
- }
-
- public mir.core.model.Content getParentContent() {
- return this.parentContent;
- }
-
- public void setParentContent(mir.core.model.Content parentContent) {
- this.parentContent = parentContent;
- }
-
- public Set getChildContent() {
- return this.childContent;
- }
-
- public void setChildContent(Set childContent) {
- this.childContent = childContent;
- }
-
- public Set getTopics() {
- return this.topics;
- }
-
- public void setTopics(Set topics) {
- this.topics = topics;
- }
-
- public Set getAttachedMedias() {
- return this.attachedMedias;
- }
-
- public void setAttachedMedias(Set attachedMedias) {
- this.attachedMedias = attachedMedias;
- }
-
- /**
- * @return
- */
- public Set getComments() {
- return comments;
- }
-
- /**
- * @param set
- */
- public void setComments(Set set) {
- comments = set;
- }
-
- public List getOperations(){
- return new ArrayList();
- }
-
- public List getTopicsAsList(){
- return new ArrayList(getTopics());
- }
-
- public String getPublicurl(){
- GregorianCalendar calendar = new GregorianCalendar();
- calendar.setTime(getWebdbCreate());
- calendar.get(GregorianCalendar.YEAR);
- return "" + calendar.get(GregorianCalendar.YEAR) + "/"
- + calendar.get(GregorianCalendar.MONTH) + "/"
- + this.getId() + ".shtml";
- }
-
- public int getCommentsSize(){
- return comments.size();
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Feature"
- table="feature"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">feature_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="80"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="filename"
- type="java.lang.String"
- column="filename"
- not-null="true"
- length="20"
- />
- <property
- name="mainUrl"
- type="java.lang.String"
- column="main_url"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Feature.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Feature
- * @author idefix
- * @version $Id: Feature.java,v 1.3 2003/09/05 20:23:59 idfx Exp $
- */
-public class Feature implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String title;
-
- /** nullable persistent field */
- private String description;
-
- /** persistent field */
- private String filename;
-
- /** nullable persistent field */
- private String mainUrl;
-
- /** persistent field */
- private boolean isPublished;
-
- /** full constructor */
- public Feature(java.lang.String title, java.lang.String description, java.lang.String filename, java.lang.String mainUrl, boolean isPublished) {
- this.title = title;
- this.description = description;
- this.filename = filename;
- this.mainUrl = mainUrl;
- this.isPublished = isPublished;
- }
-
- /** default constructor */
- public Feature() {
- }
-
- /** minimal constructor */
- public Feature(java.lang.String title, java.lang.String filename, boolean isPublished) {
- this.title = title;
- this.filename = filename;
- this.isPublished = isPublished;
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getTitle() {
- return this.title;
- }
-
- public void setTitle(java.lang.String title) {
- this.title = title;
- }
-
- public java.lang.String getDescription() {
- return this.description;
- }
-
- public void setDescription(java.lang.String description) {
- this.description = description;
- }
-
- public java.lang.String getFilename() {
- return this.filename;
- }
-
- public void setFilename(java.lang.String filename) {
- this.filename = filename;
- }
-
- public java.lang.String getMainUrl() {
- return this.mainUrl;
- }
-
- public void setMainUrl(java.lang.String mainUrl) {
- this.mainUrl = mainUrl;
- }
-
- public boolean isPublished() {
- return this.isPublished;
- }
-
- public void setPublished(boolean isPublished) {
- this.isPublished = isPublished;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof Feature) ) return false;
- Feature castOther = (Feature) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-/*
- * IComment.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-/**
- * IComment
- * @version $Id: IComment.java,v 1.1 2003/12/20 20:27:09 idfx Exp $
- * @author idefix
- */
-public interface IComment {
- public abstract java.lang.Integer getId();
- public abstract void setId(java.lang.Integer id);
- public abstract java.lang.String getTitle();
- public abstract void setTitle(java.lang.String title);
- public abstract java.lang.String getCreator();
- public abstract void setCreator(java.lang.String creator);
- public abstract java.lang.String getDescription();
- public abstract void setDescription(java.lang.String description);
- public abstract java.lang.String getMainUrl();
- public abstract void setMainUrl(java.lang.String mainUrl);
- public abstract java.lang.String getEmail();
- public abstract void setEmail(java.lang.String email);
- public abstract java.lang.String getAddress();
- public abstract void setAddress(java.lang.String address);
- public abstract java.lang.String getPhone();
- public abstract void setPhone(java.lang.String phone);
- public abstract java.util.Date getWebdbCreate();
- public abstract void setWebdbCreate(java.util.Date webdbCreate);
- public abstract boolean isPublished();
- public abstract void setPublished(boolean isPublished);
- public abstract int getChecksum();
- public abstract void setChecksum(int checksum);
- public abstract boolean isHtml();
- public abstract void setHtml(boolean isHtml);
- /**
- * @return
- */
- public abstract CommentStatus getCommentStatus();
- /**
- * @return
- */
- public abstract Language getLanguage();
- /**
- * @return
- */
- public abstract Media getMedia();
- /**
- * @param status
- */
- public abstract void setCommentStatus(CommentStatus status);
- /**
- * @param language
- */
- public abstract void setLanguage(Language language);
- /**
- * @param media
- */
- public abstract void setMedia(Media media);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * IContent.java created on 18.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.util.Set;
-
-/**
- * IContent
- * @author idefix
- * @version $Id: IContent.java,v 1.3 2003/12/20 20:27:09 idfx Exp $
- */
-public interface IContent extends IMedia {
- public abstract boolean isHtml();
- public abstract void setHtml(boolean isHtml);
- public abstract java.lang.String getContentData();
- public abstract void setContentData(java.lang.String contentData);
- public abstract ArticleType getArticleType();
- public abstract void setArticleType(ArticleType articleType);
- public abstract mir.core.model.Content getParentContent();
- public abstract void setParentContent(mir.core.model.Content parentContent);
- public abstract Set getChildContent();
- public abstract void setChildContent(Set childContent);
- public abstract Set getTopics();
- public abstract void setTopics(Set topics);
- public abstract Set getAttachedMedias();
- public abstract void setAttachedMedias(Set attachedMedias);
- public abstract Set getComments();
- public abstract void setComments(Set comments);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * IImage.java created on 18.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-/**
- * IImage
- * @author idefix
- * @version $Id: IImage.java,v 1.2 2003/09/10 20:56:25 idfx Exp $
- */
-public interface IImage extends IUploadedMedia {
- public abstract int getImageData();
- public abstract void setImageData(int imageData);
- public abstract int getIconData();
- public abstract void setIconData(int iconData);
- public abstract java.lang.String getYear();
- public abstract void setYear(java.lang.String year);
- public abstract short getImgWidth();
- public abstract void setImgWidth(short imgWidth);
- public abstract short getImgHeight();
- public abstract void setImgHeight(short imgHeight);
- public abstract short getImgFormat();
- public abstract void setImgFormat(short imgFormat);
- public abstract short getImgLayout();
- public abstract void setImgLayout(short imgLayout);
- public abstract short getImgType();
- public abstract void setImgType(short imgType);
- public abstract short getImgColor();
- public abstract void setImgColor(short imgColor);
- public abstract short getIconWidth();
- public abstract void setIconWidth(short iconWidth);
- public abstract short getIconHeight();
- public abstract void setIconHeight(short iconHeight);
- public abstract byte[] getIcon();
- public abstract byte[] getImage();
- public abstract void setIcon(byte[] bs);
- public abstract void setImage(byte[] bs);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * IMedia.java created on 18.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.util.Set;
-
-/**
- * IMedia
- * @author idefix
- * @version $Id: IMedia.java,v 1.4 2003/09/30 19:26:02 idfx Exp $
- */
-public interface IMedia {
- public abstract java.lang.Integer getId();
- public abstract void setId(java.lang.Integer id);
- public abstract java.lang.String getTitle();
- public abstract void setTitle(java.lang.String title);
- public abstract java.lang.String getSubtitle();
- public abstract void setSubtitle(java.lang.String subtitle);
- public abstract java.lang.String getEdittitle();
- public abstract void setEdittitle(java.lang.String edittitle);
- public abstract java.lang.String getDate();
- public abstract void setDate(java.lang.String date);
- public abstract java.lang.String getCreator();
- public abstract void setCreator(java.lang.String creator);
- public abstract java.lang.String getCreatorMainUrl();
- public abstract void setCreatorMainUrl(java.lang.String creatorMainUrl);
- public abstract java.lang.String getCreatorEmail();
- public abstract void setCreatorEmail(java.lang.String creatorEmail);
- public abstract java.lang.String getCreatorAddress();
- public abstract void setCreatorAddress(java.lang.String creatorAddress);
- public abstract java.lang.String getCreatorPhone();
- public abstract void setCreatorPhone(java.lang.String creatorPhone);
- public abstract java.lang.String getDescription();
- public abstract void setDescription(java.lang.String description);
- public abstract java.lang.String getComment();
- public abstract void setComment(java.lang.String comment);
- public abstract java.lang.String getSource();
- public abstract void setSource(java.lang.String source);
- public abstract java.util.Date getPublishDate();
- public abstract void setPublishDate(java.util.Date publishDate);
- public abstract java.lang.String getPublishServer();
- public abstract void setPublishServer(java.lang.String publishServer);
- public abstract java.lang.String getPublishPath();
- public abstract void setPublishPath(java.lang.String publishPath);
- public abstract java.util.Date getWebdbCreate();
- public abstract void setWebdbCreate(java.util.Date webdbCreate);
- public abstract java.util.Date getWebdbLastchange();
- public abstract void setWebdbLastchange(java.util.Date webdbLastchange);
- public abstract mir.core.model.MirUser getPublisher();
- public abstract void setPublisher(mir.core.model.MirUser publisher);
- public abstract mir.core.model.Language getLanguage();
- public abstract void setLanguage(mir.core.model.Language language);
- public abstract mir.core.model.Rights getRights();
- public abstract void setRights(mir.core.model.Rights rights);
- /**
- * @return
- */
- public abstract Set getContent();
- /**
- * @param content
- */
- public abstract void setContent(Set content);
- /**
- * @return
- */
- public abstract boolean isProduced();
- /**
- * @param isProduced
- */
- public abstract void setProduced(boolean isProduced);
- /**
- * @return
- */
- public abstract boolean isPublished();
- /**
- * @param isPublished
- */
- public abstract void setPublished(boolean isPublished);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * ITopic.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.util.Set;
-
-/**
- * ITopic
- * @version $Id: ITopic.java,v 1.1 2003/12/20 20:27:09 idfx Exp $
- * @author idefix
- */
-public interface ITopic {
- /**
- * @return
- */
- public abstract String getArchivUrl();
- /**
- * @return
- */
- public abstract String getDescription();
- /**
- * @return
- */
- public abstract String getFilename();
- /**
- * @return
- */
- public abstract Integer getId();
- /**
- * @return
- */
- public abstract String getMainUrl();
- /**
- * @return
- */
- public abstract String getTitle();
- /**
- * @param string
- */
- public abstract void setArchivUrl(String string);
- /**
- * @param string
- */
- public abstract void setDescription(String string);
- /**
- * @param string
- */
- public abstract void setFilename(String string);
- /**
- * @param integer
- */
- public abstract void setId(Integer integer);
- /**
- * @param string
- */
- public abstract void setMainUrl(String string);
- /**
- * @param string
- */
- public abstract void setTitle(String string);
- /**
- * @return
- */
- public abstract Set getChildTopics();
- /**
- * @param set
- */
- public abstract void setChildTopics(Set set);
- /**
- * @return
- */
- public abstract Topic getParentTopic();
- /**
- * @param topic
- */
- public abstract void setParentTopic(Topic topic);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * IUploadedMedia.java created on 18.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-/**
- * IUploadedMedia
- * @author idefix
- * @version $Id: IUploadedMedia.java,v 1.1 2003/08/19 00:41:54 idfx Exp $
- */
-public interface IUploadedMedia extends IMedia {
- public abstract boolean isIconIsProduced();
- public abstract void setIconIsProduced(boolean iconIsProduced);
- public abstract java.lang.String getIconPath();
- public abstract void setIconPath(java.lang.String iconPath);
- public abstract mir.core.model.MediaFolder getMediaFolder();
- public abstract void setMediaFolder(mir.core.model.MediaFolder mediaFolder);
- public abstract mir.core.model.MediaType getMediaType();
- public abstract void setMediaType(mir.core.model.MediaType mediaType);
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Image"
- table="images"
- proxy="mir.core.model.IImage"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
-
- <property
- name="iconIsProduced"
- type="boolean"
- column="icon_is_produced"
- not-null="true"
- length="1"
- />
-
- <property
- name="iconPath"
- type="java.lang.String"
- column="icon_path"
- length="255"
- />
- <property
- name="imageData"
- type="int"
- column="image_data"
- length="4"
- />
- <property
- name="iconData"
- type="int"
- column="icon_data"
- length="4"
- />
- <property
- name="year"
- type="java.lang.String"
- column="year"
- length="40"
- />
- <property
- name="imgWidth"
- type="short"
- column="img_width"
- length="2"
- />
- <property
- name="imgHeight"
- type="short"
- column="img_height"
- length="2"
- />
- <property
- name="iconWidth"
- type="short"
- column="icon_width"
- length="2"
- />
- <property
- name="iconHeight"
- type="short"
- column="icon_height"
- length="2"
- />
-
- <!-- associations -->
- <many-to-one
- name="mediaType"
- class="mir.core.model.MediaType"
- column="to_media_type"
- />
- <many-to-one
- name="mediaFolder"
- class="mir.core.model.MediaFolder"
- column="to_media_folder"
- />
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>?
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Image.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-import java.sql.Connection;
-import java.sql.SQLException;
-
-import net.sf.hibernate.CallbackException;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Lifecycle;
-import net.sf.hibernate.Session;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.postgresql.PGConnection;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-
-/**
- *
- * Image
- * @author idefix
- * @version $Id: Image.java,v 1.5 2003/09/10 20:56:25 idfx Exp $
- */
-public class Image
- extends UploadedMedia
- implements Serializable, Lifecycle, IImage {
-
- /** nullable persistent field */
- private int imageData;
-
- /** nullable persistent field */
- private int iconData;
-
- /** nullable persistent field */
- private String year;
-
- /** nullable persistent field */
- private short imgWidth;
-
- /** nullable persistent field */
- private short imgHeight;
-
- /** persistent field */
- private short imgFormat;
-
- /** persistent field */
- private short imgLayout;
-
- /** persistent field */
- private short imgType;
-
- /** persistent field */
- private short imgColor;
-
- /** nullable persistent field */
- private short iconWidth;
-
- /** nullable persistent field */
- private short iconHeight;
-
- private byte[] image;
-
- private byte[] icon;
-
- /** default constructor */
- public Image() {
- }
-
- public int getImageData() {
- return this.imageData;
- }
-
- public void setImageData(int imageData) {
- this.imageData = imageData;
- }
-
- public int getIconData() {
- return this.iconData;
- }
-
- public void setIconData(int iconData) {
- this.iconData = iconData;
- }
-
- public java.lang.String getYear() {
- return this.year;
- }
-
- public void setYear(java.lang.String year) {
- this.year = year;
- }
-
- public short getImgWidth() {
- return this.imgWidth;
- }
-
- public void setImgWidth(short imgWidth) {
- this.imgWidth = imgWidth;
- }
-
- public short getImgHeight() {
- return this.imgHeight;
- }
-
- public void setImgHeight(short imgHeight) {
- this.imgHeight = imgHeight;
- }
-
- public short getImgFormat() {
- return this.imgFormat;
- }
-
- public void setImgFormat(short imgFormat) {
- this.imgFormat = imgFormat;
- }
-
- public short getImgLayout() {
- return this.imgLayout;
- }
-
- public void setImgLayout(short imgLayout) {
- this.imgLayout = imgLayout;
- }
-
- public short getImgType() {
- return this.imgType;
- }
-
- public void setImgType(short imgType) {
- this.imgType = imgType;
- }
-
- public short getImgColor() {
- return this.imgColor;
- }
-
- public void setImgColor(short imgColor) {
- this.imgColor = imgColor;
- }
-
- public short getIconWidth() {
- return this.iconWidth;
- }
-
- public void setIconWidth(short iconWidth) {
- this.iconWidth = iconWidth;
- }
-
- public short getIconHeight() {
- return this.iconHeight;
- }
-
- public void setIconHeight(short iconHeight) {
- this.iconHeight = iconHeight;
- }
-
- /**
- * @return
- */
- public byte[] getIcon() {
- return icon;
- }
-
- /**
- * @return
- */
- public byte[] getImage() {
- return image;
- }
-
- /**
- * @param bs
- */
- public void setIcon(byte[] bs) {
- icon = bs;
- }
-
- /**
- * @param bs
- */
- public void setImage(byte[] bs) {
- image = bs;
- }
-
- public String toString() {
- return new ToStringBuilder(this).append("id", getId()).toString();
- }
-
- //====================================================
-
- /**
- * @see net.sf.hibernate.Lifecycle#onSave(net.sf.hibernate.Session)
- */
- public boolean onSave(Session session) throws CallbackException {
- LargeObject imageObj = null;
- LargeObject iconObj = null;
- try {
- Connection connection = session.connection();
- if (connection instanceof PGConnection) {
- PGConnection pgcon = (PGConnection) connection;
- LargeObjectManager largeObjectManager = pgcon.getLargeObjectAPI();
-
- int imageOID = largeObjectManager.create(LargeObjectManager.READWRITE);
- imageObj = largeObjectManager.open(imageOID, LargeObjectManager.READ);
- imageObj.write(image, 0, image.length);
- setImageData(imageOID);
-
- int iconOID = largeObjectManager.create(LargeObjectManager.READWRITE);
- iconObj = largeObjectManager.open(iconOID, LargeObjectManager.READ);
- iconObj.write(image, 0, image.length);
- setImageData(iconOID);
- }
- } catch (HibernateException e) {
- e.printStackTrace();
- return false;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- imageObj.close();
- iconObj.close();
- return true;
- } catch (Throwable e) {
- e.printStackTrace();
- return false;
- }
- }
- }
-
- /**
- * @see net.sf.hibernate.Lifecycle#onUpdate(net.sf.hibernate.Session)
- */
- public boolean onUpdate(Session session) throws CallbackException {
- LargeObject imageObj = null;
- LargeObject iconObj = null;
- try {
- Connection connection = session.connection();
- if (connection instanceof PGConnection) {
- PGConnection pgcon = (PGConnection) connection;
- LargeObjectManager largeObjectManager = pgcon.getLargeObjectAPI();
-
- imageObj = largeObjectManager.open(getImageData(), LargeObjectManager.READ);
- imageObj.write(image, 0, image.length);
-
- iconObj = largeObjectManager.open(getIconData(), LargeObjectManager.READ);
- iconObj.write(image, 0, image.length);
- }
- } catch (HibernateException e) {
- e.printStackTrace();
- return false;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- imageObj.close();
- iconObj.close();
- return true;
- } catch (Throwable e) {
- e.printStackTrace();
- return false;
- }
- }
- }
-
- /**
- * @see net.sf.hibernate.Lifecycle#onDelete(net.sf.hibernate.Session)
- */
- public boolean onDelete(Session session) throws CallbackException {
- try {
- Connection connection = session.connection();
- if (connection instanceof PGConnection) {
- PGConnection pgcon = (PGConnection) connection;
- LargeObjectManager largeObjectManager = pgcon.getLargeObjectAPI();
-
- largeObjectManager.delete(getImageData());
- setImageData(0);
-
- largeObjectManager.delete(getIconData());
- setIconData(0);
-
- return true;
- }
- return false;
- } catch (HibernateException e) {
- e.printStackTrace();
- return false;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * @see net.sf.hibernate.Lifecycle#onLoad(net.sf.hibernate.Session, java.io.Serializable)
- */
- public void onLoad(Session session, Serializable arg1) {
- LargeObject imageObj = null;
- LargeObject iconObj = null;
- try {
- Connection connection = session.connection();
- if (connection instanceof PGConnection) {
- PGConnection pgcon = (PGConnection) connection;
- LargeObjectManager largeObjectManager = pgcon.getLargeObjectAPI();
-
- imageObj =
- largeObjectManager.open(getImageData(), LargeObjectManager.READ);
- image = new byte[imageObj.size()];
- imageObj.read(image, 0, imageObj.size());
-
- iconObj =
- largeObjectManager.open(getIconData(), LargeObjectManager.READ);
- icon = new byte[iconObj.size()];
- iconObj.read(icon, 0, iconObj.size());
- }
- } catch (HibernateException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (imageObj != null) {
- imageObj.close();
- }
- if (iconObj != null) {
- iconObj.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
-}
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r
- "-//Hibernate/Hibernate Mapping DTD//EN"\r
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
- \r
-<hibernate-mapping>\r
-\r
-<!-- \r
- Created by Middlegen Hibernate plugin\r
-\r
- http://boss.bekk.no/boss/middlegen/\r
- http://hibernate.sourceforge.net/\r
--->\r
-\r
-<class \r
- name="airline.hibernate.ImgColor" \r
- table="img_color"\r
->\r
- <property\r
- name="id"\r
- type="short"\r
- column="id"\r
- not-null="true"\r
- length="2"\r
- />\r
- <property\r
- name="name"\r
- type="java.lang.String"\r
- column="name"\r
- not-null="true"\r
- length="30"\r
- />\r
-\r
- <!-- associations -->\r
-\r
-</class>\r
-</hibernate-mapping>\r
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r
- "-//Hibernate/Hibernate Mapping DTD//EN"\r
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
- \r
-<hibernate-mapping>\r
-\r
-<!-- \r
- Created by Middlegen Hibernate plugin\r
-\r
- http://boss.bekk.no/boss/middlegen/\r
- http://hibernate.sourceforge.net/\r
--->\r
-\r
-<class \r
- name="airline.hibernate.ImgFormat" \r
- table="img_format"\r
->\r
- <property\r
- name="id"\r
- type="short"\r
- column="id"\r
- not-null="true"\r
- length="2"\r
- />\r
- <property\r
- name="name"\r
- type="java.lang.String"\r
- column="name"\r
- not-null="true"\r
- length="20"\r
- />\r
- <property\r
- name="extension"\r
- type="java.lang.String"\r
- column="extension"\r
- not-null="true"\r
- length="10"\r
- />\r
- <property\r
- name="mimetype"\r
- type="java.lang.String"\r
- column="mimetype"\r
- not-null="true"\r
- length="40"\r
- />\r
- <property\r
- name="commment"\r
- type="java.lang.String"\r
- column="commment"\r
- length="255"\r
- />\r
-\r
- <!-- associations -->\r
-\r
-</class>\r
-</hibernate-mapping>\r
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r
- "-//Hibernate/Hibernate Mapping DTD//EN"\r
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
- \r
-<hibernate-mapping>\r
-\r
-<!-- \r
- Created by Middlegen Hibernate plugin\r
-\r
- http://boss.bekk.no/boss/middlegen/\r
- http://hibernate.sourceforge.net/\r
--->\r
-\r
-<class \r
- name="airline.hibernate.ImgLayout" \r
- table="img_layout"\r
->\r
- <property\r
- name="id"\r
- type="short"\r
- column="id"\r
- not-null="true"\r
- length="2"\r
- />\r
- <property\r
- name="name"\r
- type="java.lang.String"\r
- column="name"\r
- not-null="true"\r
- length="20"\r
- />\r
-\r
- <!-- associations -->\r
-\r
-</class>\r
-</hibernate-mapping>\r
+++ /dev/null
-<?xml version="1.0"?>\r
-<!DOCTYPE hibernate-mapping PUBLIC\r
- "-//Hibernate/Hibernate Mapping DTD//EN"\r
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >\r
- \r
-<hibernate-mapping>\r
-\r
-<!-- \r
- Created by Middlegen Hibernate plugin\r
-\r
- http://boss.bekk.no/boss/middlegen/\r
- http://hibernate.sourceforge.net/\r
--->\r
-\r
-<class \r
- name="airline.hibernate.ImgType" \r
- table="img_type"\r
->\r
- <property\r
- name="id"\r
- type="short"\r
- column="id"\r
- not-null="true"\r
- length="2"\r
- />\r
- <property\r
- name="name"\r
- type="java.lang.String"\r
- column="name"\r
- not-null="true"\r
- length="30"\r
- />\r
-\r
- <!-- associations -->\r
-\r
-</class>\r
-</hibernate-mapping>\r
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Language"
- table="language"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">language_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="40"
- />
- <property
- name="code"
- type="java.lang.String"
- column="code"
- not-null="true"
- length="2"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Language.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Language
- * @author idefix
- * @version $Id: Language.java,v 1.3 2003/12/20 20:27:09 idfx Exp $
- */
-public class Language implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String code;
-
- /** full constructor */
- public Language(java.lang.String name, java.lang.String code) {
- this.name = name;
- this.code = code;
- }
-
- /** default constructor */
- public Language() {
- }
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public java.lang.String getCode() {
- return this.code;
- }
-
- public void setCode(java.lang.String code) {
- this.code = code;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof Language) ) return false;
- Language castOther = (Language) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Media"
- table="media"
- proxy="mir.core.model.IMedia"
->
- <id
- name="id"
- type="int"
- column="id"
- unsaved-value="0"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
-
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
-
- <!-- associations -->
-
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
-
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
-
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
-
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Media.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.model;
-
-import java.io.Serializable;
-import java.util.Date;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Media
- * @author idefix
- * @version $Id: Media.java,v 1.7 2003/12/20 20:27:09 idfx Exp $
- */
-public class Media implements Serializable, IMedia {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String title;
-
- /** nullable persistent field */
- private String subtitle;
-
- /** nullable persistent field */
- private String edittitle;
-
- /** persistent field */
- private String date;
-
- /** nullable persistent field */
- private String creator;
-
- /** nullable persistent field */
- private String creatorMainUrl;
-
- /** nullable persistent field */
- private String creatorEmail;
-
- /** nullable persistent field */
- private String creatorAddress;
-
- /** nullable persistent field */
- private String creatorPhone;
-
- /** nullable persistent field */
- private String description;
-
- /** nullable persistent field */
- private String comment;
-
- /** nullable persistent field */
- private String source;
-
- /** nullable persistent field */
- private Date publishDate;
-
- /** nullable persistent field */
- private String publishServer;
-
- /** nullable persistent field */
- private String publishPath;
-
- /** persistent field */
- private boolean isPublished;
-
- /** persistent field */
- private boolean isProduced;
-
- /** persistent field */
- private Date webdbCreate;
-
- /** nullable persistent field */
- private Date webdbLastchange;
-
- /** nullable persistent field */
- private MirUser publisher;
-
- /** nullable persistent field */
- private Language language;
-
- /** nullable persistent field */
- private Rights rights;
-
- private Set content;
-
- /** default constructor */
- public Media() {
-
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getTitle() {
- return this.title;
- }
-
- public void setTitle(java.lang.String title) {
- this.title = title;
- }
-
- public java.lang.String getSubtitle() {
- return this.subtitle;
- }
-
- public void setSubtitle(java.lang.String subtitle) {
- this.subtitle = subtitle;
- }
-
- public java.lang.String getEdittitle() {
- return this.edittitle;
- }
-
- public void setEdittitle(java.lang.String edittitle) {
- this.edittitle = edittitle;
- }
-
- public java.lang.String getDate() {
- return this.date;
- }
-
- public void setDate(java.lang.String date) {
- this.date = date;
- }
-
- public java.lang.String getCreator() {
- return this.creator;
- }
-
- public void setCreator(java.lang.String creator) {
- this.creator = creator;
- }
-
- public java.lang.String getCreatorMainUrl() {
- return this.creatorMainUrl;
- }
-
- public void setCreatorMainUrl(java.lang.String creatorMainUrl) {
- this.creatorMainUrl = creatorMainUrl;
- }
-
- public java.lang.String getCreatorEmail() {
- return this.creatorEmail;
- }
-
- public void setCreatorEmail(java.lang.String creatorEmail) {
- this.creatorEmail = creatorEmail;
- }
-
- public java.lang.String getCreatorAddress() {
- return this.creatorAddress;
- }
-
- public void setCreatorAddress(java.lang.String creatorAddress) {
- this.creatorAddress = creatorAddress;
- }
-
- public java.lang.String getCreatorPhone() {
- return this.creatorPhone;
- }
-
- public void setCreatorPhone(java.lang.String creatorPhone) {
- this.creatorPhone = creatorPhone;
- }
-
- public java.lang.String getDescription() {
- return this.description;
- }
-
- public void setDescription(java.lang.String description) {
- this.description = description;
- }
-
- public java.lang.String getComment() {
- return this.comment;
- }
-
- public void setComment(java.lang.String comment) {
- this.comment = comment;
- }
-
- public java.lang.String getSource() {
- return this.source;
- }
-
- public void setSource(java.lang.String source) {
- this.source = source;
- }
-
- public java.util.Date getPublishDate() {
- return this.publishDate;
- }
-
- public void setPublishDate(java.util.Date publishDate) {
- this.publishDate = publishDate;
- }
-
- public java.lang.String getPublishServer() {
- return this.publishServer;
- }
-
- public void setPublishServer(java.lang.String publishServer) {
- this.publishServer = publishServer;
- }
-
- public java.lang.String getPublishPath() {
- return this.publishPath;
- }
-
- public void setPublishPath(java.lang.String publishPath) {
- this.publishPath = publishPath;
- }
-
- public java.util.Date getWebdbCreate() {
- return this.webdbCreate;
- }
-
- public void setWebdbCreate(java.util.Date webdbCreate) {
- this.webdbCreate = webdbCreate;
- }
-
- public java.util.Date getWebdbLastchange() {
- return this.webdbLastchange;
- }
-
- public void setWebdbLastchange(java.util.Date webdbLastchange) {
- this.webdbLastchange = webdbLastchange;
- }
-
- public mir.core.model.MirUser getPublisher() {
- return this.publisher;
- }
-
- public void setPublisher(mir.core.model.MirUser publisher) {
- this.publisher = publisher;
- }
-
- public mir.core.model.Language getLanguage() {
- return this.language;
- }
-
- public void setLanguage(Language language) {
- this.language = language;
- }
-
- public mir.core.model.Rights getRights() {
- return this.rights;
- }
-
- public void setRights(mir.core.model.Rights rights) {
- this.rights = rights;
- }
-
- /**
- * @return
- */
- public Set getContent() {
- return content;
- }
-
- /**
- * @param content
- */
- public void setContent(Set content) {
- this.content = content;
- }
-
- /**
- * @return
- */
- public boolean isProduced() {
- return isProduced;
- }
-
- /**
- * @return
- */
- public boolean getProduced() {
- return isProduced();
- }
-
- /**
- * @param isProduced
- */
- public void setProduced(boolean isProduced) {
- this.isProduced = isProduced;
- }
-
- /**
- * @return
- */
- public boolean isPublished() {
- return isPublished;
- }
-
- /**
- * @param isPublished
- */
- public void setPublished(boolean isPublished) {
- this.isPublished = isPublished;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof Media) ) return false;
- Media castOther = (Media) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.MediaFolder"
- table="media_folder"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_folder_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="255"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="place"
- type="java.lang.String"
- column="place"
- length="80"
- />
- <property
- name="keywords"
- type="java.lang.String"
- column="keywords"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * MediaFolder.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * MediaFolder
- * @author idefix
- * @version $Id: MediaFolder.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class MediaFolder implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String date;
-
- /** nullable persistent field */
- private String place;
-
- /** nullable persistent field */
- private String keywords;
-
- /** nullable persistent field */
- private String comment;
-
- /** persistent field */
- private java.util.Date webdbCreate;
-
- /** nullable persistent field */
- private java.util.Date webdbLastchange;
-
- /** full constructor */
- public MediaFolder(java.lang.String name, java.lang.String date, java.lang.String place, java.lang.String keywords, java.lang.String comment, java.util.Date webdbCreate, java.util.Date webdbLastchange) {
- this.name = name;
- this.date = date;
- this.place = place;
- this.keywords = keywords;
- this.comment = comment;
- this.webdbCreate = webdbCreate;
- this.webdbLastchange = webdbLastchange;
- }
-
- /** default constructor */
- public MediaFolder() {
- }
-
- /** minimal constructor */
- public MediaFolder(java.lang.String name, java.lang.String date, java.util.Date webdbCreate) {
- this.name = name;
- this.date = date;
- this.webdbCreate = webdbCreate;
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public java.lang.String getDate() {
- return this.date;
- }
-
- public void setDate(java.lang.String date) {
- this.date = date;
- }
-
- public java.lang.String getPlace() {
- return this.place;
- }
-
- public void setPlace(java.lang.String place) {
- this.place = place;
- }
-
- public java.lang.String getKeywords() {
- return this.keywords;
- }
-
- public void setKeywords(java.lang.String keywords) {
- this.keywords = keywords;
- }
-
- public java.lang.String getComment() {
- return this.comment;
- }
-
- public void setComment(java.lang.String comment) {
- this.comment = comment;
- }
-
- public java.util.Date getWebdbCreate() {
- return this.webdbCreate;
- }
-
- public void setWebdbCreate(java.util.Date webdbCreate) {
- this.webdbCreate = webdbCreate;
- }
-
- public java.util.Date getWebdbLastchange() {
- return this.webdbLastchange;
- }
-
- public void setWebdbLastchange(java.util.Date webdbLastchange) {
- this.webdbLastchange = webdbLastchange;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof MediaFolder) ) return false;
- MediaFolder castOther = (MediaFolder) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.MediaType"
- table="media_type"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_type_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="80"
- />
- <property
- name="mimeType"
- type="java.lang.String"
- column="mime_type"
- not-null="true"
- length="40"
- />
- <property
- name="classname"
- type="java.lang.String"
- column="classname"
- not-null="true"
- length="80"
- />
- <property
- name="tablename"
- type="java.lang.String"
- column="tablename"
- not-null="true"
- length="80"
- />
- <property
- name="dcname"
- type="java.lang.String"
- column="dcname"
- length="20"
- />
-
- <!-- associations -->
- <set name="mediaItems" lazy="true">
- <key column="id"/>
- <one-to-many class="mir.core.model.Media"/>
- </set>
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * MediaType.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * MediaType
- * @author idefix
- * @version $Id: MediaType.java,v 1.3 2003/08/17 19:13:19 idfx Exp $
- */
-public class MediaType implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** persistent field */
- private String mimeType;
-
- /** persistent field */
- private String classname;
-
- /** persistent field */
- private String tablename;
-
- /** nullable persistent field */
- private String dcname;
-
- private Set mediaItems;
-
- /** full constructor */
- public MediaType(java.lang.String name, java.lang.String mimeType, java.lang.String classname, java.lang.String tablename, java.lang.String dcname) {
- this.name = name;
- this.mimeType = mimeType;
- this.classname = classname;
- this.tablename = tablename;
- this.dcname = dcname;
- }
-
- /** default constructor */
- public MediaType() {
- }
-
- /** minimal constructor */
- public MediaType(java.lang.String name, java.lang.String mimeType, java.lang.String classname, java.lang.String tablename) {
- this.name = name;
- this.mimeType = mimeType;
- this.classname = classname;
- this.tablename = tablename;
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public java.lang.String getMimeType() {
- return this.mimeType;
- }
-
- public void setMimeType(java.lang.String mimeType) {
- this.mimeType = mimeType;
- }
-
- public java.lang.String getClassname() {
- return this.classname;
- }
-
- public void setClassname(java.lang.String classname) {
- this.classname = classname;
- }
-
- public java.lang.String getTablename() {
- return this.tablename;
- }
-
- public void setTablename(java.lang.String tablename) {
- this.tablename = tablename;
- }
-
- public java.lang.String getDcname() {
- return this.dcname;
- }
-
- public void setDcname(java.lang.String dcname) {
- this.dcname = dcname;
- }
-
- /**
- * @return
- */
- public Set getMediaItems() {
- return mediaItems;
- }
-
- /**
- * @param mediaItems
- */
- public void setMediaItems(Set mediaItems) {
- this.mediaItems = mediaItems;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof MediaType) ) return false;
- MediaType castOther = (MediaType) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Message"
- table="messages"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">messages_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- length="30"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- not-null="true"
- length="255"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- not-null="true"
- length="30"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Message.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Message
- * @author idefix
- * @version $Id: Message.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class Message implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** nullable persistent field */
- private String title;
-
- /** persistent field */
- private String description;
-
- /** persistent field */
- private String creator;
-
- /** persistent field */
- private java.util.Date webdbCreate;
-
- /** full constructor */
- public Message(java.lang.String title, java.lang.String description, java.lang.String creator, java.util.Date webdbCreate) {
- this.title = title;
- this.description = description;
- this.creator = creator;
- this.webdbCreate = webdbCreate;
- }
-
- /** default constructor */
- public Message() {
- }
-
- /** minimal constructor */
- public Message(java.lang.String description, java.lang.String creator, java.util.Date webdbCreate) {
- this.description = description;
- this.creator = creator;
- this.webdbCreate = webdbCreate;
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getTitle() {
- return this.title;
- }
-
- public void setTitle(java.lang.String title) {
- this.title = title;
- }
-
- public java.lang.String getDescription() {
- return this.description;
- }
-
- public void setDescription(java.lang.String description) {
- this.description = description;
- }
-
- public java.lang.String getCreator() {
- return this.creator;
- }
-
- public void setCreator(java.lang.String creator) {
- this.creator = creator;
- }
-
- public java.util.Date getWebdbCreate() {
- return this.webdbCreate;
- }
-
- public void setWebdbCreate(java.util.Date webdbCreate) {
- this.webdbCreate = webdbCreate;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof Message) ) return false;
- Message castOther = (Message) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-/*
- * MirUser.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * MirUser
- * @author idefix
- * @version $Id: MirUser.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class MirUser implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String login;
-
- /** persistent field */
- private String password;
-
- /** persistent field */
- private boolean isAdmin;
-
- /** full constructor */
- public MirUser(java.lang.String login, java.lang.String password, boolean isAdmin) {
- this.login = login;
- this.password = password;
- this.isAdmin = isAdmin;
- }
-
- /** default constructor */
- public MirUser() {
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getLogin() {
- return this.login;
- }
-
- public void setLogin(java.lang.String login) {
- this.login = login;
- }
-
- public java.lang.String getPassword() {
- return this.password;
- }
-
- public void setPassword(java.lang.String password) {
- this.password = password;
- }
-
- public boolean isIsAdmin() {
- return this.isAdmin;
- }
-
- public void setIsAdmin(boolean isAdmin) {
- this.isAdmin = isAdmin;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof MirUser) ) return false;
- MirUser castOther = (MirUser) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.OtherMedia"
- table="other_media"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
- <!-- associations -->
- <many-to-one
- name="mediaType"
- class="mir.core.model.MediaType"
- column="to_media_type"
- />
- <many-to-one
- name="mediaFolder"
- class="mir.core.model.MediaFolder"
- column="to_media_folder"
- />
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
- <property
- name="iconIsProduced"
- type="boolean"
- column="icon_is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="iconPath"
- type="java.lang.String"
- column="icon_path"
- length="255"
- />
- <property
- name="size"
- type="int"
- column="size"
- length="4"
- />
-
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * OtherMedia.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * OtherMedia
- * @author idefix
- * @version $Id: OtherMedia.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class OtherMedia extends UploadedMedia implements Serializable {
-
- /** default constructor */
- public OtherMedia() {
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Rights"
- table="rights"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="name"
- type="java.lang.String"
- column="name"
- not-null="true"
- length="80"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Rights.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * Rights
- * @author idefix
- * @version $Id: Rights.java,v 1.2 2003/08/17 19:13:19 idfx Exp $
- */
-public class Rights implements Serializable {
-
- /** identifier field */
- private Integer id;
-
- /** persistent field */
- private String name;
-
- /** nullable persistent field */
- private String description;
-
- /** full constructor */
- public Rights(java.lang.String name, java.lang.String description) {
- this.name = name;
- this.description = description;
- }
-
- /** default constructor */
- public Rights() {
- }
-
- /** minimal constructor */
- public Rights(java.lang.String name) {
- this.name = name;
- }
-
- public java.lang.Integer getId() {
- return this.id;
- }
-
- public void setId(java.lang.Integer id) {
- this.id = id;
- }
-
- public java.lang.String getName() {
- return this.name;
- }
-
- public void setName(java.lang.String name) {
- this.name = name;
- }
-
- public java.lang.String getDescription() {
- return this.description;
- }
-
- public void setDescription(java.lang.String description) {
- this.description = description;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public boolean equals(Object other) {
- if ( !(other instanceof Rights) ) return false;
- Rights castOther = (Rights) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder()
- .append(getId())
- .toHashCode();
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Topic"
- table="topic"
->
- <id
- name="id"
- type="int"
- column="id"
- unsaved-value="0"
- >
- <generator class="sequence">
- <param name="sequence">topic_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="80"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="filename"
- type="java.lang.String"
- column="filename"
- not-null="true"
- length="20"
- />
- <property
- name="mainUrl"
- type="java.lang.String"
- column="main_url"
- length="255"
- />
- <property
- name="archivUrl"
- type="java.lang.String"
- column="archiv_url"
- length="255"
- />
-
- <!-- associations -->
- <many-to-one name="parentTopic"
- class="mir.core.model.Topic"
- column="parent_id"
- cascade="none"
- not-null="false"/>
-
- <set
- name="childTopics"
- table="topic"
- cascade="all"
- inverse="true"
- >
- <key
- column="parent_id"
- />
- <one-to-many
- class="mir.core.model.Topic"
- />
- </set>
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * TopicStub.java created on 30.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-import java.util.Set;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- * TopicStub
- * @author idefix
- * @version $Id: Topic.java,v 1.6 2003/12/20 20:27:09 idfx Exp $
- */
-public class Topic implements Serializable, ITopic {
- /** identifier field */
- private Integer id;
- /** persistent field */
- private String title;
- /** nullable persistent field */
- private String description;
- /** persistent field */
- private String filename;
- /** nullable persistent field */
- private String mainUrl;
- /** nullable persistent field */
- private String archivUrl;
- private Set childTopics;
- private Topic parentTopic;
-
- /**
- *
- */
- public Topic() {
- super();
- }
-
- /**
- * @return
- */
- public String getArchivUrl() {
- return archivUrl;
- }
-
- /**
- * @return
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * @return
- */
- public String getFilename() {
- return filename;
- }
-
- /**
- * @return
- */
- public Integer getId() {
- return id;
- }
-
- /**
- * @return
- */
- public String getMainUrl() {
- return mainUrl;
- }
-
- /**
- * @return
- */
- public String getTitle() {
- return title;
- }
-
- /**
- * @param string
- */
- public void setArchivUrl(String string) {
- archivUrl = string;
- }
-
- /**
- * @param string
- */
- public void setDescription(String string) {
- description = string;
- }
-
- /**
- * @param string
- */
- public void setFilename(String string) {
- filename = string;
- }
-
- /**
- * @param integer
- */
- public void setId(Integer integer) {
- id = integer;
- }
-
- /**
- * @param string
- */
- public void setMainUrl(String string) {
- mainUrl = string;
- }
-
- /**
- * @param string
- */
- public void setTitle(String string) {
- title = string;
- }
-
- /**
- * @return
- */
- public Set getChildTopics() {
- return childTopics;
- }
-
- /**
- * @param set
- */
- public void setChildTopics(Set set) {
- childTopics = set;
- }
-
- /**
- * @return
- */
- public Topic getParentTopic() {
- return parentTopic;
- }
-
- /**
- * @param topic
- */
- public void setParentTopic(Topic topic) {
- parentTopic = topic;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .append("title", getTitle())
- .toString();
- }
-
- public boolean equals(Object other) {
- if (!(other instanceof Topic))
- return false;
- Topic castOther = (Topic) other;
- return new EqualsBuilder()
- .append(this.getId(), castOther.getId())
- .isEquals();
- }
-
- public int hashCode() {
- return new HashCodeBuilder().append(getId()).toHashCode();
- }
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.UploadedMedia"
- table="uploaded_media"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
- <property
- name="iconIsProduced"
- type="boolean"
- column="icon_is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="iconPath"
- type="java.lang.String"
- column="icon_path"
- length="255"
- />
-
- <!-- associations -->
- <many-to-one
- name="mediaType"
- class="mir.core.model.MediaType"
- column="to_media_type"
- />
- <many-to-one
- name="mediaFolder"
- class="mir.core.model.MediaFolder"
- column="to_media_folder"
- />
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * UploadedMedia.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-import java.io.Serializable;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-/**
- *
- * UploadedMedia
- * @author idefix
- * @version $Id: UploadedMedia.java,v 1.4 2003/08/19 00:41:54 idfx Exp $
- */
-public class UploadedMedia extends Media implements Serializable, IUploadedMedia {
-
- /** persistent field */
- private boolean iconIsProduced;
-
- /** nullable persistent field */
- private String iconPath;
-
- /** nullable persistent field */
- private MediaFolder mediaFolder;
-
- /** nullable persistent field */
- private MediaType mediaType;
-
- /** default constructor */
- public UploadedMedia() {
- }
-
- public boolean isIconIsProduced() {
- return this.iconIsProduced;
- }
-
- public void setIconIsProduced(boolean iconIsProduced) {
- this.iconIsProduced = iconIsProduced;
- }
-
- public java.lang.String getIconPath() {
- return this.iconPath;
- }
-
- public void setIconPath(java.lang.String iconPath) {
- this.iconPath = iconPath;
- }
-
- public String toString() {
- return new ToStringBuilder(this)
- .append("id", getId())
- .toString();
- }
-
- public mir.core.model.MediaFolder getMediaFolder() {
- return this.mediaFolder;
- }
-
- public void setMediaFolder(mir.core.model.MediaFolder mediaFolder) {
- this.mediaFolder = mediaFolder;
- }
-
- public mir.core.model.MediaType getMediaType() {
- return this.mediaType;
- }
-
- public void setMediaType(mir.core.model.MediaType mediaType) {
- this.mediaType = mediaType;
- }
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.Video"
- table="video"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">media_id_seq</param>
- </generator>
- </id>
- <property
- name="title"
- type="java.lang.String"
- column="title"
- not-null="true"
- length="255"
- />
- <property
- name="subtitle"
- type="java.lang.String"
- column="subtitle"
- length="128"
- />
- <property
- name="edittitle"
- type="java.lang.String"
- column="edittitle"
- length="128"
- />
- <property
- name="date"
- type="java.lang.String"
- column="date"
- not-null="true"
- length="8"
- />
- <property
- name="creator"
- type="java.lang.String"
- column="creator"
- length="80"
- />
- <property
- name="creatorMainUrl"
- type="java.lang.String"
- column="creator_main_url"
- length="255"
- />
- <property
- name="creatorEmail"
- type="java.lang.String"
- column="creator_email"
- length="80"
- />
- <property
- name="creatorAddress"
- type="java.lang.String"
- column="creator_address"
- length="80"
- />
- <property
- name="creatorPhone"
- type="java.lang.String"
- column="creator_phone"
- length="20"
- />
- <property
- name="description"
- type="java.lang.String"
- column="description"
- sql-type="text"
- />
- <property
- name="comment"
- type="java.lang.String"
- column="comment"
- sql-type="text"
- />
- <property
- name="source"
- type="java.lang.String"
- column="source"
- length="255"
- />
- <property
- name="publishDate"
- type="java.sql.Timestamp"
- column="publish_date"
- length="8"
- />
- <property
- name="publishServer"
- type="java.lang.String"
- column="publish_server"
- length="255"
- />
- <property
- name="publishPath"
- type="java.lang.String"
- column="publish_path"
- length="255"
- />
- <property
- name="published"
- type="boolean"
- column="is_published"
- not-null="true"
- length="1"
- />
- <property
- name="produced"
- type="boolean"
- column="is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="webdbCreate"
- type="java.sql.Timestamp"
- column="webdb_create"
- not-null="true"
- length="8"
- />
- <property
- name="webdbLastchange"
- type="java.sql.Timestamp"
- column="webdb_lastchange"
- length="8"
- />
- <property
- name="iconIsProduced"
- type="boolean"
- column="icon_is_produced"
- not-null="true"
- length="1"
- />
- <property
- name="iconPath"
- type="java.lang.String"
- column="icon_path"
- length="255"
- />
-
- <!-- associations -->
- <many-to-one
- name="mediaType"
- class="mir.core.model.MediaType"
- column="to_media_type"
- />
- <many-to-one
- name="mediaFolder"
- class="mir.core.model.MediaFolder"
- column="to_media_folder"
- />
- <many-to-one
- name="publisher"
- class="mir.core.model.MirUser"
- column="to_publisher"
- />
- <many-to-one
- name="language"
- class="mir.core.model.Language"
- column="to_language"
- />
- <many-to-one
- name="rights"
- class="mir.core.model.Rights"
- column="to_rights"
- />
- <set name="content" table="content_x_media" lazy="true">
- <key column="media_id"/>
- <many-to-many column="content_id" class="mir.core.model.Content"/>
- </set>
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * Video.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.model;
-
-/**
- * Video
- * @version $Id: Video.java,v 1.1 2003/08/16 19:15:26 idfx Exp $
- * @author idefix
- */
-public class Video extends UploadedMedia {
-
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
-
-<hibernate-mapping>
-
-<!--
- Created by Middlegen Hibernate plugin
-
- http://boss.bekk.no/boss/middlegen/
- http://hibernate.sourceforge.net/
--->
-
-<class
- name="mir.core.model.MirUser"
- table="webdb_users"
->
- <id
- name="id"
- type="int"
- column="id"
- >
- <generator class="sequence">
- <param name="sequence">webdb_users_id_seq</param>
- </generator>
- </id>
- <property
- name="login"
- type="java.lang.String"
- column="login"
- not-null="true"
- length="16"
- />
- <property
- name="password"
- type="java.lang.String"
- column="password"
- not-null="true"
- length="16"
- />
- <property
- name="isAdmin"
- type="boolean"
- column="is_admin"
- not-null="true"
- length="1"
- />
-
- <!-- associations -->
-
-</class>
-</hibernate-mapping>
+++ /dev/null
-/*
- * ArticleTypeService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.ArticleType;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * ArticleTypeService
- * @author idefix
- * @version $Id: ArticleTypeService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class ArticleTypeService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public ArticleTypeService(SessionFactory factory) {
- super(ArticleType.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) {
- // doonothing;
- }
-
-}
+++ /dev/null
-/*
- * AudioService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Audio;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * AudioService
- * @author idefix
- * @version $Id: AudioService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class AudioService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public AudioService(SessionFactory factory) {
- super(Audio.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject)
- throws HibernateException {
- if(returnObject instanceof Audio){
- Audio audio = (Audio)returnObject;
- Hibernate.initialize(audio.getContent());
-
- }
- }
-
-}
+++ /dev/null
-/*
- * BreakingService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.BreakingNewsItem;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * BreakingService
- * @author idefix
- * @version $Id: BreakingService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class BreakingService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public BreakingService(SessionFactory factory) {
- super(BreakingNewsItem.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- //do nothing
- }
-
-}
+++ /dev/null
-/*
- * CommentService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Comment;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * CommentService
- * @author idefix
- * @version $Id: CommentService.java,v 1.3 2003/09/07 16:55:00 idfx Exp $
- */
-public class CommentService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public CommentService(SessionFactory factory) {
- super(Comment.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof Comment){
- Comment comment = (Comment)returnObject;
- }
- }
-
-}
+++ /dev/null
-/*
- * CommentStatusService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.CommentStatus;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * CommentStatusService
- * @author idefix
- * @version $Id: CommentStatusService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class CommentStatusService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public CommentStatusService(SessionFactory factory) {
- super(CommentStatus.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- //do nothing
- }
-
-}
+++ /dev/null
-/*
- * ContentService.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.service.storage;
-
-import mir.core.model.Content;
-import mir.core.model.IContent;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * ContentService
- * @author idefix
- * @version $Id: ContentService.java,v 1.3 2003/12/20 20:27:09 idfx Exp $
- */
-public class ContentService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public ContentService(SessionFactory factory) {
- super(Content.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof IContent){
- IContent content = (IContent)returnObject;
- Hibernate.initialize(content.getAttachedMedias());
- Hibernate.initialize(content.getChildContent());
- Hibernate.initialize(content.getTopics());
- Hibernate.initialize(content.getComments());
- }
- }
-
-}
+++ /dev/null
-/*
- * ImageService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.IImage;
-import mir.core.model.Image;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * ImageService
- * @author idefix
- * @version $Id: ImageService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class ImageService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public ImageService(SessionFactory factory) {
- super(Image.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof IImage){
- IImage image = (IImage)returnObject;
- Hibernate.initialize(image.getContent());
- }
- }
-
-}
+++ /dev/null
-/*
- * LanguageService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Language;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * LanguageService
- * @author idefix
- * @version $Id: LanguageService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class LanguageService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public LanguageService(SessionFactory factory) {
- super(Language.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- // do nothing
- }
-
-}
+++ /dev/null
-/*
- * MediaFolderService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.MediaFolder;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * MediaFolderService
- * @author idefix
- * @version $Id: MediaFolderService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class MediaFolderService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public MediaFolderService(SessionFactory factory) {
- super(MediaFolder.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- // do nothing
- }
-
-}
+++ /dev/null
-/*
- * MessageService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Message;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * MessageService
- * @author idefix
- * @version $Id: MessageService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class MessageService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public MessageService(SessionFactory factory) {
- super(Message.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- // do nothing
- }
-
-}
+++ /dev/null
-/*
- * OtherMediaService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.IUploadedMedia;
-import mir.core.model.OtherMedia;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * OtherMediaService
- * @author idefix
- * @version $Id: OtherMediaService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class OtherMediaService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public OtherMediaService(SessionFactory factory) {
- super(OtherMedia.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof IUploadedMedia){
- IUploadedMedia media = (IUploadedMedia)returnObject;
- Hibernate.initialize(media.getContent());
- }
- }
-
-}
+++ /dev/null
-/*
- * SessionHolder.java created on 18.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Session;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * SessionHolder
- * @author idefix
- * @version $Id: SessionHolder.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class SessionHolder {
- private ThreadLocal threadLocalSession;
- private SessionFactory factory;
-
- /**
- *
- */
- public SessionHolder(SessionFactory factory) {
- super();
- threadLocalSession = new ThreadLocal();
- this.factory = factory;
- }
-
- public Session currentSession()
- throws HibernateException{
- Session session = (Session)threadLocalSession.get();
- if(session == null){
- session = factory.openSession();
- threadLocalSession.set(session);
- }
- return session;
- }
-
- public void closeSession() throws HibernateException {
- Session session = (Session) threadLocalSession.get();
- if (session != null) {
- session.flush();
- session.close();
- }
- threadLocalSession.set(null);
- }
-}
+++ /dev/null
-/*
- * StorageService.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.core.service.storage;
-
-import java.util.Iterator;
-import java.util.List;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import net.sf.hibernate.Criteria;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Session;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.Transaction;
-import net.sf.hibernate.expression.Expression;
-import net.sf.hibernate.expression.Order;
-
-/**
- *
- * StorageService
- * @author idefix
- * @version $Id: StorageService.java,v 1.8 2003/12/20 20:27:09 idfx Exp $
- */
-public abstract class StorageService {
- private final int defaultLimit;
- private Class objectClass;
- private SessionHolder sessionHolder;
- protected MirPropertiesConfiguration _configuration;
-
- protected StorageService(final Class objectClass,
- final SessionFactory factory){
- this.objectClass = objectClass;
- sessionHolder = new SessionHolder(factory);
- int limit = 30;
- try {
- _configuration = MirPropertiesConfiguration.instance();
- limit =
- _configuration.getInt("ServletModule.Default.ListSize");
- } catch (PropertiesConfigExc e) {
- e.printStackTrace();
- }
- defaultLimit = limit;
- }
-
- public List list(final int offset, final int limit){
- return list(offset, limit, null);
- }
-
- public List list(final int offset){
- return list(offset, defaultLimit, null);
- }
-
- public List list(final int offset, Order order){
- return list(offset, defaultLimit, null, order);
- }
-
- public List list(final int offset, final Expression expression){
- return list(offset, defaultLimit, expression);
- }
-
- public List list(final int offset, final Expression expression,
- final Order order){
- return list(offset, defaultLimit, expression, order);
- }
-
- public List list(final int offset, final int limit,
- final Expression expression) {
- return list(offset, limit, expression, null);
- }
-
- /**
- * Load a list of Objects from the database
- * @param offset an offset of the list
- * @param limit the limit number of Objects to be loaded
- * @param expression a Expression object which describes the
- * constraints of the objects in the list
- * @param order a Order object which describes the order of
- * the list
- * @see Expression
- * @see Order
- * @return a list of Objects
- */
- public List list(final int offset, final int limit,
- final Expression expression, final Order order) {
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- Criteria criteria = session.createCriteria(objectClass);
- if(expression != null){
- criteria = criteria.add(expression);
- }
- if(order != null){
- criteria.addOrder(order);
- }
- criteria.setFirstResult(offset)
- .setMaxResults(limit);
- List returnList = criteria.list();
- for(Iterator iterator = returnList.iterator(); iterator.hasNext();){
- initializeLazyCollections(iterator.next());
- }
- transaction.commit();
- return returnList;
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if (session != null) {
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e){
- throw new StorageServiceFailure(e);
- }
- }
-
- /**
- * Load a list of Objects from the database
- * @return a list of Objects
- */
- public List list() {
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- Criteria criteria = session.createCriteria(objectClass);
- List returnList = criteria.list();
- for(Iterator iterator = returnList.iterator(); iterator.hasNext();){
- initializeLazyCollections(iterator.next());
- }
- transaction.commit();
- return returnList;
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if (session != null) {
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e){
- throw new StorageServiceFailure(e);
- }
- }
-
-
- /**
- * Load a Object with the given unique identifier
- * @param id the identifer of the Object to be loaded
- * @return the Object according to the id
- */
- public Object load(final Integer id){
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- Object returnObject = session.load(objectClass, id);
- initializeLazyCollections(returnObject);
- transaction.commit();
- return returnObject;
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if(session != null){
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e) {
- throw new StorageServiceFailure(e);
- }
- }
-
- /**
- * Save a new Object in the database
- * @param newObject the Object to be saved
- * @return
- */
- public Integer save(final Object newObject){
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- Integer newid = (Integer)session.save(newObject);
- transaction.commit();
- return newid;
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if(session != null){
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e) {
- throw new StorageServiceFailure(e);
- }
- }
-
- /**
- * Update a given Object
- * @param toUpdate the Object to be updated
- */
- public void update(final Object toUpdate){
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- session.update(toUpdate);
- transaction.commit();
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if(session != null){
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e) {
- throw new StorageServiceFailure(e);
- }
- }
-
- /**
- * Delete a given Object from the database
- * @param toDelete the Object to be deleted
- */
- public void delete(final Object toDelete){
- try {
- Session session = null;
- Transaction transaction = null;
- try {
- session = sessionHolder.currentSession();
- transaction = session.beginTransaction();
- session.delete(toDelete);
- transaction.commit();
- } catch (HibernateException e) {
- if(transaction != null){
- transaction.rollback();
- }
- throw new StorageServiceFailure(e);
- } finally {
- if(session != null){
- sessionHolder.closeSession();
- }
- }
- } catch (Exception e) {
- throw new StorageServiceFailure(e);
- }
- }
-
- /**
- * Initialize all the lazy loaded collections
- * of an object loaded from the database
- * @param object the object to be initialized
- */
- protected abstract void initializeLazyCollections(
- final Object object) throws HibernateException;
-}
+++ /dev/null
-/*
- * StorageServiceFailure.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import multex.Failure;
-
-/**
- *
- * StorageServiceFailure
- * @author idefix
- * @version $Id: StorageServiceFailure.java,v 1.1 2003/08/17 19:11:49 idfx Exp $
- */
-public class StorageServiceFailure extends Failure {
-
- /**
- *
- * @author idefix
- *
- * To change the template for this generated type comment go to
- * Window - Preferences - Java - Code Generation - Code and Comments
- */
- public StorageServiceFailure(Throwable throwable) {
- super("A StorageFailure occured", throwable);
- }
-
-}
+++ /dev/null
-/*
- * TopicService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Topic;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * TopicService
- * @author idefix
- * @version $Id: TopicService.java,v 1.3 2003/09/30 19:27:10 idfx Exp $
- */
-public class TopicService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public TopicService(SessionFactory factory) {
- super(Topic.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- }
-
-}
+++ /dev/null
-/*
- * UploadedMediaService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.IUploadedMedia;
-import mir.core.model.UploadedMedia;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * UploadedMediaService
- * @author idefix
- * @version $Id: UploadedMediaService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class UploadedMediaService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public UploadedMediaService(SessionFactory factory) {
- super(UploadedMedia.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof IUploadedMedia){
- IUploadedMedia media = (IUploadedMedia)returnObject;
- Hibernate.initialize(media.getContent());
- }
- }
-
-}
+++ /dev/null
-/*
- * UserService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-
-import java.util.List;
-
-import mir.core.model.MirUser;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.expression.Expression;
-
-/**
- * UserService
- * @author idefix
- * @version $Id: UserService.java,v 1.3 2003/09/07 16:55:00 idfx Exp $
- */
-public class UserService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public UserService(SessionFactory factory) {
- super(MirUser.class, factory);
- }
-
- public MirUser loadUser(String user, String password){
- List list = list(0, 1,
- Expression.and(
- Expression.and(
- Expression.eq("login", user),
- Expression.eq("password", password)
- ),
- Expression.eq("isAdmin", new Boolean(true))
- )
- );
- if(list.size() == 0){
- return null;
- }
- return (MirUser)list.get(0);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- //do nothing
- }
-}
+++ /dev/null
-/*
- * VideoService.java created on 17.08.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.service.storage;
-
-import mir.core.model.Video;
-import net.sf.hibernate.Hibernate;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-
-/**
- * VideoService
- * @author idefix
- * @version $Id: VideoService.java,v 1.2 2003/09/05 20:23:59 idfx Exp $
- */
-public class VideoService extends StorageService {
-
- /**
- * @param objectClass
- * @param factory
- */
- public VideoService(SessionFactory factory) {
- super(Video.class, factory);
- }
-
- /**
- * @see mir.core.service.storage.StorageService#initializeLazyCollections(java.lang.Object)
- */
- protected void initializeLazyCollections(Object returnObject) throws HibernateException {
- if(returnObject instanceof Video){
- Video video = (Video)returnObject;
- Hibernate.initialize(video.getContent());
- }
- }
-
-}
+++ /dev/null
-/*
- * Test.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.test;
-
-import java.util.Iterator;
-import java.util.List;
-
-import mir.core.model.Audio;
-import mir.core.model.Comment;
-import mir.core.model.Content;
-import mir.core.model.IImage;
-import mir.core.model.Image;
-import mir.core.model.Media;
-import mir.core.model.Topic;
-import mir.core.model.TopicRich;
-import mir.core.model.UploadedMedia;
-import mir.core.model.Video;
-import mir.core.service.storage.ContentService;
-import mir.core.service.storage.ImageService;
-import net.sf.hibernate.Criteria;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.Session;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.Transaction;
-import net.sf.hibernate.cfg.Configuration;
-import net.sf.hibernate.expression.Order;
-import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
-
-/**
- * Test
- * @version $Id: Test.java,v 1.9 2003/12/20 20:27:09 idfx Exp $
- * @author idefix
- */
-public class Test {
-
- public static void main(String[] args) {
- //BasicConfigurator.configure();
- try {
- Configuration configuration = new Configuration().configure();
- SessionFactory factory = configuration.buildSessionFactory();
- Session session = factory.openSession();
-// SchemaExport export = new SchemaExport(configuration);
-// export.setOutputFile("/tmp/test.sql");
-// export.create(true, false);
- Transaction transaction = session.beginTransaction();
- Criteria criteria = session.createCriteria(Topic.class);
- List list = criteria.setMaxResults(10).list();
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Topic media = (Topic)iterator.next();
- System.out.println(media.toString());
- }
- criteria = session.createCriteria(Media.class);
- criteria.addOrder(Order.asc("id"));
- list = criteria.list();
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Media media = (Media)iterator.next();
- System.out.println(media.toString());
- }
- System.out.println("media size " + list.size());
-
- criteria = session.createCriteria(Comment.class);
- criteria.addOrder(Order.asc("id"));
- list = criteria.list();
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Comment media = (Comment)iterator.next();
- System.out.println(media.toString());
- }
- System.out.println("comment size " + list.size());
-
- criteria = session.createCriteria(Content.class);
- criteria.addOrder(Order.asc("id"));
- list = criteria.list();
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Content media = (Content)iterator.next();
- System.out.println(media.toString());
- }
- System.out.println("content size " + list.size());
-
- transaction.commit();
- session.close();
-
- ContentService contentService = new ContentService(factory);
-
- Object content = contentService.load(new Integer(7));
- System.out.println(content + content.getClass().getName());
-
- System.out.println("****** content media");
-
- list = contentService.list(0,10);
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Content media = (Content)iterator.next();
- System.out.println(media.getTitle());
- }
-
- session = factory.openSession();
- transaction = session.beginTransaction();
- criteria = session.createCriteria(UploadedMedia.class);
- list = criteria.setMaxResults(10).list();
- System.out.println("****** uploaded media");
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- UploadedMedia media = (UploadedMedia)iterator.next();
- System.out.println(media.toString() + media.getIconPath());
- }
- transaction.commit();
- session.close();
- ImageService imageService = new ImageService(factory);
- list = imageService.list(0,10);
- System.out.println("****** image media");
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Image media = (Image)iterator.next();
- System.out.println(media.toString() + media.getIconPath());
- }
- IImage image = (IImage)imageService.load(new Integer(18));
- System.out.println(image + " " + image.getImage().length);
- session = factory.openSession();
- transaction = session.beginTransaction();
- criteria = session.createCriteria(Audio.class);
- list = criteria.setMaxResults(10).list();
- System.out.println("****** audio media");
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Audio media = (Audio)iterator.next();
- System.out.println(media.toString() + media.getIconPath());
- }
- criteria = session.createCriteria(Video.class);
- list = criteria.setMaxResults(10).list();
- System.out.println("****** video media");
- for(Iterator iterator = list.iterator(); iterator.hasNext();){
- Video media = (Video)iterator.next();
- System.out.println(media.toString() + media.getIconPath());
- }
- transaction.commit();
- session.close();
- } catch (HibernateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-}
+++ /dev/null
-/*
- * DispatchAction.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action;
-
-import java.lang.reflect.Method;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.struts.action.Action;
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-
-
-/**
- * DispatchAction<br>
- * This Action dispatches a call of execute() to a method with a name defined
- * as parameter in the action mapping. To use this Action you have to define a
- * action mapping in the following way:<br>
- *
- * <code><pre>
- * <action-mappings>
- * <action
- * parameter="logon"
- * path="/logon"
- * type="my.action.MyAction"
- * ...
- * />
- * </action>
- * <action-mappings>
- * </pre></code><br>
- * If <code>logon.do</code> is called by the user the method <code>logon()</code>
- * of the class MyAction is called.
- *
- *
- * @version $Id: DispatchAction.java,v 1.1 2003/09/10 20:58:27 idfx Exp $
- * @author idefix
- */
-public class DispatchAction extends Action {
-
- /**
- * Dispatches to a method with a name defined as parameter of the action mapping.
- * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
- public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- String parameter = actionMapping.getParameter();
- Method method = getClass().getDeclaredMethod(parameter,
- new Class[]{ActionMapping.class, ActionForm.class,
- HttpServletRequest.class, HttpServletResponse.class});
- method.setAccessible(true);
- return (ActionForward) method.invoke(
- this, new Object[]{actionMapping, actionForm, request, response});
- }
-}
+++ /dev/null
-/*
- * AuthenticationAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.model.MirUser;
-import mir.core.service.storage.UserService;
-import mir.core.ui.action.DispatchAction;
-import mir.core.ui.servlet.ServletConstants;
-import multex.Failure;
-import net.sf.hibernate.SessionFactory;
-
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-import org.apache.struts.action.DynaActionForm;
-import org.apache.struts.action.RedirectingActionForward;
-
-/**
- * AuthenticationAction
- * @author idefix
- * @version $Id: AuthenticationAction.java,v 1.3 2003/09/18 21:42:16 idfx Exp $
- */
-public class AuthenticationAction extends DispatchAction {
- private MirPropertiesConfiguration _configuration;
-
- public AuthenticationAction(){
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
- private ActionForward logon(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- //retrieve the form input data
- DynaActionForm form = (DynaActionForm)actionForm;
- String login = (String) form.get("login");
- String password = (String) form.get("password");
-
- if((login == null || login.trim().length() == 0)
- && (password == null || password.trim().length() == 0)){
- //no input --> error
- return actionMapping.findForward("failed");
- }
-
- //access to persitence layer
- ServletContext context = this.getServlet().getServletContext();
- UserService userService =
- new UserService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
-
- //try to retrieve user for the given values
- MirUser mirUser = userService.loadUser(login, password);
- if(mirUser == null){
- //not existent user --> error
- return actionMapping.findForward("failed");
- }
-
- //add user to the session context
- HttpSession session = request.getSession();
- session.setAttribute(ServletConstants.USER, mirUser);
-
- //check if we have to redirect the user
- String requestUri =
- (String) session.getAttribute(ServletConstants.REDIRECT_ACTION);
- System.out.println(requestUri);
- if(requestUri != null && requestUri.indexOf("index") == -1
- && requestUri.indexOf("logon") == -1){
-
- // we have to redirect the user
- requestUri = requestUri.substring(requestUri.lastIndexOf("/"));
-
- //retrieve the correct action name
- String queryString =
- (String) session.getAttribute(ServletConstants.REDIRECT_QUERY_STRING);
- if(queryString != null){
- requestUri = requestUri + "?" +queryString;
- }
-
- //construct a redirect
- RedirectingActionForward actionForward =
- new RedirectingActionForward(requestUri);
- System.out.println("redirect");
- //return the redirect
- return actionForward;
- }
-
- //normal redirect to the startpage
- System.out.println("success");
- return actionMapping.findForward("success");
- }
-
- private ActionForward logoff(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- //kill session
- HttpSession session = request.getSession();
- session.setAttribute(ServletConstants.USER, null);
- session.invalidate();
-
- //return to the logon form
- return actionMapping.findForward("logon");
- }
-}
+++ /dev/null
-/*
- * ConfirmAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.ui.action.DispatchAction;
-import mir.core.ui.servlet.ServletConstants;
-import multex.Failure;
-
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-import org.apache.struts.action.DynaActionForm;
-import org.apache.struts.action.ForwardingActionForward;
-
-/**
- * ConfirmAction
- * @author idefix
- * @version $Id: ConfirmAction.java,v 1.1 2003/09/18 21:42:16 idfx Exp $
- */
-public class ConfirmAction extends DispatchAction {
- private MirPropertiesConfiguration _configuration;
-
- public ConfirmAction(){
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
- private ActionForward confirm(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- //retrieve the form input data
- DynaActionForm form = (DynaActionForm)actionForm;
- String url = null;
- if(form.get("cancel") != null && form.get("cancel").toString().length() > 0){
- url = (String) form.get("cancelurl");
- } else {
- url = (String) form.get("okurl");
- }
-
- request.setAttribute(ServletConstants.ID, form.get("id"));
- request.setAttribute("where", form.get("where"));
- request.setAttribute("order", form.get("order"));
- request.setAttribute("offset", form.get("offset"));
- request.setAttribute(ServletConstants.DELETE, new Boolean(true));
-
- if(url != null){
- //construct a redirect
- ActionForward actionForward =
- new ForwardingActionForward("/" + url);
- //return the redirect
- return actionForward;
- } else {
- return actionMapping.findForward("failed");
- }
- }
-}
+++ /dev/null
-/*
- * ContentAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.model.ArticleType;
-import mir.core.model.Content;
-import mir.core.model.IContent;
-import mir.core.model.Language;
-import mir.core.model.MirUser;
-import mir.core.service.storage.ArticleTypeService;
-import mir.core.service.storage.ContentService;
-import mir.core.service.storage.LanguageService;
-import mir.core.ui.action.DispatchAction;
-import mir.core.ui.servlet.ServletConstants;
-import multex.Failure;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.expression.Expression;
-import net.sf.hibernate.expression.Order;
-
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-import org.apache.struts.action.DynaActionForm;
-
-/**
- * TopicAction
- * @author idefix
- * @version $Id: ContentAction.java,v 1.1 2003/12/20 20:27:09 idfx Exp $
- */
-public class ContentAction extends DispatchAction {
- private MirPropertiesConfiguration _configuration;
-
- public ContentAction(){
- super();
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
- private ActionForward add(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- ContentService contentService =
- new ContentService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- request.setAttribute(ServletConstants.NEW, new Boolean(true));
- request.setAttribute(ServletConstants.ID, "");
- request.setAttribute(ServletConstants.OFFSET, "");
-
- //setting standard-values
- Content content = new Content();
- request.setAttribute("article", content);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward save(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- HttpSession httpSession = request.getSession();
- ContentService contentService =
- new ContentService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- ArticleTypeService articleTypeService =
- new ArticleTypeService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- LanguageService languageService =
- new LanguageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve the form
- DynaActionForm form = (DynaActionForm) actionForm;
- if(form == null){
- return actionMapping.findForward("failed");
- }
-
- //check if new
- Boolean isnew = (Boolean) form.get("new");
-
- //retrieve id
- IContent content = null;
- if(isnew.booleanValue()){
- content = new Content();
- //set change and create date
- content.setWebdbCreate(new Date());
- content.setWebdbLastchange(new Date());
- } else {
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- content = (IContent) contentService.load(id);
- //set last edit date
- content.setWebdbLastchange(new Date());
- }
-
- if(content == null){
- return actionMapping.findForward("failed");
- }
-
- String webDbCreate = (String) form.get("date");
- if(webDbCreate == null || webDbCreate.length() == 0){
- Date date = new Date();
- SimpleDateFormat dateFormat = new SimpleDateFormat();
- dateFormat.applyPattern("yyyyMMdd");
- webDbCreate = dateFormat.format(date);
- }
- content.setDate(webDbCreate);
-
- //set articletype
- Integer articleTypeId = (Integer) form.get("to_article_type");
- content.setArticleType(
- (ArticleType) articleTypeService.load(articleTypeId));
-
- //set language
- Integer languageTypeId = (Integer) form.get("to_language");
- content.setLanguage(
- (Language) languageService.load(languageTypeId));
-
- //set form data
- content.setPublisher(
- (MirUser) httpSession.getAttribute(ServletConstants.USER));
- content.setTitle((String) form.get("title"));
- content.setSubtitle((String) form.get("subtitle"));
- content.setComment((String) form.get("comment"));
- content.setContentData((String) form.get("content_data"));
- content.setCreator((String) form.get("creator"));
- content.setCreatorAddress((String)form.get("creator_address"));
- content.setCreatorEmail((String)form.get("creator_email"));
- content.setCreatorPhone((String)form.get("creator_phone"));
- content.setCreatorMainUrl((String)form.get("creator_main_url"));
- content.setDescription((String)form.get("description"));
- content.setEdittitle((String)form.get("edittitle"));
- if(form.get("is_html") != null){
- content.setHtml(true);
- } else {
- content.setHtml(false);
- }
- if(form.get("is_published") != null){
- content.setPublished(true);
- } else {
- content.setPublished(false);
- }
-
-// Integer parentId = (Integer)form.get("parentContent");
-// if(parentId != null && parentId.intValue() > -1){
-// Topic parentTopic = (Topic) topicService.load(parentId);
-// topic.setParentTopic(parentTopic);
-// }
-
- //save the article
- if(isnew.booleanValue()){
- Integer id = contentService.save(content);
- request.setAttribute(ServletConstants.OFFSET, "0");
- } else {
- contentService.update(content);
- }
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward delete(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- ContentService contentService =
- new ContentService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve id
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
-
- //confirm the request
- System.out.println(request.getAttribute(ServletConstants.DELETE));
- if(request.getAttribute(ServletConstants.DELETE) == null){
- return actionMapping.findForward("confirm");
- }
- //load object
- Content content = (Content) contentService.load(id);
-
- if(content == null){
- return actionMapping.findForward("failed");
- }
-
- contentService.delete(content);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward list(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- String offsetString = request.getParameter(ServletConstants.OFFSET);
- int offset = 0;
- if(offsetString != null && !offsetString.equals("")){
- offset = new Integer(offsetString).intValue();
- }
- String articleTypeString = request.getParameter("articletype");
- Integer articleTypeId = new Integer(-1);
- if(articleTypeString != null && !articleTypeString.equals("")){
- articleTypeId = new Integer(articleTypeString);
- }
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- ContentService contentService =
- new ContentService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
-
- //retrieve entities
- Order order = Order.desc("id");
- List contents;
- if(articleTypeId.intValue() >= 0){
- ArticleTypeService articleTypeService =
- new ArticleTypeService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- Expression expression =
- Expression.eq("articleType",
- articleTypeService.load(articleTypeId));
- contents = contentService.list(offset, expression, order);
- } else {
- contents = contentService.list(offset, order);
- }
-
-
- //configure the data to send to view
- int listSize = _configuration.getInt("ServletModule.Default.ListSize");
- Integer lastOffset;
- if(offset-listSize < 0){
- lastOffset = new Integer(0);
- } else {
- lastOffset = new Integer(offset-listSize);
- }
- request.setAttribute(ServletConstants.LAST_OFFSET, lastOffset);
- request.setAttribute(ServletConstants.NEXT_OFFSET,
- new Integer(offset + listSize));
- request.setAttribute(ServletConstants.OFFSET,
- new Integer(offset));
- request.setAttribute("articles", contents);
-
- //show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward edit(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- String offset = request.getParameter(ServletConstants.OFFSET);
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- ContentService contentService =
- new ContentService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve entities
- IContent content = (IContent) contentService.load(id);
-
- //configure the data to send to view
- request.setAttribute(ServletConstants.OFFSET, offset);
- request.setAttribute(ServletConstants.NEW,"0");
- request.setAttribute("article", content);
-
- //show the view
- return actionMapping.findForward("success");
- }
-}
+++ /dev/null
-/*
- * AuthenticationAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.model.Message;
-import mir.core.model.MirUser;
-import mir.core.service.storage.MessageService;
-import mir.core.ui.action.DispatchAction;
-import mir.core.ui.servlet.ServletConstants;
-import multex.Failure;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.expression.Order;
-
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-import org.apache.struts.action.DynaActionForm;
-
-/**
- * AuthenticationAction
- * @author idefix
- * @version $Id: MessageAction.java,v 1.2 2003/09/18 21:42:16 idfx Exp $
- */
-public class MessageAction extends DispatchAction {
- private MirPropertiesConfiguration _configuration;
-
- public MessageAction(){
- super();
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
- private ActionForward add(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- request.setAttribute(ServletConstants.NEW, new Boolean(true));
- request.setAttribute(ServletConstants.ID, "");
- request.setAttribute(ServletConstants.OFFSET, "");
-
- //setting standard-values
- Message message = new Message();
- HttpSession session = request.getSession();
- MirUser user = (MirUser) session.getAttribute(ServletConstants.USER);
- message.setCreator(user.getLogin());
- request.setAttribute("message", message);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward save(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- MessageService messageService =
- new MessageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- DynaActionForm form = (DynaActionForm) actionForm;
- if(form == null){
- return actionMapping.findForward("failed");
- }
- //check if new
- Boolean isnew = (Boolean) form.get("new");
-
- //retrieve id
- Message message = null;
- if(isnew.booleanValue()){
- message = new Message();
- } else {
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- message = (Message) messageService.load(id);
- }
-
- if(message == null){
- return actionMapping.findForward("failed");
- }
-
- message.setTitle((String)form.get("title"));
- message.setDescription((String)form.get("description"));
- message.setCreator((String)form.get("creator"));
-
- if(isnew.booleanValue()){
- message.setWebdbCreate(new Date());
- Integer id = messageService.save(message);
- request.setAttribute(ServletConstants.OFFSET, "0");
- } else {
- messageService.update(message);
- }
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward delete(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- MessageService messageService =
- new MessageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve id
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
-
- //confirm the request
- System.out.println(request.getAttribute(ServletConstants.DELETE));
- if(request.getAttribute(ServletConstants.DELETE) == null){
- System.out.println("call confirm");
- return actionMapping.findForward("confirm");
- }
- System.out.println("komish confirm");
- //load object
- Message message = (Message) messageService.load(id);
-
- if(message == null){
- return actionMapping.findForward("failed");
- }
-
- messageService.delete(message);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward list(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- String offsetString = request.getParameter(ServletConstants.OFFSET);
- int offset = 0;
- if(offsetString != null && !offsetString.equals("")){
- offset = new Integer(offsetString).intValue();
- }
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- MessageService messageService =
- new MessageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve entities
- Order order = Order.desc("webdbCreate");
- List messages = messageService.list(offset, order);
-
- //configure the data to send to view
- int listSize = _configuration.getInt("ServletModule.Default.ListSize");
- Integer lastOffset;
- if(offset-listSize < 0){
- lastOffset = new Integer(0);
- } else {
- lastOffset = new Integer(offset-listSize);
- }
- request.setAttribute(ServletConstants.LAST_OFFSET, lastOffset);
- request.setAttribute(ServletConstants.NEXT_OFFSET,
- new Integer(offset + listSize));
- request.setAttribute(ServletConstants.OFFSET,
- new Integer(offset));
- request.setAttribute("messages", messages);
-
- //show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward edit(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- String offset = request.getParameter(ServletConstants.OFFSET);
-
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- MessageService messageService =
- new MessageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve entities
- Message message = (Message) messageService.load(id);
-
- //configure the data to send to view
- request.setAttribute(ServletConstants.OFFSET, offset);
- request.setAttribute(ServletConstants.NEW,"0");
- request.setAttribute("message", message);
-
- //show the view
- return actionMapping.findForward("success");
- }
-}
+++ /dev/null
-/*
- * AuthenticationAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.core.service.storage.ArticleTypeService;
-import mir.core.service.storage.MessageService;
-import mir.core.ui.servlet.ServletConstants;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.expression.Order;
-
-import org.apache.struts.action.Action;
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-
-/**
- * AuthenticationAction
- * @author idefix
- * @version $Id: StartpageAction.java,v 1.3 2003/12/20 20:27:09 idfx Exp $
- */
-public class StartpageAction extends Action {
-
- /**
- * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
- public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- String param = actionMapping.getParameter();
- if(param.equals("index")){
- return index(actionMapping, actionForm, request, response);
- }
- return null;
- }
-
- private ActionForward index(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- ServletContext context = this.getServlet().getServletContext();
- MessageService messageService =
- new MessageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- ArticleTypeService articleTypeService =
- new ArticleTypeService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- Order order = Order.desc("webdbCreate");
- List messages = messageService.list(0, order);
- request.setAttribute("messages", messages);
-
- List articleTypes = articleTypeService.list();
- request.setAttribute("articletypes", articleTypes);
-
- return actionMapping.findForward("success");
- }
-}
+++ /dev/null
-/*
- * TopicAction.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.action.admin;
-
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.model.Topic;
-import mir.core.service.storage.TopicService;
-import mir.core.ui.action.DispatchAction;
-import mir.core.ui.servlet.ServletConstants;
-import multex.Failure;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.expression.Order;
-
-import org.apache.struts.action.ActionForm;
-import org.apache.struts.action.ActionForward;
-import org.apache.struts.action.ActionMapping;
-import org.apache.struts.action.DynaActionForm;
-
-/**
- * TopicAction
- * @author idefix
- * @version $Id: TopicAction.java,v 1.1 2003/09/30 19:29:32 idfx Exp $
- */
-public class TopicAction extends DispatchAction {
- private MirPropertiesConfiguration _configuration;
-
- public TopicAction(){
- super();
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
- private ActionForward add(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- List topics = topicService.list();
- Topic defaultParent = new Topic();
- defaultParent.setId(new Integer(-1));
- defaultParent.setTitle("----");
- topics.add(0, defaultParent);
-
- request.setAttribute(ServletConstants.NEW, new Boolean(true));
- request.setAttribute(ServletConstants.ID, "");
- request.setAttribute(ServletConstants.OFFSET, "");
- request.setAttribute("topics", topics);
-
- //setting standard-values
- Topic topic = new Topic();
- request.setAttribute("topic", topic);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward save(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- DynaActionForm form = (DynaActionForm) actionForm;
- if(form == null){
- return actionMapping.findForward("failed");
- }
- //check if new
- Boolean isnew = (Boolean) form.get("new");
-
- //retrieve id
- Topic topic = null;
- if(isnew.booleanValue()){
- topic = new Topic();
- } else {
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- topic = (Topic) topicService.load(id);
- }
-
- if(topic == null){
- return actionMapping.findForward("failed");
- }
-
- topic.setTitle((String)form.get("title"));
- topic.setDescription((String)form.get("title"));
- topic.setFilename((String)form.get("filename"));
- topic.setMainUrl((String)form.get("mainUrl"));
- topic.setArchivUrl((String)form.get("archivUrl"));
- topic.setParentTopic(null);
-
- Integer parentId = (Integer)form.get("parentTopic");
- if(parentId != null && parentId.intValue() > -1){
- Topic parentTopic = (Topic) topicService.load(parentId);
- topic.setParentTopic(parentTopic);
- }
-
- if(isnew.booleanValue()){
- System.out.println(topic);
- Integer id = topicService.save(topic);
- request.setAttribute(ServletConstants.OFFSET, "0");
- } else {
- topicService.update(topic);
- }
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward delete(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve id
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
-
- //confirm the request
- System.out.println(request.getAttribute(ServletConstants.DELETE));
- if(request.getAttribute(ServletConstants.DELETE) == null){
- return actionMapping.findForward("confirm");
- }
- //load object
- Topic topic = (Topic) topicService.load(id);
-
- if(topic == null){
- return actionMapping.findForward("failed");
- }
-
- topicService.delete(topic);
-
- // show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward list(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- String offsetString = request.getParameter(ServletConstants.OFFSET);
- int offset = 0;
- if(offsetString != null && !offsetString.equals("")){
- offset = new Integer(offsetString).intValue();
- }
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve entities
- Order order = Order.desc("id");
- List topics = topicService.list(offset, order);
-
- //configure the data to send to view
- int listSize = _configuration.getInt("ServletModule.Default.ListSize");
- Integer lastOffset;
- if(offset-listSize < 0){
- lastOffset = new Integer(0);
- } else {
- lastOffset = new Integer(offset-listSize);
- }
- request.setAttribute(ServletConstants.LAST_OFFSET, lastOffset);
- request.setAttribute(ServletConstants.NEXT_OFFSET,
- new Integer(offset + listSize));
- request.setAttribute(ServletConstants.OFFSET,
- new Integer(offset));
- request.setAttribute("topics", topics);
-
- //show the view
- return actionMapping.findForward("success");
- }
-
- private ActionForward edit(ActionMapping actionMapping, ActionForm actionForm,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- //retrieve parameters
- Integer id = new Integer(request.getParameter(ServletConstants.ID));
- String offset = request.getParameter(ServletConstants.OFFSET);
-
-
- //access to persistence
- ServletContext context = getServlet().getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
-
- //retrieve entities
- Topic topic = (Topic) topicService.load(id);
-
- List topics = topicService.list();
- Topic defaultParent = new Topic();
- defaultParent.setId(new Integer(-1));
- defaultParent.setTitle("----");
- topics.add(0, defaultParent);
-
- //configure the data to send to view
- request.setAttribute(ServletConstants.OFFSET, offset);
- request.setAttribute(ServletConstants.NEW,"0");
- request.setAttribute("topic", topic);
- request.setAttribute("topics", topics);
-
- //show the view
- return actionMapping.findForward("success");
- }
-}
+++ /dev/null
-/*
- * AuthenticationFilter.java created on 04.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.filter;
-
-import java.io.IOException;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import mir.core.model.MirUser;
-import mir.core.ui.servlet.*;
-
-/**
- * AuthenticationFilter
- * @author idefix
- * @version $Id: AuthenticationFilter.java,v 1.3 2003/09/18 21:42:17 idfx Exp $
- */
-public class AuthenticationFilter implements Filter {
- private FilterConfig _filterConfig;
-
- /**
- *
- */
- public AuthenticationFilter() {
- super();
- }
-
- /**
- * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
- */
- public void init(final FilterConfig filterConfig)
- throws ServletException {
- _filterConfig = filterConfig;
- }
-
- /**
- * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- public void doFilter(ServletRequest servletRequest,
- ServletResponse servletResponse, FilterChain filterChain)
- throws IOException, ServletException {
-
- HttpServletRequest request = (HttpServletRequest)servletRequest;
- String requestUri = request.getRequestURI();
- if(requestUri != null
- && requestUri.startsWith(request.getContextPath() + "/admin")
- && requestUri.indexOf("logon") == -1){
- //check if authenticated, only if in admin-module
- HttpSession httpSession = request.getSession();
- MirUser mirUser =
- (MirUser)httpSession.getAttribute(ServletConstants.USER);
-
- if(mirUser == null){
- //user is not authorized to access
- //set redirect attributes that the user comes to place he wants to be
- httpSession.setAttribute(ServletConstants.REDIRECT_ACTION, requestUri);
- httpSession.setAttribute(ServletConstants.REDIRECT_QUERY_STRING,
- request.getQueryString());
-
- //send user to logon-page
- servletRequest.getRequestDispatcher("/admin/logon.do")
- .forward(servletRequest, servletResponse);
- } else {
- filterChain.doFilter(servletRequest, servletResponse);
- }
- } else {
- filterChain.doFilter(servletRequest, servletResponse);
- }
- }
-
- /**
- * @see javax.servlet.Filter#destroy()
- */
- public void destroy() {
- _filterConfig = null;
- }
-
-}
+++ /dev/null
-/*
- * CachingFilter.java created on 04.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.filter;
-
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * CachingFilter
- * @author idefix
- * @version $Id: CachingFilter.java,v 1.1 2003/09/18 21:42:17 idfx Exp $
- */
-public class CachingFilter implements Filter {
- private final static String EXPIRATION_DATE;
- private FilterConfig _filterConfig;
-
- static {
- // Generate expiration date that is one year from now in the past
- GregorianCalendar expiration = new GregorianCalendar();
- expiration.roll(Calendar.YEAR, -1);
- SimpleDateFormat httpDate =
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", java.util.Locale.US);
- EXPIRATION_DATE = httpDate.format(expiration.getTime());
- }
-
- /**
- *
- */
- public CachingFilter() {
- super();
- }
-
- /**
- * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
- */
- public void init(final FilterConfig filterConfig)
- throws ServletException {
- _filterConfig = filterConfig;
- }
-
- /**
- * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- public void doFilter(ServletRequest servletRequest,
- ServletResponse servletResponse, FilterChain filterChain)
- throws IOException, ServletException {
-
- filterChain.doFilter(servletRequest, servletResponse);
-
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- // HTTP 1.1 browsers should defeat caching on this header
- response.setHeader( "Cache-Control" ,"no-cache" );
- // HTTP 1.0 browsers should defeat caching on this header
- response.setHeader( "Pragma" ,"no-cache" );
- // Last resort for those that ignore all of the above
- response.setHeader( "Expires" , EXPIRATION_DATE);
- }
-
- /**
- * @see javax.servlet.Filter#destroy()
- */
- public void destroy() {
- _filterConfig = null;
- }
-
-}
+++ /dev/null
-/*
- * ConfigurationPlugin.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.plugin;
-
-import javax.servlet.ServletException;
-
-import mir.config.MirPropertiesConfiguration;
-import mircoders.global.MirGlobal;
-
-import org.apache.struts.action.ActionServlet;
-import org.apache.struts.action.PlugIn;
-import org.apache.struts.config.ModuleConfig;
-
-/**
- * ConfigurationPlugin
- * @version $Id: ConfigurationPlugin.java,v 1.1 2003/09/07 16:55:00 idfx Exp $
- * @author idefix
- */
-public class ConfigurationPlugin implements PlugIn {
-
- /**
- * @see org.apache.struts.action.PlugIn#destroy()
- */
- public void destroy() {
- }
-
- /**
- * @see org.apache.struts.action.PlugIn#init(org.apache.struts.action.ActionServlet, org.apache.struts.config.ModuleConfig)
- */
- public void init(ActionServlet actionServlet, ModuleConfig config)
- throws ServletException {
- MirPropertiesConfiguration.setContext(actionServlet.getServletContext());
- try {
- MirPropertiesConfiguration.instance();
- }
- catch (Throwable t) {
- throw new ServletException("can't read configuration: " + t.toString());
- }
-
- try {
- MirGlobal.localizer();
- }
- catch (Throwable t) {
- throw new ServletException("can't get localizer: " + t.toString());
- }
- }
-
-}
+++ /dev/null
-/*
- * HibernatePlugin.java
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.plugin;
-
-import javax.servlet.ServletException;
-
-import mir.core.ui.servlet.ServletConstants;
-import net.sf.hibernate.HibernateException;
-import net.sf.hibernate.SessionFactory;
-import net.sf.hibernate.cfg.Configuration;
-
-import org.apache.struts.action.ActionServlet;
-import org.apache.struts.action.PlugIn;
-import org.apache.struts.config.ModuleConfig;
-
-/**
- * HibernatePlugin
- * @version $Id: HibernatePlugin.java,v 1.4 2003/12/20 20:27:09 idfx Exp $
- * @author idefix
- */
-public class HibernatePlugin implements PlugIn {
- private SessionFactory factory;
-
- /**
- * @see org.apache.struts.action.PlugIn#destroy()
- */
- public void destroy() {
- if(factory != null){
- try {
- factory.close();
- } catch (HibernateException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * @see org.apache.struts.action.PlugIn#init(org.apache.struts.action.ActionServlet, org.apache.struts.config.ModuleConfig)
- */
- public void init(ActionServlet actionServlet, ModuleConfig config)
- throws ServletException {
- //BasicConfigurator.configure();
- try {
- SessionFactory factory =
- new Configuration().configure().buildSessionFactory();
- actionServlet.getServletContext()
- .setAttribute(ServletConstants.SESSION_FACTORY, factory);
- } catch (HibernateException e) {
- throw new ServletException(e);
- }
- }
-
-}
+++ /dev/null
-/*
- * ServletConstants.java created on 05.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.servlet;
-
-/**
- * ServletConstants<br>
- * Some constant string values needed as keys to store values in the servlet context.
- * @author idefix
- * @version $Id: ServletConstants.java,v 1.4 2003/12/20 20:27:10 idfx Exp $
- */
-public interface ServletConstants {
- public static final String TOPICS = "topics";
-
- public static final String LANGUAGES = "languages";
-
- public static final String ARTICLE_TYPES = "articletypes";
-
- public static final String DELETE = "delete";
-
- public static final String NEW = "new";
-
- public static final String ID = "id";
-
- public static final String REDIRECT_ACTION = "redirect action";
-
- public static final String REDIRECT_QUERY_STRING = "redirect query string";
-
- public static final String NEXT_OFFSET = "nextoffset";
-
- public static final String LAST_OFFSET = "lastoffset";
-
- public static final String OFFSET = "offset";
-
- public static final String DEFAULT_LANGUAGE = "defaultlanguage";
-
- public static final String LOGIN_LANGUAGES = "languages";
-
- public static final String SESSION_FACTORY = "session factory";
-
- public static final String USER = "user";
-
-}
+++ /dev/null
-/*
- * TemplateServlet.java created on 01.09.2003
- *
- * Copyright (C) 2001, 2002, 2003 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.core.ui.servlet;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.core.service.storage.ArticleTypeService;
-import mir.core.service.storage.LanguageService;
-import mir.core.service.storage.TopicService;
-import mir.servlet.ServletModuleExc;
-import mir.util.GeneratorDateTimeFunctions;
-import mir.util.GeneratorExpressionFunctions;
-import mir.util.GeneratorHTMLFunctions;
-import mir.util.GeneratorIntegerFunctions;
-import mir.util.GeneratorListFunctions;
-import mir.util.GeneratorRegularExpressionFunctions;
-import mir.util.GeneratorStringFunctions;
-import mir.util.ResourceBundleGeneratorFunction;
-import mir.util.StringRoutines;
-import mircoders.global.MirGlobal;
-import mircoders.servlet.ServletHelper;
-import multex.Failure;
-import net.sf.hibernate.SessionFactory;
-
-import org.apache.struts.util.MessageResources;
-
-/**
- * TemplateServlet
- * @author idefix
- * @version $Id: TemplateServlet.java,v 1.4 2003/12/20 20:27:10 idfx Exp $
- */
-public class TemplateServlet extends HttpServlet {
- private MirPropertiesConfiguration _configuration;
-
- /**
- *
- */
- public TemplateServlet() {
- super();
- try {
- _configuration = MirPropertiesConfiguration.instance();
- } catch (PropertiesConfigExc e) {
- throw new Failure("could not load config", e);
- }
- }
-
-
-
- /**
- * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
- protected final void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- process(request, response);
- }
-
- /**
- * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
- */
- protected final void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- process(request, response);
- }
-
- /**
- * Processes the request and invokes the presentation
- * @param request
- * @param response
- */
- protected void process(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- try {
- //setting some data which are needed often
- //should be done a bit smarter
- setLoginLanguages(getServletContext());
- ServletContext context = getServletContext();
- TopicService topicService =
- new TopicService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- LanguageService languageService =
- new LanguageService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- ArticleTypeService articleTypeService =
- new ArticleTypeService((SessionFactory)context
- .getAttribute(ServletConstants.SESSION_FACTORY));
- context.setAttribute(ServletConstants.TOPICS, topicService.list());
- context.setAttribute(ServletConstants.LANGUAGES, languageService.list());
- context.setAttribute(ServletConstants.ARTICLE_TYPES, articleTypeService.list());
-
-
- Map requestData = new HashMap();
- Enumeration keys = request.getAttributeNames();
- while(keys.hasMoreElements()){
- final String key = (String)keys.nextElement();
- requestData.put(key, request.getAttribute(key));
- }
- requestData.putAll(request.getParameterMap());
-
- Map sessionData = new HashMap();
- HttpSession httpSession = request.getSession();
- keys = httpSession.getAttributeNames();
- while(keys.hasMoreElements()){
- final String key = (String)keys.nextElement();
- sessionData.put(key, httpSession.getAttribute(key));
- }
-
- Map applicationData = new HashMap();
- ServletContext servletContext = getServletContext();
- keys = servletContext.getAttributeNames();
- while(keys.hasMoreElements()){
- final String key = (String)keys.nextElement();
- applicationData.put(key, servletContext.getAttribute(key));
- }
-
- Map utilityMap = new HashMap();
- utilityMap.put("compressWhitespace",
- new freemarker.template.utility.CompressWhitespace());
- utilityMap.put("encodeHTML",
- new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction());
- utilityMap.put("encodeXML",
- new GeneratorHTMLFunctions.encodeXMLGeneratorFunction());
- utilityMap.put("encodeURI",
- new GeneratorHTMLFunctions.encodeURIGeneratorFunction());
- utilityMap.put("subString",
- new GeneratorStringFunctions.subStringFunction());
- utilityMap.put("subList",
- new GeneratorListFunctions.subListFunction());
- utilityMap.put("isOdd",
- new GeneratorIntegerFunctions.isOddFunction());
- utilityMap.put("increment",
- new GeneratorIntegerFunctions.incrementFunction());
- utilityMap.put("evaluate",
- new GeneratorExpressionFunctions.evaluateExpressionFunction());
- utilityMap.put("constructString",
- new GeneratorStringFunctions.constructStructuredStringFunction());
- utilityMap.put("escapeJDBCString",
- new GeneratorStringFunctions.jdbcStringEscapeFunction());
- utilityMap.put("regexpreplace",
- new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction());
- utilityMap.put("datetime",
- new GeneratorDateTimeFunctions.DateTimeFunctions(
- MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
- utilityMap.put("encodeLink",
- new GeneratorHTMLFunctions.encodeLinksGeneratorFunction(response));
-
- Map configData = MirPropertiesConfiguration.instance().allSettings();
- configData.put("docRoot", request.getContextPath());
- configData.put("now", new Date());
-
- //administeroperations
- List administerOperations = new Vector();
- String settings[] = MirPropertiesConfiguration.instance().getStringArray("Mir.Localizer.Admin.AdministerOperations");
- if (settings!=null) {
- for (int i = 0; i < settings.length; i++) {
- String setting = settings[i].trim();
-
- if (setting.length() > 0) {
- List parts = StringRoutines.splitString(setting, ":");
- if (parts.size() != 2) {
-// logger.error("config error: " + settings[i] + ", 2 parts expected");
- }
- else {
- Map entry = new HashMap();
- entry.put("name", (String) parts.get(0));
- entry.put("url", (String) parts.get(1));
- administerOperations.add(entry);
- }
- }
- }
- }
-
- Map templateData = new HashMap();
- templateData.put("request", requestData);
- templateData.put("session", sessionData);
- templateData.put("application", applicationData);
- templateData.put("utility", utilityMap);
- templateData.put("config", configData);
- templateData.put("administeroperations", administerOperations);
-
- String templateName = generateTemplateString(request);
- System.out.println(templateName);
- Locale[] locales = new Locale[2];
- locales[0] = request.getLocale();
- locales[1] = request.getLocale();
-
- //write the servlet
- PrintWriter printWriter = response.getWriter();
- generateResponse(printWriter, templateData, templateName, locales);
- } catch (Throwable e) {
- throw new ServletException(e);
- }
- }
-
- private String generateTemplateString(HttpServletRequest request){
- String returnString = request.getServletPath();
- returnString = returnString.substring(0, returnString.indexOf("."));
- return returnString + ".tmpl";
- }
-
- private void generateResponse(PrintWriter printWriter, Map map,
- String templateString, Locale[] locales)
- throws ServletModuleExc{
- if(templateString.startsWith("/admin")){
- map.put( "lang",
- new ResourceBundleGeneratorFunction( locales,
- new MessageResources[] {
- MessageResources.getMessageResources("bundles.admin"),
- MessageResources.getMessageResources("bundles.adminlocal")
- }));
-
- templateString = templateString.substring(templateString.lastIndexOf('/'));
- ServletHelper.generateResponse(printWriter, map, templateString);
- }
- if(templateString.startsWith("/open")){
- map.put( "lang",
- new ResourceBundleGeneratorFunction( locales,
- new MessageResources[] {
- MessageResources.getMessageResources("bundles.open"),
- MessageResources.getMessageResources("bundles.open")
- }));
-
- templateString = templateString.substring(templateString.lastIndexOf('/'));
- ServletHelper.generateOpenPostingResponse(printWriter, map, templateString);
- }
- }
-
- private void setLoginLanguages(ServletContext context) throws ServletException {
- List loginLanguages =
- (List) context.getAttribute(ServletConstants.LOGIN_LANGUAGES);
- try {
- if (loginLanguages == null) {
- MessageResources messageResources =
- MessageResources.getMessageResources("bundles.adminlocal");
- MessageResources messageResources2 =
- MessageResources.getMessageResources("bundles.admin");
-
- List languages =
- StringRoutines.splitString(
- MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
-
- loginLanguages = new ArrayList();
- Iterator i = languages.iterator();
- while (i.hasNext()) {
- String code = (String) i.next();
- Locale locale = new Locale(code, "");
- String name = messageResources.getMessage(locale, "languagename");
-
- if (name == null) {
- name = messageResources2.getMessage(locale, "languagename");
- }
-
- if (name == null) {
- name = code;
- }
-
- Map record = new HashMap();
- record.put("name", name);
- record.put("code", code);
- loginLanguages.add(record);
- }
- context.setAttribute(ServletConstants.LOGIN_LANGUAGES,
- loginLanguages);
- context.setAttribute(ServletConstants.DEFAULT_LANGUAGE,
- _configuration.getString("Mir.Login.DefaultLanguage"));
- }
- } catch (Throwable t) {
- throw new ServletException(t.getMessage());
- }
- }
-
- /**
- * @see javax.servlet.Servlet#destroy()
- */
- public void destroy() {
- super.destroy();
- }
-
- /**
- * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
- */
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- MirPropertiesConfiguration.setContext(servletConfig.getServletContext());
- try {
- MirPropertiesConfiguration.instance();
- }
- catch (Throwable t) {
- throw new ServletException("can't read configuration: " + t.toString());
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.xml;
-
-
-// XXX this interface is not final, but a prototype.
-
-/** SAX Context - used to match and perform actions
- * provide access to the current stack and XML elements.
- *
- * Inspired by Tomcat's SAX context, although our's is
- * implemented and used slightly differently.
- *
- * @author
- */
-public class SaxContext {
-
- private String tagStack[];
- private int pos;
-
- // -------------------- Konstruktor
-
- public SaxContext() {
- pos=0;
- tagStack = new String[256];
- }
-
- // -------------------- Access to parsing context
-
- /** Depth of the tag stack.
- */
- public int getTagCount() {
- return pos;
- }
-
- /** Access a particular tag
- */
- public String getTag( int pos ) {
- return tagStack[pos];
- }
-
- // ------------------- Adjusting the parsing context
- public void push(String tag) {
- tagStack[pos] = tag;
- pos++;
- }
-
- public void pop() {
- if(pos > 1)
- tagStack[pos]=null;
-
- pos--;
- }
-
-}
-
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.xml;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import mir.misc.ConfigException;
-import mir.misc.Location;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.DefaultHandler;
-
-/**
- * Configures a based on
- * a XML config file.
- *
- * Based and inspired by ant's XmlConfigurator.java
- * It's a simplified version of the ant parser with
- * the addition of calling set* methods for defined
- * classes as well as the inclusion of a method to
- * add parameters (nested tags) that are required.
- * (the addRequired method) in the config file.
- * that part is from tomcat.
- *
- * much code is stolen from ant ProjectHelper.java.
- *
- * @author -mh <heckmann@hbe.ca>
- * @version 2001.10.21
- */
-
-public class XmlConfigurator {
-
- private static SAXParserFactory parserFactory = null;
-
- private SAXParser saxParser;
- //private Project project;
- private File configFile;
- private File configFileParent;
- private Locator locator;
-
- private SaxContext saxContext;
-
- XmlMatch requiredXmlMatch[]=new XmlMatch[256]; //maximum amount of rules
- int requiredXmlMatchCount=0;
- boolean matched[] = new boolean[256];
- int matchedCount=0;
-
- XmlMatch mustComeFirstMatch[]=new XmlMatch[256]; //maximum amount of rules
- int comeFirstMatchCount=0;
-
- Property comesFirstArr[]=new Property[128];
- int comesFirstCount=0;
-
- Property propertyArr[]=new Property[128];
- int propertyCount=0;
-
- private static XmlConfigurator instance = new XmlConfigurator();
- public static XmlConfigurator getInstance() { return instance; }
-
- /**
- * Configures the Project with the contents of the specified XML file.
- */
- public void configure(File configFile) throws ConfigException {
- setConfigFile(configFile);
- parse();
- }
-
- /**
- * konstruktor. private so no one calls "new" on us.
- */
- private XmlConfigurator() {}
-
-
- /**
- * Constructs a new Ant parser for the specified XML file.
- */
- private void setConfigFile(File configFile) {
- this.configFile = new File(configFile.getAbsolutePath());
- configFileParent = new File(this.configFile.getParent());
- saxContext = new SaxContext();
- }
-
- /**
- * Parses the config file.
- */
- private void parse() throws ConfigException {
- FileInputStream inputStream = null;
- InputSource inputSource = null;
-
- try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- saxParser = factory.newSAXParser();
-
- String uri = "file:" + configFile.getAbsolutePath().replace('\\', '/');
- for (int index = uri.indexOf('#'); index != -1; index = uri.indexOf('#')) {
- uri = uri.substring(0, index) + "%23" + uri.substring(index+1);
- }
-
- inputStream = new FileInputStream(configFile);
- inputSource = new InputSource(inputStream);
- inputSource.setSystemId(uri);
- saxParser.parse(inputSource, new RootHandler());
- if(matchedCount < requiredXmlMatchCount) {
- for( int i=0; i<requiredXmlMatchCount; i++) {
- if( !matched[i] )
- throw new ConfigException("Error parsing config file, missing required element: "+requiredXmlMatch[i].toString());
- }
- }
- try {
- for(int i=0; i<comesFirstCount;i++) {
- comesFirstArr[i].set();
- }
- for(int i=0; i<propertyCount;i++) {
- propertyArr[i].set();
- System.out.println("about to set: "+i);
- }
- } catch (Exception e) {
- throw new SAXParseException(e.toString(), locator);
- }
-}
- catch(ParserConfigurationException exc) {
- throw new ConfigException("Parser has not been configured correctly", exc);
- }
- catch(SAXParseException exc) {
- Location location =
- new Location(configFile.toString(), exc.getLineNumber(), exc.getColumnNumber());
-
- Throwable t = exc.getException();
- if (t instanceof ConfigException) {
- ConfigException be = (ConfigException) t;
- if (be.getLocation() == Location.UNKNOWN_LOCATION) {
- be.setLocation(location);
- }
- throw be;
- }
-
- throw new ConfigException(exc.getMessage(), t, location);
- }
- catch(SAXException exc) {
- Throwable t = exc.getException();
- if (t instanceof ConfigException) {
- throw (ConfigException) t;
- }
- throw new ConfigException(exc.getMessage(), t);
- }
- catch(FileNotFoundException exc) {
- throw new ConfigException(exc);
- }
- catch(IOException exc) {
- throw new ConfigException("Error reading config file", exc);
- }
- finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- }
- catch (IOException ioe) {
- // ignore this
- }
- }
- }
- }
-
- /**
- * The common superclass for all sax event handlers in Ant. Basically
- * throws an exception in each method, so subclasses should override
- * what they can handle.
- *
- * Each type of xml element (task, target, etc) in ant will
- * have its own subclass of AbstractHandler.
- *
- * In the constructor, this class takes over the handling of sax
- * events from the parent handler, and returns
- * control back to the parent in the endElement method.
- */
- private class AbstractHandler extends DefaultHandler {
- protected ContentHandler parentHandler;
-
- public AbstractHandler(ContentHandler parentHandler) {
- this.parentHandler = parentHandler;
-
- // Start handling SAX events
- try {
- saxParser.getXMLReader().setContentHandler(this);
- } catch (SAXException e) {
- throw new ConfigException("Error getting XMLReader",e);
- }
-
- }
-
- public void startElement(String uri, String tag, String qName, Attributes attrs) throws SAXParseException {
- throw new SAXParseException("Unexpected element \"" + tag + "\"", locator);
- }
-
- public void characters(char[] buf, int start, int end) throws SAXParseException {
- String s = new String(buf, start, end).trim();
-
- if (s.length() > 0) {
- throw new SAXParseException("Unexpected text \"" + s + "\"", locator);
- }
- }
-
- /**
- * Called when this element and all elements nested into it have been
- * handeled.
- */
- protected void finished() {}
-
- public void endElement(String uri, String tag, String qName) throws SAXException {
- finished();
- // Let parent resume handling SAX events
- saxParser.getXMLReader().setContentHandler(parentHandler);
- }
- }
-
- /**
- * Handler for the root element. It's only child must be the "mir" element.
- */
- private class RootHandler extends DefaultHandler {
-
- /**
- * resolve file: URIs as relative to the build file.
- */
- public InputSource resolveEntity(String publicId,
- String systemId) {
-
-
- if (systemId.startsWith("file:")) {
- String path = systemId.substring(5);
- int index = path.indexOf("file:");
-
- // we only have to handle these for backward compatibility
- // since they are in the FAQ.
- while (index != -1) {
- path = path.substring(0, index) + path.substring(index + 5);
- index = path.indexOf("file:");
- }
-
- String entitySystemId = path;
- index = path.indexOf("%23");
- // convert these to #
- while (index != -1) {
- path = path.substring(0, index) + "#" + path.substring(index + 3);
- index = path.indexOf("%23");
- }
-
- File file = new File(path);
- if (!file.isAbsolute()) {
- file = new File(configFileParent, path);
- }
-
- try {
- InputSource inputSource = new InputSource(new FileInputStream(file));
- inputSource.setSystemId("file:" + entitySystemId);
- return inputSource;
- } catch (FileNotFoundException fne) {
- System.out.println(file.getAbsolutePath()+" could not be found");
- }
- }
- // use default if not file or file not found
- return null;
- }
-
- public void startElement(String uri, String tag, String qName, Attributes attrs) throws SAXParseException {
- if (tag.equals("mir")) {
- new MirHandler(this).init(tag, attrs);
- } else {
- throw new SAXParseException("Config file is not of expected XML type", locator);
- }
- }
-
- public void setDocumentLocator(Locator locator) {
- XmlConfigurator.this.locator = locator;
- }
- }
-
- /**
- * Handler for the top level "project" element.
- */
- private class MirHandler extends AbstractHandler {
- public MirHandler(ContentHandler parentHandler) {
- super(parentHandler);
- }
-
- public void init(String tag, Attributes attrs) throws SAXParseException {
- String name = null;
-
- for (int i = 0; i < attrs.getLength(); i++) {
- String key = attrs.getLocalName(i);
- String value = attrs.getValue(i);
-
- if (key.equals("name")) {
- name = value;
- } else {
- throw new SAXParseException("Unexpected attribute \"" + attrs.getLocalName(i) + "\"", locator);
- }
- }
-
- if (name == null) {
- throw new SAXParseException("The default attribute of \"name\" is required",
- locator);
- }
-
- saxContext.push(tag);
- matchedCount += checkRequiredTag(saxContext);
-
- //MirConfig.setName(name);
-
- }
-
- public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXParseException {
- if (name.equals("class")) {
- handleClassdef(name, attrs);
- } else {
- throw new SAXParseException("Unexpected element \"" + name + "\"", locator);
- }
- }
-
- public void finished() {
- System.out.println("COUNT "+saxContext.getTagCount()+" TAG "+saxContext.getTag(saxContext.getTagCount()-1));
- saxContext.pop();
- }
-
- private void handleClassdef(String name, Attributes attrs) throws SAXParseException {
- (new ClassHandler(this)).init(name, attrs);
- }
-
- }
-
- /**
- * Handler for "class" elements.
- */
- private class ClassHandler extends AbstractHandler {
-
- Class classN;
-
- public ClassHandler(ContentHandler parentHandler) {
- super(parentHandler);
- }
-
- public void init(String tag, Attributes attrs) throws SAXParseException {
- String name = null;
-
- for (int i = 0; i < attrs.getLength(); i++) {
- String key = attrs.getLocalName(i);
- String value = attrs.getValue(i);
-
- if (key.equals("name")) {
- name = value;
- } else {
- throw new SAXParseException("Unexpected attribute \"" + key + "\"", locator);
- }
- }
-
- if (name == null) {
- throw new SAXParseException("class element appears without a \"name\" attribute", locator);
- }
-
- saxContext.push(tag+":"+name);
- matchedCount += checkRequiredTag(saxContext);
- try {
- classN=Class.forName(name, false, this.getClass().getClassLoader());
- } catch (ClassNotFoundException e) {
- throw new ConfigException("Error invoking class: \""+name+
- "\"",e);
- }
-
- }
-
- public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXParseException {
- if (name.equals("property")) {
- handleProperties(name, attrs);
- } else {
- throw new SAXParseException("Unexpected element \"" + name + "\"", locator);
- }
- }
-
- public void finished() {
- System.out.println("COUNT "+saxContext.getTagCount()+" TAG "+saxContext.getTag(saxContext.getTagCount()-1));
- System.out.println("COUNT "+saxContext.getTagCount());
- saxContext.pop();
- }
-
- private void handleProperties(String name, Attributes attrs) throws SAXParseException {
- (new PropertiesHandler(this, classN )).init(name, attrs);
- }
-
- }
-
- /**
- * Handler for all property elements.
- */
- private class PropertiesHandler extends AbstractHandler {
- private Class classN;
-
- public PropertiesHandler(ContentHandler parentHandler, Class classN) {
- super(parentHandler);
-
- this.classN = classN;
- }
-
- public void init(String tag, Attributes attrs) throws SAXParseException {
- String name=null;
- String value=null;
-
- for (int i = 0; i < attrs.getLength(); i++) {
- String key = attrs.getLocalName(i);
- String v = attrs.getValue(i);
-
- if (key.equals("name")) {
- name = v;
- } else if (key.equals("value")) {
- value = v;
- } else {
- throw new SAXParseException("Unexpected attribute \"" + key + "\"", locator);
- }
- }
-
- if (name == null) {
- throw new SAXParseException("property element appears without a \"name\" attribute", locator);
- }
- if (value == null) {
- throw new SAXParseException("property element appears without a \"value\" attribute", locator);
- }
- saxContext.push(tag+":"+name);
- matchedCount += checkRequiredTag(saxContext);
-
- //finally add it to the lists
- //to be processed later
- if (checkComesFirstTag(saxContext)) {
- comesFirstArr[comesFirstCount]=new Property(classN, name, value);
- comesFirstCount++;
- } else {
- propertyArr[propertyCount]=new Property(classN, name, value);
- propertyCount++;
- }
- }
-
- protected void finished() {
- System.out.println("COUNT "+saxContext.getTagCount()+" TAG "+saxContext.getTag(saxContext.getTagCount()-1));
- System.out.println("COUNT "+saxContext.getTagCount());
- saxContext.pop();
- }
-
- }
-
- public void addComesFirstTag(String xmlPath) {
- mustComeFirstMatch[comeFirstMatchCount]=new XmlMatch(xmlPath);
- comeFirstMatchCount++;
- }
-
- private boolean checkComesFirstTag(SaxContext ctx) {
- for( int i=0; i<comeFirstMatchCount; i++ ) {
- if( mustComeFirstMatch[i].match(ctx) ) {
- return true;
- }
- }
- return false;
- }
-
- public void addRequiredTag(String xmlPath) {
- requiredXmlMatch[requiredXmlMatchCount]=new XmlMatch(xmlPath);
- matched[requiredXmlMatchCount]=false;
- requiredXmlMatchCount++;
- }
-
- private int checkRequiredTag(SaxContext ctx) {
- int matchCount=0;
- for( int i=0; i<requiredXmlMatchCount; i++ ) {
- if( requiredXmlMatch[i].match(ctx) ) {
- matched[i]=true;
- matchCount++;
- }
- }
- return matchCount;
- }
-
-
- private static String capitalize(String name) {
- if (name == null || name.length() == 0) {
- return name;
- }
- char chars[] = name.toCharArray();
- chars[0] = Character.toUpperCase(chars[0]);
- return new String(chars);
- }
-
- private class Property {
- Class classN;
- String name;
- String value;
-
- public Property( Class classN, String name, String value) {
- this.classN=classN;
- this.name=name;
- this.value=value;
- }
-
- /** Find a method with the right name
- * If found, call the method ( if param is int or boolean we'll convert
- * value to the right type before) - that means you can have setDebug(1).
- */
- public void set() throws Exception {
-
- String setter= "set" +capitalize(name);
-
- try {
- Method methods[]=classN.getMethods();
- Method setPropertyMethod=null;
-
- // First, the ideal case - a setFoo( String ) method
- for( int i=0; i< methods.length; i++ ) {
- Class paramT[]=methods[i].getParameterTypes();
- if( setter.equals( methods[i].getName() ) &&
- paramT.length == 1 &&
- "java.lang.String".equals( paramT[0].getName())) {
-
- methods[i].invoke( null, new Object[] { value } );
- return;
- }
- } //end for
-
- // Try a setFoo ( int ), (float) or ( boolean )
- for( int i=0; i< methods.length; i++ ) {
- boolean ok=true;
- if( setter.equals( methods[i].getName() ) &&
- methods[i].getParameterTypes().length == 1) {
-
- // match - find the type and invoke it
- Class paramType=methods[i].getParameterTypes()[0];
- Object params[]=new Object[1];
- if ("java.lang.Integer".equals( paramType.getName()) ||
- "int".equals( paramType.getName())) {
- try {
- params[0]=new Integer(value);
- } catch( NumberFormatException ex ) {ok=false;}
- } else if ("java.lang.Float".equals( paramType.getName()) ||
- "float".equals( paramType.getName())) {
- try {
- params[0]=new Float(value);
- } catch( NumberFormatException ex ) {ok=false;}
- } else if ("java.lang.Boolean".equals( paramType.getName()) ||
- "boolean".equals( paramType.getName())) {
- params[0]=new Boolean(value);
- } else {
- throw new Exception("Unknown type " + paramType.getName() + "for property \""+name+"\"with value \""+value+"\"");
- }
-
- if( ok ) {
- System.out.println("XXX: " + methods[i] + " " + classN + " " + params[0] );
- methods[i].invoke( null, params );
- return;
- } //end if
- } //end if setter
- } //end for
-
- //if we got this far it means we were not successful in setting the
- //property
- throw new Exception("Count not find method \""+setter+"\" in Class \""+classN.getName()+"\" in order to set property \""+name+"\"");
-
- } catch( SecurityException ex1 ) {
- throw new Exception("SecurityException for " + classN.getName() + " " + name + "=" + value +")" );
- //if( ctx.getDebug() > 1 ) ex1.printStackTrace();
- } catch (IllegalAccessException iae) {
- throw new Exception("IllegalAccessException for " + classN.getName() + " " + name + "=" + value +")" );
- //if( ctx.getDebug() > 1 ) iae.printStackTrace();
- } catch (InvocationTargetException ie) {
- throw new Exception("InvocationTargetException for " + classN.getName() + " " + name + "=" + value +")" );
- //if( ctx.getDebug() > 1 ) ie.printStackTrace();
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mir.xml;
-
-import java.util.StringTokenizer;
-
-/** micro-XPath match - match a path
- */
-class XmlMatch {
- String names[]=new String[10]; //max path depth
- int pos=0;
-
- public XmlMatch( String tagName ) {
- StringTokenizer st=new StringTokenizer( tagName, "/" );
- while( st.hasMoreTokens() ) {
- names[pos]=st.nextToken();
- pos++;
- }
- }
-
- public boolean match( SaxContext ctx ) {
- int depth=ctx.getTagCount();
-
- for( int j=pos-1; j>=0; j--) {
- if( depth<1) {
- // System.out.println("Pattern too long ");
- return false;
- }
- String tag=ctx.getTag(depth-1);
- if( ! names[j].equals( tag ) ) {
- // System.out.println("XXX" + names[j] + " " + tag);
- return false;
- }
- depth--;
- }
-
-
- return true;
- }
-
- public String toString() {
- String tag="/";
- int i=0;
- while ( names[i] != null) {
- tag=tag+names[i]+"/";
- i++;
- }
- return tag;
- }
-
-}
-
package mircoders.accesscontrol;
-import java.util.List;
-import java.util.Vector;
-
import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
import mircoders.entity.EntityUsers;
+import mircoders.module.ModuleContent;
+
+import java.util.List;
+import java.util.Vector;
public class AccessControl {
private UserAccessControl user;
private GeneralAccessControl general;
+ private ArticleAccessControl article;
protected LoggerWrapper logger = new LoggerWrapper("Global.AccessControl");
protected MirPropertiesConfiguration configuration;
user = new UserAccessControl(configuration.getVector("AccessControl.SuperUsers"));
general = new GeneralAccessControl();
+ article = new ArticleAccessControl(
+ configuration.getString("AccessControl.LockingEnabled", "0").equals("1"),
+ configuration.getString("AccessControl.LockingOptional", "0").equals("1"));
}
catch (Throwable t) {
throw new RuntimeException(t.toString());
return general;
}
+ public ArticleAccessControl article() {
+ return article;
+ }
+
public class GeneralAccessControl {
public boolean mayDeleteArticles(EntityUsers aSubject) {
return configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1");
}
public boolean mayAddUsers(EntityUsers aSubject) {
- return superusers.contains(aSubject.getValue("login"));
+ return superusers.contains(aSubject.getFieldValue("login"));
+ }
+
+ protected boolean isSuperUser(EntityUsers aUser) {
+ return superusers.contains(aUser.getFieldValue("login"));
}
public void assertMayEditUser(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
}
public boolean mayEditUser(EntityUsers aSubject, EntityUsers anObject) {
- return superusers.contains(aSubject.getValue("login"));
+ return superusers.contains(aSubject.getFieldValue("login"));
}
public boolean mayEditUsers(EntityUsers aSubject) {
- return superusers.contains(aSubject.getValue("login"));
+ return superusers.contains(aSubject.getFieldValue("login"));
}
public void assertMayDeleteUser(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
}
public boolean mayDeleteUser(EntityUsers aSubject, EntityUsers anObject) {
- return superusers.contains(aSubject.getValue("login"));
+ return superusers.contains(aSubject.getFieldValue("login"));
}
public boolean mayDeleteUsers(EntityUsers aSubject) {
- return superusers.contains(aSubject.getValue("login"));
+ return superusers.contains(aSubject.getFieldValue("login"));
}
public boolean mayChangeUserPassword(EntityUsers aSubject, EntityUsers anObject) {
- return aSubject.getId().equals(anObject.getId()) || superusers.contains(aSubject.getValue("login"));
+ return aSubject.getId().equals(anObject.getId()) || superusers.contains(aSubject.getFieldValue("login"));
}
public void assertMayChangeUserPassword(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
}
}
}
+
+ public class ArticleAccessControl {
+ private ModuleContent contentModule;
+ private boolean lockingEnabled;
+ private boolean lockingOptional;
+
+ public ArticleAccessControl(boolean aLockingEnabled, boolean aLockingOptional) {
+ contentModule = new ModuleContent();
+ lockingEnabled = aLockingEnabled;
+ lockingOptional = aLockingOptional;
+ }
+
+ public boolean mayEditArticle(EntityUsers aSubject, String anArticleId) {
+ String userId = aSubject.getId();
+
+ if (userId==null)
+ return false;
+ if (!lockingEnabled)
+ return true;
+
+ String lockingUser = contentModule.queryArticleLock(anArticleId);
+
+ return userId.equals(lockingUser) || ((lockingUser==null) && lockingOptional);
+ }
+
+ public boolean mayLockArticle(EntityUsers aSubject, String anArticleId) {
+ String userId = aSubject.getId();
+
+ if (userId==null)
+ return false;
+ if (!lockingEnabled)
+ return false;
+
+ String lockingUser = contentModule.queryArticleLock(anArticleId);
+
+ return (lockingUser==null);
+ }
+
+ public boolean mayForceLockArticle(EntityUsers aSubject, String anArticleId) {
+ String userId = aSubject.getId();
+
+ if (userId==null)
+ return false;
+ if (!lockingEnabled)
+ return false;
+
+ String lockingUser = contentModule.queryArticleLock(anArticleId);
+
+ return (lockingUser!=null) && !userId.equals(lockingUser) && user().isSuperUser(aSubject);
+ }
+
+ public boolean mayUnlockArticle(EntityUsers aSubject, String anArticleId) {
+ String userId = aSubject.getId();
+
+ if (userId==null)
+ return false;
+ if (!lockingEnabled)
+ return false;
+
+ String lockingUser = contentModule.queryArticleLock(anArticleId);
+
+ return userId.equals(lockingUser);
+ }
+ }
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
* This class handles storage of audio data and meta data
*
* @author mh
- * @version $Id: EntityAudio.java,v 1.11 2003/04/21 12:42:53 idfx Exp $
+ * @version $Id: EntityAudio.java,v 1.12 2004/11/06 19:56:13 idfx Exp $
*/
setStorage(theStorage);
}
- public void setValues(Map theStringValues) {
+ public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
theStringValues.put("is_published", "0");
}
- super.setValues(theStringValues);
+ super.setFieldValues(theStringValues);
}
}
import java.util.Map;
-import mir.entity.Entity;
+import mir.entity.AbstractEntity;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
import mircoders.storage.DatabaseCommentToMedia;
/**
* This class maps one line of the comment-table to a java-object.
*
- * @author $Author: zapata $
- * @version $Revision: 1.17 $ $Date: 2003/09/03 18:29:04 $
+ * @author $Author: idfx $
+ * @version $Revision: 1.18 $ $Date: 2004/11/06 19:56:13 $
*/
-public class EntityComment extends Entity
-{
+public class EntityComment extends AbstractEntity {
public EntityComment()
{
/**
- * overridden method setValues to patch creator_main_url
+ * overridden method setFieldValues to patch creator_main_url
*/
- public void setValues(Map theStringValues)
+ public void setFieldValues(Map theStringValues)
{
if (theStringValues != null) {
if (theStringValues.containsKey("main_url")){
}
}
- super.setValues(theStringValues);
+ super.setFieldValues(theStringValues);
}
/**
public void dettach(String aCommentId,String aMediaId) throws StorageObjectFailure
{
if (aMediaId!=null){
- try{
- DatabaseCommentToMedia.getInstance().delete(aCommentId, aMediaId);
- }
- catch (Exception e){
- throwStorageObjectFailure(e, "dettach: failed to get instance");
- }
-
- DatabaseContent.getInstance().setUnproduced("id="+getValue("to_media"));
+ DatabaseCommentToMedia.getInstance().delete(aCommentId, aMediaId);
+ DatabaseContent.getInstance().setUnproduced("id="+getFieldValue("to_media"));
}
}
public void attach(String aMediaId) throws StorageObjectFailure
{
if (aMediaId!=null) {
- try{
- DatabaseCommentToMedia.getInstance().addMedia(getId(), aMediaId);
- }
- catch(StorageObjectFailure e){
- throwStorageObjectFailure(e, "attach: could not get the instance");
- }
-
- DatabaseContent.getInstance().setUnproduced("id="+getValue("to_media"));
+ DatabaseCommentToMedia.getInstance().addMedia(getId(), aMediaId);
+ DatabaseContent.getInstance().setUnproduced("id="+getFieldValue("to_media"));
}
else {
logger.error("EntityContent: attach without mid");
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
-import java.util.HashMap;
import java.util.Map;
-import mir.entity.Entity;
-import mir.entity.EntityList;
+import mir.entity.AbstractEntity;
import mir.log.LoggerWrapper;
import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
import mir.storage.StorageObjectFailure;
-import mircoders.storage.DatabaseContent;
import mircoders.storage.DatabaseContentToMedia;
-import mircoders.storage.DatabaseContentToTopics;
/**
* this class implements mapping of one line of the database table content
* to a java object
*
- * @version $Id: EntityContent.java,v 1.20 2003/09/03 18:29:04 zapata Exp $
+ * @version $Id: EntityContent.java,v 1.21 2004/11/06 19:56:13 idfx Exp $
* @author mir-coders group
*
*/
-public class EntityContent extends Entity
-{
-
- String mirconf_extLinkName = configuration.getString("Producer.ExtLinkName");
- String mirconf_intLinkName = configuration.getString("Producer.IntLinkName");
- String mirconf_mailLinkName = configuration.getString("Producer.MailLinkName");
- String mirconf_imageRoot = configuration.getString("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
- Map _entCache = new HashMap();
- Boolean _hasMedia = null;
-
+public class EntityContent extends AbstractEntity {
// constructors
public EntityContent()
setStorage(theStorage);
}
- //
- // methods
-
/**
* set is_produced flag for the article
*/
-
public void setProduced(boolean yesno) throws StorageObjectFailure
{
String value = (yesno) ? "1":"0";
- if (value.equals( getValue("is_produced") )) return;
+ if (value.equals( getFieldValue("is_produced") )) return;
Connection con=null;Statement stmt=null;
String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
try {
- con = theStorageObject.getPooledCon();
- /** @todo should be preparedStatement: faster!! */
+ con = storageObject.obtainConnection();
+ /** todo should be preparedStatement: faster!! */
stmt = con.createStatement();
- theStorageObject.executeUpdate(stmt,sql);
+ storageObject.executeUpdate(stmt,sql);
}
catch (StorageObjectFailure e) {
- throwStorageObjectFailure(e, "\n -- set produced failed");
+ throw e;
}
catch (SQLException e) {
- throwStorageObjectFailure(e, "\n -- set produced failed");
+ throw new StorageObjectFailure(e);
}
finally {
- theStorageObject.freeConnection(con,stmt);
+ storageObject.freeConnection(con,stmt);
}
}
public void dettach(String anArticleId, String aMediaId) throws StorageObjectFailure
{
if (aMediaId!=null){
- try{
- DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId);
- }
- catch (Exception e){
- throwStorageObjectFailure(e, "\n -- failed to get instance");
- }
+ DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId);
setProduced(false);
}
}
/**
- * Attaches media to an article
- *
- * @param mid
- * @throws StorageObjectFailure
+ * Attaches media to the article
*/
public void attach(String aMediaId) throws StorageObjectFailure
{
if (aMediaId!=null) {
- try{
- DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId);
- }
- catch(StorageObjectFailure e){
- throwStorageObjectFailure(e, "attach: could not get the instance");
- }
+ DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId);
setProduced(false);
}
else {
}
/**
- * overridden method setValues to patch creator_main_url
+ * overridden method setFieldValues to patch creator_main_url
*/
- public void setValues(Map theStringValues) {
+ public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (theStringValues.containsKey("creator_main_url")){
if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
}
}
}
- super.setValues(theStringValues);
- }
-
- private boolean hasMedia() throws StorageObjectFailure
- {
- if (_hasMedia == null) {
- try {
- _hasMedia =
- new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
- } catch (StorageObjectExc e) {
- throw new StorageObjectFailure(e);
- }
- }
- return _hasMedia.booleanValue();
+ super.setFieldValues(theStringValues);
}
}
+++ /dev/null
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.entity;
-
-import mir.entity.Entity;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import mircoders.storage.DatabaseContent;
-/**
- * Diese Klasse enth?lt die Daten eines MetaObjekts
- *
- * @author RK
- * @version 29.6.1999
- */
-
-
-public class EntityFeature extends Entity
-{
- public EntityFeature()
- {
- super();
- }
-
- public EntityFeature(StorageObject theStorage) {
- this();
- setStorage(theStorage);
- }
-
- public void update() throws StorageObjectFailure{
- super.update();
- DatabaseContent dbContent = DatabaseContent.getInstance();
- dbContent.setUnproduced("to_feature="+getId());
- }
-}
package mircoders.entity;
-import java.io.File;
-import java.io.IOException;
+import java.io.ByteArrayOutputStream;
import java.io.InputStream;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
import java.sql.SQLException;
-import java.sql.Statement;
-import org.postgresql.PGConnection;
-import org.postgresql.largeobject.BlobInputStream;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-
-import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
-import mir.misc.FileUtil;
import mir.storage.StorageObject;
import mir.storage.StorageObjectFailure;
+import mir.util.StreamCopier;
import mircoders.media.ImageProcessor;
/**
- * Diese Klasse enth?lt die Daten eines MetaObjekts
*
* @author RK, mh, mir-coders
- * @version $Id: EntityImages.java,v 1.22 2003/08/16 19:15:57 idfx Exp $
+ * @version $Id: EntityImages.java,v 1.23 2004/11/06 19:56:13 idfx Exp $
*/
setStorage(theStorage);
}
- //
- // methods
-
-
+ /**
+ * Retrieves the image data
+ */
public InputStream getImage() throws StorageObjectFailure {
- logger.debug("EntityImages.getimage started");
- java.sql.Connection con=null;
- Statement stmt=null;
- BlobInputStream in;
- InputStream img_in = null;
try {
- con = theStorageObject.getPooledCon();
- con.setAutoCommit(false);
- 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 = ((PGConnection)jCon).getLargeObjectAPI();
- if(rs!=null) {
- if (rs.next()) {
- LargeObject lob = lom.open(rs.getInt(1));
- in = (BlobInputStream)lob.getInputStream();
- img_in = new ImageInputStream(in, con, stmt);
- }
- rs.close();
- }
+ return storageObject.getBinaryField("select image_data from images where id="+getId());
}
- catch (Throwable t) {
- logger.error("EntityImages.getImage failed: " + t.toString());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
- try {
- con.setAutoCommit(true);
- }
- catch (Throwable e) {
- logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString());
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- }
-
- try {
- theStorageObject.freeConnection(con, stmt);
- }
- catch (Throwable e) {
- logger.error("EntityImages.getImage freeing connection failed: " +e.toString());
- }
-
- throwStorageObjectFailure(t, "EntityImages -- getImage failed: ");
+ catch (SQLException e) {
+ throw new StorageObjectFailure(e);
}
- return img_in;
}
- public void setImage(InputStream in, String type) throws StorageObjectFailure {
-
- if (in != null) {
-
- Connection con = null;
- PreparedStatement pstmt = null;
- File f = null;
+ /**
+ * Processes and saves image data
+ */
+ public void setImage(InputStream anInputStream, String type) throws StorageObjectFailure {
+ // todo: failures should be treated anInputStream a better way: exception -> rollback instead
+ // of commit
+ if (anInputStream != null) {
try {
- logger.debug("EntityImages.settimage :: making internal representation of image");
-
- f = File.createTempFile("mir", ".tmp",
- new File(MirPropertiesConfiguration.instance().getString("TempDir")));
- FileUtil.write(f, in);
- ImageProcessor processor = new ImageProcessor(f);
+ ByteArrayOutputStream inputData = new ByteArrayOutputStream();
+ StreamCopier.copy(anInputStream, inputData);
- con = theStorageObject.getPooledCon();
- con.setAutoCommit(false);
- LargeObjectManager lom;
- java.sql.Connection connection;
- connection = ((com.codestudio.sql.PoolManConnectionHandle)con).getNativeConnection();
+ ImageProcessor processor = new ImageProcessor(inputData.toByteArray());
+ processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction);
- lom = ((PGConnection) connection).getLargeObjectAPI();
+ ByteArrayOutputStream imageData = new ByteArrayOutputStream();
+ processor.writeScaledData(imageData, type);
+ storageObject.setBinaryField("update images set image_data = ? where id = "+getId(), imageData.toByteArray());
- int oidImage = lom.create();
- LargeObject lobImage = lom.open(oidImage);
- processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction);
- processor.writeScaledData(lobImage.getOutputStream(), type);
- lobImage.close();
- setValueForProperty("img_height", new Integer(processor.getScaledHeight()).toString());
- setValueForProperty("img_width", new Integer(processor.getScaledWidth()).toString());
+ setFieldValue("img_height", new Integer(processor.getScaledHeight()).toString());
+ setFieldValue("img_width", new Integer(processor.getScaledWidth()).toString());
- int oidIcon = lom.create();
- LargeObject lobIcon = lom.open(oidIcon);
+ imageData.reset();
processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction);
- processor.writeScaledData(lobIcon.getOutputStream(), type);
- lobIcon.close();
+ processor.writeScaledData(imageData, type);
+ storageObject.setBinaryField("update images set icon_data = ? where id = "+getId(), imageData.toByteArray());
- setValueForProperty("icon_height", new Integer(processor.getScaledHeight()).toString());
- setValueForProperty("icon_width", new Integer(processor.getScaledWidth()).toString());
+ setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
+ setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
- setValueForProperty("image_data", new Integer(oidImage).toString());
- setValueForProperty("icon_data", new Integer(oidIcon).toString());
update();
}
catch (Exception e) {
- throwStorageObjectFailure(e, "settimage :: setImage gescheitert: ");
- }
- finally {
- try {
- if (con!=null)
- con.setAutoCommit(true);
- // get rid of the temp. file
- f.delete();
- } catch (SQLException e) {
- throwStorageObjectFailure(e,"Resetting transaction-mode failed");
- }
- if (con!=null)
- theStorageObject.freeConnection(con,pstmt);
+ throw new StorageObjectFailure(e);
}
}
}
* It will also take care of closing the OutputStream.
*/
public InputStream getIcon() throws StorageObjectFailure {
- Connection con=null;
- Statement stmt=null;
- BlobInputStream in=null;
- ImageInputStream img_in=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());
- jCon = ((com.codestudio.sql.PoolManConnectionHandle)con)
- .getNativeConnection();
- lom = ((PGConnection)jCon).getLargeObjectAPI();
- if(rs!=null) {
- if (rs.next()) {
- LargeObject lob = lom.open(rs.getInt(1));
- in = (BlobInputStream)lob.getInputStream();
- img_in = new ImageInputStream( in, con ,stmt);
- //img_data = rs.getBytes(1);
- }
- rs.close();
- }
- }
- catch (Throwable t) {
- logger.error("EntityImages.getIcon failed: "+t.toString());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
- try {
- con.setAutoCommit(true);
- }
- catch (SQLException e) {
- logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString());
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- }
- try {
- theStorageObject.freeConnection(con, stmt);
- }
- catch (Throwable e) {
- logger.error("EntityImages -- freeing connection failed: " + e.getMessage());
- }
-
- throwStorageObjectFailure(t, "EntityImages -- getIcon failed:");
+ return storageObject.getBinaryField("select icon_data from images where id="+getId());
}
-
- return img_in;
- }
-
- /**
- * a small wrapper class that allows us to store the DB connection resources
- * that the BlobInputStream is using and free them upon closing of the stream
- */
- private class ImageInputStream extends InputStream {
-
- InputStream _in;
- Connection _con;
- Statement _stmt;
-
- public ImageInputStream(BlobInputStream in, Connection con,
- Statement stmt ) {
- _in = in;
- _con = con;
- _stmt = stmt;
- }
-
- public void close () throws IOException {
- _in.close();
- try {
- _con.setAutoCommit(true);
- theStorageObject.freeConnection(_con,_stmt);
- } catch (Exception e) {
- throw new IOException("close(): "+e.toString());
- }
- }
-
- public int read() throws IOException {
- return _in.read();
+ catch (SQLException e) {
+ throw new StorageObjectFailure(e);
}
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
setStorage(theStorage);
}
- public void setValues(Map theStringValues) {
+ public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
theStringValues.put("is_published", "0");
}
- super.setValues(theStringValues);
+ super.setFieldValues(theStringValues);
}
}
package mircoders.entity;
-import mir.entity.Entity;
+import mir.entity.StorableObjectEntity;
import mir.storage.StorageObject;
/**
* Diese Klasse enth?lt die Daten eines MetaObjekts
*/
-public class EntityTopics extends Entity {
+public class EntityTopics extends StorableObjectEntity {
public EntityTopics(){
super();
}
this();
setStorage(theStorage);
}
+
+
}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.entity;\r
-\r
-import java.sql.SQLException;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaHelper;\r
-import mir.media.MirMedia;\r
-import mir.misc.NumberUtils;\r
-import mir.storage.StorageObject;\r
-import mir.storage.StorageObjectFailure;\r
-import mircoders.storage.DatabaseUploadedMedia;\r
-\r
-/**\r
- *\r
- * @author mh, mir-coders group\r
- * @version $Id: EntityUploadedMedia.java,v 1.27 2003/09/03 18:29:04 zapata Exp $\r
- */\r
-\r
-\r
-public class EntityUploadedMedia extends Entity {\r
-\r
-\r
- public EntityUploadedMedia() {\r
- super();\r
-\r
- logger = new LoggerWrapper("Entity.UploadedMedia");\r
- }\r
-\r
- public EntityUploadedMedia(StorageObject theStorage) {\r
- this();\r
- setStorage(theStorage);\r
- }\r
-\r
- public void update() throws StorageObjectFailure {\r
- super.update();\r
- try {\r
- theStorageObject.executeUpdate("update content set is_produced='0' where exists(select * from content_x_media where to_content=content.id and to_media=" + getId()+")");\r
- }\r
- catch (SQLException e) {\r
- throwStorageObjectFailure(e, "EntityAudio :: update :: failed!! ");\r
- }\r
- }\r
-\r
- public void setValues(Map theStringValues) {\r
- if (theStringValues != null) {\r
- if (!theStringValues.containsKey("is_published"))\r
- theStringValues.put("is_published", "0");\r
- }\r
- super.setValues(theStringValues);\r
- }\r
-\r
-\r
- /**\r
- * fetches the MediaType entry assiciated w/ this media\r
- *\r
- * @return mir.entity.Entity\r
- */\r
- public Entity getMediaType() throws StorageObjectFailure {\r
- Entity ent = null;\r
- try {\r
- ent = DatabaseUploadedMedia.getInstance().getMediaType(this);\r
- }\r
- catch (StorageObjectFailure e) {\r
- throwStorageObjectFailure(e, "get MediaType failed -- ");\r
- }\r
- return ent;\r
- }\r
-\r
- public String getValue(String key) {\r
- String returnValue = null;\r
-\r
- if (key != null) {\r
- if (key.equals("big_icon"))\r
- returnValue = getBigIconName();\r
- else if (key.equals("descr") || key.equals("media_descr"))\r
- returnValue = getDescr();\r
- else if (key.equals("mediatype"))\r
- returnValue = getMediaTypeString();\r
- else if (key.equals("mimetype"))\r
- returnValue = getMimeType();\r
- else if (key.equals("human_readable_size")) {\r
- String size = super.getValue("size");\r
- if (size != null)\r
- returnValue = NumberUtils.humanReadableSize(Double.parseDouble(size));\r
- }\r
- else\r
- returnValue = super.getValue(key);\r
- }\r
- return returnValue;\r
- }\r
-\r
- // @todo all these methods should be merged into 1\r
- // and the MediaHandler should be cached somehow.\r
- private String getMediaTypeString() {\r
- MirMedia mediaHandler = null;\r
- Entity mediaType = null;\r
-\r
- try {\r
- mediaType = getMediaType();\r
- mediaHandler = MediaHelper.getHandler(mediaType);\r
- String t;\r
- if (mediaHandler.isAudio())\r
- return "audio";\r
- else if (mediaHandler.isImage())\r
- return "image";\r
- else if (mediaHandler.isVideo())\r
- return "video";\r
- else\r
- return "other";\r
- }\r
- catch (Exception ex) {\r
- logger.warn("EntityUploadedMedia.getMediaTypeString: could not fetch data: " + ex.toString());\r
- }\r
- return null;\r
- }\r
-\r
- private String getBigIconName() {\r
- MirMedia mediaHandler = null;\r
- Entity mediaType = null;\r
-\r
- try {\r
- mediaType = getMediaType();\r
- mediaHandler = MediaHelper.getHandler(mediaType);\r
- return mediaHandler.getBigIconName();\r
- }\r
- catch (Exception ex) {\r
- logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());\r
- }\r
- return null;\r
- }\r
-\r
- private List getUrl() {\r
- MirMedia mediaHandler = null;\r
- Entity mediaType = null;\r
-\r
- try {\r
- mediaType = getMediaType();\r
- mediaHandler = MediaHelper.getHandler(mediaType);\r
- return mediaHandler.getURL(this, mediaType);\r
- }\r
- catch (Throwable t) {\r
- logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString());\r
- }\r
- return null;\r
- }\r
-\r
- private String getDescr() {\r
- MirMedia mediaHandler = null;\r
- Entity mediaType = null;\r
-\r
- try {\r
- mediaType = getMediaType();\r
- mediaHandler = MediaHelper.getHandler(mediaType);\r
- return mediaHandler.getDescr(mediaType);\r
- }\r
- catch (Exception ex) {\r
- logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString());\r
- }\r
- return null;\r
- }\r
- private String getMimeType() {\r
- Entity mediaType = null;\r
-\r
- try {\r
- mediaType = getMediaType();\r
- return mediaType.getValue("mime_type");\r
- }\r
- catch (Exception ex) {\r
- logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());\r
- }\r
- return null;\r
- }\r
-\r
-}\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.entity;
+
+import java.sql.SQLException;
+import java.util.Map;
+
+import mir.entity.AbstractEntity;
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.storage.StorageObject;
+import mir.storage.StorageObjectFailure;
+import mircoders.storage.DatabaseUploadedMedia;
+
+/**
+ *
+ * @author mh, mir-coders group
+ * @version $Id: EntityUploadedMedia.java,v 1.28 2004/11/06 19:56:13 idfx Exp $
+ */
+
+public class EntityUploadedMedia extends AbstractEntity {
+ public EntityUploadedMedia() {
+ super();
+
+ logger = new LoggerWrapper("Entity.UploadedMedia");
+ }
+
+ public EntityUploadedMedia(StorageObject theStorage) {
+ this();
+
+ setStorage(theStorage);
+ }
+
+ public void update() throws StorageObjectFailure {
+ super.update();
+
+ try {
+ storageObject.executeUpdate( "update content set is_produced='0' where exists(select * from content_x_media where content_id=content.id and media_id=" + getId()+")");
+ storageObject.executeUpdate( "update content set is_produced='0' where exists(select * from comment_x_media, comment where comment_x_media.comment_id=comment.id and comment.to_media=content.id and comment_x_media.media_id=" + getId()+")");
+ }
+ catch (SQLException e) {
+ throw new StorageObjectFailure(e);
+ }
+ }
+
+ public void setFieldValues(Map theStringValues) {
+ if (theStringValues != null) {
+ if (!theStringValues.containsKey("is_published"))
+ theStringValues.put("is_published", "0");
+ }
+ super.setFieldValues(theStringValues);
+ }
+
+
+ /**
+ * fetches the MediaType entry assiciated w/ this media
+ *
+ * @return mir.entity.Entity
+ */
+ public Entity getMediaType() throws StorageObjectFailure {
+ Entity ent = null;
+ try {
+ ent = DatabaseUploadedMedia.getInstance().getMediaType(this);
+ }
+ catch (StorageObjectFailure e) {
+ throw new StorageObjectFailure(e);
+ }
+ return ent;
+ }
+}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.entity;
import mir.entity.Entity;
+import mir.entity.AbstractEntity;
import mir.storage.StorageObject;
/**
*/
-public class EntityUsers extends Entity
-{
+public class EntityUsers extends AbstractEntity {
public EntityUsers()
{
public boolean isAdmin()
{
- String admin=getValue("is_admin");
+ String admin=getFieldValue("is_admin");
//theLog.printDebugInfo("admin::::"+admin);
return (admin!=null&&admin.equals("1"))?true:false;
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.entity;
setStorage(theStorage);
}
- public void setValues(Map theStringValues) {
+ public void setFieldValues(Map theStringValues) {
if (theStringValues != null) {
if (!theStringValues.containsKey("is_published"))
theStringValues.put("is_published", "0");
}
- super.setValues(theStringValues);
+ super.setFieldValues(theStringValues);
}
}
\ No newline at end of file
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.global;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.FileOutputStream;\r
-import java.util.Arrays;\r
-import java.util.Date;\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Random;\r
-import java.util.Vector;\r
-import javax.servlet.http.Cookie;\r
-import javax.servlet.http.HttpServletResponse;\r
-\r
-import org.apache.commons.collections.ExtendedProperties;\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.session.Request;\r
-import mir.util.GeneratorFormatAdapters;\r
-import mir.util.StringRoutines;\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityUsers;\r
-import mircoders.localizer.MirAdminInterfaceLocalizer;\r
-import mircoders.localizer.MirAntiAbuseFilterType;\r
-\r
-\r
-public class Abuse {\r
- private List filterRules;\r
- private Map filterTypes;\r
- private List filterTypeIds;\r
- private int maxIdentifier;\r
- private LoggerWrapper logger;\r
- private LoggerWrapper adminUsageLogger;\r
- private int logSize;\r
- private boolean logEnabled;\r
- private boolean openPostingDisabled;\r
- private boolean openPostingPassword;\r
- private boolean cookieOnBlock;\r
- private String articleBlockAction;\r
- private String commentBlockAction;\r
- private List log;\r
- private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");\r
-\r
- private MirPropertiesConfiguration configuration;\r
-\r
- private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");\r
- private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");\r
-\r
- public Abuse() {\r
- logger = new LoggerWrapper("Global.Abuse");\r
- adminUsageLogger = new LoggerWrapper("AdminUsage");\r
- filterRules = new Vector();\r
- maxIdentifier = 0;\r
- log = new Vector();\r
-\r
- try {\r
- configuration = MirPropertiesConfiguration.instance();\r
- }\r
- catch (Throwable e) {\r
- throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
- }\r
-\r
- logSize = 100;\r
- logEnabled = false;\r
- articleBlockAction = "";\r
- commentBlockAction = "";\r
- openPostingPassword = false;\r
- openPostingDisabled = false;\r
- cookieOnBlock = false;\r
-\r
- try {\r
- filterTypes = new HashMap();\r
- filterTypeIds = new Vector();\r
-\r
- Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();\r
-\r
- while (i.hasNext()) {\r
- MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();\r
- filterTypes.put(filterType.getName(), filterType);\r
- filterTypeIds.add(filterType.getName());\r
- }\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException("Can't get filter types: " + t.getMessage());\r
- }\r
-\r
- load();\r
- }\r
-\r
- private void setCookie(HttpServletResponse aResponse) {\r
- Random random = new Random();\r
-\r
- Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));\r
- cookie.setMaxAge(cookieMaxAge);\r
- cookie.setPath("/");\r
-\r
- if (aResponse!=null)\r
- aResponse.addCookie(cookie);\r
- }\r
-\r
- private boolean checkCookie(List aCookies) {\r
- if (getCookieOnBlock()) {\r
- Iterator i = aCookies.iterator();\r
-\r
- while (i.hasNext()) {\r
- Cookie cookie = (Cookie) i.next();\r
-\r
- if (cookie.getName().equals(cookieName)) {\r
- logger.debug("cookie match");\r
- return true;\r
- }\r
- }\r
- }\r
-\r
- return false;\r
- }\r
-\r
- FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {\r
- Iterator iterator = filterRules.iterator();\r
-\r
- while (iterator.hasNext()) {\r
- FilterRule rule = (FilterRule) iterator.next();\r
-\r
- if (rule.test(anEntity, aRequest))\r
- return rule;\r
- }\r
-\r
- return null;\r
- }\r
-\r
- public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {\r
- logComment(aComment, aRequest);\r
-\r
- try {\r
- long time = System.currentTimeMillis();\r
-\r
- FilterRule filterRule = findMatchingFilter(aComment, aRequest);\r
-\r
- if (filterRule!=null) {\r
- logger.debug("Match for " + filterRule.getType()+" rule '"+ filterRule.getExpression()+"'");\r
- filterRule.setLastHit(new GregorianCalendar().getTime());\r
- MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());\r
- setCookie(aResponse);\r
- save();\r
- }\r
-\r
- logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");\r
- }\r
- catch (Throwable t) {\r
- t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
- logger.error("Abuse.checkComment: " + t.toString());\r
- }\r
- }\r
-\r
- public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {\r
- logArticle(anArticle, aRequest);\r
-\r
- try {\r
- long time = System.currentTimeMillis();\r
-\r
- FilterRule filterRule = findMatchingFilter(anArticle, aRequest);\r
-\r
- if (filterRule!=null) {\r
- logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression()+"'");\r
- filterRule.setLastHit(new GregorianCalendar().getTime());\r
- MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());\r
- setCookie(aResponse);\r
- save();\r
- }\r
-\r
- logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");\r
- }\r
- catch (Throwable t) {\r
- t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
- logger.error("Abuse.checkArticle: " + t.toString());\r
- }\r
- }\r
-\r
- public boolean getLogEnabled() {\r
- return logEnabled;\r
- }\r
-\r
- public void setLogEnabled(boolean anEnabled) {\r
- if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))\r
- logEnabled = anEnabled;\r
- truncateLog();\r
- }\r
-\r
- public int getLogSize() {\r
- return logSize;\r
- }\r
-\r
- public void setLogSize(int aSize) {\r
- logSize = aSize;\r
- truncateLog();\r
- }\r
-\r
- public boolean getOpenPostingDisabled() {\r
- return openPostingDisabled;\r
- }\r
-\r
- public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {\r
- openPostingDisabled = anOpenPostingDisabled;\r
- }\r
-\r
- public boolean getOpenPostingPassword() {\r
- return openPostingPassword;\r
- }\r
-\r
- public void setOpenPostingPassword(boolean anOpenPostingPassword) {\r
- openPostingPassword = anOpenPostingPassword;\r
- }\r
-\r
- public boolean getCookieOnBlock() {\r
- return cookieOnBlock;\r
- }\r
-\r
- public void setCookieOnBlock(boolean aCookieOnBlock) {\r
- cookieOnBlock = aCookieOnBlock;\r
- }\r
-\r
- public String getArticleBlockAction() {\r
- return articleBlockAction;\r
- }\r
-\r
- public void setArticleBlockAction(String anAction) {\r
- articleBlockAction = anAction;\r
- }\r
-\r
- public String getCommentBlockAction() {\r
- return commentBlockAction;\r
- }\r
-\r
- public void setCommentBlockAction(String anAction) {\r
- commentBlockAction = anAction;\r
- }\r
-\r
- public List getLog() {\r
- synchronized(log) {\r
- try {\r
- List result = new Vector();\r
-\r
- Iterator i = log.iterator();\r
- while (i.hasNext()) {\r
- LogEntry logEntry = (LogEntry) i.next();\r
- Map entry = new HashMap();\r
-\r
- entry.put("ip", logEntry.getIpNumber());\r
- entry.put("id", logEntry.getId());\r
- entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));\r
- if (logEntry.getIsArticle())\r
- entry.put("type", "content");\r
- else\r
- entry.put("type", "comment");\r
- entry.put("browser", logEntry.getBrowserString());\r
-\r
- result.add(entry);\r
- }\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
- }\r
-\r
- public void logComment(Entity aComment, Request aRequest) {\r
- String ipAddress = aRequest.getHeader("ip");\r
- String id = aComment.getId();\r
- String browser = aRequest.getHeader("User-Agent");\r
-\r
- logComment(ipAddress, id, new Date(), browser);\r
- }\r
-\r
- public void logArticle(Entity anArticle, Request aRequest) {\r
- String ipAddress = aRequest.getHeader("ip");\r
- String id = anArticle.getId();\r
- String browser = aRequest.getHeader("User-Agent");\r
-\r
- logArticle(ipAddress, id, new Date(), browser);\r
- }\r
-\r
- public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
- appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));\r
- }\r
-\r
- public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
- appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));\r
- }\r
-\r
- public void load() {\r
- synchronized (filterRules) {\r
- try {\r
- ExtendedProperties configuration = new ExtendedProperties();\r
-\r
- try {\r
- configuration = new ExtendedProperties(configFile);\r
- }\r
- catch (FileNotFoundException e) {\r
- }\r
-\r
- getFilterConfig(filterRules, "abuse.filter", configuration);\r
-\r
- setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));\r
- setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));\r
- setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));\r
- setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));\r
- setLogSize(configuration.getInt("abuse.logSize", 10));\r
- setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));\r
- setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
- }\r
-\r
- public void save() {\r
- synchronized (filterRules) {\r
- try {\r
- ExtendedProperties configuration = new ExtendedProperties();\r
-\r
- setFilterConfig(filterRules, "abuse.filter", configuration);\r
-\r
- configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled() ? "1" : "0");\r
- configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword() ? "1" : "0");\r
- configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock() ? "1" : "0");\r
- configuration.addProperty("abuse.logEnabled", getLogEnabled() ? "1" : "0");\r
- configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));\r
- configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());\r
- configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());\r
-\r
- configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
- }\r
-\r
- public List getFilterTypes() {\r
- try {\r
- List result = new Vector();\r
-\r
- Iterator i = filterTypeIds.iterator();\r
- while (i.hasNext()) {\r
- String id = (String) i.next();\r
-\r
- Map action = new HashMap();\r
- action.put("resource", id);\r
- action.put("identifier", id);\r
-\r
- result.add(action);\r
- }\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException("can't get article actions");\r
- }\r
- }\r
-\r
- public List getArticleActions() {\r
- try {\r
- List result = new Vector();\r
-\r
- Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();\r
- while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-\r
- Map action = new HashMap();\r
- action.put("resource", operation.getName());\r
- action.put("identifier", operation.getName());\r
-\r
- result.add(action);\r
- }\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException("can't get article actions");\r
- }\r
- }\r
-\r
- public List getCommentActions() {\r
- try {\r
- List result = new Vector();\r
-\r
- Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();\r
- while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
- (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
-\r
- Map action = new HashMap();\r
- action.put("resource", operation.getName());\r
- action.put("identifier", operation.getName());\r
-\r
- result.add(action);\r
- }\r
-\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- throw new RuntimeException("can't get comment actions");\r
- }\r
- }\r
-\r
- public List getFilters() {\r
- List result = new Vector();\r
-\r
- synchronized(filterRules) {\r
- Iterator i = filterRules.iterator();\r
- while (i.hasNext()) {\r
- FilterRule filter = (FilterRule) i.next();\r
- result.add(filter.clone());\r
- }\r
- return result;\r
- }\r
- }\r
-\r
- public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
- return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);\r
- }\r
-\r
- public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {\r
- return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);\r
- }\r
-\r
- public FilterRule getFilter(String anId) {\r
- synchronized (filterRules) {\r
- FilterRule result = (FilterRule) findFilter(filterRules, anId);\r
- if (result==null)\r
- return result;\r
- else\r
- return (FilterRule) result.clone();\r
- }\r
- }\r
-\r
- public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
- return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);\r
- }\r
-\r
- public void deleteFilter(String anIdentifier) {\r
- deleteFilter(filterRules, anIdentifier);\r
- }\r
-\r
- private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {\r
- MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
-\r
- if (type==null)\r
- return "invalidtype";\r
-\r
- if (!type.validate(anExpression)) {\r
- return "invalidexpression";\r
- }\r
-\r
- FilterRule filter = new FilterRule();\r
-\r
- filter.setId(generateId());\r
- filter.setExpression(anExpression);\r
- filter.setType(aType);\r
- filter.setComments(aComments);\r
- filter.setArticleAction(anArticleAction);\r
- filter.setCommentAction(aCommentAction);\r
- filter.setLastHit(aLastHit);\r
-\r
- synchronized (aFilters) {\r
- aFilters.add(filter);\r
- }\r
-\r
- return null;\r
- }\r
-\r
- private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
- MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
-\r
- if (type==null)\r
- return "invalidtype";\r
-\r
- if (!type.validate(anExpression)) {\r
- return "invalidexpression";\r
- }\r
-\r
- synchronized (aFilters) {\r
- FilterRule filter = findFilter(aFilters, anIdentifier);\r
-\r
- if (filter!=null) {\r
- filter.setExpression(anExpression);\r
- filter.setType(aType);\r
- filter.setCommentAction(aCommentAction);\r
- filter.setArticleAction(anArticleAction);\r
- filter.setComments(aComments);\r
- }\r
-\r
- return null;\r
- }\r
- }\r
-\r
- private FilterRule findFilter(List aFilters, String anIdentifier) {\r
- synchronized (aFilters) {\r
- Iterator i = aFilters.iterator();\r
- while (i.hasNext()) {\r
- FilterRule filter = (FilterRule) i.next();\r
-\r
- if (filter.getId().equals(anIdentifier)) {\r
- return filter;\r
- }\r
- }\r
- }\r
-\r
- return null;\r
- }\r
-\r
- private void deleteFilter(List aFilters, String anIdentifier) {\r
- synchronized (aFilters) {\r
- FilterRule filter = findFilter(aFilters, anIdentifier);\r
-\r
- if (filter!=null) {\r
- aFilters.remove(filter);\r
- }\r
- }\r
- }\r
-\r
- private String generateId() {\r
- synchronized(this) {\r
- maxIdentifier = maxIdentifier+1;\r
-\r
- return Integer.toString(maxIdentifier);\r
- }\r
- }\r
-\r
- public class FilterRule {\r
- private String identifier;\r
- private String expression;\r
- private String type;\r
- private String comments;\r
- private String articleAction;\r
- private String commentAction;\r
- private Date lastHit;\r
-\r
- public FilterRule() {\r
- expression = "";\r
- type = "";\r
- identifier = "";\r
- comments = "";\r
- articleAction = articleBlockAction;\r
- commentAction = commentBlockAction;\r
- lastHit = null;\r
- }\r
-\r
- public Date getLastHit() {\r
- return lastHit;\r
- }\r
-\r
- public void setLastHit(Date aDate) {\r
- lastHit = aDate;\r
- }\r
-\r
- public String getId() {\r
- return identifier;\r
- }\r
-\r
- public void setId(String anId) {\r
- identifier = anId;\r
- }\r
-\r
- public String getExpression() {\r
- return expression;\r
- }\r
-\r
- public void setExpression(String anExpression) {\r
- expression = anExpression;\r
- }\r
-\r
- public String getType() {\r
- return type;\r
- }\r
-\r
- public void setType(String aType) {\r
- type = aType;\r
- }\r
-\r
- public void setComments(String aComments) {\r
- comments = aComments;\r
- }\r
-\r
- public String getComments() {\r
- return comments;\r
- }\r
-\r
- public String getArticleAction() {\r
- return articleAction;\r
- }\r
-\r
- public void setArticleAction(String anArticleAction) {\r
- articleAction = anArticleAction;\r
- }\r
-\r
- public String getCommentAction() {\r
- return commentAction;\r
- }\r
-\r
- public void setCommentAction(String aCommentAction) {\r
- commentAction = aCommentAction;\r
- }\r
-\r
- public boolean test(Entity anEntity, Request aRequest) {\r
- MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);\r
- try {\r
- if (filterType != null)\r
- return filterType.test(expression, anEntity, aRequest);\r
- }\r
- catch (Throwable t) {\r
- logger.error("error while testing "+type+"-filter '"+expression+"'");\r
- }\r
-\r
- return false;\r
- };\r
-\r
- public Object clone() {\r
- FilterRule result = new FilterRule();\r
- result.setComments(getComments());\r
- result.setExpression(getExpression());\r
- result.setId(getId());\r
- result.setType(getType());\r
- result.setArticleAction(getArticleAction());\r
- result.setCommentAction(getCommentAction());\r
- result.setLastHit(getLastHit());\r
-\r
- return result;\r
- }\r
- }\r
-\r
- private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
- synchronized(aFilters) {\r
- Iterator i = aFilters.iterator();\r
-\r
- while (i.hasNext()) {\r
- FilterRule filter = (FilterRule) i.next();\r
-\r
- String filterconfig =\r
- StringRoutines.replaceStringCharacters(filter.getType(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
- StringRoutines.replaceStringCharacters(filter.getExpression(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
- StringRoutines.replaceStringCharacters(filter.getArticleAction(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
- StringRoutines.replaceStringCharacters(filter.getCommentAction(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
- StringRoutines.replaceStringCharacters(filter.getComments(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"}) + ":";\r
-\r
- if (filter.getLastHit()!=null)\r
- filterconfig = filterconfig + filter.getLastHit().getTime();\r
-\r
- aConfiguration.addProperty(aConfigKey, filterconfig);\r
- }\r
- }\r
- }\r
-\r
- private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
- synchronized(aFilters) {\r
- aFilters.clear();\r
-\r
- if (aConfiguration.getStringArray(aConfigKey)!=null) {\r
-\r
- Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).\r
- iterator();\r
-\r
- while (i.hasNext()) {\r
- String filter = (String) i.next();\r
- List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');\r
- if (parts.size() == 2) {\r
- parts.add(articleBlockAction);\r
- parts.add(commentBlockAction);\r
- parts.add("");\r
- parts.add("");\r
- }\r
-\r
- if (parts.size() >= 5) {\r
- Date lastHit = null;\r
-\r
- if (parts.size()>=6) {\r
- String lastHitString = (String) parts.get(5);\r
-\r
- try {\r
- lastHit = new Date(Long.parseLong(lastHitString));\r
- }\r
- catch (Throwable t) {\r
- }\r
- }\r
-\r
- addFilter( (String) parts.get(0), (String) parts.get(1), (String) parts.get(4), (String) parts.get(3), (String) parts.get(2), lastHit);\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- private static class LogEntry {\r
- private String ipNumber;\r
- private String browserString;\r
- private String id;\r
- private Date timeStamp;\r
- private boolean isArticle;\r
-\r
- public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {\r
- ipNumber = anIpNumber;\r
- browserString = aBrowserString;\r
- id = anId;\r
- isArticle = anIsArticle;\r
- timeStamp=aTimeStamp;\r
- }\r
-\r
- public String getIpNumber() {\r
- return ipNumber;\r
- }\r
-\r
- public String getBrowserString() {\r
- return browserString;\r
- }\r
-\r
- public String getId() {\r
- return id;\r
- }\r
-\r
- public Date getTimeStamp() {\r
- return timeStamp;\r
- }\r
-\r
- public boolean getIsArticle() {\r
- return isArticle;\r
- }\r
- }\r
-\r
- private void truncateLog() {\r
- synchronized(log) {\r
- if (!logEnabled)\r
- log.clear();\r
- else {\r
- while (log.size()>0 && log.size()>logSize) {\r
- log.remove(0);\r
- }\r
- }\r
- }\r
- };\r
-\r
- private void appendLog(LogEntry anEntry) {\r
- synchronized (log) {\r
- if (logEnabled) {\r
- log.add(anEntry);\r
- truncateLog();\r
- }\r
- }\r
- }\r
-\r
- public void logAdminUsage(EntityUsers aUser, String aDescription) {\r
- try {\r
- String user = "unknown (" + aUser.toString() +")";\r
- if (user!=null)\r
- user = aUser.getValue("login");\r
- adminUsageLogger.info(user + ": " + aDescription);\r
- }\r
- catch (Throwable t) {\r
- logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());\r
- }\r
- }\r
-}
\ No newline at end of file
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.global;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Vector;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.util.DateTimeFunctions;
+import mir.util.GeneratorFormatAdapters;
+import mir.util.StringRoutines;
+import mir.util.EntityUtility;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+import mircoders.localizer.MirAdminInterfaceLocalizer;
+import mircoders.localizer.MirAntiAbuseFilterType;
+
+import org.apache.commons.collections.ExtendedProperties;
+
+
+public class Abuse {
+ private List filterRules;
+ private Map filterTypes;
+ private List filterTypeIds;
+ private int maxIdentifier;
+ private LoggerWrapper logger;
+ private int logSize;
+ private boolean logEnabled;
+ private boolean openPostingDisabled;
+ private boolean openPostingPassword;
+ private boolean cookieOnBlock;
+ private String articleBlockAction;
+ private String commentBlockAction;
+ private List log;
+ private File configFile = MirGlobal.config().getFile("Abuse.Config");
+
+ private MirPropertiesConfiguration configuration;
+
+ private static String cookieName = MirGlobal.config().getString("Abuse.CookieName");
+ private static int cookieMaxAge = 60 * 60 * MirGlobal.config().getInt("Abuse.CookieMaxAge");
+
+ public Abuse() {
+ logger = new LoggerWrapper("Global.Abuse");
+ filterRules = new Vector();
+ maxIdentifier = 0;
+ log = new Vector();
+
+ try {
+ configuration = MirPropertiesConfiguration.instance();
+ }
+ catch (Throwable e) {
+ throw new RuntimeException("Can't get configuration: " + e.getMessage());
+ }
+
+ logSize = 100;
+ logEnabled = false;
+ articleBlockAction = "";
+ commentBlockAction = "";
+ openPostingPassword = false;
+ openPostingDisabled = false;
+ cookieOnBlock = false;
+
+ try {
+ filterTypes = new HashMap();
+ filterTypeIds = new Vector();
+
+ Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
+
+ while (i.hasNext()) {
+ MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();
+ filterTypes.put(filterType.getName(), filterType);
+ filterTypeIds.add(filterType.getName());
+ }
+ }
+ catch (Throwable t) {
+ throw new RuntimeException("Can't get filter types: " + t.getMessage());
+ }
+
+ load();
+ }
+
+ private void setCookie(HttpServletResponse aResponse) {
+ Random random = new Random();
+
+ Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
+ cookie.setMaxAge(cookieMaxAge);
+ cookie.setPath("/");
+
+ if (aResponse != null)
+ aResponse.addCookie(cookie);
+ }
+
+ private boolean checkCookie(List aCookies) {
+ if (getCookieOnBlock()) {
+ Iterator i = aCookies.iterator();
+
+ while (i.hasNext()) {
+ Cookie cookie = (Cookie) i.next();
+
+ if (cookie.getName().equals(cookieName)) {
+ logger.debug("cookie match");
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {
+ Iterator iterator = filterRules.iterator();
+
+ while (iterator.hasNext()) {
+ FilterRule rule = (FilterRule) iterator.next();
+
+ if (rule.test(anEntity, aRequest))
+ return rule;
+ }
+
+ return null;
+ }
+
+ public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
+ try {
+ long time = System.currentTimeMillis();
+
+ FilterRule filterRule = findMatchingFilter(aComment, aRequest);
+
+ if (filterRule != null) {
+ logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
+ filterRule.setLastHit(new GregorianCalendar().getTime());
+
+ StringBuffer line = new StringBuffer();
+
+ line.append(DateTimeFunctions.advancedDateFormat(
+ configuration.getString("Mir.DefaultDateTimeFormat"),
+ (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));
+
+ line.append(" ");
+ line.append("filter");
+
+ line.append(" ");
+ line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");
+ EntityUtility.appendLineToField(aComment, "comment", line.toString());
+
+ MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());
+ setCookie(aResponse);
+ save();
+ logComment(aComment, aRequest, filterRule.getType(), filterRule.getExpression());
+ }
+ else
+ logComment(aComment, aRequest);
+
+
+ logger.info("checkComment: " + (System.currentTimeMillis() - time) + "ms");
+ }
+ catch (Throwable t) {
+ t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ logger.error("Abuse.checkComment: " + t.toString());
+ }
+ }
+
+ public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
+ try {
+ long time = System.currentTimeMillis();
+
+ FilterRule filterRule = findMatchingFilter(anArticle, aRequest);
+
+ if (filterRule != null) {
+ logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression() + "'");
+ filterRule.setLastHit(new GregorianCalendar().getTime());
+
+ StringBuffer line = new StringBuffer();
+
+ line.append(DateTimeFunctions.advancedDateFormat(
+ configuration.getString("Mir.DefaultDateTimeFormat"),
+ (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone")));
+
+ line.append(" ");
+ line.append("filter");
+
+ line.append(" ");
+ line.append(filterRule.getType() +" ("+ filterRule.getExpression()+")");
+ EntityUtility.appendLineToField(anArticle, "comment", line.toString());
+
+ MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());
+ setCookie(aResponse);
+ save();
+ logArticle(anArticle, aRequest, filterRule.getType(), filterRule.getExpression());
+ }
+ else
+ logArticle(anArticle, aRequest);
+
+ logger.info("checkArticle: " + (System.currentTimeMillis() - time) + "ms");
+ }
+ catch (Throwable t) {
+ t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ logger.error("Abuse.checkArticle: " + t.toString());
+ }
+ }
+
+ public boolean getLogEnabled() {
+ return logEnabled;
+ }
+
+ public void setLogEnabled(boolean anEnabled) {
+ if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))
+ logEnabled = anEnabled;
+ truncateLog();
+ }
+
+ public int getLogSize() {
+ return logSize;
+ }
+
+ public void setLogSize(int aSize) {
+ logSize = aSize;
+ truncateLog();
+ }
+
+ public boolean getOpenPostingDisabled() {
+ return openPostingDisabled;
+ }
+
+ public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
+ openPostingDisabled = anOpenPostingDisabled;
+ }
+
+ public boolean getOpenPostingPassword() {
+ return openPostingPassword;
+ }
+
+ public void setOpenPostingPassword(boolean anOpenPostingPassword) {
+ openPostingPassword = anOpenPostingPassword;
+ }
+
+ public boolean getCookieOnBlock() {
+ return cookieOnBlock;
+ }
+
+ public void setCookieOnBlock(boolean aCookieOnBlock) {
+ cookieOnBlock = aCookieOnBlock;
+ }
+
+ public String getArticleBlockAction() {
+ return articleBlockAction;
+ }
+
+ public void setArticleBlockAction(String anAction) {
+ articleBlockAction = anAction;
+ }
+
+ public String getCommentBlockAction() {
+ return commentBlockAction;
+ }
+
+ public void setCommentBlockAction(String anAction) {
+ commentBlockAction = anAction;
+ }
+
+ public List getLog() {
+ synchronized (log) {
+ try {
+ List result = new Vector();
+
+ Iterator i = log.iterator();
+ while (i.hasNext()) {
+ LogEntry logEntry = (LogEntry) i.next();
+ Map entry = new HashMap();
+
+ entry.put("ip", logEntry.getIpNumber());
+ entry.put("id", logEntry.getId());
+ entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
+ if (logEntry.getIsArticle())
+ entry.put("type", "content");
+ else
+ entry.put("type", "comment");
+ entry.put("browser", logEntry.getBrowserString());
+ entry.put("hitfiltertype", logEntry.getHitFilterType());
+ entry.put("hitfilterexpression", logEntry.getHitFilterExpression());
+
+ result.add(entry);
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.toString());
+ }
+ }
+ }
+
+ public void logComment(Entity aComment, Request aRequest) {
+ logComment(aComment, aRequest, null, null);
+ }
+
+ public void logComment(Entity aComment, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+ String ipAddress = aRequest.getHeader("ip");
+ String id = aComment.getId();
+ String browser = aRequest.getHeader("User-Agent");
+
+ logComment(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+ }
+
+ public void logArticle(Entity anArticle, Request aRequest) {
+ logArticle(anArticle, aRequest, null, null);
+ }
+
+ public void logArticle(Entity anArticle, Request aRequest, String aHitFilterType, String aHitFilterExpression) {
+ String ipAddress = aRequest.getHeader("ip");
+ String id = anArticle.getId();
+ String browser = aRequest.getHeader("User-Agent");
+
+ logArticle(ipAddress, id, new Date(), browser, aHitFilterType, aHitFilterExpression);
+ }
+
+ public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
+ appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false, aHitFilterType, aHitFilterExpression));
+ }
+
+ public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser, String aHitFilterType, String aHitFilterExpression) {
+ appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true, aHitFilterType, aHitFilterExpression));
+ }
+
+ public void load() {
+ synchronized (filterRules) {
+ try {
+ ExtendedProperties configuration = new ExtendedProperties();
+
+ try {
+ configuration = new ExtendedProperties(configFile.getAbsolutePath());
+ }
+ catch (FileNotFoundException e) {
+ }
+
+ getFilterConfig(filterRules, "abuse.filter", configuration);
+
+ setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
+ setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
+ setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
+ setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
+ setLogSize(configuration.getInt("abuse.logSize", 10));
+ setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
+ setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.toString());
+ }
+ }
+ }
+
+ public void save() {
+ synchronized (filterRules) {
+ try {
+ ExtendedProperties configuration = new ExtendedProperties();
+
+ setFilterConfig(filterRules, "abuse.filter", configuration);
+
+ configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled() ? "1" : "0");
+ configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword() ? "1" : "0");
+ configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock() ? "1" : "0");
+ configuration.addProperty("abuse.logEnabled", getLogEnabled() ? "1" : "0");
+ configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
+ configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
+ configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
+
+ configuration.save(new BufferedOutputStream(new FileOutputStream(configFile),8192), "Anti abuse configuration");
+ }
+ catch (Throwable t) {
+ throw new RuntimeException(t.toString());
+ }
+ }
+ }
+
+ public List getFilterTypes() {
+ try {
+ List result = new Vector();
+
+ Iterator i = filterTypeIds.iterator();
+ while (i.hasNext()) {
+ String id = (String) i.next();
+
+ Map action = new HashMap();
+ action.put("resource", id);
+ action.put("identifier", id);
+
+ result.add(action);
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException("can't get article actions");
+ }
+ }
+
+ public List getArticleActions() {
+ try {
+ List result = new Vector();
+
+ Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
+ while (i.hasNext()) {
+ MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
+ (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+
+ Map action = new HashMap();
+ action.put("resource", operation.getName());
+ action.put("identifier", operation.getName());
+
+ result.add(action);
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException("can't get article actions");
+ }
+ }
+
+ public List getCommentActions() {
+ try {
+ List result = new Vector();
+
+ Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
+ while (i.hasNext()) {
+ MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
+ (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
+
+ Map action = new HashMap();
+ action.put("resource", operation.getName());
+ action.put("identifier", operation.getName());
+
+ result.add(action);
+ }
+
+ return result;
+ }
+ catch (Throwable t) {
+ throw new RuntimeException("can't get comment actions");
+ }
+ }
+
+ public List getFilters() {
+ List result = new Vector();
+
+ synchronized (filterRules) {
+ Iterator i = filterRules.iterator();
+ while (i.hasNext()) {
+ FilterRule filter = (FilterRule) i.next();
+ result.add(filter.clone());
+ }
+ return result;
+ }
+ }
+
+ public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+ return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);
+ }
+
+ public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {
+ return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);
+ }
+
+ public FilterRule getFilter(String anId) {
+ synchronized (filterRules) {
+ FilterRule result = findFilter(filterRules, anId);
+ if (result == null)
+ return result;
+ else
+ return (FilterRule) result.clone();
+ }
+ }
+
+ public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+ return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);
+ }
+
+ public void deleteFilter(String anIdentifier) {
+ deleteFilter(filterRules, anIdentifier);
+ }
+
+ public void moveFilterUp(String anIdentifier) {
+ moveFilter(filterRules, anIdentifier, -1);
+ }
+
+ public void moveFilterDown(String anIdentifier) {
+ moveFilter(filterRules, anIdentifier, 1);
+ }
+
+ public void moveFilterToTop(String anIdentifier) {
+ setFilterPosition(filterRules, anIdentifier, 0);
+ }
+
+ public void moveFilterToBottom(String anIdentifier) {
+ setFilterPosition(filterRules, anIdentifier, Integer.MAX_VALUE);
+ }
+
+ private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {
+ MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
+
+ if (type == null)
+ return "invalidtype";
+
+ if (!type.validate(anExpression)) {
+ return "invalidexpression";
+ }
+
+ FilterRule filter = new FilterRule();
+
+ filter.setId(generateId());
+ filter.setExpression(anExpression);
+ filter.setType(aType);
+ filter.setComments(aComments);
+ filter.setArticleAction(anArticleAction);
+ filter.setCommentAction(aCommentAction);
+ filter.setLastHit(aLastHit);
+
+ synchronized (aFilters) {
+ aFilters.add(filter);
+ }
+
+ return null;
+ }
+
+ private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
+ MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
+
+ if (type == null)
+ return "invalidtype";
+
+ if (!type.validate(anExpression)) {
+ return "invalidexpression";
+ }
+
+ synchronized (aFilters) {
+ FilterRule filter = findFilter(aFilters, anIdentifier);
+
+ if (filter != null) {
+ filter.setExpression(anExpression);
+ filter.setType(aType);
+ filter.setCommentAction(aCommentAction);
+ filter.setArticleAction(anArticleAction);
+ filter.setComments(aComments);
+ }
+
+ return null;
+ }
+ }
+
+ private FilterRule findFilter(List aFilters, String anIdentifier) {
+ synchronized (aFilters) {
+ Iterator i = aFilters.iterator();
+ while (i.hasNext()) {
+ FilterRule filter = (FilterRule) i.next();
+
+ if (filter.getId().equals(anIdentifier)) {
+ return filter;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private void setFilterPosition(List aFilters, String anIdentifier, int aPosition) {
+ synchronized (aFilters) {
+ if (aPosition<0)
+ aPosition=0;
+
+ for (int i = 0; i < aFilters.size(); i++) {
+ FilterRule rule = (FilterRule) aFilters.get(i);
+
+ if (rule.getId().equals(anIdentifier)) {
+ aFilters.remove(rule);
+
+ if (aPosition<aFilters.size())
+ aFilters.add(aPosition, rule);
+ else
+ aFilters.add(rule);
+ break;
+ }
+ }
+ }
+ }
+
+ private void moveFilter(List aFilters, String anIdentifier, int aDirection) {
+ synchronized (aFilters) {
+ for (int i = 0; i < aFilters.size(); i++) {
+ FilterRule rule = (FilterRule) aFilters.get(i);
+
+ if (rule.getId().equals(anIdentifier) && (i + aDirection >= 0) && (i + aDirection < aFilters.size())) {
+ aFilters.remove(rule);
+ aFilters.add(i + aDirection, rule);
+ break;
+ }
+ }
+ }
+ }
+
+ private void deleteFilter(List aFilters, String anIdentifier) {
+ synchronized (aFilters) {
+ FilterRule filter = findFilter(aFilters, anIdentifier);
+
+ if (filter != null) {
+ aFilters.remove(filter);
+ }
+ }
+ }
+
+ private String generateId() {
+ synchronized (this) {
+ maxIdentifier = maxIdentifier + 1;
+
+ return Integer.toString(maxIdentifier);
+ }
+ }
+
+ public class FilterRule {
+ private String identifier;
+ private String expression;
+ private String type;
+ private String comments;
+ private String articleAction;
+ private String commentAction;
+ private Date lastHit;
+
+ public FilterRule() {
+ expression = "";
+ type = "";
+ identifier = "";
+ comments = "";
+ articleAction = articleBlockAction;
+ commentAction = commentBlockAction;
+ lastHit = null;
+ }
+
+ public Date getLastHit() {
+ return lastHit;
+ }
+
+ public void setLastHit(Date aDate) {
+ lastHit = aDate;
+ }
+
+ public String getId() {
+ return identifier;
+ }
+
+ public void setId(String anId) {
+ identifier = anId;
+ }
+
+ public String getExpression() {
+ return expression;
+ }
+
+ public void setExpression(String anExpression) {
+ expression = anExpression;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String aType) {
+ type = aType;
+ }
+
+ public void setComments(String aComments) {
+ comments = aComments;
+ }
+
+ public String getComments() {
+ return comments;
+ }
+
+ public String getArticleAction() {
+ return articleAction;
+ }
+
+ public void setArticleAction(String anArticleAction) {
+ articleAction = anArticleAction;
+ }
+
+ public String getCommentAction() {
+ return commentAction;
+ }
+
+ public void setCommentAction(String aCommentAction) {
+ commentAction = aCommentAction;
+ }
+
+ public boolean test(Entity anEntity, Request aRequest) {
+ MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);
+ try {
+ if (filterType != null)
+ return filterType.test(expression, anEntity, aRequest);
+ }
+ catch (Throwable t) {
+ logger.error("error while testing " + type + "-filter '" + expression + "'");
+ }
+
+ return false;
+ };
+
+ public Object clone() {
+ FilterRule result = new FilterRule();
+ result.setComments(getComments());
+ result.setExpression(getExpression());
+ result.setId(getId());
+ result.setType(getType());
+ result.setArticleAction(getArticleAction());
+ result.setCommentAction(getCommentAction());
+ result.setLastHit(getLastHit());
+
+ return result;
+ }
+ }
+
+ private String escapeConfigListEntry(String aFilterPart) {
+ return StringRoutines.replaceStringCharacters(aFilterPart,
+ new char[] {'\\', ':'},
+ new String[] {"\\\\", "\\:"});
+ }
+
+ private String escapeFilterPart(String aFilterPart) {
+ return StringRoutines.replaceStringCharacters(aFilterPart,
+ new char[] {'\\', '\n', '\r', '\t', ' '},
+ new String[] {"\\\\", "\\n", "\\r", "\\t", "\\ "});
+ }
+
+ private String deescapeFilterPart(String aFilterPart) {
+ return StringRoutines.replaceEscapedStringCharacters(aFilterPart,
+ '\\',
+ new char[] {'\\', ':', 'n', 'r', 't', ' '},
+ new String[] {"\\", ":", "\n", "\r", "\t", " "});
+ }
+
+ private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
+ synchronized (aFilters) {
+ Iterator i = aFilters.iterator();
+
+ while (i.hasNext()) {
+ FilterRule filter = (FilterRule) i.next();
+
+ String filterconfig =
+ escapeConfigListEntry(escapeFilterPart(filter.getType())) + ":" +
+ escapeConfigListEntry(escapeFilterPart(filter.getExpression())) + ":" +
+ escapeConfigListEntry(escapeFilterPart(filter.getArticleAction())) + ":" +
+ escapeConfigListEntry(escapeFilterPart(filter.getCommentAction())) + ":" +
+ escapeConfigListEntry(escapeFilterPart(filter.getComments())) + ":";
+
+ if (filter.getLastHit() != null)
+ filterconfig = filterconfig + filter.getLastHit().getTime();
+
+ aConfiguration.addProperty(aConfigKey, filterconfig);
+ }
+ }
+ }
+
+ private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
+ synchronized (aFilters) {
+ aFilters.clear();
+
+ if (aConfiguration.getStringArray(aConfigKey) != null) {
+
+ Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).
+ iterator();
+
+ while (i.hasNext()) {
+ String filter = (String) i.next();
+ List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');
+ if (parts.size() == 2) {
+ parts.add(articleBlockAction);
+ parts.add(commentBlockAction);
+ parts.add("");
+ parts.add("");
+ }
+
+ if (parts.size() >= 5) {
+ Date lastHit = null;
+
+ if (parts.size() >= 6) {
+ String lastHitString = (String) parts.get(5);
+
+ try {
+ lastHit = new Date(Long.parseLong(lastHitString));
+ }
+ catch (Throwable t) {
+ }
+ }
+
+ addFilter(deescapeFilterPart( (String) parts.get(0)),
+ deescapeFilterPart( (String) parts.get(1)),
+ deescapeFilterPart( (String) parts.get(4)),
+ deescapeFilterPart( (String) parts.get(3)),
+ deescapeFilterPart( (String) parts.get(2)), lastHit);
+ }
+ }
+ }
+ }
+ }
+
+ private static class LogEntry {
+ private String ipNumber;
+ private String browserString;
+ private String id;
+ private Date timeStamp;
+ private boolean isArticle;
+ private String hitFilterType;
+ private String hitFilterExpression;
+
+ public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle, String aHitFilterType, String aHitFilterExpression) {
+ ipNumber = anIpNumber;
+ browserString = aBrowserString;
+ id = anId;
+ isArticle = anIsArticle;
+ timeStamp = aTimeStamp;
+ hitFilterType = aHitFilterType;
+ hitFilterExpression = aHitFilterExpression;
+ }
+
+ public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
+ this(aTimeStamp, anIpNumber, aBrowserString, anId, anIsArticle, null, null);
+ }
+
+ public String getIpNumber() {
+ return ipNumber;
+ }
+
+ public String getBrowserString() {
+ return browserString;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getHitFilterType() {
+ return hitFilterType;
+ }
+
+ public String getHitFilterExpression() {
+ return hitFilterExpression;
+ }
+
+ public Date getTimeStamp() {
+ return timeStamp;
+ }
+
+ public boolean getIsArticle() {
+ return isArticle;
+ }
+ }
+
+ private void truncateLog() {
+ synchronized (log) {
+ if (!logEnabled)
+ log.clear();
+ else {
+ while (log.size() > 0 && log.size() > logSize) {
+ log.remove(log.size()-1);
+ }
+ }
+ }
+ };
+
+ private void appendLog(LogEntry anEntry) {
+ synchronized (log) {
+ if (logEnabled) {
+ log.add(0, anEntry);
+ truncateLog();
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.global;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.util.Properties;
+
+import mir.config.MirPropertiesConfiguration;
+import org.apache.commons.dbcp.ConnectionFactory;
+import org.apache.commons.dbcp.DriverConnectionFactory;
+import org.apache.commons.dbcp.PoolableConnection;
+import org.apache.commons.dbcp.PoolableConnectionFactory;
+import org.apache.commons.pool.ObjectPool;
+import org.apache.commons.pool.impl.GenericObjectPool;
+
+public class DatabaseEngine {
+ private ObjectPool connectionPool;
+
+ public DatabaseEngine() {
+ MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+
+ Properties connectionProperties = new Properties();
+ connectionProperties.put("user", configuration.getString("Database.Username"));
+ connectionProperties.put("password", configuration.getString("Database.Password"));
+ String dbHost = configuration.getString("Database.Host");
+ String dbPort = configuration.getString("Database.Port");
+ String dbName = configuration.getString("Database.Name");
+ String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName+"?compatible=7.1";
+ String dbDriver = configuration.getString("Database.Driver");
+ Driver driver;
+ try {
+ driver = (Driver) (Class.forName(dbDriver)).newInstance();
+ }
+ catch (ClassNotFoundException e) {
+ throw new Error("JDBC Driver not found: " + e.toString());
+ }
+ catch (InstantiationException e) {
+ throw new Error("Can't instantiate JDBC Driver: " + e.toString());
+ }
+ catch (IllegalAccessException e) {
+ throw new Error("No access to JDBC Driver: " + e.toString());
+ }
+
+ connectionPool = new GenericObjectPool(null);
+ ConnectionFactory rawConnectionFactory =
+ new DriverConnectionFactory(driver, dbUrl, connectionProperties);
+ new PoolableConnectionFactory(rawConnectionFactory, connectionPool,
+ null, "select now()", false, true);
+
+ // test the connection right before someone borrows it
+ ((GenericObjectPool) connectionPool).setTestOnBorrow(true);
+
+
+ }
+
+ /**
+ * Obtain a database connection
+ */
+ public Connection obtainConnection() throws Exception {
+ return (Connection) connectionPool.borrowObject();
+ }
+
+ /**
+ * release a previously obtained database connection
+ */
+ public void releaseConnection(Connection aConnection) throws Exception {
+ connectionPool.returnObject(aConnection);
+ }
+
+ /**
+ * Returns the native connection of a previously obtained connection
+ */
+ public Connection getNativeConnection(Connection aConnection) {
+ return ((PoolableConnection) aConnection).getDelegate();
+ }
+
+ public String getStatus() {
+ return
+ connectionPool.getNumActive() + " / " +
+ (connectionPool.getNumIdle()+connectionPool.getNumActive()) +
+ " db conn.";
+ }
+}
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Vector;
+import java.util.ArrayList;
import mir.log.LoggerWrapper;
// important: objects passed as data must not be altered once put into a job
public class JobQueue {
- private Vector jobHandlers;
+ private List jobHandlers;
private Map identifierToJobHandler;
private int nrJobs;
private int jobCleanupTreshold;
public JobQueue(LoggerWrapper aLogger) {
logger = aLogger;
- jobHandlers = new Vector();
+ jobHandlers = new ArrayList();
identifierToJobHandler = new HashMap();
nrJobs = 0;
lastCleanup = 0;
jobCleanupTreshold = 900; // seconds
queueRunner = new JobQueueRunner(logger);
thread = new Thread(queueRunner);
+ thread.setDaemon(true);
thread.start();
}
identifierToJobHandler.put(jobHandler.getIdentifier(), jobHandler);
jobHandler.setPending();
+ jobHandlers.notify();
+
return jobHandler.getIdentifier();
}
}
public List getJobsInfo() {
- List result = new Vector();
+ List result = new ArrayList();
synchronized (jobHandlers) {
Iterator i = jobHandlers.iterator();
}
private void cleanupJobList() {
- List toRemove = new Vector();
+ List toRemove = new ArrayList();
+
synchronized (jobHandlers) {
Iterator i = jobHandlers.iterator();
lastCleanup = System.currentTimeMillis();
}
- private JobHandler acquirePendingJob() {
- synchronized (jobHandlers) {
- int priorityFound= 0;
- JobHandler jobFound;
+ /**
+ * Returns when a new producer job has become available
+ */
+ private JobHandler acquirePendingJob() throws InterruptedException {
+ int priorityFound= 0;
+ JobHandler jobFound;
- jobFound = null;
- Iterator i = jobHandlers.iterator();
- while (i.hasNext()) {
- JobHandler job = (JobHandler) i.next();
+ synchronized (jobHandlers) {
+ do {
+ jobFound = null;
+ Iterator i = jobHandlers.iterator();
+ while (i.hasNext()) {
+ JobHandler job = (JobHandler) i.next();
+
+ if (job.isPending() && (jobFound==null || priorityFound<job.getPriority())) {
+ jobFound = job;
+ priorityFound = job.getPriority();
+ }
+ }
- if (job.isPending() && (jobFound==null || priorityFound<job.getPriority())) {
- jobFound = job;
- priorityFound = job.getPriority();
+ if (jobFound==null) {
+ jobHandlers.wait();
}
- }
+
+ } while (jobFound==null);
return jobFound;
}
}
}
+ public void cancelAllJobs() {
+ synchronized (jobHandlers) {
+ Iterator i = jobHandlers.iterator();
+
+ while (i.hasNext()) {
+ ((JobHandler) i.next()).cancelOrAbortJob();
+ }
+ }
+ }
+
public interface Job {
+ /**
+ * This method should cause the run() method to terminate as soon as
+ * possible.
+ */
void abort();
/**
- *
- *
+ * This method should perform the actions associated with the job.
* @return <code>true</code> if terminated normally, <code>false</code> if aborted
*/
boolean run();
try {
while (true) {
- JobHandler job = acquirePendingJob();
- if (job != null) {
+ try {
+ JobHandler job = acquirePendingJob();
+
logger.debug(" starting job ("+job.getIdentifier()+"): " +job.getDescription());
job.runJob();
logger.debug(" finished job ("+job.getIdentifier()+"): " +job.getDescription());
+
+ job=null;
}
- else {
- try {
- Thread.sleep(1500);
- }
- catch (InterruptedException e) {
- }
+ catch (InterruptedException e) {
}
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.global;
private MirPropertiesConfiguration configuration;
private LoggerWrapper logger;
-
-
public MRUCache() {
logger = new LoggerWrapper("Global.MRUCache");
- try {
- configuration = MirPropertiesConfiguration.instance();
- }
- catch (PropertiesConfigExc e) {
- throw new RuntimeException("Can't get configuration: " + e.getMessage());
- }
+ configuration = MirPropertiesConfiguration.instance();
cacheMaxItems=Integer.parseInt(configuration.getString("Global.Cache.Items"));
cache = new HashMap();
mruList= new LinkedList();
-
}
/**
- * Checks if the cache has an object with the specified key
+ * Checks if the cache has an object with the specified key
*/
public boolean hasObject(CacheKey aCacheKey) {
return cache.containsKey(aCacheKey);
}
}
-
+
/**
* Stores an object in the cache by placing it at the top of the
* list If the object is in the cache, it promotes it to the top of
public void storeObject(CacheKey aCacheKey,Object data) {
synchronized (cache) {
- if (! hasObject(aCacheKey)){
- // add to the cache
- cache.put(aCacheKey,data);
- if (mruList.size() >= cacheMaxItems){
- removeObject((CacheKey) mruList.getLast());
- }
+ if (!hasObject(aCacheKey)) {
+ // add to the cache
+ cache.put(aCacheKey, data);
+ if (mruList.size() >= cacheMaxItems) {
+ removeObject((CacheKey) mruList.getLast());
+ }
}
mruList.remove(aCacheKey);
mruList.addFirst(aCacheKey);
}
- }
-
- public void removeObject(CacheKey aCacheKey){
+ }
+
+ public void removeObject(CacheKey aCacheKey) {
synchronized (cache) {
mruList.remove(aCacheKey);
cache.remove(aCacheKey);
}
}
-
+
/**
* Moves requested item to front of cache
*/
- public Object getObject(CacheKey aCacheKey){
+ public Object getObject(CacheKey aCacheKey) {
synchronized (cache) {
mruList.remove(aCacheKey);
mruList.addFirst(aCacheKey);
\r
package mircoders.global;\r
\r
-import java.util.*;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
\r
+import mir.bundle.BasicBundleFactory;\r
+import mir.bundle.BundleFactory;\r
+import mir.bundle.CascadingBundleFactory;\r
+import mir.bundle.PropertiesFileBundleLoader;\r
import mir.config.MirPropertiesConfiguration;\r
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.log.LoggerEngine;\r
+import mir.log.LoggerWrapper;\r
import mir.misc.ConfigException;\r
+import mircoders.accesscontrol.AccessControl;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.localizer.MirAdminInterfaceLocalizer;\r
import mircoders.localizer.MirCachingLocalizerDecorator;\r
-import mircoders.localizer.*;\r
-import mircoders.accesscontrol.*;\r
-import mircoders.entity.*;\r
-import mir.entity.adapter.*;\r
+import mircoders.localizer.MirLocalizer;\r
\r
public class MirGlobal {\r
- static private MirPropertiesConfiguration configuration;\r
static private MirLocalizer localizer;\r
static private ProducerEngine producerEngine;\r
static private Abuse abuse;\r
static private AccessControl accessControl;\r
static private Map articleOperations;\r
static private Map commentOperations;\r
+ static private Map loggedInUsers = new HashMap();\r
+ static private Map loggedInUserIds = new HashMap();\r
+ static private LoggerWrapper logger = new LoggerWrapper("Global");\r
+ static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");\r
+// static private ChangeEngine changeEngine = new ChangeEngine();\r
+ static private DatabaseEngine databaseEngine;\r
+\r
+ static private BundleFactory bundleFactory =\r
+ new CascadingBundleFactory(\r
+ new BasicBundleFactory(\r
+ new PropertiesFileBundleLoader(\r
+ config().getHome())));\r
\r
public synchronized static MirLocalizer localizer() {\r
String localizerClassName;\r
localizerClass = Class.forName(localizerClassName);\r
}\r
catch (Throwable t) {\r
- throw new ConfigException("localizer class '" + localizerClassName + "' not found: " + t.toString());\r
+ throw new ConfigException("localizer class '" +\r
+ localizerClassName + "' not found: " + t.toString());\r
}\r
\r
if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))\r
- throw new ConfigException("localizer class '" + localizerClassName + "' is not assignable from MirLocalizer");\r
+ throw new ConfigException("localizer class '" +\r
+ localizerClassName + "' is not assignable from MirLocalizer");\r
\r
try {\r
localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());\r
}\r
catch (Throwable t) {\r
- throw new ConfigException("localizer class '" + localizerClassName + "' cannot be instantiated: " + t.toString());\r
+ throw new ConfigException("localizer class '" +\r
+ localizerClassName + "' cannot be instantiated: " + t.toString());\r
}\r
}\r
\r
return localizer;\r
}\r
\r
- public static Abuse abuse() {\r
- if (abuse==null) {\r
- synchronized(MirGlobal.class) {\r
- if (abuse==null)\r
- abuse = new Abuse();\r
- }\r
- }\r
+ /**\r
+ * Returns a string that provides some global status information\r
+ */\r
+ public static String getStatus() {\r
+ StringBuffer result = new StringBuffer();\r
+\r
+ result.append((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/(1024*1024));\r
+ result.append("M in use, ");\r
+ result.append(Thread.currentThread().activeCount()).append(" threads, ");\r
+ result.append(getDatabaseEngine().getStatus());\r
+\r
+ return result.toString();\r
+ }\r
+\r
+ public synchronized static Abuse abuse() {\r
+ if (abuse==null)\r
+ abuse = new Abuse();\r
\r
return abuse;\r
}\r
\r
+ /**\r
+ * returns the global change engine (used to track changed files)\r
+ */\r
+// public static ChangeEngine getChangeEngine() {\r
+// return changeEngine;\r
+// }\r
+\r
public static MirPropertiesConfiguration config() {\r
- try {\r
- return MirPropertiesConfiguration.instance();\r
- }\r
- catch (PropertiesConfigExc e) {\r
- throw new RuntimeException(e.getMessage());\r
- }\r
+ return MirPropertiesConfiguration.instance();\r
+ }\r
+\r
+ public synchronized static DatabaseEngine getDatabaseEngine() {\r
+ if (databaseEngine==null)\r
+ databaseEngine = new DatabaseEngine();\r
+\r
+ return databaseEngine;\r
}\r
\r
- public static ProducerEngine producerEngine() {\r
+ public static ProducerEngine getProducerEngine() {\r
if (producerEngine == null) {\r
producerEngine = new ProducerEngine();\r
}\r
MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getArticleOperationForName(anOperation);\r
\r
try {\r
+ EntityAdapter user = null;\r
+ if (aUser!=null)\r
+ user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
+\r
if (operation!=null)\r
operation.perform(\r
- localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser),\r
+ user,\r
localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));\r
}\r
catch (Throwable t) {\r
+ t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+\r
throw new RuntimeException(t.toString());\r
}\r
}\r
MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getCommentOperationForName(anOperation);\r
\r
try {\r
+ EntityAdapter user = null;\r
+ if (aUser!=null)\r
+ user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);\r
+\r
if (operation!=null)\r
operation.perform(\r
- localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser),\r
+ user,\r
localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));\r
}\r
catch (Throwable t) {\r
}\r
}\r
\r
- private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getArticleOperationForName(String aName) {\r
+ private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation\r
+ getArticleOperationForName(String aName) {\r
try {\r
if (articleOperations == null) {\r
articleOperations = new HashMap();\r
Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();\r
while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+ MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+ (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
articleOperations.put(operation.getName(), operation);\r
}\r
}\r
}\r
}\r
\r
- private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getCommentOperationForName(String aName) {\r
+ private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation\r
+ getCommentOperationForName(String aName) {\r
try {\r
if (commentOperations == null) {\r
commentOperations = new HashMap();\r
Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();\r
while (i.hasNext()) {\r
- MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+ MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+ (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
commentOperations.put(operation.getName(), operation);\r
}\r
}\r
}\r
}\r
\r
+ public static boolean isUserLoggedIn(String anId) {\r
+ synchronized (loggedInUserIds) {\r
+ return loggedInUserIds.containsKey(anId);\r
+ }\r
+ }\r
+\r
+ public static List getLoggedInUsers() {\r
+ List result = new Vector();\r
+\r
+ synchronized (loggedInUsers) {\r
+ Iterator i = loggedInUsers.entrySet().iterator();\r
+\r
+ while (i.hasNext()) {\r
+ Map.Entry entry = (Map.Entry) i.next();\r
+\r
+ Map item = new HashMap();\r
+ item.put("name", entry.getKey());\r
+ item.put("count", entry.getValue());\r
+ result.add(item);\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ public static BundleFactory getBundleFactory() {\r
+ return bundleFactory;\r
+ }\r
+\r
+ public static void registerLogin(String aName, String anId) {\r
+ modifyLoggedInCount(aName, anId, 1);\r
+ }\r
+\r
+ public static void registerLogout(String aName, String anId) {\r
+ modifyLoggedInCount(aName, anId, -1);\r
+ }\r
+\r
+ private static void modifyLoggedInCount(String aName, String anId, int aModifier) {\r
+ synchronized (loggedInUsers) {\r
+ Integer count = (Integer) loggedInUsers.get(aName);\r
+ if (count==null)\r
+ count = new Integer(0);\r
+\r
+ if (count.intValue()+aModifier<=0) {\r
+ loggedInUsers.remove(aName);\r
+ }\r
+ else {\r
+ loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));\r
+ }\r
+ }\r
+\r
+ synchronized (loggedInUserIds) {\r
+ Integer count = (Integer) loggedInUserIds.get(anId);\r
+ if (count==null)\r
+ count = new Integer(0);\r
+\r
+ if (count.intValue()+aModifier<=0) {\r
+ loggedInUserIds.remove(anId);\r
+ }\r
+ else {\r
+ loggedInUserIds.put(anId, new Integer(count.intValue() + aModifier));\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Called whenever a modifying admin action occurs. Used to log\r
+ * the action, if admin activity logging is turned on,\r
+ */\r
+ public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {\r
+ try {\r
+ if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {\r
+ String user = "unknown (" + aUser.toString() + ")";\r
+ if (aUser != null)\r
+ user = aUser.getFieldValue("login");\r
+ adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);\r
+ }\r
+ }\r
+ catch (Throwable t) {\r
+ logger.error("Error while logging admin usage ("+\r
+ aUser.toString()+", "+aDescription+"): " +t.toString());\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Reloads all reloadable configurations, such as the producer subsystem.\r
+ */\r
+ public static void reloadConfigurations() throws MirGlobalExc, MirGlobalFailure {\r
+ getProducerEngine().reloadConfiguration();\r
+ try {\r
+ LoggerEngine.reload();\r
+ }\r
+ catch (Throwable e) {\r
+ throw new MirGlobalFailure(e);\r
+ }\r
+ getBundleFactory().reload();\r
+ }\r
}\r
\r
\r
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.global;
+
+import multex.Exc;
+
+public class MirGlobalExc extends Exc {
+ public MirGlobalExc(String aMessage) {
+ super(aMessage);
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.global;
+
+import multex.Failure;
+
+public class MirGlobalFailure extends Failure {
+ public MirGlobalFailure(Throwable aCause){
+ super(aCause.getMessage(), aCause);
+ }
+
+ public MirGlobalFailure(String msg, Exception cause){
+ super(msg,cause);
+ }
+}
package mircoders.global;
import java.io.PrintWriter;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
+import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerToWriterAdapter;
import mir.log.LoggerWrapper;
import mir.producer.Producer;
import mir.producer.ProducerFactory;
-import mir.util.*;
-import mir.config.*;
+import mir.util.GeneratorFormatAdapters;
import mir.util.StringRoutines;
-import multex.Exc;
-import multex.Failure;
public class ProducerEngine {
-// private Map producers;
private JobQueue producerJobQueue;
private LoggerWrapper logger;
-
+ private Map nameToFactory;
+ private List factories;
protected ProducerEngine() {
logger = new LoggerWrapper("Producer");
producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue"));
+
+ factories = new ArrayList();
+ nameToFactory = new HashMap();
+
+ try {
+ reloadConfiguration();
+ }
+ catch (Throwable t) {
+ }
+ }
+
+ /**
+ * Reloads the producer configuration
+ */
+ public void reloadConfiguration() throws MirGlobalExc, MirGlobalFailure {
+ try {
+ factories = MirGlobal.localizer().producers().loadFactories();
+
+ synchronized (nameToFactory) {
+ nameToFactory.clear();
+
+ Iterator i = factories.iterator();
+ while (i.hasNext()) {
+ ProducerFactory factory = (ProducerFactory) i.next();
+ nameToFactory.put(factory.getName(), factory);
+ }
+ }
+ }
+ catch (Throwable t) {
+ throw new MirGlobalFailure(t);
+ }
+ }
+
+ /**
+ * Looks up a producer factory by name
+ */
+ private ProducerFactory getFactoryForName(String aName) {
+ synchronized (nameToFactory) {
+ return (ProducerFactory) nameToFactory.get(aName);
+ }
+ }
+
+ /**
+ * Returns all factories
+ */
+ public List getFactories() {
+ return factories;
}
+ /**
+ * Adds a producer job to the queue
+ */
+ public void addJob(String aProducerFactory, String aVerb) throws MirGlobalExc, MirGlobalFailure {
+ ProducerFactory factory;
+
+ factory = getFactoryForName( aProducerFactory );
+
+ if (factory==null)
+ throw new MirGlobalExc("Unknown producer: " + aProducerFactory);
- public void addJob(String aProducerFactory, String aVerb) {
- producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb);
+ if (!factory.allowVerb(aVerb))
+ throw new MirGlobalExc("illegal producer/verb combination: " + aProducerFactory+"::"+aVerb);
+
+ producerJobQueue.appendJob(
+ new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb);
}
+ /**
+ * Cancels a list of jobs by job identifier
+ */
public void cancelJobs(List aJobs) {
producerJobQueue.cancelJobs(aJobs);
};
- public void addTask(ProducerTask aTask) {
- addJob(aTask.getProducer(), aTask.getVerb());
- }
-
- public void addTasks(List aTasks) {
- Iterator i = aTasks.iterator();
+ /**
+ * Cancels all jobs in the queue
+ */
+ public void cancelAllJobs() {
+ producerJobQueue.cancelAllJobs();
+ };
- while (i.hasNext()) {
- addTask((ProducerTask) i.next());
- }
+ public void addTask(ProducerTask aTask) throws MirGlobalExc, MirGlobalFailure {
+ addJob(aTask.getProducer(), aTask.getVerb());
}
private String convertStatus(JobQueue.JobInfo aJob) {
long endTime;
boolean result = false;
Map startingMap = new HashMap();
+ Map mirMap = new HashMap();
+ mirMap.put("producer", factoryName);
+ mirMap.put("verb", verb);
+
+ startingMap.put("Mir", mirMap);
startTime = System.currentTimeMillis();
logger.info("Producing job: "+factoryName+"."+verb);
try {
- factory = MirGlobal.localizer().producers().getFactoryForName( factoryName );
+ factory = getFactoryForName(factoryName);
if (factory!=null) {
MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap);
}
}
- public static class ProducerEngineExc extends Exc {
- public ProducerEngineExc(String aMessage) {
- super(aMessage);
- }
- }
-
- public static class ProducerEngineRuntimeExc extends Failure {
- public ProducerEngineRuntimeExc(String msg, Exception cause){
- super(msg,cause);
- }
- }
-
public static class ProducerTask {
private String producer;
private String verb;
return producer;
}
- public static List parseProducerTaskList(String aList) throws ProducerEngineExc {
+ public static List parseProducerTaskList(String aList) throws MirGlobalExc {
Iterator i;
List result = new Vector();
List parts = StringRoutines.splitString(taskExpression, ".");
if (parts.size() != 2)
- throw new ProducerEngineExc("Invalid producer expression: '" + taskExpression + "'");
+ throw new MirGlobalExc("Invalid producer expression: '" + taskExpression + "'");
else
result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1)));
}
*/
package mircoders.localizer;
+import mir.entity.adapter.EntityAdapter;
+import mir.generator.Generator;
+
import java.util.List;
import java.util.Map;
-import mir.entity.adapter.EntityAdapter;
-
/**
+ * Interface to allow for localized changed to the workings of the admin system
*
- * <p>Title: Interface to allow for localized changed to the workings of the admin system</p>
* @author Zapata
- * @version 1.0
*/
public interface MirAdminInterfaceLocalizer {
*/
public String makePasswordDigest(String aPassword);
-
/**
+ * Allows different "generators" (templates) to be used for certain pages
*
+ * @param aPage The identifier of the page
+ * @param aUser the user (can be used to allow different users to see different pages
+ * @param aDefault The default generator
* @return
*/
- public List simpleCommentOperations();
+ public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser, String aDefault) throws MirLocalizerExc;
/**
+ * Prepares an article preview
*
- * @return
+ * @param aPreviewPage there may be different preview pages for a single article.
+ * (i.e. the same article may lead to different pages) this parameter selects one
+ * of those versions. See also {@link #getPreviewPages}.
+ * @param anArticle the article to be previewed
+ * @param aContext the context to be supplied to the generator
+ * @return the generator to be used to generate the preview
+ */
+ public Generator prepareArticlePreview(String aPreviewPage, EntityAdapter anArticle, Map aContext)
+ throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * Return the available preview variations of one article
+ */
+ public List getPreviewPages(EntityAdapter anArticle) throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * Get the {@link List} of {@link MirSimpleEntityOperation}s available for comments
+ */
+ public List simpleCommentOperations();
+
+ /**
+ * Get the {@link List} of {@link MirSimpleEntityOperation}s available for articles
*/
public List simpleArticleOperations();
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer;\r
-\r
-import mir.entity.Entity;\r
-import mir.session.Request;\r
-\r
-/**\r
- *\r
- *\r
- * <p>Title: Anti-abuse filter type</p>\r
- * <p>Description: Interface to define filter types for the anti-abuse system\r
- * </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: Mir coders</p>\r
- * @author Zapata\r
- * @version 1.0\r
- */\r
-\r
-public interface MirAntiAbuseFilterType {\r
- /**\r
- * The identifying name of the filter type. Must be unique.\r
- *\r
- * @return\r
- */\r
- public String getName();\r
-\r
- /**\r
- * Must return <code>true</code> if the expression is valid for this filter. <code>false</code> if not.\r
- * @param anExpression\r
- * @return\r
- */\r
- public boolean validate(String anExpression);\r
-\r
- /**\r
- * Must return <code>true</code> if the posting matches the filter.\r
- * @param anExpression\r
- * @return\r
- */\r
- public boolean test(String anExpression, Entity anEntity, Request aRequest);\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer;
+
+import mir.entity.Entity;
+import mir.session.Request;
+
+/**
+ * Interface to define filter types for the anti-abuse system
+ */
+
+public interface MirAntiAbuseFilterType {
+ /**
+ * The identifying name of the filter type. Must be unique.
+ *
+ * @return
+ */
+ public String getName();
+
+ /**
+ * Must return <code>true</code> if the expression is valid for this filter. <code>false</code> if not.
+ * @param anExpression
+ * @return
+ */
+ public boolean validate(String anExpression);
+
+ /**
+ * Must return <code>true</code> if the posting matches the filter.
+ * @param anExpression
+ * @return
+ */
+ public boolean test(String anExpression, Entity anEntity, Request aRequest);
}
\ No newline at end of file
package mircoders.localizer;
+import mir.entity.adapter.EntityAdapterModel;
import mir.generator.Generator;
import mir.generator.WriterEngine;
-import mir.entity.adapter.*;
public class MirCachingLocalizerDecorator implements MirLocalizer {
private MirLocalizer localizer;
private MirProducerAssistantLocalizer producerAssistantLocalizer;
private MirDataModelLocalizer dataModelLocalizer;
private MirAdminInterfaceLocalizer adminInterfaceLocalizer;
+ private MirMediaLocalizer mediaLocalizer;
public MirCachingLocalizerDecorator(MirLocalizer aLocalizer) {
localizer = aLocalizer;
return adminInterfaceLocalizer;
};
+ public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
+ if (mediaLocalizer==null) {
+ mediaLocalizer = localizer.media();
+ }
+
+ return mediaLocalizer;
+ }
+
private static class MirCachingDatamodelLocalizer implements MirDataModelLocalizer {
private MirDataModelLocalizer master;
private EntityAdapterModel adapterModel;
private static class MirCachingGeneratorLocalizer implements MirGeneratorLocalizer {
private MirGeneratorLocalizer master;
private WriterEngine writerEngine;
- private Generator.GeneratorLibrary producerGeneratorLibrary;
- private Generator.GeneratorLibrary adminGeneratorLibrary;
- private Generator.GeneratorLibrary openPostingGeneratorLibrary;
+ private Generator.Library producerGeneratorLibrary;
+ private Generator.Library adminGeneratorLibrary;
+ private Generator.Library openPostingGeneratorLibrary;
public MirCachingGeneratorLocalizer(MirGeneratorLocalizer aMaster) {
master = aMaster;
return writerEngine;
};
- public Generator.GeneratorLibrary makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
if (producerGeneratorLibrary==null) {
producerGeneratorLibrary = master.makeProducerGeneratorLibrary();
}
return producerGeneratorLibrary;
};
- public Generator.GeneratorLibrary makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
if (adminGeneratorLibrary==null) {
adminGeneratorLibrary = master.makeAdminGeneratorLibrary();
}
return adminGeneratorLibrary;
};
- public Generator.GeneratorLibrary makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
if (openPostingGeneratorLibrary==null) {
openPostingGeneratorLibrary = master.makeOpenPostingGeneratorLibrary();
}
public interface MirGeneratorLocalizer {
public WriterEngine makeWriterEngine() throws MirLocalizerExc, MirLocalizerFailure;
- public Generator.GeneratorLibrary makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
- public Generator.GeneratorLibrary makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
- public Generator.GeneratorLibrary makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
+ public Generator.Library makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
+ public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
+ public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure;
}
\ No newline at end of file
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc;
public MirGeneratorLocalizer generators() throws MirLocalizerFailure, MirLocalizerExc;
public MirDataModelLocalizer dataModel() throws MirLocalizerFailure, MirLocalizerExc;
+ public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc;
}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.localizer;
+
+import mir.media.MediaHandler;
+
+/**
+ * Interface to allow for customization of the way Mir handles media publication,
+ * manipulation and storage
+ */
+
+public interface MirMediaLocalizer {
+ /** returns the {@link MediaHandler} belonging to handler identifier <code>aName</code> */
+ public MediaHandler getHandler(String aName);
+}
\ No newline at end of file
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer;\r
-\r
-import java.util.List;\r
-\r
-import mir.session.Request;\r
-import mir.session.Session;\r
-import mir.session.SessionHandler;\r
-\r
-import mircoders.entity.EntityComment;\r
-import mircoders.entity.EntityContent;\r
-\r
-public interface MirOpenPostingLocalizer {\r
-\r
- /**\r
- * Class to encapsulate a validation error\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
- /**\r
- *\r
- * @param aRequest\r
- * @param aSession\r
- * @return\r
- * @throws MirLocalizerExc\r
- * @throws MirLocalizerFailure\r
- */\r
- public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
- /**\r
- *\r
- * @param aComment\r
- * @throws MirLocalizerExc\r
- * @throws MirLocalizerFailure\r
- */\r
- public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
- /**\r
- * This method will be called after an article is posted via the open posting interface.\r
- *\r
- * @param aContent\r
- * @throws MirLocalizerExc\r
- * @throws MirLocalizerFailure\r
- */\r
- public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;\r
-\r
- /**\r
- *\r
- *\r
- * @return\r
- * @throws MirLocalizerExc\r
- * @throws MirLocalizerFailure\r
- */\r
-\r
- public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;\r
-}\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer;
+
+import java.util.List;
+
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionHandler;
+import mircoders.entity.EntityComment;
+import mircoders.entity.EntityContent;
+
+public interface MirOpenPostingLocalizer {
+
+ /**
+ *
+ */
+ public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * This method will be called after a comment has been posted
+ * via the open posting interface.
+ */
+ public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ * This method will be called after an article is posted via the open posting interface.
+ */
+ public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;
+
+ /**
+ *
+ */
+
+ public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;
+}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.localizer;
import java.util.List;
-import mir.producer.ProducerFactory;
-
public interface MirProducerLocalizer {
- public List factories() throws MirLocalizerExc, MirLocalizerFailure;
- public ProducerFactory getFactoryForName(String aName);
- public void produceAllNew();
+ /**
+ * Loads the factories. Should return a list of implementations of
+ * {@link mir.producer.ProducerFactory}
+ */
+ public List loadFactories() throws MirLocalizerExc, MirLocalizerFailure;
+
+ public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure;
+ public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure;
}
package mircoders.localizer.basic;
-import java.text.SimpleDateFormat;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.List;
-import java.util.*;
-import java.util.Vector;
-
+import mir.bundle.Bundle;
+import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityAdapterExc;
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
+import mir.module.ModuleExc;
import mir.storage.StorageObjectFailure;
+import mir.util.DateTimeFunctions;
+import mir.util.EntityUtility;
import mir.util.StringRoutines;
+import mir.util.generator.BundleGeneratorFunction;
import mircoders.entity.EntityComment;
import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
import mircoders.localizer.MirAdminInterfaceLocalizer;
import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.MirLocalizerFailure;
+import mircoders.module.ModuleLanguage;
import mircoders.storage.DatabaseContent;
+import java.util.*;
+
public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocalizer {
- private Vector simpleCommentOperations;
- private Vector simpleArticleOperations;
+ /** preview page name (String) -> generator name (String) */
+ private Map previewPages;
+ private List previewPageNames;
+
+ private List simpleCommentOperations;
+ private List simpleArticleOperations;
private Map simpleCommentOperationsMap;
private Map simpleArticleOperationsMap;
- private static SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
- public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure, MirLocalizerExc {
- simpleCommentOperations = new Vector();
- simpleArticleOperations = new Vector();
+ protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface");;
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
+
+ public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure {
+
+ simpleCommentOperations = new ArrayList();
+ simpleArticleOperations = new ArrayList();
simpleCommentOperationsMap = new HashMap();
simpleArticleOperationsMap = new HashMap();
+ previewPages = new HashMap();
+ previewPageNames = new ArrayList();
+
+ String[] previewConfiguration = configuration.getStringArray("Mir.Localizer.Admin.ArticlePreview");
+
+ for (int i = 0; i<previewConfiguration.length; i++) {
+ try {
+ List parts = StringRoutines.separateString(previewConfiguration[i], "=");
+ if (parts.size() == 2) {
+ String key = ((String) parts.get(0)).trim();
+ previewPages.put(key,((String) parts.get(1)).trim());
+ previewPageNames.add(key);
+ }
+ else {
+ throw new Exception("'=' expected");
+ }
+ }
+ catch (Exception e) {
+ logger.error("Error while processing preview configuration '" + previewConfiguration[i] + "': " + e.toString());
+ }
+ }
+
addSimpleArticleOperation(new ChangeArticleFieldOperation("newswire", "to_article_type", "0", "1", false));
addSimpleArticleOperation(new ModifyArticleFieldOperation("unhide", "is_published", "1", false));
addSimpleArticleOperation(new ModifyArticleFieldOperation("hide", "is_published", "0", false));
addSimpleCommentOperation(new ModifyCommentFieldOperation("hide", "is_published", "0"));
}
+ /** {@inheritDoc} */
+ public String getAdminPageGenerator(String aPage, Map aTemplateData, EntityAdapter aUser, String aDefault) throws MirLocalizerExc {
+ return aDefault;
+ }
+
+ /** {@inheritDoc} */
+ public Generator prepareArticlePreview(String aPreviewPage, EntityAdapter anArticle, Map aContext) throws MirLocalizerExc {
+ MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(aContext);
+ aContext.put("article", anArticle);
+
+
+ try {
+ aContext.put(
+ "language",
+ MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("language",
+ new ModuleLanguage().languageForCode(configuration.getString("Mir.Localizer.Admin.ArticlePreviewLanguage"))));
+ }
+ catch (EntityAdapterExc e) {
+ throw new MirLocalizerFailure("Can't create entity adapter", e);
+ }
+ catch (ModuleExc e) {
+ throw new MirLocalizerFailure("Can't find language", e);
+ }
+ aContext.put("pathprefix", configuration.getString("Mir.Localizer.Admin.ArticlePreviewLanguage"));
+
+ aContext.put("lang",
+ new BundleGeneratorFunction(
+ new Bundle[] {
+ MirGlobal.getBundleFactory().getBundle(
+ "etc/bundles/producer",
+ new String[] {
+ configuration.getString("Mir.Localizer.Admin.ArticlePreviewLanguage") }) }));
+
+
+ if (previewPages.containsKey(aPreviewPage)) {
+ try {
+ return MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator((String) previewPages.get(aPreviewPage));
+ }
+ catch (GeneratorExc e) {
+ throw new MirLocalizerFailure(e);
+ }
+ }
+ else {
+ throw new MirLocalizerExc("Unknown preview: " + aPreviewPage);
+ }
+ }
+
+ /** {@inheritDoc} */
+ public List getPreviewPages(EntityAdapter anArticle) throws MirLocalizerExc{
+ return Collections.unmodifiableList(previewPageNames);
+ }
+
+ /** {@inheritDoc} */
public String makePasswordDigest(String aPassword) {
return aPassword;
}
};
public List simpleCommentOperations() {
- return simpleCommentOperations;
+ return Collections.unmodifiableList(simpleCommentOperations);
};
public List simpleArticleOperations() {
- return simpleArticleOperations;
+ return Collections.unmodifiableList(simpleArticleOperations);
};
public MirSimpleEntityOperation simpleArticleOperationForName(String aName) {
protected abstract static class EntityModifyingOperation implements MirSimpleEntityOperation {
private String name;
+ private boolean logOperation;
- protected EntityModifyingOperation(String aName) {
+ protected EntityModifyingOperation(String aName, boolean aLogOperation) {
name = aName;
+ logOperation = aLogOperation;
}
public String getName() {
Entity entity = anEntity.getEntity();
try {
performModification(aUser, entity);
+
+ if (logOperation) {
+ try {
+ StringBuffer line = new StringBuffer();
+
+ line.append(DateTimeFunctions.advancedDateFormat(
+ MirGlobal.config().getString("Mir.DefaultDateTimeFormat"),
+ (new GregorianCalendar()).getTime(),
+ MirGlobal.config().getString("Mir.DefaultTimezone")));
+ line.append(" ");
+ if (aUser != null)
+ line.append(aUser.get("login"));
+ else
+ line.append("unknown");
+
+ line.append(" ");
+ line.append(getName());
+ EntityUtility.appendLineToField(entity, "comment", line.toString());
+ }
+ catch (Throwable t) {
+ logger.error("Error while trying to log an article operation: " + t.toString());
+ }
+ }
+
entity.update();
}
catch (Throwable t) {
}
public static abstract class CommentModifyingOperation extends EntityModifyingOperation {
+ public CommentModifyingOperation(String aName, boolean aLogOperation) {
+ super(aName, aLogOperation);
+ }
+
public CommentModifyingOperation(String aName) {
- super(aName);
+ this(aName, true);
}
protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
performModification(aUser, (EntityComment) anEntity);
- DatabaseContent.getInstance().setUnproduced("id="+anEntity.getValue("to_media"));
+ DatabaseContent.getInstance().setUnproduced("id="+anEntity.getFieldValue("to_media"));
};
protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ;
}
public static abstract class ArticleModifyingOperation extends EntityModifyingOperation {
- private boolean logOperation;
-
public ArticleModifyingOperation(String aName, boolean aLogOperation) {
- super(aName);
-
- logOperation = aLogOperation;
+ super(aName, aLogOperation);
}
protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure {
protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure {
performModification(aUser, (EntityContent) anEntity);
- anEntity.setValueForProperty("is_produced", "0");
-
- if (logOperation) {
- StringBuffer comment = new StringBuffer();
- try {
- comment.append(StringRoutines.interpretAsString(anEntity.getValue("comment")));
- }
- catch (Throwable t) {
- }
- if (comment.length()>0 && comment.charAt(comment.length()-1)!='\n') {
- comment.append('\n');
- }
- comment.append(dateFormatter.format((new GregorianCalendar()).getTime()));
- comment.append(" ");
- try {
- comment.append(StringRoutines.interpretAsString(aUser.get("login")));
- }
- catch (Throwable t) {
- }
- comment.append(" ");
- comment.append(getName());
- anEntity.setValueForProperty("comment", comment.toString());
- }
+ anEntity.setFieldValue("is_produced", "0");
};
protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ;
}
protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
- aComment.setValueForProperty(field, value);
+ aComment.setFieldValue(field, value);
}
}
protected static class SetCommentFieldsOperation extends CommentModifyingOperation {
private Map values;
- public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) throws MirLocalizerExc {
+ public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) {
super(aName);
values = new HashMap();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
- aComment.setValueForProperty((String) entry.getKey(), (String) entry.getValue());
+ aComment.setFieldValue((String) entry.getKey(), (String) entry.getValue());
}
}
}
}
protected boolean isAvailable(EntityComment aComment) {
- return aComment.getValue(field) == null || !aComment.getValue(field).equals(value);
+ return aComment.getFieldValue(field) == null || !aComment.getFieldValue(field).equals(value);
}
protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
- aComment.setValueForProperty(field, value);
+ aComment.setFieldValue(field, value);
}
}
}
protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
- anArticle.setValueForProperty(field, value);
+ anArticle.setFieldValue(field, value);
}
}
}
protected boolean isAvailable(EntityContent anArticle) {
- return anArticle.getValue(field) == null || !anArticle.getValue(field).equals(value);
+ return anArticle.getFieldValue(field) == null || !anArticle.getFieldValue(field).equals(value);
}
protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
- anArticle.setValueForProperty(field, value);
+ anArticle.setFieldValue(field, value);
}
}
}
protected boolean isAvailable(EntityContent anArticle) {
- return anArticle.getValue(field) != null && oldValues.contains(anArticle.getValue(field));
+ return anArticle.getFieldValue(field) != null && oldValues.contains(anArticle.getFieldValue(field));
}
protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
- anArticle.setValueForProperty(field, newValue);
+ anArticle.setFieldValue(field, newValue);
}
}
}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.*;\r
-\r
-import gnu.regexp.*;\r
-\r
-import mir.entity.Entity;\r
-import mir.session.Request;\r
-import mir.util.InternetFunctions;\r
-import mircoders.localizer.MirAntiAbuseFilterType;\r
-\r
-\r
-/**\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
-public class MirBasicAntiAbuseFilterTypes {\r
- private MirBasicAntiAbuseFilterTypes() {\r
- }\r
-\r
- public static abstract class BasicFilterType implements MirAntiAbuseFilterType {\r
- private String name;\r
-\r
- public BasicFilterType(String aName) {\r
- name = aName;\r
- }\r
-\r
- public String getName() {\r
- return name;\r
- }\r
- }\r
-\r
- /**\r
- * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
- public static class IPFilter extends BasicFilterType {\r
- public IPFilter(String aName) {\r
- super(aName);\r
- }\r
-\r
- public boolean validate(String anExpression) {\r
- try {\r
- InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);\r
- return true;\r
- }\r
- catch (Throwable t) {\r
- return false;\r
- }\r
- };\r
-\r
- public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
- try {\r
- return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);\r
- }\r
- catch (Throwable t) {\r
- return false;\r
- }\r
- };\r
- }\r
-\r
- /**\r
- * A regular expression filter.\r
- *\r
- * <p>Title: </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-\r
- public static class RegularExpressionFilter extends BasicFilterType {\r
- private boolean exactMatch;\r
- private boolean caseSensitive;\r
- private List selectedFields;\r
-\r
- public RegularExpressionFilter(String aName) {\r
- this(aName, false, false, null);\r
- }\r
-\r
- public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {\r
- super(aName);\r
-\r
- caseSensitive = aCaseSensitive;\r
- exactMatch = anExactMatch;\r
- if (aSelectedFields==null)\r
- selectedFields = null;\r
- else\r
- selectedFields = Arrays.asList(aSelectedFields);\r
- }\r
-\r
- public boolean validate(String anExpression) {\r
- try {\r
- new RE(anExpression);\r
- return true;\r
- }\r
- catch (Throwable t) {\r
- return false;\r
- }\r
- };\r
-\r
- public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
- try {\r
- Iterator j;\r
- int flags = 0;\r
-\r
- if (caseSensitive)\r
- flags |= RE.REG_ICASE;\r
-\r
- RE regularExpression = new RE(anExpression, RE.REG_ICASE);\r
-\r
- if (selectedFields!=null)\r
- j = selectedFields.iterator();\r
- else\r
- j = anEntity.getFields().iterator();\r
-\r
- while (j.hasNext()) {\r
- String field = anEntity.getValue( (String) j.next());\r
-\r
- if (exactMatch) {\r
- if (field != null && regularExpression.isMatch(field)) {\r
- return true;\r
- }\r
- }\r
- else {\r
- if (field != null && regularExpression.getMatch(field) != null) {\r
- return true;\r
- }\r
- }\r
- }\r
- }\r
- catch (Throwable t) {\r
- }\r
- return false;\r
- }\r
- }\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.localizer.basic;
+
+import gnu.regexp.RE;
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.util.InternetFunctions;
+import mircoders.localizer.MirAntiAbuseFilterType;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+
+/**
+ * Wrapper around a collection of common filter classes for Mir's
+ * anti-abuse filtering system.
+ */
+public class MirBasicAntiAbuseFilterTypes {
+ protected static final LoggerWrapper logger = new LoggerWrapper("Localizer.ProducerAssistant");
+
+ private MirBasicAntiAbuseFilterTypes() {
+ }
+
+ public static abstract class BasicFilterType implements MirAntiAbuseFilterType {
+ private String name;
+
+ public BasicFilterType(String aName) {
+ name = aName;
+ }
+
+ public String getName() {
+ return name;
+ }
+ }
+
+ /**
+ * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.
+ */
+ public static class IPFilter extends BasicFilterType {
+ /**
+ *
+ */
+ public IPFilter(String aName) {
+ super(aName);
+ }
+
+ /**
+ *
+ */
+ public boolean validate(String anExpression) {
+ try {
+ InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);
+ return true;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ };
+
+ /**
+ *
+ */
+ public boolean test(String anExpression, Entity anEntity, Request aRequest) {
+ try {
+ return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ };
+ }
+
+ /**
+ * A regular expression filter.
+ */
+ public static class RegularExpressionFilter extends BasicFilterType {
+ private boolean exactMatch;
+ private boolean caseSensitive;
+ private int fieldKind;
+ private List selectedFields;
+
+ public static final int ENTITY_FIELDS = 0;
+ public static final int REQUEST_HEADERS = 2;
+
+ public RegularExpressionFilter(String aName) {
+ this(aName, false, false, null);
+ }
+
+ public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {
+ this (aName, aCaseSensitive, anExactMatch, ENTITY_FIELDS, aSelectedFields);
+ }
+
+ public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, int aFieldKind, String[] aSelectedFields) {
+ super(aName);
+
+ fieldKind = aFieldKind;
+
+ caseSensitive = aCaseSensitive;
+ exactMatch = anExactMatch;
+ if (aSelectedFields==null)
+ selectedFields = null;
+ else
+ selectedFields = Arrays.asList(aSelectedFields);
+ }
+
+ public boolean validate(String anExpression) {
+ try {
+ new RE(anExpression);
+ return true;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ };
+
+ public boolean test(String anExpression, Entity anEntity, Request aRequest) {
+ try {
+ Iterator j;
+ int flags = 0;
+
+ if (!caseSensitive) {
+ flags |= RE.REG_ICASE;
+ }
+
+ RE regularExpression = new RE(anExpression, flags);
+
+ switch (fieldKind) {
+ case REQUEST_HEADERS:
+ if (selectedFields != null) {
+ j = selectedFields.iterator();
+
+ while (j.hasNext()) {
+ String fieldName = (String) j.next();
+ String field = aRequest.getHeader(fieldName);
+
+ if (exactMatch) {
+ if (field != null && regularExpression.isMatch(field)) {
+ return true;
+ }
+ }
+ else {
+ if (field != null && regularExpression.getMatch(field) != null) {
+ return true;
+ }
+ }
+ }
+ }
+ break;
+ case ENTITY_FIELDS:
+ if (selectedFields != null)
+ j = selectedFields.iterator();
+ else
+ j = anEntity.getFieldNames().iterator();
+
+ while (j.hasNext()) {
+ String field = anEntity.getFieldValue( (String) j.next());
+
+ if (exactMatch) {
+ if (field != null && regularExpression.isMatch(field)) {
+ return true;
+ }
+ }
+ else {
+ if (field != null && regularExpression.getMatch(field) != null) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ catch (Throwable t) {
+ }
+ return false;
+ }
+ }
+
}
\ No newline at end of file
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import mir.entity.Entity;\r
-import mir.misc.StringUtil;\r
-import mir.session.Request;\r
-import mir.session.Response;\r
-import mir.session.Session;\r
-import mir.session.SessionExc;\r
-import mir.session.SessionFailure;\r
-import mir.session.UploadedFile;\r
-import mir.session.ValidationError;\r
-import mir.session.ValidationHelper;\r
-import mir.util.ExceptionFunctions;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.media.MediaUploadProcessor;\r
-import mircoders.module.ModuleContent;\r
-import mircoders.module.*;\r
-import mircoders.storage.*;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseContentToMedia;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-\r
-/**\r
- *\r
- * <p>Title: Experimental session handler for article postings </p>\r
- * <p>Description: </p>\r
- * <p>Copyright: Copyright (c) 2003</p>\r
- * <p>Company: </p>\r
- * @author Zapata\r
- * @version 1.0\r
- */\r
-\r
-public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {\r
- protected ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());\r
- protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();\r
- protected DatabaseContent contentDatabase = DatabaseContent.getInstance();\r
-\r
- public MirBasicArticlePostingHandler() {\r
- super();\r
-\r
- setResponseGenerators(\r
- configuration.getString("Localizer.OpenSession.article.EditTemplate"),\r
- configuration.getString("Localizer.OpenSession.article.DupeTemplate"),\r
- configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),\r
- configuration.getString("Localizer.OpenSession.article.DoneTemplate"));\r
- }\r
-\r
- protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
- super.initializeResponseData(aRequest, aSession, aResponse);\r
-\r
- Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
- while (i.hasNext()) {\r
- String field = (String) i.next();\r
- aResponse.setResponseValue(field, aRequest.getParameter(field));\r
- }\r
- aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));\r
- }\r
-\r
- public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
- super.validate(aResults, aRequest, aSession);\r
-\r
- ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);\r
- ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);\r
- ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);\r
- ValidationHelper.testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);\r
- }\r
-\r
- public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {\r
- try {\r
- anArticle.setValueForProperty("is_published", "1");\r
- anArticle.setValueForProperty("is_produced", "0");\r
- anArticle.setValueForProperty("date",\r
- StringUtil.date2webdbDate(new GregorianCalendar()));\r
- anArticle.setValueForProperty("is_html", "0");\r
- anArticle.setValueForProperty("publish_path",\r
- StringUtil.webdbDate2path(anArticle.\r
- getValue("date")));\r
- ModuleArticleType module = new ModuleArticleType(DatabaseArticleType.\r
- getInstance());\r
-\r
- anArticle.setValueForProperty("to_article_type",\r
- module.articleTypeIdForName(configuration.\r
- getString("Localizer.OpenSession.article.DefaultArticleType")));\r
- anArticle.setValueForProperty("to_publisher", "1");\r
- }\r
- catch (Throwable t) {\r
- throw new SessionFailure(t);\r
- }\r
- }\r
-\r
- public void setArticleTopics(Request aRequest, Session aSession, EntityContent aContent) throws SessionExc, SessionFailure {\r
- // topics:\r
- List topics = aRequest.getParameters("to_topic");\r
- if (topics.size() > 0) {\r
- try {\r
- DatabaseContentToTopics.getInstance().setTopics(aContent.getId(), topics);\r
- }\r
- catch (Throwable e) {\r
- logger.error("setting content_x_topic failed");\r
- throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);\r
- }\r
- }\r
- }\r
-\r
- public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
- try {\r
- String id;\r
- Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
-\r
- EntityContent article = (EntityContent) contentModule.createNew();\r
- article.setValues(values);\r
-\r
- finalizeArticle(aRequest, aSession, article);\r
- id = article.insert();\r
- if (id == null) {\r
- logger.info("Duplicate article rejected");\r
- throw new DuplicatePostingExc("Duplicate article rejected");\r
- }\r
- aSession.setAttribute("content", article);\r
-\r
-\r
- setArticleTopics(aRequest, aSession, article);\r
-\r
- }\r
- catch (Throwable t) {\r
- throw new SessionFailure(t);\r
- }\r
- }\r
-\r
- public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {\r
- try {\r
- Map values = new HashMap();\r
- values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));\r
- values.put("creator", aRequest.getParameter("creator"));\r
- values.put("to_publisher", "0");\r
- values.put("is_published", "1");\r
- values.put("is_produced", "1");\r
- Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);\r
- mediaItem.update();\r
- contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());\r
- }\r
- catch (Throwable t) {\r
- throw new SessionFailure(t);\r
- }\r
- }\r
-\r
- public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
- EntityContent article = (EntityContent) aSession.getAttribute("content");\r
-\r
- MirGlobal.abuse().checkArticle(article, aRequest, null);\r
- try {\r
- MirGlobal.localizer().openPostings().afterContentPosting(article);\r
- }\r
- catch (Throwable t) {\r
- throw new SessionFailure(t);\r
- }\r
- logger.info("article posted");\r
- };\r
-\r
-}
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.localizer.basic;
+
+import mir.entity.Entity;
+import mir.misc.StringUtil;
+import mir.session.*;
+import mircoders.entity.EntityContent;
+import mircoders.global.MirGlobal;
+import mircoders.media.MediaUploadProcessor;
+import mircoders.module.ModuleArticleType;
+import mircoders.module.ModuleContent;
+import mircoders.module.ModuleMediafolder;
+import mircoders.storage.*;
+
+import java.util.*;
+
+/**
+ * Extensible handler for open article postings
+ */
+
+public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {
+ protected ModuleContent contentModule = new ModuleContent();
+ protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();
+ protected DatabaseContent contentDatabase = DatabaseContent.getInstance();
+
+ public MirBasicArticlePostingHandler() {
+ this(false);
+ }
+
+ public MirBasicArticlePostingHandler(boolean aPersistentUploadedFiles) {
+ super(aPersistentUploadedFiles);
+
+ setResponseGenerators(
+ configuration.getString("Localizer.OpenSession.article.EditTemplate"),
+ configuration.getString("Localizer.OpenSession.article.DupeTemplate"),
+ configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),
+ configuration.getString("Localizer.OpenSession.article.DoneTemplate"));
+ }
+ /**
+ * {@inheritDoc}
+ */
+ protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ super.initializeResponseData(aRequest, aSession, aResponse);
+
+ Iterator i = DatabaseContent.getInstance().getFields().iterator();
+ while (i.hasNext()) {
+ String field = (String) i.next();
+ aResponse.setResponseValue(field, aRequest.getParameter(field));
+ }
+ aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ super.validate(aResults, aRequest, aSession);
+
+ ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);
+ ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);
+ ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);
+ ValidationHelper.testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);
+ }
+ /**
+ * Called just before the article is stored in the database.
+ * The last opportunity to alter fields.
+ */
+ public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
+ try {
+ anArticle.setFieldValue("is_published", "1");
+ anArticle.setFieldValue("is_produced", "0");
+ anArticle.setFieldValue("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+ anArticle.setFieldValue("is_html", "0");
+ anArticle.setFieldValue("publish_path", StringUtil.webdbDate2path(anArticle. getFieldValue("date")));
+
+ ModuleArticleType module = new ModuleArticleType();
+ anArticle.setFieldValue("to_article_type", module.articleTypeIdForName(configuration.getString("Localizer.OpenSession.article.DefaultArticleType")));
+ anArticle.setFieldValue("to_publisher", "1");
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+ /**
+ * Extracts topics from the request and associated the
+ * article to them.
+ */
+ public void setArticleTopics(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
+ // topics:
+ List topics = aRequest.getParameters("to_topic");
+ if (topics.size() > 0) {
+ try {
+ DatabaseContentToTopics.getInstance().setTopics(anArticle.getId(), topics);
+ }
+ catch (Throwable e) {
+ logger.error("setting content_x_topic failed");
+ throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);
+ }
+ }
+ }
+
+ public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ try {
+ String id;
+ Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());
+
+ EntityContent article = (EntityContent) contentModule.createNew();
+ article.setFieldValues(values);
+
+ finalizeArticle(aRequest, aSession, article);
+ id = article.insert();
+ if (id == null) {
+ logger.info("Duplicate article rejected");
+ throw new DuplicatePostingExc("Duplicate article rejected");
+ }
+ aSession.setAttribute("content", article);
+
+ setArticleTopics(aRequest, aSession, article);
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+ public void processAttachment(Request aRequest, Session aSession, Attachment aFile) throws SessionExc, SessionFailure {
+ try {
+ Map values = new HashMap();
+ values.put("creator", aRequest.getParameter("creator"));
+ values.putAll(aFile.getAllAttributes());
+ values.put("creator", aRequest.getParameter("creator"));
+ values.put("to_publisher", "0");
+ values.put("is_published", "1");
+ values.put("is_produced", "1");
+ ModuleMediafolder module = new ModuleMediafolder();
+ values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.article.DefaultMediaFolder")));
+
+ Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);
+ mediaItem.update();
+ contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ }
+
+ public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ EntityContent article = (EntityContent) aSession.getAttribute("content");
+
+ MirGlobal.abuse().checkArticle(article, aRequest, null);
+ try {
+ MirGlobal.localizer().openPostings().afterContentPosting(article);
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
+ logger.info("article posted");
+ };
+
+}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.localizer.basic;\r
-\r
-import mir.session.Request;\r
-import mir.session.Session;\r
-import mir.session.SessionExc;\r
-import mir.session.SessionFailure;\r
-import mircoders.entity.EntityContent;\r
-\r
-\r
-public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler {\r
- public MirBasicChildArticlePostingHandler() {\r
- super();\r
-\r
- setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate"));\r
- }\r
-\r
- public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {\r
- super.finalizeArticle(aRequest, aSession, anArticle);\r
-\r
- anArticle.setValueForProperty("to_content", (String) aSession.getAttribute("to_content"));\r
- }\r
-\r
- protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
- super.initializeSession(aRequest, aSession);\r
-\r
- String parentId = aRequest.getParameter("to_content");\r
- if (parentId==null)\r
- throw new SessionExc("initializeSession: parent id not set!");\r
-\r
- aSession.setAttribute("to_content", parentId);\r
- };\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.localizer.basic;
+
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mircoders.entity.EntityContent;
+
+/**
+ * Handler for open postings of "child articles", that is articles
+ * linked to other articles. Used frequently for translations.
+ */
+public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler {
+ public MirBasicChildArticlePostingHandler() {
+ super();
+
+ setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate"));
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>
+ * This class overrides this method to set the parent article.
+ */
+ public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
+ super.finalizeArticle(aRequest, aSession, anArticle);
+
+ anArticle.setFieldValue("to_content", (String) aSession.getAttribute("to_content"));
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>
+ * Overridden by this class to retrieve and store the to be associated
+ * parent article for subsequent usage.
+ */
+ protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ super.initializeSession(aRequest, aSession);
+
+ String parentId = aRequest.getParameter("to_content");
+ if (parentId==null)
+ throw new SessionExc("initializeSession: parent id not set!");
+
+ aSession.setAttribute("to_content", parentId);
+ };
}
\ No newline at end of file
*/
package mircoders.localizer.basic;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
import mir.entity.Entity;
-import mir.session.Request;
-import mir.session.Response;
-import mir.session.Session;
-import mir.session.SessionExc;
-import mir.session.SessionFailure;
-import mir.session.UploadedFile;
-import mir.session.ValidationError;
-import mir.session.ValidationHelper;
-import mir.util.ExceptionFunctions;
+import mir.session.*;
import mircoders.entity.EntityComment;
import mircoders.global.MirGlobal;
import mircoders.media.MediaUploadProcessor;
import mircoders.module.ModuleComment;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseCommentToMedia;
-import mircoders.storage.DatabaseContent;
+import mircoders.module.ModuleCommentStatus;
+import mircoders.module.ModuleMediafolder;
+import mircoders.storage.*;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
/**
*
*/
public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler {
- protected ModuleComment commentModule = new ModuleComment(DatabaseComment.getInstance());
+ protected ModuleComment commentModule = new ModuleComment();
protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance();
public MirBasicCommentPostingHandler() {
- super();
+ this(false);
+ }
+
+
+ public MirBasicCommentPostingHandler(boolean aPersistentUploadedFiles) {
+ super(aPersistentUploadedFiles);
setResponseGenerators(
configuration.getString("Localizer.OpenSession.comment.EditTemplate"),
};
public void finalizeComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure {
- aComment.setValueForProperty("is_published", "1");
- aComment.setValueForProperty("to_comment_status", "1");
- aComment.setValueForProperty("is_html","0");
- aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media"));
+ try {
+ aComment.setFieldValue("is_published", "1");
+ ModuleCommentStatus module = new ModuleCommentStatus();
+ aComment.setFieldValue("to_comment_status", module.commentStatusIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultCommentStatus")));
+ aComment.setFieldValue("is_html", "0");
+ aComment.setFieldValue("to_media", (String) aSession.getAttribute("to_media"));
+ }
+ catch (Throwable t) {
+ throw new SessionFailure(t);
+ }
}
public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
Map values = getIntersectingValues(aRequest, DatabaseComment.getInstance());
EntityComment comment = (EntityComment) commentModule.createNew();
- comment.setValues(values);
+ comment.setFieldValues(values);
finalizeComment(aRequest, aSession, comment);
id = comment.insert();
if (id == null) {
}
}
- public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
+ public void processAttachment(Request aRequest, Session aSession, Attachment aFile) throws SessionExc, SessionFailure {
try {
Map values = new HashMap();
- values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));
values.put("creator", aRequest.getParameter("creator"));
+ values.putAll(aFile.getAllAttributes());
values.put("to_publisher", "0");
values.put("is_published", "1");
+ ModuleMediafolder module = new ModuleMediafolder();
+ values.put("to_media_folder", module.mediaFolderIdForName(configuration.getString("Localizer.OpenSession.comment.DefaultMediaFolder")));
+
Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);
mediaItem.update();
commentToMedia.addMedia(((EntityComment) aSession.getAttribute("comment")).getId(), mediaItem.getId());
catch (Throwable t) {
throw new SessionFailure(t);
}
- DatabaseContent.getInstance().setUnproduced("id=" + comment.getValue("to_media"));
+ DatabaseContent.getInstance().setUnproduced("id=" + comment.getFieldValue("to_media"));
logger.info("Comment posted");
};
*/\r
package mircoders.localizer.basic;\r
\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
import mir.config.MirPropertiesConfiguration;\r
import mir.entity.Entity;\r
import mir.entity.adapter.EntityAdapter;\r
import mir.entity.adapter.EntityAdapterDefinition;\r
import mir.entity.adapter.EntityAdapterModel;\r
+import mir.generator.Generator;\r
+import mir.generator.GeneratorExc;\r
+import mir.generator.GeneratorFailure;\r
import mir.log.LoggerWrapper;\r
-import mir.media.MediaHelper;\r
-import mir.media.MirMedia;\r
+import mir.media.MediaHandler;\r
+import mir.misc.NumberUtils;\r
+import mir.util.JDBCStringRoutines;\r
import mir.util.ParameterExpander;\r
import mir.util.RewindableIterator;\r
import mir.util.StructuredContentParser;\r
import mircoders.localizer.MirDataModelLocalizer;\r
import mircoders.localizer.MirLocalizerExc;\r
import mircoders.localizer.MirLocalizerFailure;\r
-import mircoders.storage.DatabaseArticleType;\r
-import mircoders.storage.DatabaseAudio;\r
-import mircoders.storage.DatabaseBreaking;\r
-import mircoders.storage.DatabaseComment;\r
-import mircoders.storage.DatabaseCommentStatus;\r
-import mircoders.storage.DatabaseContent;\r
-import mircoders.storage.DatabaseContentToMedia;\r
-import mircoders.storage.DatabaseContentToTopics;\r
-import mircoders.storage.DatabaseImageType;\r
-import mircoders.storage.DatabaseImages;\r
-import mircoders.storage.DatabaseLanguage;\r
-import mircoders.storage.DatabaseMediaType;\r
-import mircoders.storage.DatabaseMediafolder;\r
-import mircoders.storage.DatabaseMessages;\r
-import mircoders.storage.DatabaseOther;\r
-import mircoders.storage.DatabaseTopics;\r
-import mircoders.storage.DatabaseUploadedMedia;\r
-import mircoders.storage.DatabaseUsers;\r
-import mircoders.storage.DatabaseVideo;\r
-\r
-public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {\r
- protected LoggerWrapper logger;\r
- protected MirPropertiesConfiguration configuration;\r
+import mircoders.media.MediaHelper;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.module.ModuleLanguage;\r
+import mircoders.storage.*;\r
+import multex.Failure;\r
\r
- public MirBasicDataModelLocalizer() throws MirLocalizerFailure, MirLocalizerExc {\r
- logger = new LoggerWrapper("Localizer.DataModel");\r
+import java.util.*;\r
\r
- try {\r
- configuration = MirPropertiesConfiguration.instance();\r
- }\r
- catch (Throwable e) {\r
- throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e);\r
- }\r
- }\r
+public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {\r
+ protected LoggerWrapper logger = new LoggerWrapper("Localizer.DataModel");\r
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();\r
+ protected ModuleLanguage languageModule = new ModuleLanguage();\r
\r
protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc {\r
try {\r
anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange", configuration.getString("Mir.DefaultTimezone"));\r
anEntityAdapterDefinition.addMirDateField("date", "date", configuration.getString("Mir.DefaultTimezone"));\r
+\r
+ anEntityAdapterDefinition.addCalculatedField("lockinguser", new ContentToUserField("to_locking_user"));\r
+ anEntityAdapterDefinition.addCalculatedField("is_locked", new ContentToIsLockedField());\r
+\r
anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField());\r
anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField());\r
anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField());\r
anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'"));\r
anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField(""));\r
\r
+\r
+ anEntityAdapterDefinition.addCalculatedField("mediacount", new ContentMediaCountField("uploaded_media", true));\r
+ anEntityAdapterDefinition.addCalculatedField("fullmediacount", new ContentMediaCountField("uploaded_media", false));\r
+\r
anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" ));\r
anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" ));\r
anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" ));\r
anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" ));\r
anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" ));\r
+\r
+ anEntityAdapterDefinition.addCalculatedField("firstImage", new ContentToFirstMediaField( "image" ));\r
+ anEntityAdapterDefinition.addCalculatedField("firstAudio", new ContentToFirstMediaField( "audio" ));\r
+ anEntityAdapterDefinition.addCalculatedField("firstVideo", new ContentToFirstMediaField( "video" ));\r
+ anEntityAdapterDefinition.addCalculatedField("firstOther", new ContentToFirstMediaField( "otherMedia" ));\r
+\r
anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false));\r
anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new ContentToMediaField( "image", false));\r
anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false));\r
\r
anEntityAdapterDefinition.addCalculatedField("operations",\r
new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));\r
+ \r
+ anEntityAdapterDefinition.addCalculatedField("languagename", new ContentToLanguageNameField());\r
+\r
+ anEntityAdapterDefinition.addCalculatedField("is_original", new ContentIsOriginalField());\r
+ anEntityAdapterDefinition.addCalculatedField("to_original", new ContentToOriginalField());\r
+ anEntityAdapterDefinition.addCalculatedField("to_translations", new ContentToTranslationsField());\r
+ anEntityAdapterDefinition.addCalculatedField("to_translation", new ContentToTranslationField());\r
+\r
+ anEntityAdapterDefinition.addCalculatedField("previews", new EntityAdapterDefinition.CalculatedField() {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return MirGlobal.localizer().adminInterface().getPreviewPages(anEntityAdapter);\r
+ }\r
+ catch (MirLocalizerExc e) {\r
+ throw new Failure("Cannot get previews for article", e);\r
+ }\r
+ }\r
+ });\r
}\r
catch (Throwable t) {\r
throw new MirLocalizerFailure(t.getMessage(), t);\r
}\r
}\r
\r
+\r
+\r
protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure {\r
try {\r
anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
definition = new EntityAdapterDefinition();\r
constructCommentAdapterDefinition( definition );\r
result.addMapping( "comment", DatabaseComment.getInstance(), definition);\r
+ result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());\r
\r
result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());\r
+\r
+ result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());\r
+\r
\r
definition = new EntityAdapterDefinition();\r
definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
\r
definition = new EntityAdapterDefinition();\r
definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("info", new MediaToMediaInfoField());\r
result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), definition);\r
definition = new EntityAdapterDefinition();\r
definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("info", new MediaToMediaInfoField());\r
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
result.addMapping( "image", DatabaseImages.getInstance(), definition);\r
definition = new EntityAdapterDefinition();\r
definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("info", new MediaToMediaInfoField());\r
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
result.addMapping( "audio", DatabaseAudio.getInstance(), definition);\r
definition = new EntityAdapterDefinition();\r
definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("info", new MediaToMediaInfoField());\r
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
result.addMapping( "video", DatabaseVideo.getInstance(), definition);\r
+\r
definition = new EntityAdapterDefinition();\r
definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+ definition.addCalculatedField("human_readable_size", new HumanReadableSizeField("value"));\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("info", new MediaToMediaInfoField());\r
+ definition.addCalculatedField("big_icon", new MediaToBigIconField());\r
result.addMapping( "otherMedia", DatabaseOther.getInstance(), definition);\r
\r
\r
result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition());\r
result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());\r
result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition());\r
- result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition());\r
+\r
+ definition = new EntityAdapterDefinition();\r
+ definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addDBDateField("lastlogindate", "lastlogin", configuration.getString("Mir.DefaultTimezone"));\r
+ definition.addCalculatedField("structuredProfile", new StructuredContentField("profile"));\r
+ result.addMapping( "user", DatabaseUsers.getInstance(), definition);\r
\r
result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition());\r
\r
protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField {\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
- logger.debug("ContentToParentField.getValue");\r
+ logger.debug("ContentToParentField.getFieldValue");\r
return anEntityAdapter.getToOneRelation(\r
"id="+anEntityAdapter.get("to_content"),\r
"id",\r
}\r
}\r
\r
+ public static class MediaInfo {\r
+ private MediaHandler mediaHandler;\r
+\r
+ public MediaInfo(MediaHandler aHandler) {\r
+ mediaHandler = aHandler;\r
+ }\r
+ public String getBigIcon() {\r
+ if (mediaHandler == null)\r
+ return "bla";\r
+ else\r
+ return mediaHandler.getBigIconName();\r
+ }\r
+\r
+ public String getSmallIcon() {\r
+ if (mediaHandler == null)\r
+ return "bla";\r
+ else\r
+ return mediaHandler.getTinyIconName();\r
+ }\r
+\r
+ public String getMediaType() {\r
+ return "";\r
+ }\r
+ }\r
+\r
+ protected class MediaToMediaInfoField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ MediaHandler mediaHandler = MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType());\r
+\r
+ return new MediaInfo(mediaHandler);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class MediaToBigIconField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return MediaHelper.getHandler(((EntityUploadedMedia) anEntityAdapter.getEntity()).getMediaType()).getBigIconName();\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField {\r
private String extracondition;\r
private String order;\r
\r
protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField {\r
private String topicCondition;\r
+ private String topicOrder;\r
\r
public ContentToTopicsField() {\r
this(null);\r
}\r
\r
public ContentToTopicsField(String aTopicCondition) {\r
+ this(aTopicCondition, "title");\r
+ }\r
+\r
+ public ContentToTopicsField(String aTopicCondition, String aTopicOrder) {\r
topicCondition = aTopicCondition;\r
+ topicOrder = aTopicOrder;\r
}\r
\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
- String condition = "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)";\r
+\r
+ Vector extraTable = new Vector();\r
+ extraTable.add("content_x_topic cxt");\r
+ String condition = "cxt.content_id="+anEntityAdapter.get("id")+\r
+ " and cxt.topic_id=t.id";\r
+\r
if (topicCondition!=null && topicCondition.length()>0)\r
condition = "(" + topicCondition + ") and " + condition;\r
\r
- return anEntityAdapter.getRelation(\r
- condition,\r
- "title",\r
- "topic" );\r
+ return anEntityAdapter.getComplexRelation("t", extraTable,\r
+ condition, topicOrder, "topic" );\r
}\r
catch (Throwable t) {\r
throw new RuntimeException(t.getMessage());\r
\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
- String condition = "exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)";\r
+ String condition = "cxm.content_id="+ anEntityAdapter.get("id") +\r
+ " and cxm.media_id = m.id";\r
if (published)\r
condition = "is_published='t' and " + condition;\r
- return anEntityAdapter.getRelation(\r
- condition,\r
- "id",\r
- definition);\r
+\r
+ List extraTables = new Vector();\r
+ extraTables.add("content_x_media cxm");\r
+\r
+ return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToFirstMediaField implements EntityAdapterDefinition.CalculatedField {\r
+ private String definition;\r
+ private boolean published;\r
+\r
+ public ContentToFirstMediaField(String aDefinition, boolean anOnlyPublished) {\r
+ definition = aDefinition;\r
+ published = anOnlyPublished;\r
+ }\r
+\r
+ public ContentToFirstMediaField(String aDefinition) {\r
+ this(aDefinition, true);\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ String condition = "cxm.content_id="+ anEntityAdapter.get("id") +\r
+ " and cxm.media_id = m.id";\r
+ if (published)\r
+ condition = "is_published='t' and " + condition;\r
+\r
+ List extraTables = new Vector();\r
+ extraTables.add("content_x_media cxm");\r
+\r
+ return anEntityAdapter.getComplexToOneRelation("m", extraTables, condition, "id", definition);\r
}\r
catch (Throwable t) {\r
throw new RuntimeException(t.getMessage());\r
\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
- String condition = "exists (select * from comment_x_media where comment_id="+anEntityAdapter.get("id")+" and media_id=id)";\r
+\r
+ String condition = "cxm.comment_id="+ anEntityAdapter.get("id") +\r
+ " and cxm.media_id = m.id";\r
if (published)\r
- condition = "is_published='t' and " + condition;\r
- return anEntityAdapter.getRelation(\r
- condition,\r
- "id",\r
- definition);\r
+ condition = "is_published='t' and " + condition;\r
+\r
+ List extraTables = new Vector();\r
+ extraTables.add("comment_x_media cxm");\r
+ return anEntityAdapter.getComplexRelation("m", extraTables, condition, "id", definition);\r
+\r
}\r
catch (Throwable t) {\r
throw new RuntimeException(t.getMessage());\r
Entity mediaType;\r
RewindableIterator iterator;\r
Map result;\r
- MirMedia mediaHandler;\r
+ MediaHandler mediaHandler;\r
String tinyIcon;\r
String iconAlt;\r
\r
mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType();\r
mediaHandler = MediaHelper.getHandler( mediaType );\r
\r
- if (mediaHandler.isVideo()) {\r
- tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo");\r
- iconAlt = "Video";\r
- }\r
- else if (mediaHandler.isAudio()) {\r
- tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio");\r
- iconAlt = "Audio";\r
- }\r
- else if (mediaHandler.isImage()) {\r
- tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage");\r
- iconAlt = "Image";\r
- }\r
- else {\r
- tinyIcon = mediaHandler.getTinyIconName();\r
- iconAlt = mediaHandler.getIconAltName();\r
- }\r
-\r
+ tinyIcon = mediaHandler.getTinyIconName();\r
+ iconAlt = mediaHandler.getIconAltName();\r
}\r
}\r
catch (Throwable t) {\r
}\r
}\r
\r
+ protected class HumanReadableSizeField implements EntityAdapterDefinition.CalculatedField {\r
+ private String fieldName;\r
+\r
+ public HumanReadableSizeField(String aFieldName) {\r
+ fieldName= aFieldName;\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ String size = (String) anEntityAdapter.get(fieldName);\r
+ if (size!=null)\r
+ return NumberUtils.humanReadableSize(Double.parseDouble(size));\r
+ else\r
+ return "";\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+\r
protected class ContentMediaCountField implements EntityAdapterDefinition.CalculatedField {\r
private String table;\r
private boolean published;\r
\r
public Object getValue(EntityAdapter anEntityAdapter) {\r
try {\r
- String subQuery = "select * from "+table+" where id = media_id";\r
+ Vector extraTable = new Vector();\r
+ extraTable.add(table+" m");\r
+ String selectSql = "cxm.media_id=m.id and cxm.content_id="+\r
+ anEntityAdapter.get("id");\r
if (published)\r
- subQuery = subQuery + " and is_published='t'";\r
+ selectSql+= " and m.is_published='t'";\r
\r
return Integer.toString(\r
DatabaseContentToMedia.getInstance().getSize(\r
- "exists ("+subQuery+")"));\r
+ "cxm", extraTable, selectSql));\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToUserField implements EntityAdapterDefinition.CalculatedField {\r
+ private String fieldName;\r
+\r
+ public ContentToUserField(String aFieldName) {\r
+ fieldName = aFieldName;\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return anEntityAdapter.getToOneRelation(\r
+ "id=" + anEntityAdapter.get(fieldName),\r
+ "id",\r
+ "user");\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToIsLockedField implements EntityAdapterDefinition.CalculatedField {\r
+ private ModuleContent contentModule;\r
+\r
+ public ContentToIsLockedField() {\r
+ contentModule = new ModuleContent();\r
+ }\r
+\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return new Boolean(contentModule.queryArticleLock(anEntityAdapter.getEntity().getId())!=null);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new RuntimeException(t.getMessage());\r
+ }\r
+ }\r
+ }\r
+ protected class ContentIsOriginalField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
+ try {\r
+\r
+ //ML: add check on article type\r
+ boolean result = (anEntityAdapter.get("parent")==null);\r
+\r
+ return new Boolean(result);\r
+ }\r
+ catch (Throwable t) {\r
+ throw new MirLocalizerFailure(t);\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToOriginalField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
+ try {\r
+ if (anEntityAdapter.get("parent")!=null)\r
+ return anEntityAdapter.get("parent");\r
+ else\r
+ return anEntityAdapter;\r
+ }\r
+ catch (Throwable t) {\r
+ throw new MirLocalizerFailure(t);\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToTranslationsField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) {\r
+ try {\r
+ return anEntityAdapter.getRelation(\r
+ "is_published='t' and to_content="+anEntityAdapter.get("id"),\r
+ "id",\r
+ "content" );\r
}\r
catch (Throwable t) {\r
throw new RuntimeException(t.getMessage());\r
}\r
}\r
}\r
+\r
+ protected class ContentToLanguageNameField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
+ try {\r
+ String result = "";\r
+ EntityAdapter language = (EntityAdapter) anEntityAdapter.get("language");\r
+ if (language != null) {\r
+ if (language.get("code").equals("ot")) {\r
+ result = ((String) anEntityAdapter.get("subtitle")).trim();\r
+ if (result == null || result.equals(""))\r
+ result = (String) language.get("name");\r
+ } else {\r
+ result = (String) language.get("name");\r
+ }\r
+ }\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable t) {\r
+ throw new MirLocalizerFailure(t);\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToTranslationFunction implements Generator.Function {\r
+ private EntityAdapter target;\r
+ private String targetId;\r
+ private String targetLanguageId;\r
+\r
+ public ContentToTranslationFunction(EntityAdapter aTarget) {\r
+ target = aTarget;\r
+ targetId = (String) target.get("id");\r
+ targetLanguageId = (String) target.get("to_language");\r
+ }\r
+\r
+ public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {\r
+ if (aParameters.size()!=1 || !(aParameters.get(0) instanceof String))\r
+ throw new GeneratorExc("1 string parameter expected");\r
+\r
+ try {\r
+ String language = (String) aParameters.get(0);\r
+ String languageId = languageModule.languageIdForCode(language);\r
+ Object result = null;\r
+\r
+ if (languageId != null && !targetLanguageId.equals(languageId)) {\r
+ result = target.getToOneRelation(\r
+ "is_published='t' and to_content=" + targetId + " and to_language='" + JDBCStringRoutines.escapeStringLiteral(languageId) + "'",\r
+ "id", "content");\r
+ }\r
+\r
+ if (result == null)\r
+ result = target;\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable t) {\r
+ t.printStackTrace(System.out);\r
+ throw new GeneratorFailure(t);\r
+ }\r
+ }\r
+ }\r
+\r
+ protected class ContentToTranslationField implements EntityAdapterDefinition.CalculatedField {\r
+ public Object getValue(EntityAdapter anEntityAdapter) throws MirLocalizerFailure {\r
+ try {\r
+ return new ContentToTranslationFunction((EntityAdapter) anEntityAdapter.get("to_original"));\r
+ }\r
+ catch (Throwable t) {\r
+ throw new MirLocalizerFailure(t);\r
+ }\r
+ }\r
+ }\r
}\r
+\r
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer.basic;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Vector;
+import java.util.Collections;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.generator.Generator;
+import mir.generator.GeneratorHelper;
+import mir.log.LoggerWrapper;
+import mir.session.Request;
+import mir.session.Response;
+import mir.session.Session;
+import mir.session.SessionExc;
+import mir.session.SessionFailure;
+import mir.session.SessionHandler;
+import mir.session.ValidationHelper;
+import mir.session.HTTPAdapters.HTTPRequestAdapter;
+import mir.util.StringRoutines;
+import mircoders.entity.EntityContent;
+import mircoders.global.CacheKey;
+import mircoders.global.MirGlobal;
+import mircoders.module.ModuleContent;
+import mircoders.storage.DatabaseContent;
+
+import org.apache.commons.net.smtp.SMTPClient;
+import org.apache.commons.net.smtp.SMTPReply;
+
+
+/**
+ *
+ * <p>Title: Tenative session handler for emailing postings </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author john
+ * @version 1.0
+ */
+
+
+public class MirBasicEmailArticleHandler implements SessionHandler {
+ protected LoggerWrapper logger;
+ protected MirPropertiesConfiguration configuration;
+
+ public MirBasicEmailArticleHandler() {
+ logger = new LoggerWrapper("Localizer.EmailArticle");
+ try {
+ configuration = MirPropertiesConfiguration.instance();
+ }
+ catch (Throwable t) {
+ logger.fatal("Cannot load configuration: " + t.toString());
+
+ throw new RuntimeException("Cannot load configuration: " + t.toString());
+ }
+ }
+
+ public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ if (aSession.getAttribute("initialRequest") == null) {
+ aSession.setAttribute("initialRequest", "no");
+ initialRequest(aRequest, aSession, aResponse);
+ }
+ else {
+ subsequentRequest(aRequest, aSession, aResponse);
+ }
+ }
+
+ protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ initializeSession(aRequest, aSession);
+ makeInitialResponse(aRequest, aSession, aResponse);
+ }
+
+ protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ /* do nothing for now */
+
+ }
+
+ protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ /* if you do not supply an aid to this handler, it should return an error page */
+ /* if you supply a non-functioning/non-published aid to this handler, it should return an error page, but at a
+ later stage, because we don't check the db until we are potentially populating the cache*/
+ /* otherwise you get to address an article and add some comments */
+ String articleID = aRequest.getParameter("mail_aid");
+ if (articleID == null){
+ throw new SessionExc("makeInitialResponse: article id not set!");
+ }
+ else {
+ aSession.setAttribute("email.aid",articleID);
+ aResponse.setResponseValue("errors", null);
+
+ String mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
+ aResponse.setResponseValue("mail_language",mail_language);
+ aResponse.setResponseValue("mail_to","");
+ aResponse.setResponseValue("mail_from","");
+ aResponse.setResponseValue("mail_from_name","");
+ aResponse.setResponseValue("mail_comment","");
+
+ aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
+
+
+ }
+ }
+
+ protected boolean shouldSendMail(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
+ if (validate(aRequest,aSession,aResponse,aValidationErrors)){
+ String to=aRequest.getParameter("mail_to");
+ if (to.indexOf('@') == -1
+ || to.indexOf('\n') != -1
+ || to.indexOf('\r') != -1
+ || to.indexOf(',') != -1) {
+ throw new SessionExc("Invalid to address"); // we might want to see this in a log, so it is not a validation error
+ }
+ else return true; // go for it
+ }
+ else{
+ return false; //validation failed, but not in a potentially abusive way
+ }
+
+ }
+
+
+
+
+
+ protected boolean validate(Request aRequest, Session aSession, Response aResponse,List aValidationErrors) throws SessionExc, SessionFailure{
+
+ if (ValidationHelper.testFieldEntered(aRequest, "mail_to", "validationerror.missing", aValidationErrors))
+ aResponse.setResponseValue("mail_to",aRequest.getParameter("mail_to"));
+ if (ValidationHelper.testFieldEntered(aRequest, "mail_from", "validationerror.missing", aValidationErrors))
+ aResponse.setResponseValue("mail_from",aRequest.getParameter("mail_from"));
+ if (ValidationHelper.testFieldEntered(aRequest, "mail_from_name", "validationerror.missing", aValidationErrors))
+ aResponse.setResponseValue("mail_from_name",aRequest.getParameter("mail_from_name"));
+ if (ValidationHelper.testFieldEntered(aRequest, "mail_language", "validationerror.missing", aValidationErrors))
+ aResponse.setResponseValue("mail_language",aRequest.getParameter("mail_language"));
+
+ return (aValidationErrors==null || aValidationErrors.size() == 0);
+ }
+
+ protected String getEmailText(String aid,String language) throws SessionExc{
+ String theText;
+ CacheKey theCacheKey=new CacheKey("email",aid+language);
+
+ if (MirGlobal.mruCache().hasObject(theCacheKey)){
+ logger.info("fetching email text for article "+aid+" from cache");
+ theText = (String) MirGlobal.mruCache().getObject(theCacheKey);
+ }
+ else {
+ try {
+ ModuleContent contentModule = new ModuleContent();
+ EntityContent contentEnt = (EntityContent) contentModule.getById(aid);
+
+ Map articleData = new HashMap();
+ articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
+ articleData.put("languagecode", language);
+ Map responseData = GeneratorHelper.makeBasicGenerationData(new Locale[] {new Locale(language,""),new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "")},"bundles.open","bundles.open");
+ responseData.put("data",articleData);
+
+ String emailAnArticleTemplate = configuration.getString("Localizer.OpenSession.email.MailTemplate");
+
+ Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(emailAnArticleTemplate);
+
+ StringWriter theEmailStringWriter = new StringWriter();
+ PrintWriter theEmailPrintWriter = new PrintWriter(theEmailStringWriter);
+ generator.generate(theEmailPrintWriter, responseData, logger);
+
+ theEmailStringWriter.close();
+
+ theText = theEmailStringWriter.toString();
+ MirGlobal.mruCache().storeObject(theCacheKey, theText);
+ }
+ catch (Throwable e) {
+ throw new SessionExc("Couldn't get content for article " + aid + language + ": " + e.getMessage());
+ }
+ }
+
+ return theText;
+ }
+
+ protected String getExtraEmailHeaders(Request aRequest,String to,String from) throws SessionExc {
+
+ String headers = "To: " + to + "\nReply-To: "+ from+"\n";;
+ if (configuration.getString("Localizer.OpenSession.email.includeSenderIP","no").equals("yes"))
+ headers= headers+"X-Originating-IP: "+ ((HTTPRequestAdapter)aRequest).getRequest().getRemoteAddr() + "\n";
+
+ return headers;
+ }
+
+ protected String interpolateComment(String emailText,String comment,String from_name,String language) throws SessionExc{
+ if (comment != null) {
+ String commentTextToInsert =
+ MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new String[] { language }).
+ getValue("email.comment.intro" , Collections.singletonList(from_name)) + "\n";
+
+ try {
+ emailText = StringRoutines.performRegularExpressionReplacement(emailText, "!COMMENT!", commentTextToInsert);
+ }
+ catch (Throwable e) {
+ throw new SessionExc("Problem doing regular expression replacement :" + e.toString());
+ }
+ }
+ else {
+ try {
+ emailText = StringRoutines.performRegularExpressionReplacement(emailText, "!COMMENT!", "");
+ }
+ catch (Throwable e) {
+ throw new SessionExc("Problem doing regular expression replacement " + e.toString());
+ }
+ }
+ return emailText;
+ }
+
+ protected boolean doTheSMTP(String aMessage,String aTo,String aFrom) throws SessionExc{
+ SMTPClient client=new SMTPClient();
+ try {
+ int reply;
+ client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
+ reply = client.getReplyCode();
+
+ if (!SMTPReply.isPositiveCompletion(reply)) {
+ client.disconnect();
+ throw new SessionExc("SMTP server refused connection.");
+ }
+ boolean trueIfItWorked = client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), aTo, aMessage);
+ client.disconnect();
+ // mission accomplished??
+ if (! trueIfItWorked)
+ throw new SessionExc(client.getReplyString());
+ else
+ return trueIfItWorked;
+ }
+ catch(IOException e) {
+ if(client.isConnected()) {
+ try {
+ client.disconnect();
+ } catch(IOException f) {
+ // do nothing
+ }
+ }
+ throw new SessionExc(e.getMessage());
+ }
+ }
+
+ protected boolean sendMail(Request aRequest,Session aSession,Response aResponse) throws SessionExc,SessionFailure {
+ String to=aRequest.getParameter("mail_to");
+ String from=aRequest.getParameter("mail_from");
+ String from_name=aRequest.getParameter("mail_from_name");
+ String language=aRequest.getParameter("mail_language");
+ String comment=aRequest.getParameter("mail_comment");
+
+ String theEmailText=getEmailText((String) aSession.getAttribute("email.aid"),language);
+ String headers=getExtraEmailHeaders(aRequest,to,from);
+ theEmailText=interpolateComment(theEmailText,comment,from_name,language);
+ String message=headers+theEmailText; // the space between headers and content is in the template
+
+ return doTheSMTP(message,to,from);
+
+ }
+
+
+ protected void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ List validationErrors = new Vector();
+ if (shouldSendMail(aRequest,aSession,aResponse,validationErrors)){
+
+ sendMail(aRequest,aSession,aResponse);
+ aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.DoneTemplate"));
+ }
+ else {
+ aResponse.setResponseValue("mail_comment",aRequest.getParameter("mail_comment")); //everything else is required
+ aResponse.setResponseValue("errors",validationErrors);
+ aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.email.PrepareTemplate"));
+ }
+
+ }
+
+ /*
+ String mail_language = aRequest.getParameter("mail_language");
+ if (mail_language == null)
+ mail_language = configuration.getString("Mir.Login.DefaultLanguage", "en");
+
+ aResponse.setResponseValue("mail_language",mail_language);
+ */
+
+
+
+
+}
package mircoders.localizer.basic;
import mir.generator.FreemarkerGenerator;
+import mir.generator.VelocityGenerator;
+import mir.generator.TALGenerator;
import mir.generator.Generator;
import mir.generator.GeneratorLibraryRepository;
import mir.generator.WriterEngine;
protected void buildRepository(GeneratorLibraryRepository aRepository) {
aRepository.registerLibraryFactory(
"freemarker",
- new FreemarkerGenerator.FreemarkerGeneratorLibraryFactory(MirGlobal.config().getString("Home") ) );
+ new FreemarkerGenerator.FreemarkerGeneratorLibraryFactory(
+ MirGlobal.config().getHome()));
+ aRepository.registerLibraryFactory(
+ "velocity",
+ new VelocityGenerator.VelocityGeneratorLibraryFactory(MirGlobal.config().getHome() ) );
+ aRepository.registerLibraryFactory(
+ "tal",
+ new TALGenerator.TALGeneratorLibraryFactory(MirGlobal.config().getHome() ) );
}
- public Generator.GeneratorLibrary makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeProducerGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
try {
- return repository.constructCompositeLibrary(MirGlobal.config().getString("Mir.Localizer.Producer.GeneratorLibrary"));
+ return repository.constructCompositeLibrary(MirGlobal.config().getStringArray("Mir.Localizer.Producer.GeneratorLibrary"));
}
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
};
- public Generator.GeneratorLibrary makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeAdminGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
try {
- return repository.constructCompositeLibrary(MirGlobal.config().getString("Mir.Localizer.Admin.GeneratorLibrary"));
+ return repository.constructCompositeLibrary(MirGlobal.config().getStringArray("Mir.Localizer.Admin.GeneratorLibrary"));
}
catch (Throwable t) {
throw new MirLocalizerFailure(t);
}
};
- public Generator.GeneratorLibrary makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
+ public Generator.Library makeOpenPostingGeneratorLibrary() throws MirLocalizerExc, MirLocalizerFailure {
try {
- return repository.constructCompositeLibrary(MirGlobal.config().getString("Mir.Localizer.OpenPosting.GeneratorLibrary"));
+ return repository.constructCompositeLibrary(MirGlobal.config().getStringArray("Mir.Localizer.OpenPosting.GeneratorLibrary"));
}
catch (Throwable t) {
throw new MirLocalizerFailure(t);
import mircoders.localizer.MirOpenPostingLocalizer;
import mircoders.localizer.MirProducerAssistantLocalizer;
import mircoders.localizer.MirProducerLocalizer;
+import mircoders.localizer.MirMediaLocalizer;
public class MirBasicLocalizer implements MirLocalizer {
public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc {
return new MirBasicAdminInterfaceLocalizer();
- };
+ }
+ public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc {
+ return new MirBasicMediaLocalizer();
+ }
}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer.basic;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import mir.media.MediaHandler;
+import mir.config.*;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.localizer.MirMediaLocalizer;
+import mircoders.media.*;
+
+/**
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public class MirBasicMediaLocalizer implements MirMediaLocalizer {
+ private Map mediaHandlers;
+
+ /**
+ *
+ * @throws MirLocalizerExc
+ * @throws MirLocalizerFailure
+ */
+ public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure {
+ MirPropertiesConfiguration configuration;
+
+ try {
+ configuration = MirPropertiesConfiguration.instance();
+ }
+ catch (Throwable t) {
+ throw new MirLocalizerFailure("Can't get configuration", t);
+ }
+
+ mediaHandlers = new HashMap();
+
+
+ registerMediaHandler("Audio", new MediaHandlerAudio());
+ registerMediaHandler("Generic", new MediaHandlerGeneric());
+ registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern());
+ registerMediaHandler("ImagesJpeg", new MediaHandlerImagesJpeg());
+ registerMediaHandler("ImagesPng", new MediaHandlerImagesPng());
+ registerMediaHandler("Mp3", new MediaHandlerMp3());
+ registerMediaHandler("Ogg", new MediaHandlerOgg());
+ registerMediaHandler("RealAudio", new MediaHandlerRealAudio());
+ registerMediaHandler("RealVideo", new MediaHandlerRealVideo());
+ registerMediaHandler("Video", new MediaHandlerVideo());
+
+ registerMediaHandler("VideoUrl", new URLMediaHandler(
+ configuration.getString("Producer.Icon.BigVideo"),
+ configuration.getString("Producer.Icon.TinyVideo"),
+ "Video Url"));
+
+ registerMediaHandler("AudioUrl", new URLMediaHandler(
+ configuration.getString("Producer.Icon.BigAudio"),
+ configuration.getString("Producer.Icon.TinyAudio"),
+ "Audio Url"));
+
+ registerMediaHandler("ImageUrl", new URLMediaHandler(
+ configuration.getString("Producer.Icon.BigImage"),
+ configuration.getString("Producer.Icon.TinyImage"),
+ "Image Url"));
+
+ registerMediaHandler("OtherUrl", new URLMediaHandler(
+ configuration.getString("Producer.Icon.BigAudio"),
+ configuration.getString("Producer.Icon.TinyAudio"),
+ "Url"));
+ }
+
+ /** returns the {@link MediaHandler} associated with name <code>aName</code> by way of
+ * an internal <code>Map</code>. This <code>Map</code> can be manipulated by calling
+ * <code>registerMediaHandler</code> and <code>unregisterMediaHandler</code>
+ */
+ public MediaHandler getHandler(String aName) {
+ synchronized (mediaHandlers) {
+ return (MediaHandler) mediaHandlers.get(aName);
+ }
+ }
+
+ /** adds a media handler to the registry */
+ public void registerMediaHandler(String aName, MediaHandler aHandler) {
+ synchronized (mediaHandlers) {
+ mediaHandlers.put(aName, aHandler);
+ }
+ }
+
+ /** removes a media handler from the registry*/
+ public void unregisterMediaHandler(String aName) {
+ synchronized (mediaHandlers) {
+ mediaHandlers.remove(aName);
+ }
+ }
+}
\ No newline at end of file
*/
package mircoders.localizer.basic;
-import java.util.*;
-import java.util.Random;
-
import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
import mir.session.Request;
import mircoders.entity.EntityContent;
import mircoders.global.MirGlobal;
import mircoders.global.ProducerEngine;
-import mircoders.localizer.*;
+import mircoders.localizer.MirAntiAbuseFilterType;
+import mircoders.localizer.MirLocalizerExc;
import mircoders.localizer.MirLocalizerFailure;
import mircoders.localizer.MirOpenPostingLocalizer;
+import mircoders.localizer.basic.filters.ThrottleFilter;
+
+import java.util.*;
public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
private List afterContentProducerTasks;
filterTypesMap = new HashMap();
addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("regexp"));
+ addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("useragent", false, false,
+ MirBasicAntiAbuseFilterTypes.RegularExpressionFilter.REQUEST_HEADERS, new String[] {"User-Agent"}));
addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.IPFilter("ip"));
+ addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("hostname", false, false,
+ MirBasicAntiAbuseFilterTypes.RegularExpressionFilter.REQUEST_HEADERS, new String[] {"hostname"}));
+ addSimpleAntiAbuseFilterType(new ThrottleFilter("throttle", 60*60*1000));
}
- public SessionHandler getOpenSessionHandler(String aSessionType) {
+ public SessionHandler getOpenSessionHandler(String aSessionType) throws MirLocalizerExc, MirLocalizerFailure {
+ if (aSessionType!=null && aSessionType.equals("email"))
+ return new MirBasicEmailArticleHandler();
+
if (aSessionType!=null && aSessionType.equals("comment"))
- return new MirBasicCommentPostingHandler();
+ return new MirBasicCommentPostingHandler(configuration.getBoolean("Localizer.OpenSession.PersistentUploadedFiles"));
- return new MirBasicArticlePostingHandler();
+ return new MirBasicArticlePostingHandler(configuration.getBoolean("Localizer.OpenSession.PersistentUploadedFiles"));
}
public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure {
}
public void afterContentPosting() {
- MirGlobal.producerEngine().addTasks(afterContentProducerTasks);
+ Iterator i = afterContentProducerTasks.iterator();
+
+ while (i.hasNext()) {
+ ProducerEngine.ProducerTask task = (ProducerEngine.ProducerTask) i.next();
+
+ try {
+ MirGlobal.getProducerEngine().addTask(task);
+ }
+ catch (Throwable t) {
+ logger.error("Error adding content task "+task.getProducer()+"::"+task.getVerb()+": " + t.toString());
+ }
+ }
}
public void afterContentPosting(EntityContent aContent) {
}
public void afterCommentPosting() {
- MirGlobal.producerEngine().addTasks(afterCommentProducerTasks);
+ Iterator i = afterCommentProducerTasks.iterator();
+
+ while (i.hasNext()) {
+ ProducerEngine.ProducerTask task = (ProducerEngine.ProducerTask) i.next();
+
+ try {
+ MirGlobal.getProducerEngine().addTask(task);
+ }
+ catch (Throwable t) {
+ logger.error("Error adding comment task "+task.getProducer()+"::"+task.getVerb()+": " + t.toString());
+ }
+ }
}
public String generateOnetimePassword() {
*/
package mircoders.localizer.basic;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Vector;
-
import mir.config.MirPropertiesConfiguration;
import mir.log.LoggerWrapper;
-import mir.session.Request;
-import mir.session.Response;
-import mir.session.Session;
-import mir.session.SessionExc;
-import mir.session.SessionFailure;
-import mir.session.SessionHandler;
-import mir.session.UploadedFile;
-import mir.session.ValidationError;
-import mir.session.ValidationHelper;
+import mir.session.*;
import mir.storage.StorageObject;
import mir.util.ExceptionFunctions;
+import mir.util.FileFunctions;
import mircoders.global.MirGlobal;
import mircoders.module.ModuleMediaType;
+import java.io.*;
+import java.util.*;
+
/**
- *
- * <p>Title: Experimental session handler for comment postings </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
+ * Extensible handler for open postings.
+ * Behaviour can be altered by overriding methods.
*/
-
public abstract class MirBasicPostingSessionHandler implements SessionHandler {
- protected LoggerWrapper logger;
- protected MirPropertiesConfiguration configuration;
+ protected static LoggerWrapper logger = new LoggerWrapper("Localizer.OpenPosting");
+ protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();;
+
+ /** Previously uploaded files */
+ protected List attachments;
+ /** counter to generate unique field names for uploaded files */
+ protected int uploadedFileIndex = 0;
private String normalResponseGenerator;
private String dupeResponseGenerator;
private String unsupportedMediaTypeResponseGenerator;
private String finalResponseGenerator;
+ private boolean persistentUploadedFiles;
- public MirBasicPostingSessionHandler() {
- logger = new LoggerWrapper("Localizer.OpenPosting");
- try {
- configuration = MirPropertiesConfiguration.instance();
- }
- catch (Throwable t) {
- logger.fatal("Cannot load configuration: " + t.toString());
-
- throw new RuntimeException("Cannot load configuration: " + t.toString());
- }
+ public MirBasicPostingSessionHandler(boolean aPersistentUploadedFiles) {
+ attachments = new ArrayList();
+ persistentUploadedFiles = aPersistentUploadedFiles;
}
protected void setNormalResponseGenerator(String aGenerator) {
normalResponseGenerator = aGenerator;
}
- protected void setResponseGenerators(String aNormalResponseGenerator, String aDupeResponseGenerator,
- String anUnsupportedMediaTypeResponseGenerator, String aFinalResponseGenerator) {
+ protected void setResponseGenerators(String aNormalResponseGenerator,
+ String aDupeResponseGenerator, String anUnsupportedMediaTypeResponseGenerator,
+ String aFinalResponseGenerator) {
setNormalResponseGenerator(aNormalResponseGenerator);
dupeResponseGenerator = aDupeResponseGenerator;
unsupportedMediaTypeResponseGenerator = anUnsupportedMediaTypeResponseGenerator;
makeInitialResponse(aRequest, aSession, aResponse);
}
+ protected void processAttachments(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ Iterator i = attachments.iterator();
+ while (i.hasNext()) {
+ processAttachment(aRequest, aSession, (Attachment) i.next());
+ }
+ }
+
public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
try {
-
try {
- List validationErrors = new Vector();
+ List validationErrors = new ArrayList();
+
+ preprocessPreviousAttachments(aRequest, aSession);
+ preProcessNewAttachments(aRequest, aSession);
if (!shouldProcessRequest(aRequest, aSession, validationErrors)) {
initializeResponseData(aRequest, aSession, aResponse);
}
else {
preProcessRequest(aRequest, aSession);
- Iterator i = aRequest.getUploadedFiles().iterator();
- while (i.hasNext()) {
- processUploadedFile(aRequest, aSession, (UploadedFile) i.next());
- }
+
+ processAttachments(aRequest, aSession, aResponse);
+
postProcessRequest(aRequest, aSession);
initializeResponseData(aRequest, aSession, aResponse);
makeFinalResponse(aRequest, aSession, aResponse);
}
}
+ /**
+ * Initializes a session.
+ * This may happen in the case of a new session being initiated, but also
+ * when an older session gets re-initiated after a session timeout.
+ */
protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
if (MirGlobal.abuse().getOpenPostingPassword()) {
String password = (String) aSession.getAttribute("password");
aSession.deleteAttribute("password");
}
- logger.debug("referrer = " + aRequest.getHeader("Referer"));
-
aSession.setAttribute("referer", aRequest.getHeader("Referer"));
- aSession.setAttribute("nrmediaitems",
- new Integer(configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems")));
}
+ /**
+ * Called every time a response is being prepared.
+ * This may be at the initial response, or on a subsequent one.
+ */
protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
- int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
- List mediaItems = new Vector();
- int i=0;
+ int nrMediaItems = configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems", 5);
+
+ if (aSession.getAttribute("nrmediaitems")!=null) {
+ nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
+ }
- while (i<nrMediaItems) {
- i++;
+ try {
+ nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));
+ }
+ catch (Throwable t) {
+ }
+
+ aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));
+
+ List mediaItems = new ArrayList();
+ for (int i=1; i<=nrMediaItems; i++) {
mediaItems.add(new Integer(i));
}
aResponse.setResponseValue("password", aSession.getAttribute("password"));
aResponse.setResponseValue("referer", aSession.getAttribute("referer"));
aResponse.setResponseValue("errors", null);
+
+ if (configuration.getBoolean("Localizer.OpenSession.AllowFTPUploads", false)) {
+ aResponse.setResponseValue("ftpfiles",
+ FileFunctions.getDirectoryContentsAsList(configuration.getFile("Localizer.OpenSession.FTPDirectory"),
+ new FilenameFilter() {
+ public boolean accept(File aDir, String aName) {
+ return !(new File(aDir, aName).isDirectory());
+ }
+ }));
+ }
+ else {
+ aResponse.setResponseValue("ftpfiles", null);
+ }
+
+ initializeAttachmentResponseData(aRequest, aSession, aResponse);
+ }
+
+ /**
+ * Process possible changes to previously uploaded files
+ */
+ protected void initializeAttachmentResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
+ List result = new ArrayList();
+ if (persistentUploadedFiles) {
+ Iterator i = attachments.iterator();
+ while (i.hasNext()) {
+ Attachment attachment = (Attachment) i.next();
+ Map attachmentData = new HashMap();
+ attachmentData.putAll(attachment.getAllAttributes());
+ attachmentData.put("fieldname", attachment.getFieldName());
+ attachmentData.put("filename", attachment.getFileName());
+ result.add(attachmentData);
+ }
+ }
+
+ aResponse.setResponseValue("attachments", result);
+ }
+
+ /**
+ * Process possible changes to previously uploaded files
+ */
+ protected void preprocessPreviousAttachments(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ synchronized (attachments) {
+ List previouslyUploadedFiles = new ArrayList(attachments);
+ attachments.clear();
+
+ if (persistentUploadedFiles) {
+ Iterator i = previouslyUploadedFiles.iterator();
+ while (i.hasNext()) {
+ Attachment uploadedFile = (Attachment) i.next();
+ if (!(aRequest.getParameter(uploadedFile.getFieldName()+"_cancel")!=null)) {
+ addAttachment(aRequest, aSession, uploadedFile, uploadedFile.getFieldName());
+ }
+ }
+ }
+ }
+ }
+
+ protected void addAttachment(Request aRequest, Session aSession, Attachment anAttachment, String aFieldName) throws SessionExc, SessionFailure {
+ List parameters = aRequest.getPrefixedParameterNames(aFieldName+"_");
+ Iterator j = parameters.iterator();
+ while (j.hasNext()) {
+ String parameter = ((String) j.next());
+ anAttachment.setAttribute(
+ parameter.substring(aFieldName.length()+1),
+ aRequest.getParameter(parameter));
+ }
+ attachments.add(anAttachment);
+ }
+
+ public void preprocessNewAttachment(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
+ Attachment uploadedFile =
+ new Attachment(aFile, aFile.getFileName(), "attachment"+ ++uploadedFileIndex, aFile.getContentType());
+
+ addAttachment(aRequest, aSession, uploadedFile, aFile.getFieldName());
+ }
+
+
+ /**
+ * Process newly uploaded files
+ */
+ protected void preProcessNewAttachments(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
+ Iterator i = aRequest.getUploadedFiles().iterator();
+ while (i.hasNext()) {
+ preprocessNewAttachment(aRequest, aSession, (UploadedFile) i.next());
+ }
+
+ if (configuration.getBoolean("Localizer.OpenSession.AllowFTPUploads", false)) {
+ File FTPDirectory = configuration.getFile("Localizer.OpenSession.FTPDirectory");
+
+ List ftpUploads = aRequest.getPrefixedParameterNames("ftpupload");
+ i = ftpUploads.iterator();
+ while (i.hasNext()) {
+ final String fieldName = (String) i.next();
+
+ if (fieldName.indexOf("_")<0) {
+ final String fileName = aRequest.getParameter(fieldName);
+
+ if (fileName!=null && fileName.trim().length()>0) {
+ final File sourceFile = new File(FTPDirectory, fileName);
+
+ if (sourceFile.getParentFile().equals(FTPDirectory)) {
+ preprocessNewAttachment(aRequest, aSession, new UploadedFile() {
+ public void writeToFile(File aFile) throws SessionFailure {
+ try {
+ FileFunctions.move(sourceFile, aFile);
+ }
+ catch (IOException e) {
+ throw new SessionFailure(e);
+ }
+ }
+
+ public InputStream getInputStream() throws SessionFailure {
+ try {
+ return new FileInputStream(sourceFile);
+ }
+ catch (IOException e) {
+ throw new SessionFailure(e);
+ }
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public String getContentType() {
+ return null;
+ }
+ });
+ }
+ }
+ }
+ }
+ }
}
protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
};
protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {
- anError.printStackTrace();
Throwable rootCause = ExceptionFunctions.traceCauseException(anError);
if (rootCause instanceof DuplicatePostingExc)
aResponse.setResponseGenerator(unsupportedMediaTypeResponseGenerator);
}
else {
- aResponse.setResponseValue("errorstring", anError.getMessage());
- aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.ErrorTemplate"));
+ List errors = new ArrayList();
+ errors.add(new ValidationError("", "general.unexpectederror",
+ new Object[] {anError.getMessage()}));
+ makeResponse(aRequest, aSession, aResponse, errors);
}
};
aResponse.setResponseGenerator(configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
}
+ /**
+ *
+ */
protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
};
- public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
+ public void processAttachment(Request aRequest, Session aSession, Attachment aFile) throws SessionExc, SessionFailure {
};
protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
};
+ /**
+ * Determine whether the request shoudl be processed: that is, the validate,
+ * preprocess, postprocess methods should be called to perform validations,
+ * store data, etc
+ */
protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {
- int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
- try {
- nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));
- }
- catch (Throwable t) {
- }
-
- aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));
-
if (aRequest.getParameter("post")==null)
return false;
else {
}
}
+ /**
+ * Method used to validate user input.
+ * Multiple {@link ValidationError}s may be added to the
+ * <code>aResults</code> parameter.
+ * The request is considered validated if, after calling this method,
+ * <code>aResults</code> is empty.
+ */
protected void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
String password = (String) aSession.getAttribute("password");
*
* @return a password, to be used once
*/
-
protected String generateOnetimePassword() {
Random r = new Random();
int random = r.nextInt();
return returnString.substring(5);
}
-
/**
- *
- * @param aRequest
- * @param aStorage
- * @return
- * @throws SessionExc
- * @throws SessionFailure
+ * Method to filter the attributes and their values of a request
+ * based on the fields of a storage object.
*/
-
- protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
+ protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionFailure {
Map result = new HashMap();
Iterator i = aStorage.getFields().iterator();
return result;
}
+ /**
+ * Exception to be thrown when an article or comment was already posted
+ */
protected static class DuplicatePostingExc extends SessionExc {
public DuplicatePostingExc(String aMessage) {
super(aMessage);
}
}
+ /**
+ * A file that has been attached to a session
+ */
+ protected static class Attachment implements UploadedFile {
+ private UploadedFile uploadedFile;
+ private String filename;
+ private String fieldName;
+ private String contentType;
+ private Map attributes;
+
+ public Attachment(UploadedFile anUploadedFile, String aFilename, String aFieldName, String aContentType) {
+ attributes = new HashMap();
+ filename = aFilename;
+ fieldName = aFieldName;
+ contentType = aContentType;
+ uploadedFile = anUploadedFile;
+ }
+
+ public void writeToFile(File aFile) throws SessionExc, SessionFailure {
+ uploadedFile.writeToFile(aFile);
+ }
+
+ public InputStream getInputStream() throws SessionExc, SessionFailure {
+ return uploadedFile.getInputStream();
+ }
+
+ public String getFileName() {
+ return filename;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
+
+ public String getAttribute(String anAttribute) {
+ return (String) attributes.get(anAttribute);
+ }
+
+ public void setAttribute(String anAttribute, String aValue) {
+ attributes.put(anAttribute, aValue);
+ }
+
+ public Map getAllAttributes() {
+ return Collections.unmodifiableMap(attributes);
+ }
+ }
}
+
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.localizer.basic;\r
-\r
-import java.util.GregorianCalendar;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.Map;\r
-\r
-import mir.config.MirPropertiesConfiguration;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.entity.adapter.EntityIteratorAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.util.GeneratorDateTimeFunctions;\r
-import mir.util.GeneratorExpressionFunctions;\r
-import mir.util.GeneratorFormatAdapters;\r
-import mir.util.GeneratorHTMLFunctions;\r
-import mir.util.GeneratorIntegerFunctions;\r
-import mir.util.GeneratorListFunctions;\r
-import mir.util.GeneratorRegularExpressionFunctions;\r
-import mir.util.GeneratorStringFunctions;\r
-import mircoders.global.MirGlobal;\r
-import mircoders.localizer.MirLocalizerExc;\r
-import mircoders.localizer.MirLocalizerFailure;\r
-import mircoders.localizer.MirProducerAssistantLocalizer;\r
-\r
-public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {\r
- protected LoggerWrapper logger;\r
-\r
- public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure {\r
- try {\r
- Iterator i;\r
-\r
- Map configMap = new HashMap();\r
- Map utilityMap = new HashMap();\r
-\r
- logger = new LoggerWrapper("Localizer.ProducerAssistant");\r
-\r
-// obsolete:\r
- configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));\r
- configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));\r
- configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));\r
- configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));\r
- configMap.put("docRoot", MirGlobal.config().getString("RootUri"));\r
- configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");\r
- configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));\r
- configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));\r
- configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));\r
- configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));\r
- configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));\r
- configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));\r
- configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));\r
-\r
-// "new":\r
- configMap.putAll(MirPropertiesConfiguration.instance().allSettings());\r
-\r
- utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace());\r
- utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction());\r
- utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction());\r
- utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction());\r
- utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction());\r
- utilityMap.put("subList", new GeneratorListFunctions.subListFunction());\r
- utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction());\r
- utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction());\r
- utilityMap.put("evaluate", new GeneratorExpressionFunctions.evaluateExpressionFunction());\r
- utilityMap.put("constructString", new GeneratorStringFunctions.constructStructuredStringFunction());\r
- utilityMap.put("escapeJDBCString", new GeneratorStringFunctions.jdbcStringEscapeFunction());\r
- utilityMap.put("regexpreplace", new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction());\r
- utilityMap.put("datetime", new GeneratorDateTimeFunctions.DateTimeFunctions(\r
- MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));\r
-\r
- aValueSet.put("config", configMap);\r
- aValueSet.put("utility", utilityMap);\r
-\r
- aValueSet.put("languages",\r
- new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));\r
-\r
- aValueSet.put("topics",\r
- new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
-\r
- Map articleTypeMap = new HashMap();\r
- articleTypeMap.put("openposting", "0");\r
- articleTypeMap.put("newswire", "1");\r
- articleTypeMap.put("feature", "2");\r
- articleTypeMap.put("topicspecial", "3");\r
- articleTypeMap.put("startspecial", "4");\r
-\r
- i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");\r
- while (i.hasNext()) {\r
- EntityAdapter articleType = (EntityAdapter) i.next();\r
-\r
- articleTypeMap.put(articleType.get("name"), articleType.get("id"));\r
- }\r
- aValueSet.put("articletype", articleTypeMap);\r
-\r
- Map commentStatusMap = new HashMap();\r
- i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");\r
- while (i.hasNext()) {\r
- EntityAdapter commentStatus = (EntityAdapter) i.next();\r
-\r
- commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));\r
- }\r
- aValueSet.put("commentstatus", commentStatusMap);\r
- }\r
- catch (Throwable t) {\r
- logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());\r
- throw new RuntimeException(t.getMessage());\r
- }\r
-\r
- };\r
-\r
- public String filterNonHTMLText(String aText) {\r
-\r
- logger.debug("about to filter non HTML Text of length " + aText.length());\r
- try {\r
- String result =\r
- StringUtil.createHTML(\r
- StringUtil.removeHTMLTags(aText),\r
- MirGlobal.config().getString("Producer.ImageRoot"),\r
- MirGlobal.config().getString("Producer.MailLinkName"),\r
- MirGlobal.config().getString("Producer.ExtLinkName"),\r
- MirGlobal.config().getString("Producer.IntLinkName")\r
- );\r
- logger.debug("done filtering non-HTML text ");\r
- return result;\r
- }\r
- catch (Throwable t) {\r
- logger.error("error while filtering non-HTML text: " + t.toString());\r
-\r
- throw new RuntimeException(t.toString());\r
- }\r
- }\r
-\r
- public String filterHTMLText(String aText) {\r
- return StringUtil.deleteForbiddenTags(aText);\r
- }\r
-}\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer.basic;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.generator.GeneratorFailure;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.util.*;
+import mir.util.generator.ReflectionGeneratorFunctionsAdapter;
+import mircoders.global.MirGlobal;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.localizer.MirProducerAssistantLocalizer;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.tidy.Tidy;
+import org.w3c.tidy.Configuration;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
+ protected LoggerWrapper logger;
+
+ public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure {
+ try {
+ Iterator i;
+
+ Map configMap = new HashMap();
+
+ logger = new LoggerWrapper("Localizer.ProducerAssistant");
+
+// obsolete:
+ configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));
+ configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));
+ configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));
+ configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));
+ configMap.put("docRoot", MirGlobal.config().getString("RootUri"));
+ configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");
+ configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));
+ configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));
+ configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));
+ configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));
+ configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));
+ configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));
+ configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));
+
+// "new":
+ configMap.putAll(MirPropertiesConfiguration.instance().allSettings());
+
+ aValueSet.put("config", configMap);
+
+ aValueSet.put("utility", new Utility());
+
+ aValueSet.put("languages",
+ new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
+
+ aValueSet.put("topics",
+ new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
+
+ Map articleTypeMap = new HashMap();
+ articleTypeMap.put("openposting", "0");
+ articleTypeMap.put("newswire", "1");
+ articleTypeMap.put("feature", "2");
+ articleTypeMap.put("topicspecial", "3");
+ articleTypeMap.put("startspecial", "4");
+
+ i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");
+ while (i.hasNext()) {
+ EntityAdapter articleType = (EntityAdapter) i.next();
+
+ articleTypeMap.put(articleType.get("name"), articleType.get("id"));
+ }
+ aValueSet.put("articletype", articleTypeMap);
+
+ Map commentStatusMap = new HashMap();
+ i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");
+ while (i.hasNext()) {
+ EntityAdapter commentStatus = (EntityAdapter) i.next();
+
+ commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));
+ }
+ aValueSet.put("commentstatus", commentStatusMap);
+ aValueSet.put("languageCodeToId", new getLanguageIdFunction());
+ }
+ catch (Throwable t) {
+ logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
+ throw new RuntimeException(t.getMessage());
+ }
+
+ };
+ public static class getLanguageIdFunction implements Generator.Function {
+ private Map languageCodeToId;
+ private String otherLanguageId;
+ private LoggerWrapper logger = new LoggerWrapper("Localizer.Earth.getLanguageIdFunction");
+
+ public getLanguageIdFunction() throws MirLocalizerFailure {
+ try {
+ otherLanguageId = "";
+ languageCodeToId = new HashMap();
+
+ Iterator i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language");
+ while (i.hasNext()) {
+ EntityAdapter language = (EntityAdapter) i.next();
+ if (language.get("code").equals("ot"))
+ otherLanguageId = (String) language.get("id");
+
+ languageCodeToId.put(language.get("code"), language.get("id"));
+ }
+ }
+ catch (Throwable t) {
+ logger.error(t.toString());
+
+ throw new MirLocalizerFailure(t);
+ }
+ }
+
+ public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+ try {
+ if (aParameters.size() != 1)
+ throw new GeneratorExc("getLanguageIdFunction: 1 parameter expected: language-code");
+
+ String result = (String) languageCodeToId.get(aParameters.get(0));
+ if (result == null)
+ result = otherLanguageId;
+
+ return result;
+ }
+ catch (GeneratorExc e) {
+ throw e;
+ }
+ catch (Throwable t) {
+ throw new GeneratorFailure("getLanguageIdFunction: " + t.getMessage(), t);
+ }
+ };
+ }
+
+
+ public String filterNonHTMLText(String aText) {
+
+ logger.debug("about to filter non HTML Text of length " + aText.length());
+ try {
+ String result =
+ StringUtil.createHTML(
+ StringUtil.removeHTMLTags(aText),
+ MirGlobal.config().getString("Producer.ImageRoot"),
+ MirGlobal.config().getString("Producer.MailLinkName"),
+ MirGlobal.config().getString("Producer.ExtLinkName"),
+ MirGlobal.config().getString("Producer.IntLinkName")
+ );
+ logger.debug("done filtering non-HTML text ");
+ return result;
+ }
+ catch (Throwable t) {
+ logger.error("error while filtering non-HTML text: " + t.toString());
+
+ throw new RuntimeException(t.toString());
+ }
+ }
+ public String filterHTMLText(String aText) {
+ try {
+ StringWriter out = new StringWriter();
+ Tidy tidy = new Tidy();
+ ByteArrayInputStream in = new ByteArrayInputStream(aText.getBytes("UTF8"));
+ tidy.setMakeClean(true);
+ tidy.setCharEncoding(Configuration.UTF8);
+ print(tidy.parseDOM(in, null), out);
+ return out.toString();
+ } catch (IOException e) {
+ return e.getMessage();
+ }
+ }
+
+ private boolean checkAttr(String attrName) {
+ if (attrName.equals("onLoad") || attrName.equals("onClick") || attrName.equals("onFocus") || attrName.equals("onBlur") || attrName.equals("onMouseOver") || attrName.equals("onMouseOut") || attrName.equals("style") || attrName.equals("STYLE") || attrName.equals("height") || attrName.equals("width") || attrName.equals("HEIGHT") || attrName.equals("WIDTH"))
+ return false;
+ else
+ return true;
+
+ }
+
+ private boolean checkNode(String nodeName) {
+ if (nodeName.equals("a") ||
+ nodeName.equals("img") ||
+ nodeName.equals("h1") ||
+ nodeName.equals("h2") ||
+ nodeName.equals("h3") ||
+ nodeName.equals("h4") ||
+ nodeName.equals("h5") ||
+ nodeName.equals("h6") ||
+ nodeName.equals("br") ||
+ nodeName.equals("form") ||
+ nodeName.equals("input") ||
+ nodeName.equals("hr") ||
+ nodeName.equals("strong") ||
+ nodeName.equals("font") ||
+ nodeName.equals("b") ||
+ nodeName.equals("i") ||
+ nodeName.equals("em") ||
+ nodeName.equals("p") ||
+ nodeName.equals("table") ||
+ nodeName.equals("tr") ||
+ nodeName.equals("td") ||
+ nodeName.equals("th") ||
+ nodeName.equals("ul") ||
+ nodeName.equals("ol") ||
+ nodeName.equals("li")
+ ) {
+ return true;
+ } else {
+
+ return false;
+ }
+ }
+
+ private void print(Node node, StringWriter out) throws IOException {
+ if (node == null) {
+ return;
+ }
+ int type = node.getNodeType();
+ boolean canOutput = checkNode(node.getNodeName());
+
+ switch (type) {
+
+ case Node.DOCUMENT_NODE:
+
+ print(((Document) node).getDocumentElement(), out);
+ out.flush();
+ break;
+
+ case Node.ELEMENT_NODE:
+ if (canOutput) {
+ out.write('<');
+
+ out.write(node.getNodeName());
+ NamedNodeMap attrs = node.getAttributes();
+
+ for (int i = 0; i < attrs.getLength(); i++) {
+ String attrName = attrs.item(i).getNodeName();
+ if (checkAttr(attrName)) {
+ out.write(' ');
+ out.write(attrs.item(i).getNodeName());
+ out.write("=\"");
+
+ out.write(attrs.item(i).getNodeValue());
+ out.write('"');
+ }
+ }
+
+ if (node.getChildNodes()==null || node.getChildNodes().getLength()==0) {
+ out.write("/");
+ }
+ out.write('>');
+ }
+ NodeList children = node.getChildNodes();
+ if (children != null) {
+ int len = children.getLength();
+ for (int i = 0; i < len; i++) {
+ print(children.item(i), out);
+ }
+ }
+ break;
+
+ case Node.TEXT_NODE:
+ out.write(node.getNodeValue());
+ break;
+
+ }
+
+ if (type == Node.ELEMENT_NODE && canOutput && node.getChildNodes()!=null && node.getChildNodes().getLength()>0) {
+ out.write("</");
+ out.write(node.getNodeName());
+ out.write('>');
+ }
+
+ out.flush();
+ }
+
+ public static class Utility extends ReflectionGeneratorFunctionsAdapter {
+ public Utility () {
+ super(new MirBasicUtilityFunctions());
+ }
+ public Object getDatetime() {
+ return new GeneratorDateTimeFunctions.DateTimeFunctions(
+ MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone"));
+ }
+
+ public Object getCompressWhitespace() {
+ return new freemarker.template.utility.CompressWhitespace();
+ }
+ }
+}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.localizer.basic;
import mir.generator.Generator;
import mir.generator.WriterEngine;
import mir.log.LoggerWrapper;
-import mir.producer.ProducerFactory;
import mir.producer.reader.DefaultProducerNodeBuilders;
import mir.producer.reader.ProducerConfigReader;
import mir.producer.reader.ProducerNodeBuilderLibrary;
-import mir.util.FileMonitor;
+import mir.util.StringRoutines;
import mircoders.global.MirGlobal;
import mircoders.global.ProducerEngine;
import mircoders.localizer.MirLocalizerExc;
import mircoders.producer.reader.SupplementalProducerNodeBuilders;
public class MirBasicProducerLocalizer implements MirProducerLocalizer {
- private List producerFactories;
- private Map nameToFactory;
- private List allNewProducerTasks;
+ private Map producerRecipes;
+ private List producerRecipeNames;
- protected FileMonitor fileMonitor;
protected EntityAdapterModel model;
- protected Generator.GeneratorLibrary generatorLibrary;
+ protected Generator.Library generatorLibrary;
protected WriterEngine writerEngine;
protected LoggerWrapper logger;
try {
logger = new LoggerWrapper("Localizer.Basic.Producer");
+ producerRecipes = new HashMap();
+ producerRecipeNames = new Vector();
+
+ String[] recipes = MirGlobal.config().getStringArray("Mir.Localizer.Producer.ProducerRecipes");
+ for (int i = 0; i<recipes.length; i++) {
+ try {
+ List parts = StringRoutines.separateString(recipes[i], "=");
+ if (parts.size() == 2) {
+ String key = ((String) parts.get(0)).trim();
+ producerRecipes.put(key, ProducerEngine.ProducerTask.parseProducerTaskList(
+ ((String) parts.get(1)).trim()));
+ producerRecipeNames.add(key);
+ }
+ else {
+ throw new Exception("'=' expected");
+ }
+ }
+ catch (Throwable t) {
+ logger.error("Error while processing producer recipe '" + recipes[i] + "': " + t.toString());
+ }
+ }
+
+ // for backward compatibility:
String allNewProducers = MirGlobal.config().getString("Mir.Localizer.Producer.AllNewProducers");
- allNewProducerTasks = ProducerEngine.ProducerTask.parseProducerTaskList(allNewProducers);
+ if (allNewProducers!=null && allNewProducers.length()>0) {
+ producerRecipes.put("allnew", ProducerEngine.ProducerTask.parseProducerTaskList(allNewProducers));
+
+ if (!producerRecipeNames.contains("allnew")) {
+ producerRecipeNames.add("allnew");
+ }
+ }
- producerFactories = new Vector();
model = MirGlobal.localizer().dataModel().adapterModel();
generatorLibrary = MirGlobal.localizer().generators().makeProducerGeneratorLibrary();
writerEngine = MirGlobal.localizer().generators().makeWriterEngine();
- nameToFactory = new HashMap();
}
catch (Throwable t) {
logger.error("MirBasicProducerLocalizer(): Exception "+t.getMessage());
}
}
- public List factories() throws MirLocalizerExc {
- if (fileMonitor==null || producerFactories == null || fileMonitor.hasChanged()) {
- try {
- List newProducers = new Vector();
- FileMonitor newFileMonitor = new FileMonitor();
- setupFactories(newProducers, newFileMonitor);
-
- producerFactories = newProducers;
- fileMonitor = newFileMonitor;
- logger.info("MirBasicProducerLocalizer.factories(): successfully setup factories");
-
- nameToFactory.clear();
- Iterator i = producerFactories.iterator();
- while (i.hasNext()) {
- ProducerFactory factory = (ProducerFactory) i.next();
- nameToFactory.put(factory.getName(), factory);
+ public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure {
+ return producerRecipeNames;
+ }
+
+ public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure {
+ if (producerRecipes.containsKey(aName)) {
+ Iterator i = ((List) producerRecipes.get(aName)).iterator();
+
+ while (i.hasNext()) {
+ ProducerEngine.ProducerTask task = (ProducerEngine.ProducerTask) i.next();
+
+ try {
+ MirGlobal.getProducerEngine().addTask(task);
+ }
+ catch (Throwable t) {
+ logger.error("Error recipe "+aName+" tasks "+
+ task.getProducer()+"::"+task.getVerb()+": " + t.toString());
}
- }
- catch (Throwable t) {
- logger.error("MirBasicProducerLocalizer.factories(): Unable to setup factories: "+t.getMessage());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
}
}
+ else
+ throw new MirLocalizerExc("Unknown recipe name: " + aName);
+ }
- return producerFactories;
+ /**
+ * Loads factories from a file with a {@link ProducerConfigReader}
+ */
+ public List loadFactories() throws MirLocalizerExc {
+ try {
+ List producers = new Vector();
+ ProducerConfigReader reader;
+ ProducerNodeBuilderLibrary library = new ProducerNodeBuilderLibrary();
+ setupProducerNodeBuilderLibrary(library);
+ reader = new ProducerConfigReader();
+ File inputFile =
+ MirGlobal.config().getFile("Mir.Localizer.ProducerConfigFile");
+ reader.parse(inputFile, library, producers);
+
+ logger.info("MirBasicProducerLocalizer.loadFactories(): successfully loaded factories");
+
+ return producers;
+ }
+ catch (Throwable t) {
+ logger.error("MirBasicProducerLocalizer.loadFactories(): Unable to load factories: "+
+ t.getMessage());
+ throw new MirLocalizerFailure(t);
+ }
};
+ /**
+ * Sets up a {@link ProducerNodeBuilderLibrary} for use by the producer
+ * definition reader. Can be overridden by subclasses to tweak the standard
+ * library.
+ */
protected void setupProducerNodeBuilderLibrary(ProducerNodeBuilderLibrary aLibrary) throws MirLocalizerFailure {
try {
DefaultProducerNodeBuilders.registerBuilders(
aLibrary, model, generatorLibrary, writerEngine,
- MirGlobal.config().getString("Home"), MirGlobal.config().getString("Producer.StorageRoot"));
- SupplementalProducerNodeBuilders.registerBuilders(aLibrary, model);
+ MirGlobal.config().getHome(), MirGlobal.config().getFile("Producer.StorageRoot"));
+ SupplementalProducerNodeBuilders.registerBuilders(aLibrary, MirGlobal.config().getHome());
}
catch (Throwable t) {
throw new MirLocalizerFailure(t.getMessage(), t);
}
}
- protected void setupFactories(List aFactories, FileMonitor aFileMonitor) throws MirLocalizerExc, MirLocalizerFailure {
- ProducerConfigReader reader;
- ProducerNodeBuilderLibrary library = new ProducerNodeBuilderLibrary();
- setupProducerNodeBuilderLibrary(library);
- List usedFiles = new Vector();
- Iterator i;
-
- aFileMonitor.clear();
- reader = new ProducerConfigReader();
- reader.parseFile(MirGlobal.config().getString("Home") + File.separatorChar + MirGlobal.config().getString("Mir.Localizer.ProducerConfigFile"), library, aFactories, usedFiles);
-
- i = usedFiles.iterator();
- while (i.hasNext())
- aFileMonitor.addFile((File) i.next());
- }
-
- public void produceAllNew() {
- MirGlobal.producerEngine().addTasks(allNewProducerTasks);
- };
-
- public ProducerFactory getFactoryForName(String aName) {
- try {
- factories();
- }
- catch (Throwable t) {
- }
-
- return (ProducerFactory) nameToFactory.get(aName);
- }
}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer.basic;\r
+\r
+import mir.util.*;\r
+import mir.config.MirPropertiesConfiguration;\r
+\r
+import java.util.Collections;\r
+import java.util.List;\r
+\r
+public class MirBasicUtilityFunctions {\r
+ public String encodeXML(Object anObject) throws Exception {\r
+ return HTMLRoutines.encodeXML(StringRoutines.interpretAsString(anObject));\r
+ }\r
+\r
+ public String encodeHTML(Object aString) throws Exception {\r
+ return HTMLRoutines.encodeHTML(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public String prettyEncodeHTML(Object aString) throws Exception {\r
+ return HTMLRoutines.prettyEncodeHTML(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public String encodeURI(Object aString) throws Exception {\r
+ return HTMLRoutines.encodeURL(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public String encodeURI(Object aString, Object anEncoding) throws Exception {\r
+ return HTMLRoutines.encodeURL(\r
+ StringRoutines.interpretAsString(aString),\r
+ StringRoutines.interpretAsString(anEncoding));\r
+ }\r
+\r
+ public String subString(Object aString, Object aFrom) throws Exception {\r
+ return StringRoutines.interpretAsString(aString).substring(StringRoutines.interpretAsInteger(aFrom));\r
+ }\r
+\r
+ public String subString(Object aString, Object aFrom, Object aLength) throws Exception {\r
+ int length = StringRoutines.interpretAsInteger(aLength);\r
+ String target = StringRoutines.interpretAsString(aString);\r
+ if (length<0 || length>target.length()) {\r
+ length=target.length();\r
+ }\r
+\r
+ return target.substring(StringRoutines.interpretAsInteger(aFrom), length);\r
+ }\r
+\r
+ public String escapeJDBCString(Object aString) throws Exception {\r
+ return JDBCStringRoutines.escapeStringLiteral(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public String constructString(Object aString) throws Exception {\r
+ if (aString==null)\r
+ return StructuredContentParser.constructStringLiteral("");\r
+ else\r
+ return StructuredContentParser.constructStringLiteral(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public Object parseStructuredString(Object aString) throws Exception {\r
+ if (aString==null)\r
+ return null;\r
+ else\r
+ return StructuredContentParser.parse(StringRoutines.interpretAsString(aString));\r
+ }\r
+\r
+ public boolean isOdd(Object anInteger) throws Exception {\r
+ return (StringRoutines.interpretAsInteger(anInteger) & 1) == 1;\r
+ }\r
+\r
+ public int increment(Object anInteger) throws Exception {\r
+ final Integer ONE = new Integer(1);\r
+\r
+ return increment(anInteger, ONE);\r
+ }\r
+\r
+ public int increment(Object anInteger, Object anIncrement) throws Exception {\r
+ return StringRoutines.interpretAsInteger(anInteger) +\r
+ StringRoutines.interpretAsInteger(anIncrement);\r
+ }\r
+\r
+ public Object subList(Object aList, Object aSkip) throws Exception {\r
+ return subList(aList, aSkip, new Integer(-1));\r
+ }\r
+\r
+ public Object subList(Object aList, Object aSkip, Object aMaxSize) throws Exception {\r
+ int skip = StringRoutines.interpretAsInteger(aSkip);\r
+ int maxSize = StringRoutines.interpretAsInteger(aMaxSize);\r
+\r
+ if (aList instanceof RewindableIterator)\r
+ return new SubsetIterator((RewindableIterator) aList, skip, maxSize);\r
+ else {\r
+ List list = (List) aList;\r
+\r
+ if (skip>=list.size())\r
+ return Collections.EMPTY_LIST;\r
+ if (maxSize<0 || (skip+maxSize)>=list.size())\r
+ return list.subList(skip, list.size());\r
+ else\r
+ return list.subList(skip, skip+maxSize);\r
+ }\r
+ }\r
+\r
+ public int listSize(RewindableIterator anIterator) {\r
+ anIterator.rewind();\r
+ int result=0;\r
+\r
+ while (anIterator.hasNext()) {\r
+ result++;\r
+ anIterator.next();\r
+ }\r
+\r
+ anIterator.rewind();\r
+\r
+ return result;\r
+ }\r
+\r
+ public int listSize(List aList) {\r
+ return aList.size();\r
+ }\r
+\r
+ public Object evaluate(Object aTarget, String anExpression) throws Exception {\r
+ return ParameterExpander.expandExpression(aTarget, anExpression);\r
+ }\r
+\r
+ public String regexpreplace(String aString, String anExpression, String aReplacement) {\r
+ return StringRoutines.performRegularExpressionReplacement(aString, anExpression, aReplacement);\r
+ }\r
+\r
+ public boolean regexpmatch(String aString, String anExpression) {\r
+ return StringRoutines.performRegularExpressionSearch(aString, anExpression);\r
+ }\r
+}\r
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.localizer.basic;
+import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
File file;
File dir;
- if (anEncoding!=null && !anEncoding.equals(""))
+ if (anEncoding != null && !anEncoding.equals(""))
encoding = anEncoding;
else
encoding = defaultEncoding;
-// MirGlobal.getConfigProperty("Mir.DefaultEncoding");
try {
- file = new File( anIdentifier );
- dir = new File(file.getParent());
- if (dir!=null && !dir.exists()){
- dir.mkdirs();
+ file = new File(anIdentifier);
+
+ dir = file.getParentFile();
+
+ if (dir != null && !dir.exists()) {
+ dir.mkdirs();
}
return new PrintWriter(
- new OutputStreamWriter(
- new FileOutputStream(file), encoding
- )
+ new BufferedWriter(
+ new OutputStreamWriter(
+ new FileOutputStream(file), encoding
+ ), 8192)
);
}
catch (Throwable t) {
- throw new MirLocalizerFailure("Failure while opening a PrintWriter: "+t.getMessage(),t);
+ throw new MirLocalizerFailure("Failure while opening a PrintWriter: " + t.getMessage(), t);
}
};
--- /dev/null
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.localizer.basic.actions;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Iterator;
+
+import mir.entity.adapter.EntityAdapter;
+import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.MirLocalizerFailure;
+import mircoders.localizer.basic.MirBasicAdminInterfaceLocalizer;
+import mircoders.storage.DatabaseContentToTopics;
+
+public class ArticleTopicAction implements MirBasicAdminInterfaceLocalizer.MirSimpleEntityOperation{
+ private String name;
+ private List deleteTopics;
+ private List addTopics;
+
+ public ArticleTopicAction(String aName, int[] aDeleteTopics, int[] anAddTopics) {
+ name = aName;
+ deleteTopics = new ArrayList();
+ for (int i=0; i< aDeleteTopics.length; i++) {
+ deleteTopics.add(Integer.toString(aDeleteTopics[i]));
+ }
+ addTopics = new ArrayList();
+ for (int i=0; i< anAddTopics.length; i++) {
+ addTopics.add(Integer.toString(anAddTopics[i]));
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isAvailable(EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+ return true;
+ }
+
+ public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+ DatabaseContentToTopics db = DatabaseContentToTopics.getInstance();
+
+ List topicsToSet = new ArrayList(db.getTopicsOfContent(anEntity.getEntity().getId()));
+
+ topicsToSet.removeAll(deleteTopics);
+ topicsToSet.addAll(addTopics);
+
+ db.setTopics(anEntity.getEntity().getId(), topicsToSet);
+ }
+ public void perform2(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure {
+ DatabaseContentToTopics db = DatabaseContentToTopics.getInstance();
+
+ List integerTopicsToSet = new ArrayList(db.getTopicsOfContent(anEntity.getEntity().getId()));
+ List topicsToSet = new ArrayList();
+ Iterator i = integerTopicsToSet.iterator();
+ while (i.hasNext()) {
+ topicsToSet.add(i.next().toString());
+ }
+
+ topicsToSet.removeAll(deleteTopics);
+ topicsToSet.addAll(addTopics);
+
+ db.setTopics(anEntity.getEntity().getId(), topicsToSet);
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer.basic.filters;\r
+\r
+import mircoders.localizer.basic.MirBasicAntiAbuseFilterTypes;\r
+import mircoders.entity.EntityComment;\r
+\r
+import java.util.*;\r
+\r
+import mir.util.StringRoutines;\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+\r
+/**\r
+ * A ip-based throttling filter.\r
+ *\r
+ * <p>\r
+ * Expressions have the form <time in minutes>:<posting limit>\r
+ */\r
+public class ThrottleFilter extends MirBasicAntiAbuseFilterTypes.BasicFilterType {\r
+ private long overallHorizon;\r
+\r
+ private ThrottleManager throttleManager;\r
+\r
+ public ThrottleFilter(String aName, long anOverallHorizon) {\r
+ super(aName);\r
+\r
+ overallHorizon = anOverallHorizon;\r
+ throttleManager = new ThrottleManager(overallHorizon);\r
+ }\r
+\r
+ /** * {@inheritDoc} */\r
+ public boolean validate(String anExpression) {\r
+ List parts = StringRoutines.splitString(anExpression.trim(), ":");\r
+\r
+ try {\r
+ if (parts.size()==2) {\r
+ Integer.parseInt((String) parts.get(0));\r
+ Integer.parseInt((String) parts.get(1));\r
+\r
+ return true;\r
+ }\r
+ }\r
+ catch (Throwable t) {\r
+ }\r
+\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ *\r
+ */\r
+ public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
+ String ip = aRequest.getHeader("ip");\r
+ int limit;\r
+ long period;\r
+\r
+ List parts = StringRoutines.splitString(anExpression, ":");\r
+\r
+ try {\r
+ period = Integer.parseInt((String) parts.get(0))*1000*60;\r
+ limit = Integer.parseInt((String) parts.get(1));\r
+ }\r
+ catch (Throwable t) {\r
+ return false;\r
+ }\r
+\r
+ return throttleManager.addMessage(ip, anEntity, limit, period);\r
+ };\r
+\r
+ private class ThrottleManager {\r
+ private Map throttles;\r
+ private long overallHorizon;\r
+ private Thread cleanUpThread;\r
+\r
+ public ThrottleManager(long anOverallHorizon) {\r
+ throttles = new HashMap();\r
+ overallHorizon = anOverallHorizon;\r
+\r
+ cleanUpThread = new Thread() {\r
+ public void run() {\r
+ while (true) {\r
+ synchronized(throttles) {\r
+ List toDelete = new ArrayList();\r
+ Iterator i = throttles.entrySet().iterator();\r
+\r
+ while (i.hasNext()) {\r
+ Map.Entry entry = (Map.Entry) i.next();\r
+ try {\r
+ if (((Throttle) entry.getValue()).flush()) {\r
+ toDelete.add(entry.getKey());\r
+ }\r
+ }\r
+ catch (Throwable t) {\r
+ toDelete.add(entry.getKey());\r
+ }\r
+ }\r
+\r
+ i = toDelete.iterator();\r
+ while (i.hasNext()) {\r
+ throttles.remove(i.next());\r
+ }\r
+ }\r
+ try {\r
+ Thread.sleep(60*10*1000);\r
+ }\r
+ catch (InterruptedException e) {\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ };\r
+\r
+ cleanUpThread.setDaemon(true);\r
+ cleanUpThread.start();\r
+ }\r
+\r
+ public boolean addMessage(String anIP, Entity anEntity, int aLimit, long aPeriod) {\r
+ synchronized (throttles) {\r
+ Throttle throttle = (Throttle) throttles.get(anIP);\r
+\r
+ if (throttle==null) {\r
+ throttle = new Throttle(overallHorizon);\r
+ throttles.put(anIP, throttle);\r
+ }\r
+ return throttle.addMessage(anEntity, aLimit, aPeriod);\r
+ }\r
+ }\r
+\r
+ private class Throttle {\r
+ private List messages;\r
+ private long horizon;\r
+\r
+ public Throttle(long aHorizon) {\r
+ messages = new ArrayList();\r
+ horizon = aHorizon;\r
+ }\r
+\r
+ public boolean flush() {\r
+ long limit = System.currentTimeMillis() - horizon;\r
+\r
+ while (messages.size()>0 && ((Message) messages.get(0)).getTime()<=limit) {\r
+ messages.remove(0);\r
+ }\r
+\r
+ return messages.size()==0;\r
+ }\r
+\r
+ public boolean addMessage(Entity anEntity, int aLimit, long aPeriod) {\r
+ Message lastMessage=null;\r
+ if (messages.size()>0) {\r
+ lastMessage = (Message) messages.get(messages.size()-1);\r
+ }\r
+\r
+ Message newMessage = new Message(anEntity.getId(),\r
+ anEntity instanceof EntityComment, System.currentTimeMillis());\r
+\r
+ if (!newMessage.equals(lastMessage))\r
+ messages.add(newMessage);\r
+\r
+ if (messages.size()>=aLimit) {\r
+ Message message = (Message) messages.get(messages.size()-aLimit);\r
+ return (System.currentTimeMillis()-message.getTime())<aPeriod;\r
+ }\r
+\r
+ return false;\r
+ }\r
+\r
+ private class Message {\r
+ private String id;\r
+ private boolean isComment;\r
+ private long time;\r
+\r
+ public Message(String anId, boolean anIsComment, long aTime) {\r
+ id = anId;\r
+ isComment = anIsComment;\r
+ time = aTime;\r
+ }\r
+\r
+ public String getId() {\r
+ return id;\r
+ }\r
+\r
+ public boolean getIsComment() {\r
+ return isComment;\r
+ }\r
+\r
+ public long getTime() {\r
+ return time;\r
+ }\r
+\r
+ public int hashCode() {\r
+ return getId().hashCode();\r
+ }\r
+\r
+ public boolean equals(Object anObject) {\r
+ if (anObject instanceof Message) {\r
+ Message that = (Message) anObject;\r
+\r
+ if (that.getId().equals(getId()) && that.getIsComment() == getIsComment()) {\r
+ return true;\r
+ }\r
+ }\r
+\r
+ return false;\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
package mircoders.media;
+import java.awt.RenderingHints;
+import java.awt.image.ColorModel;
+import java.awt.image.DataBuffer;
+import java.awt.image.PixelInterleavedSampleModel;
+import java.awt.image.RenderedImage;
+import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
+
import javax.media.jai.ImageLayout;
import javax.media.jai.InterpolationBilinear;
import javax.media.jai.JAI;
import javax.media.jai.ParameterBlockJAI;
-import javax.media.jai.PlanarImage;
-import java.awt.RenderingHints;
-import java.awt.image.ColorModel;
-import java.awt.image.DataBuffer;
-import java.awt.image.PixelInterleavedSampleModel;
+import mir.log.LoggerWrapper;
import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.SeekableStream;
-import mir.log.LoggerWrapper;
-
/**
*
* <p>Title: Image processor</p>
public class ImageProcessor {
static final LoggerWrapper logger = new LoggerWrapper("media");
- private PlanarImage image;
- private PlanarImage scaledImage;
+ private RenderedImage image;
+ private RenderedImage scaledImage;
- private byte[] iconData;
- private byte[] imageData;
- private int iconWidth;
- private int iconHeight;
+ public ImageProcessor(RenderedImage anImage) throws IOException {
+ image = anImage;
+ scaledImage = anImage;
+ }
public ImageProcessor(SeekableStream anImageStream) throws IOException {
- PlanarImage tempImage = JAI.create("stream", anImageStream);
+ RenderedImage tempImage = JAI.create("stream", anImageStream);
ParameterBlockJAI params = new ParameterBlockJAI("format");
int bands[];
int nrComponents;
}
public void writeScaledData(File aFile, String anImageType) throws IOException {
- writeScaledData(new FileOutputStream(aFile), anImageType);
+ writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType);
}
}
package mircoders.media;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
/**
* 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
+ * @see mir.media.MediaHandler
* @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerAudio.java,v 1.11 2003/09/03 18:29:04 zapata Exp $
*/
-public class MediaHandlerAudio extends MediaHandlerGeneric implements MirMedia
+public class MediaHandlerAudio extends MediaHandlerGeneric implements MediaHandler
{
+ private String tinyIcon;
+ private String bigIcon;
- private static String tinyIcon;
- private static String bigIcon;
-
- static {
+ public MediaHandlerAudio() {
tinyIcon = configuration.getString("Producer.Icon.TinyAudio");
bigIcon = configuration.getString("Producer.Icon.BigAudio");
}
- public String getTinyIcon()
+ public String getTinyIconName()
{
return tinyIcon;
}
return bigIcon;
}
- public String getIconAlt()
+ public String getIconAltName()
{
return "Audio";
}
-
- public boolean isAudio()
- {
- return true;
- }
-
}
*/
package mircoders.media;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Vector;
-import javax.servlet.ServletContext;
-
-import freemarker.template.SimpleList;
-
import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
-import mir.media.MirMedia;
-import mir.misc.FileUtil;
+import mir.media.MediaHandler;
import mir.misc.StringUtil;
+import mir.util.FileFunctions;
+import mir.session.UploadedFile;
+
+import javax.servlet.ServletContext;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Vector;
/**
* we don't have entered in the media_type table, (like RTF documents,
* PS, PDF, etc..)
* <p>
- * Of course it implements the MirMedia interface.
+ * Of course it implements the MirMediaHandler interface.
*
- * @see mir.media.MirMedia
+ * @see mir.media.MediaHandler
* @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerGeneric.java,v 1.22 2003/09/03 18:29:04 zapata Exp $
*/
-public class MediaHandlerGeneric implements MirMedia
+public class MediaHandlerGeneric extends AbstractMediaHandler
{
- protected static MirPropertiesConfiguration configuration;
- protected static String imageHost;
- protected static String imageRoot;
-
- protected LoggerWrapper logger;
-
- static {
- try {
- configuration = MirPropertiesConfiguration.instance();
- }
- catch (MirPropertiesConfiguration.PropertiesConfigExc e) {
- }
- imageHost = configuration.getString("Producer.Image.Host");
- imageRoot = configuration.getString("Producer.ImageRoot");
- }
+ protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
- public MediaHandlerGeneric() {
- logger = new LoggerWrapper("Media.Generic");
- }
+ protected LoggerWrapper logger = new LoggerWrapper("Media.Generic");
- public void set (InputStream in, Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {
- String ext = mediaTypeEnt.getValue("name");
- String mediaFname = ent.getId() + "." + ext;
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- try {
- long size = FileUtil.write(getStoragePath() + File.separator + datePath +
- File.separator + mediaFname, in);
- ent.setValueForProperty("publish_path", datePath + mediaFname);
- ent.setValueForProperty("size", new Long(size).toString());
- ent.update();
- }
- catch (Throwable e) {
- logger.error("MediaHandlerGeneric.set: " + e.toString());
- throw new MediaFailure(e);
- }
+ /** {@inheritDoc} */
+ public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ FileFunctions.move(aFile, getStorageFile(aMedia, aMediaType));
+
+ aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
+ aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
+ aMedia.update();
+ }
+ catch (Throwable e) {
+ logger.error("MediaHandlerGeneric.set: " + e.toString());
+ throw new MediaFailure(e);
}
+ }
- public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {
- //check first if the media file exist since produced
- //location is also the storage location
+ /** {@inheritDoc} */
+ public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ anUploadedFile.writeToFile(getStorageFile(aMedia, aMediaType));
- String date = ent.getValue("date");
- String datePath = StringUtil.webdbDate2path(date);
- String relPath = datePath+ent.getId()+"."+mediaTypeEnt.getValue("name");
- String fname = getStoragePath()+relPath;
- if(! new File(fname).exists())
- throw new MediaExc("error in MirMedia.produce(): " + relPath + " does not exist!");
+ aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
+ aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
+ aMedia.update();
}
-
- public InputStream getMedia (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
- String publishPath = ent.getValue("publish_path");
- String fname = getStoragePath()+publishPath;
- File f = new File(fname);
- if(! f.exists())
- throw new MediaExc("error in MirMedia.getMedia(): " + fname + " does not exist!");
-
- FileInputStream inputStream;
- try {
- inputStream = new FileInputStream(f);
- }
- catch (Throwable e) {
- throw new MediaFailure("MediaHandlerGeneric.getMedia(): " + e.toString(), e);
- }
-
- return inputStream;
+ catch (Throwable e) {
+ logger.error("MediaHandlerGeneric.set: " + e.toString());
+ throw new MediaFailure(e);
}
+ }
- public InputStream getIcon (Entity ent) throws MediaExc, MediaFailure {
- return null;
+ /** {@inheritDoc} */
+ public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ FileFunctions.copy(anInputStream, getStorageFile(aMedia, aMediaType));
+
+ aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType));
+ aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length()));
+ aMedia.update();
+ }
+ catch (Throwable e) {
+ logger.error("MediaHandlerGeneric.set: " + e.toString());
+ throw new MediaFailure(e);
}
+ }
- public String getIconMimeType (Entity aMediaEntity, Entity aMediaType) throws MediaExc, MediaFailure {
- ServletContext servletContext = MirPropertiesConfiguration.getContext();
- String fileName = aMediaEntity.getId()+"."+aMediaType.getValue("name");
+ public void produce(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ if (!getStorageFile(aMedia, aMediaType).exists())
+ throw new MediaExc("error in producing media:: " + getStorageFile(aMedia, aMediaType) + " does not exist!");
+ }
- return servletContext.getMimeType(fileName);
- };
+ /**
+ * Get access to the raw media data by an {@link InputStream}
+ */
+ public InputStream getMedia(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ File file = getStorageFile(aMedia, aMediaType);
+ if (!file.exists())
+ throw new MediaExc("error in MirMediaHandler.getMedia(): " + file + " does not exist!");
- public String getStoragePath()
- {
- return configuration.getString("Producer.Media.Path");
+ try {
+ return new BufferedInputStream(new FileInputStream(file));
}
-
- public String getIconStoragePath()
- {
- return configuration.getString("Producer.Image.IconPath");
+ catch (Throwable e) {
+ throw new MediaFailure("MediaHandlerGeneric.getMedia(): " + e.toString(), e);
}
+ }
- public String getPublishHost()
- {
- return StringUtil.removeSlash(configuration.getString("Producer.Media.Host"));
- }
+ public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure {
+ return null;
+ }
- public String getTinyIconName()
- {
- return configuration.getString("Producer.Icon.TinyText");
- }
+ public String getThumbnailMimeType(Entity aMediaEntity, Entity aMediaType) throws MediaExc, MediaFailure {
+ ServletContext servletContext = MirPropertiesConfiguration.getContext();
+ String fileName = aMediaEntity.getId() + "." + aMediaType.getFieldValue("name");
- public String getBigIconName()
- {
- return configuration.getString("Producer.Icon.BigText");
- }
+ return servletContext.getMimeType(fileName);
+ };
- public String getIconAltName()
- {
- return "Generic media";
- }
+ public String getStoragePath() {
+ return configuration.getString("Producer.Media.Path");
+ }
- public List getURL(Entity ent, Entity mediaTypeEnt)
- {
- List theList = new Vector();
- theList.add(ent);
- return theList;
- }
+ public String getIconStoragePath() {
+ return configuration.getString("Producer.Image.IconPath");
+ }
- public boolean isVideo()
- {
- return false;
- }
+ public String getPublishHost() {
+ return StringUtil.removeSlash(configuration.getString("Producer.Media.Host"));
+ }
- public boolean isAudio()
- {
- return false;
- }
+ public String getTinyIconName() {
+ return configuration.getString("Producer.Icon.TinyText");
+ }
- public boolean isImage()
- {
- return false;
- }
+ public String getBigIconName() {
+ return configuration.getString("Producer.Icon.BigText");
+ }
- public String getDescr( Entity mediaType)
- {
- return mediaType.getValue("mime_type");
- }
+ public String getIconAltName() {
+ return "Generic media";
+ }
+
+ public List getURL(Entity ent, Entity mediaTypeEnt) {
+ List theList = new Vector();
+ theList.add(ent);
+ return theList;
+ }
+
+ public String getDescr(Entity mediaType) {
+ return mediaType.getFieldValue("mime_type");
+ }
}
import java.io.File;
import java.io.InputStream;
-import java.util.*;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.util.List;
+import java.util.Vector;
import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
import mir.misc.FileUtil;
import mir.misc.StringUtil;
+import mir.session.UploadedFile;
+import mir.session.SessionExc;
import mircoders.entity.EntityImages;
/**
* 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.
+ * It implements the MirMediaHandler 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
+ * @see mir.media.MediaHandler
* @author mh
- * @version $Id: MediaHandlerImages.java,v 1.24 2003/09/03 18:29:04 zapata Exp $
*/
-public abstract class MediaHandlerImages implements MirMedia
-{
- protected static MirPropertiesConfiguration configuration;
+public abstract class MediaHandlerImages extends AbstractMediaHandler implements MediaHandler {
+ protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
protected static final String PNG = "PNG";
protected static final String JPEG = "JPEG";
protected LoggerWrapper logger;
- static {
- try {
- configuration = MirPropertiesConfiguration.instance();
- }
- catch (PropertiesConfigExc e) {
- throw new RuntimeException("Can't get configuration: " + e.getMessage());
- }
- }
-
abstract String getType();
public MediaHandlerImages() {
return inputStream;
}
- public void set(InputStream in, Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
+ public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ store(anUploadedFile.getInputStream(), aMedia, aMediaType);
+ }
+ catch (SessionExc e) {
+ throw new MediaFailure(e);
+ }
+ }
+ public void store(InputStream in, Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
try {
((EntityImages)ent).setImage(in, getType());
}
catch (Throwable e) {
- logger.error("MediaHandlerImages.set: "+e.getMessage());
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ logger.error("MediaHandlerImages.store: "+e.toString());
+ e.printStackTrace(logger.asPrintWriter(LoggerWrapper.ERROR_MESSAGE));
+
+ throw new MediaExc("A problem has occurred processing the media file: " + e.toString());
+ }
+ }
+ public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure {
+ try {
+ store(new FileInputStream(aFile), aMedia, aMediaType);
+ }
+ catch (FileNotFoundException e) {
throw new MediaFailure(e);
}
}
public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
- String date = ent.getValue("date");
+ String date = ent.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
- String ext = "."+mediaTypeEnt.getValue("name");
+ String ext = "."+mediaTypeEnt.getFieldValue("name");
String filepath = datePath+ent.getId()+ext;
String iconFilePath = configuration.getString("Producer.StorageRoot")
+getIconStoragePath() + filepath;
String productionFilePath = getStoragePath() + File.separator + filepath;
- if (ent.getValue("icon_data")!= null &&
- ent.getValue("image_data")!= null) {
+ if (ent.getFieldValue("icon_data")!= null &&
+ ent.getFieldValue("image_data")!= null) {
// make icon
try {
- InputStream in = ((EntityImages)ent).getIcon();
+ InputStream in = ((EntityImages) ent).getIcon();
FileUtil.write(iconFilePath, in);
in = ((EntityImages)ent).getImage();
FileUtil.write(productionFilePath, in);
- ent.setValueForProperty("icon_path",getIconStoragePath()+filepath);
- ent.setValueForProperty("publish_path",filepath);
+ ent.setFieldValue("icon_path",getIconStoragePath()+filepath);
+ ent.setFieldValue("publish_path",filepath);
ent.update();
}
catch (Throwable e) {
}
}
-
- public InputStream getIcon(Entity ent) throws MediaExc, MediaFailure {
+ public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure {
InputStream in;
try {
- in = ((EntityImages)ent).getIcon();
+ in = ((EntityImages) ent).getIcon();
}
catch (Throwable e) {
logger.error("MediaHandlerImages.getIcon: " + e.toString());
return "Image";
}
- public boolean isVideo() {
- return false;
- }
-
- public boolean isAudio() {
- return false;
- }
-
- public boolean isImage () {
- return true;
- }
-
public String getDescr(Entity mediaType) {
return "image/jpeg";
}
package mircoders.media;
+import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
-import mir.config.MirPropertiesConfiguration;
import mir.entity.Entity;
import mir.log.LoggerWrapper;
import mir.media.MediaExc;
import mir.media.MediaFailure;
import mir.misc.StringUtil;
-import mircoders.storage.DatabaseUploadedMedia;
-import mircoders.module.*;
/**
public MediaHandlerImagesExtern() {
logger = new LoggerWrapper("Media.Images.Extern");
- try {
- MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
- }
- catch (Throwable t) {
- logger.fatal("MediaHandlerImagesExtern: can't get configuration");
-
- throw new RuntimeException(t.toString());
- }
maxIconSize = configuration.getInt("Producer.Image.MaxIconSize");
minDescaleRatio = configuration.getFloat("Producer.Image.MinDescalePercentage")/100;
public void produce(Entity anImageEntity, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
try {
- String date = anImageEntity.getValue("date");
+ String date = anImageEntity.getFieldValue("date");
String datePath = StringUtil.webdbDate2path(date);
- String ext = "." + mediaTypeEnt.getValue("name");
+ String ext = "." + mediaTypeEnt.getFieldValue("name");
String fileBasePath = datePath + anImageEntity.getId();
String filePath = fileBasePath + ext;
String iconPath = getIconStoragePath() + fileBasePath + ".jpg";
}
processor.writeScaledData(iconFile, "JPEG");
- anImageEntity.setValueForProperty("img_height", new Integer(processor.getHeight()).toString());
- anImageEntity.setValueForProperty("img_width", new Integer(processor.getWidth()).toString());
+ anImageEntity.setFieldValue("img_height", new Integer(processor.getHeight()).toString());
+ anImageEntity.setFieldValue("img_width", new Integer(processor.getWidth()).toString());
- anImageEntity.setValueForProperty("icon_height", new Integer(processor.getScaledHeight()).toString());
- anImageEntity.setValueForProperty("icon_width", new Integer(processor.getScaledWidth()).toString());
+ anImageEntity.setFieldValue("icon_height", new Integer(processor.getScaledHeight()).toString());
+ anImageEntity.setFieldValue("icon_width", new Integer(processor.getScaledWidth()).toString());
- anImageEntity.setValueForProperty("icon_path", iconPath);
- anImageEntity.setValueForProperty("publish_path", filePath);
+ anImageEntity.setFieldValue("icon_path", iconPath);
+ anImageEntity.setFieldValue("publish_path", filePath);
anImageEntity.update();
}
}
catch(Throwable t) {
- logger.error("MediaHandlerImagesExtern.produce: " + t.getMessage());
+ logger.error("MediaHandlerImagesExtern.produce: " + t.toString());
t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
throw new MediaFailure(t.getMessage(), t);
}
}
- public InputStream getIcon(Entity anImageEntity) throws MediaExc, MediaFailure {
+ /** {@inheritDoc} */
+ public InputStream getThumbnail(Entity anImageEntity) throws MediaExc, MediaFailure {
try {
- String filePath =
- configuration.getString("Producer.StorageRoot") + anImageEntity.getValue("icon_path");
+ File file = new File(configuration.getString("Producer.StorageRoot") + anImageEntity.getFieldValue("icon_path"));
- logger.info(filePath);
+ if (!file.exists()) {
+ // hackish
+ file = new File(configuration.getHome(), "../img/photo_big.gif");
+ }
- return new FileInputStream(new File(filePath));
+ return new BufferedInputStream(
+ new FileInputStream(file),8192);
}
catch (Throwable t) {
return null;
return "Image";
}
- public boolean isVideo()
- {
- return false;
- }
-
- public boolean isAudio()
- {
- return false;
- }
-
- public boolean isImage ()
- {
- return true;
- }
-
public String getDescr(Entity mediaType)
{
return "image/jpeg";
package mircoders.media;
import mir.entity.Entity;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
/**
* This class handles saving, fetching creating representations
* for all JPeg images. The image content is stored in the DB. The content is
* written out to a file at the ProducerImages level.
- * It implements the MirMedia interface.
+ * It implements the MirMediaHandler interface.
* <p>
*
- * @see mir.media.MirMedia
+ * @see mir.media.MediaHandler
* @see mircoders.media.MediaHandlerImages
* @author mh, mir-coders group
- * @version $Id: MediaHandlerImagesJpeg.java,v 1.6 2003/04/29 02:36:50 zapata Exp $
*/
-public class MediaHandlerImagesJpeg extends MediaHandlerImages implements MirMedia
+public class MediaHandlerImagesJpeg extends MediaHandlerImages implements MediaHandler
{
public String getType() {
return JPEG;
return "image/jpeg";
}
- public String getIconMimeType(Entity aMedia, Entity aMediaType) {
+ public String getThumbnailMimeType(Entity aMedia, Entity aMediaType) {
return "image/jpeg";
}
}
package mircoders.media;
import mir.entity.Entity;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
/**
* This class handles saving, fetching creating representations
* for all png images. The image content is stored in the DB. The content is
* written out to a file at the ProducerImages level.
- * It implements the MirMedia interface.
+ * It implements the MediaHandler interface.
* <p>
*
- * @see mir.media.MirMedia
+ * @see mir.media.MediaHandler
* @see mircoders.media.MediaHandlerImages
* @author mh ,mir-coders
- * @version $Id: MediaHandlerImagesPng.java,v 1.7 2003/04/29 02:36:50 zapata Exp $
+ * @version $Id: MediaHandlerImagesPng.java,v 1.8 2004/11/06 20:04:00 idfx Exp $
*/
-public class MediaHandlerImagesPng extends MediaHandlerImages implements MirMedia
+public class MediaHandlerImagesPng extends MediaHandlerImages implements MediaHandler
{
public String getType() {
return PNG;
return "image/png";
}
- public String getIconMimeType(Entity aMedia, Entity aMediaType) {
+ public String getThumbnailMimeType(Entity aMedia, Entity aMediaType) {
return "image/png";
}
}
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.media;\r
-\r
-import java.io.StringReader;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaExc;\r
-import mir.media.MediaFailure;\r
-import mir.media.MirMedia;\r
-import mir.misc.FileUtil;\r
-import mir.misc.StringUtil;\r
-\r
-/**\r
- * Please note: this media handler produces\r
- * 3 media files, the raw .mp3, a .m3u which is\r
- * contains the URL for the mp3 and a .pls which\r
- * contains the URL to the mp3 in shoutcast playlist\r
- * format. What's important is that the web server (of\r
- * the media host) must recognize the .m3u and .pls file\r
- * extensions and send the proper "audio/x-mpegurl"\r
- * and "audio/x-scpls" mime-types respectively.\r
- * If the web server is apache, it's easy, just\r
- * add:\r
- *\r
- * audio/x-mpegurl m3u\r
- * audio/x-scpl pls\r
- *\r
- * to the file pointed to by the "TypesConfig"\r
- * command in your apache config file. Or add\r
- * and equivalent AddType command to your httpd.conf.\r
- * Of course this assumes that the mod_mime is loaded.\r
- *\r
- * If the web server is not apache, then your on your own.\r
- *\r
- * @see mir.media.MirMedia\r
- * @author mh <mh@nadir.org>\r
- * @version $Id: MediaHandlerMp3.java,v 1.16 2003/09/03 18:29:04 zapata Exp $\r
- */\r
-\r
-public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia\r
-{\r
- protected LoggerWrapper logger;\r
-\r
- public MediaHandlerMp3() {\r
- logger = new LoggerWrapper("Media.Audio.Mp3");\r
- }\r
-\r
- public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {\r
-\r
- // first check if the file exists\r
- super.produce(ent, mediaTypeEnt);\r
-\r
- String baseName = ent.getId();\r
- String date = ent.getValue("date");\r
- String datePath = StringUtil.webdbDate2path(date);\r
- String mp3Pointer = getPublishHost() + ent.getValue("publish_path");\r
- String mpegURLFile = baseName + ".m3u";\r
- String playlistFile = baseName + ".pls";\r
-\r
- try {\r
- //write the "meta" files\r
- //first the .m3u since it only contains one line\r
- FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,\r
- new StringReader(mp3Pointer), "US-ASCII");\r
- //now the .pls file\r
- FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,\r
- new StringReader(mp3Pointer), "US-ASCII");\r
- }\r
- catch (Throwable e) {\r
- logger.error("MediaHandlerMp3.produce: " + e.toString());\r
-\r
- throw new MediaFailure(e);\r
- }\r
- }\r
-\r
- public List getURL(Entity ent, Entity mediaTypeEnt) {\r
- List theList = new Vector();\r
-\r
- //String stringSize = ent.getValue("size");\r
- //int size = Integer.parseInt(stringSize, 10)/1024;\r
- theList.add(ent);\r
-\r
- String basePath = StringUtil.regexpReplace(ent.getValue("publish_path"),\r
- ".mp3$", "");\r
-\r
- // @todo the texts ("title") below urgently need to be sanely localizaeble\r
- // somehow\r
- Map m3uHash = new HashMap();\r
- m3uHash.put("publish_path", basePath + ".m3u");\r
- m3uHash.put("publish_server", ent.getValue("publish_server"));\r
- m3uHash.put("title", "stream URL");\r
- theList.add(m3uHash);\r
-\r
- Map plsHash = new HashMap();\r
- plsHash.put("publish_path", basePath + ".pls");\r
- plsHash.put("publish_server", ent.getValue("publish_server"));\r
- plsHash.put("title", "playlist URL");\r
- theList.add(plsHash);\r
-\r
- return theList;\r
-\r
- }\r
-\r
- public String getDescr(Entity mediaType) {\r
- return "mp3";\r
- }\r
-}\r
-\r
-\r
-\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.media;
+
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MediaHandler;
+import mir.misc.FileUtil;
+import mir.misc.StringUtil;
+
+/**
+ * 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.MediaHandler
+ * @author mh <mh@nadir.org>
+ * @version $Id: MediaHandlerMp3.java,v 1.17 2004/11/06 20:04:00 idfx Exp $
+ */
+
+public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler
+{
+
+ public MediaHandlerMp3() {
+ logger = new LoggerWrapper("Media.Audio.Mp3");
+ }
+
+ public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
+
+ // first check if the file exists
+ super.produce(ent, mediaTypeEnt);
+
+ String baseName = ent.getId();
+ String date = ent.getFieldValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String mp3Pointer = getPublishHost() + ent.getFieldValue("publish_path");
+ String mpegURLFile = baseName + ".m3u";
+ String playlistFile = baseName + ".pls";
+
+ try {
+ //write the "meta" files
+ //first the .m3u since it only contains one line
+ FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,
+ new StringReader(mp3Pointer), "US-ASCII");
+ //now the .pls file
+ FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,
+ new StringReader(mp3Pointer), "US-ASCII");
+ }
+ catch (Throwable e) {
+ logger.error("MediaHandlerMp3.produce: " + e.toString());
+
+ throw new MediaFailure(e);
+ }
+ }
+
+ public List getURL(Entity ent, Entity mediaTypeEnt) {
+ List theList = new Vector();
+
+ //String stringSize = ent.getFieldValue("size");
+ //int size = Integer.parseInt(stringSize, 10)/1024;
+ theList.add(ent);
+
+ String basePath = StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
+ ".mp3$", "");
+
+ // @todo the texts ("title") below urgently need to be sanely localizaeble
+ // somehow
+ Map m3uHash = new HashMap();
+ m3uHash.put("publish_path", basePath + ".m3u");
+ m3uHash.put("publish_server", ent.getFieldValue("publish_server"));
+ m3uHash.put("title", "stream URL");
+ theList.add(m3uHash);
+
+ Map plsHash = new HashMap();
+ plsHash.put("publish_path", basePath + ".pls");
+ plsHash.put("publish_server", ent.getFieldValue("publish_server"));
+ plsHash.put("title", "playlist URL");
+ theList.add(plsHash);
+
+ return theList;
+
+ }
+
+ public String getDescr(Entity mediaType) {
+ return "mp3";
+ }
+}
+
+
+
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.media;\r
-\r
-import java.io.StringReader;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaExc;\r
-import mir.media.MediaFailure;\r
-import mir.media.MirMedia;\r
-import mir.misc.FileUtil;\r
-import mir.misc.StringUtil;\r
-\r
-\r
-\r
-/**\r
- * Handles realAudio .it manages the ram file.\r
- *\r
- * 03.2002 - reworked Realmedia handling. -mh\r
- *\r
- * @see mir.media.MediaHandlerGeneric\r
- * @see mir.media.MirMedia\r
- * @author john <john@manifestor.org>, mh <heckmann@hbe.ca>\r
- * @version $Id: MediaHandlerRealAudio.java,v 1.20 2003/09/03 18:29:04 zapata Exp $\r
- */\r
-\r
-\r
-public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia\r
-{\r
- public MediaHandlerRealAudio() {\r
- logger = new LoggerWrapper("Media.Audio.Real");\r
- }\r
-\r
- public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {\r
-\r
- // first see if the file exists\r
- super.produce(ent, mediaTypeEnt);\r
-\r
- String baseName = ent.getId();\r
- String date = ent.getValue("date");\r
- String datePath = StringUtil.webdbDate2path(date);\r
- String rtspDir = configuration.getString("Producer.RealMedia.Path");\r
- String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");\r
-\r
- String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");\r
- String RealMediaFile = datePath+ent.getId()+".ram";\r
- try {\r
- //write an rm (ram?. -mh) file\r
- FileUtil.write(super.getStoragePath()+"/"+RealMediaFile,\r
- new StringReader(RealMediaPointer), "US-ASCII");\r
- }\r
- catch (Throwable e) {\r
- logger.error("MediaHandlerRealAudio.produce: " + e.toString());\r
- throw new MediaFailure(e);\r
- }\r
- }\r
-\r
- public List getURL(Entity ent, Entity mediaTypeEnt)\r
- {\r
- List theList = new Vector();\r
-\r
- //String stringSize = ent.getValue("size");\r
- //int size = Integer.parseInt(stringSize, 10)/1024;\r
- theList.add(ent);\r
-\r
- String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),\r
- ".ra$","");\r
-\r
- // @todo the texts ("title") below urgently need to be sanely localizaeble\r
- // somehow\r
- Map ramHash = new HashMap();\r
- ramHash.put("publish_path", basePath+".ram");\r
- ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));\r
- ramHash.put("title", "stream URL");\r
- theList.add(ramHash);\r
-\r
- return theList;\r
- }\r
-\r
- public String getStoragePath()\r
- {\r
- return configuration.getString("Producer.RealMedia.Path");\r
- }\r
-\r
- public String getDescr(Entity mediaType)\r
- {\r
- return "RealMedia";\r
- }\r
-\r
- public String getPublishHost()\r
- {\r
- return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));\r
- }\r
-\r
-}\r
-\r
-\r
-\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.media;
+
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MediaHandler;
+import mir.misc.FileUtil;
+import mir.misc.StringUtil;
+
+
+
+/**
+ * Handles realAudio .it manages the ram file.
+ *
+ * 03.2002 - reworked Realmedia handling. -mh
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MediaHandler
+ * @author john <john@manifestor.org>, mh <heckmann@hbe.ca>
+ * @version $Id: MediaHandlerRealAudio.java,v 1.21 2004/11/06 20:04:00 idfx Exp $
+ */
+
+
+public class MediaHandlerRealAudio extends MediaHandlerAudio implements MediaHandler
+{
+ public MediaHandlerRealAudio() {
+ logger = new LoggerWrapper("Media.Audio.Real");
+ }
+
+ public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {
+
+ // first see if the file exists
+ super.produce(ent, mediaTypeEnt);
+
+ String baseName = ent.getId();
+ String date = ent.getFieldValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String rtspDir = configuration.getString("Producer.RealMedia.Path");
+ String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
+
+ String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path");
+ String RealMediaFile = datePath+ent.getId()+".ram";
+ try {
+ //write an rm (ram?. -mh) file
+ FileUtil.write(super.getStoragePath()+"/"+RealMediaFile,
+ new StringReader(RealMediaPointer), "US-ASCII");
+ }
+ catch (Throwable e) {
+ logger.error("MediaHandlerRealAudio.produce: " + e.toString());
+ throw new MediaFailure(e);
+ }
+ }
+
+ public List getURL(Entity ent, Entity mediaTypeEnt)
+ {
+ List theList = new Vector();
+
+ //String stringSize = ent.getFieldValue("size");
+ //int size = Integer.parseInt(stringSize, 10)/1024;
+ theList.add(ent);
+
+ String basePath=StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
+ ".ra$","");
+
+ // @todo the texts ("title") below urgently need to be sanely localizaeble
+ // somehow
+ Map ramHash = new HashMap();
+ ramHash.put("publish_path", basePath+".ram");
+ ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
+ ramHash.put("title", "stream URL");
+ theList.add(ramHash);
+
+ return theList;
+ }
+
+ public String getStoragePath()
+ {
+ return configuration.getString("Producer.RealMedia.Path");
+ }
+
+ public String getDescr(Entity mediaType)
+ {
+ return "RealMedia";
+ }
+
+ public String getPublishHost()
+ {
+ return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));
+ }
+
+}
+
+
+
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-package mircoders.media;\r
-\r
-import java.io.File;\r
-import java.io.StringReader;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Vector;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.media.MediaExc;\r
-import mir.media.MediaFailure;\r
-import mir.media.MirMedia;\r
-import mir.misc.FileUtil;\r
-import mir.misc.StringUtil;\r
-\r
-\r
-\r
-/**\r
- * Handles realVideo .it manages the ram file.\r
- *\r
- * 03.2002 - reworked Realmedia handling. -mh\r
- *\r
- * @see mir.media.MediaHandlerGeneric\r
- * @see mir.media.MirMedia\r
- * @author john <john@manifestor.org>, mh <mh@nadir.org>\r
- * @version $Id: MediaHandlerRealVideo.java,v 1.20 2003/09/03 18:29:04 zapata Exp $\r
- */\r
-\r
-\r
-public class MediaHandlerRealVideo extends MediaHandlerVideo implements MirMedia\r
-{\r
- protected LoggerWrapper logger;\r
-\r
- public MediaHandlerRealVideo() {\r
- logger = new LoggerWrapper("Media.Video.Real");\r
- }\r
-\r
- public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {\r
- // first see if the file exists\r
- super.produce(ent, mediaTypeEnt);\r
-\r
- String baseName = ent.getId();\r
- String date = ent.getValue("date");\r
- String datePath = StringUtil.webdbDate2path(date);\r
- String rtspDir = configuration.getString("Producer.RealMedia.Path");\r
- String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");\r
-\r
- String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");\r
- String RealMediaFile = datePath+ent.getId()+".ram";\r
- try {\r
- //write an rm (ram?. -mh) file\r
- FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile,\r
- new StringReader(RealMediaPointer), "US-ASCII");\r
- }\r
- catch (Throwable e) {\r
- logger.error("MediaHandlerRealVideo.produce: " + e.toString());\r
-\r
- throw new MediaFailure(e);\r
- }\r
- }\r
-\r
- public List getURL(Entity ent, Entity mediaTypeEnt) {\r
- List theList = new Vector();\r
-\r
- //String stringSize = ent.getValue("size");\r
- //int size = Integer.parseInt(stringSize, 10)/1024;\r
- theList.add(ent);\r
-\r
- String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),\r
- ".rm$","");\r
-\r
- // @todo the texts ("title") below urgently need to be sanely localizaeble\r
- // somehow\r
- Map ramHash = new HashMap();\r
- ramHash.put("publish_path", basePath+".ram");\r
- ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));\r
- ramHash.put("title", "stream URL");\r
- theList.add(ramHash);\r
-\r
- return theList;\r
-\r
- }\r
-\r
- public String getStoragePath() {\r
- return configuration.getString("Producer.RealMedia.Path");\r
- }\r
-\r
- public String getDescr(Entity mediaType) {\r
- return "RealMedia";\r
- }\r
-\r
- public String getPublishHost() {\r
- return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));\r
- }\r
-\r
-}\r
-\r
-\r
-\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.media;
+
+import java.io.File;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.media.MediaExc;
+import mir.media.MediaFailure;
+import mir.media.MediaHandler;
+import mir.misc.FileUtil;
+import mir.misc.StringUtil;
+
+
+
+/**
+ * Handles realVideo .it manages the ram file.
+ *
+ * 03.2002 - reworked Realmedia handling. -mh
+ *
+ * @see mir.media.MediaHandlerGeneric
+ * @see mir.media.MediaHandler
+ * @author john <john@manifestor.org>, mh <mh@nadir.org>
+ * @version $Id: MediaHandlerRealVideo.java,v 1.21 2004/11/06 20:04:00 idfx Exp $
+ */
+
+
+public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHandler
+{
+
+ public MediaHandlerRealVideo() {
+ logger = new LoggerWrapper("Media.Video.Real");
+ }
+
+ public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
+ // first see if the file exists
+ super.produce(ent, mediaTypeEnt);
+
+ String baseName = ent.getId();
+ String date = ent.getFieldValue("date");
+ String datePath = StringUtil.webdbDate2path(date);
+ String rtspDir = configuration.getString("Producer.RealMedia.Path");
+ String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
+
+ String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path");
+ String RealMediaFile = datePath+ent.getId()+".ram";
+ try {
+ //write an rm (ram?. -mh) file
+ FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile,
+ new StringReader(RealMediaPointer), "US-ASCII");
+ }
+ catch (Throwable e) {
+ logger.error("MediaHandlerRealVideo.produce: " + e.toString());
+
+ throw new MediaFailure(e);
+ }
+ }
+
+ public List getURL(Entity ent, Entity mediaTypeEnt) {
+ List theList = new Vector();
+
+ //String stringSize = ent.getFieldValue("size");
+ //int size = Integer.parseInt(stringSize, 10)/1024;
+ theList.add(ent);
+
+ String basePath=StringUtil.regexpReplace(ent.getFieldValue("publish_path"),
+ ".rm$","");
+
+ // @todo the texts ("title") below urgently need to be sanely localizaeble
+ // somehow
+ Map ramHash = new HashMap();
+ ramHash.put("publish_path", basePath+".ram");
+ ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
+ ramHash.put("title", "stream URL");
+ theList.add(ramHash);
+
+ return theList;
+
+ }
+
+ public String getStoragePath() {
+ return configuration.getString("Producer.RealMedia.Path");
+ }
+
+ public String getDescr(Entity mediaType) {
+ return "RealMedia";
+ }
+
+ public String getPublishHost() {
+ return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));
+ }
+
+}
+
+
+
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.media;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
/**
* It is MediaHandlerGeneric with different icons.
*
* @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
+ * @see mir.media.MediaHandler
* @author john <john@manifestor.org>
- * @version $Id: MediaHandlerVideo.java,v 1.9 2003/04/21 12:42:48 idfx Exp $
*/
-public class MediaHandlerVideo extends MediaHandlerGeneric implements MirMedia
+public class MediaHandlerVideo extends MediaHandlerGeneric implements MediaHandler
{
private static String tinyIcon;
private static String bigIcon;
bigIcon = configuration.getString("Producer.Icon.BigVideo");
}
- public String getTinyIcon() {
+ public String getTinyIconName() {
return tinyIcon;
}
return bigIcon;
}
- public String getIconAlt() {
+ public String getIconAltName() {
return "Video";
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.media;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Map;
-
import mir.entity.Entity;
import mir.media.MediaExc;
import mir.media.MediaFailure;
-import mir.media.MediaHelper;
-import mir.media.MirMedia;
+import mir.media.MediaHandler;
import mir.misc.StringUtil;
import mir.session.UploadedFile;
import mir.storage.Database;
+import mir.log.LoggerWrapper;
+import mir.util.FileFunctions;
import mircoders.module.ModuleMediaType;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Map;
+
public class MediaUploadProcessor {
+ private static LoggerWrapper logger = new LoggerWrapper("Media.UploadProcessor");
+ private static ModuleMediaType mediaTypeModule = new ModuleMediaType();
+
+ /**
+ * Processes an uploaded media file.
+ * Will create the media entity and so on.
+ */
public static Entity processMediaUpload(UploadedFile aFile, Map aValues) throws MediaExc, MediaFailure {
- String mediaId;
- MirMedia mediaHandler;
+ MediaHandler mediaHandler;
Entity mediaType;
- ModuleMediaType mediaTypeModule;
Database mediaStorage;
Map values = new HashMap();
- String MediaId;
Entity mediaEntity;
+ String contentType = aFile.getContentType();
+ logger.debug("processing media upload of " + aFile.getFileName() + " (content type = " + contentType + ")");
- try {
- String contentType = aFile.getContentType();
-
+ if (contentType!=null) {
if (contentType.equals("text/plain") ||
contentType.equals("application/octet-stream") ||
contentType == null) {
throw new MediaExc("Invalid content-type: " + contentType);
}
+ }
- values.putAll(aValues);
- values.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
- values.put("is_produced", "0");
-
- mediaTypeModule = new ModuleMediaType();
- mediaType = mediaTypeModule.findMediaTypeForMimeType(contentType);
-
- try {
- mediaHandler = MediaHelper.getHandler(mediaType);
- mediaStorage = MediaHelper.getStorage(mediaType, "mircoders.storage.Database");
+ try {
+ if (contentType!=null) {
+ mediaType = mediaTypeModule.findMediaTypeForExtension(contentType);
}
- catch (Throwable e) {
- throw new MediaFailure(e);
+ else {
+ String extension = FileFunctions.getExtension(aFile.getFileName());
+ mediaType = mediaTypeModule.findMediaTypeForExtension(extension);
}
+ }
+ catch (Throwable t) {
+ throw new MediaFailure(t);
+ }
- values.put("to_media_type", mediaType.getId());
+ values.putAll(aValues);
+ values.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
+ values.put("is_produced", "0");
- try {
- mediaEntity = (Entity) mediaStorage.getEntityClass().newInstance();
- mediaEntity.setStorage(mediaStorage);
- }
- catch (Throwable e) {
- throw new MediaFailure(e);
- }
+ try {
+ mediaHandler = MediaHelper.getHandler(mediaType);
+ mediaStorage = MediaHelper.getStorage(mediaType, mediaType.getFieldValue("tablename"));
+ }
+ catch (Throwable e) {
+ throw new MediaFailure(e);
+ }
- mediaEntity.setValues(values);
- mediaId = mediaEntity.insert();
+ values.put("to_media_type", mediaType.getId());
- try {
- mediaHandler.set(aFile.getInputStream(), mediaEntity, mediaType);
- }
- catch (Throwable e) {
- throw new MediaFailure(e);
- }
+ try {
+ mediaEntity = (Entity) mediaStorage.getEntityClass().newInstance();
+ mediaEntity.setStorage(mediaStorage);
+ }
+ catch (Throwable e) {
+ throw new MediaFailure(e);
+ }
- return mediaEntity;
+ mediaEntity.setFieldValues(values);
+ try {
+ mediaEntity.insert();
+ mediaHandler.store(aFile, mediaEntity, mediaType);
}
catch (Throwable e) {
throw new MediaFailure(e);
}
+ return mediaEntity;
}
}
\ No newline at end of file
*/
package mircoders.module;
-import mir.log.LoggerWrapper;\r
-import mir.module.AbstractModule;\r
-import mir.module.ModuleExc;\r
-import mir.module.ModuleFailure;\r
-import mir.storage.StorageObject;\r
+import mir.log.LoggerWrapper;
+import mir.module.AbstractModule;
+import mir.module.ModuleExc;
+import mir.module.ModuleFailure;
import mir.util.JDBCStringRoutines;
+import mircoders.storage.DatabaseArticleType;
public class ModuleArticleType extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.ArticleType");
- public ModuleArticleType (StorageObject theStorage) {
-
- if (theStorage == null)
- logger.warn("ModuleArticleType -- StorageObject was null!");
-
- this.theStorage = theStorage;
+ public ModuleArticleType() {
+ super(DatabaseArticleType.getInstance());
}
public String articleTypeIdForName(String aName) throws ModuleExc, ModuleFailure {
try {
- return theStorage.executeFreeSingleValueSql("select id from article_type where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ return storage.executeFreeSingleValueSql("select id from article_type where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
}
catch (Throwable t) {
throw new ModuleFailure(t);
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.module;
-import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.storage.StorageObject;
+import mircoders.storage.DatabaseBreaking;
{
static LoggerWrapper logger = new LoggerWrapper("Module.Breaking");
- public ModuleBreaking (StorageObject theStorage)
+ public ModuleBreaking ()
{
- if (theStorage == null) logger.warn("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) {
- logger.error("--getBreakingNews(): could not fetch Breaking News" + ex.toString());
- }
- return returnList;
+ super (DatabaseBreaking.getInstance());
}
}
*/
package mircoders.module;
-import java.util.Map;\r
-\r
-import mir.entity.Entity;\r
-import mir.log.LoggerWrapper;\r
-import mir.module.AbstractModule;\r
-import mir.module.ModuleExc;\r
-import mir.module.ModuleFailure;\r
-import mir.storage.StorageObject;\r
+import mir.entity.Entity;
+import mir.log.LoggerWrapper;
+import mir.module.AbstractModule;
+import mir.module.ModuleExc;
+import mir.module.ModuleFailure;
+import mircoders.storage.DatabaseComment;
import mircoders.storage.DatabaseContent;
+import java.util.Map;
+
/*
* ModuleComment - methods and access for comments
{
static LoggerWrapper logger = new LoggerWrapper("Module.Comment");
- public ModuleComment(StorageObject theStorage)
+ public ModuleComment()
{
- if (theStorage == null) logger.warn("StorageObject was null!");
- this.theStorage = theStorage;
+ super(DatabaseComment.getInstance());
}
public void deleteById (String anId) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = theStorage.selectById((String)anId);
+ Entity theEntity = storage.selectById((String)anId);
if (theEntity != null)
- DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getValue("to_media"));
+ DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getFieldValue("to_media"));
super.deleteById(anId);
}
public String set(Map theValues) throws ModuleExc, ModuleFailure {
try {
- Entity theEntity = theStorage.selectById((String)theValues.get("id"));
+ Entity theEntity = storage.selectById((String)theValues.get("id"));
if (theEntity == null)
throw new ModuleExc("No Object in the database with id " + theValues.get("id"));
- DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getValue("to_media"));
- theEntity.setValues(theValues);
+ DatabaseContent.getInstance().setUnproduced("id=" + theEntity.getFieldValue("to_media"));
+ theEntity.setFieldValues(theValues);
theEntity.update();
return theEntity.getId();
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.module;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.storage.StorageObject;
+import mir.module.ModuleExc;
+import mir.module.ModuleFailure;
+import mir.util.JDBCStringRoutines;
+import mircoders.storage.DatabaseCommentStatus;
public class ModuleCommentStatus extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.CommentStatus");
- public ModuleCommentStatus (StorageObject theStorage) {
- if (theStorage == null)
- logger.warn("ModuleCommentStatus -- StorageObject was null!");
+ public ModuleCommentStatus () {
+ super(DatabaseCommentStatus.getInstance());
+ }
- this.theStorage = theStorage;
+ public String commentStatusIdForName(String aName) throws ModuleExc, ModuleFailure {
+ try {
+ return storage.executeFreeSingleValueSql("select id from comment_status where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ }
+ catch (Throwable t) {
+ throw new ModuleFailure(t);
+ }
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.module;
-import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
+import mir.util.JDBCStringRoutines;
+import mircoders.global.MirGlobal;
+import mircoders.storage.DatabaseContent;
/**
*
static LoggerWrapper logger = new LoggerWrapper("Module.Content");
public ModuleContent() {
- super();
+ super(DatabaseContent.getInstance());
}
- public ModuleContent(StorageObject theStorage) {
- this.theStorage = theStorage;
+ public void expireArticleLock(String anId, String aUserId) {
+ if (!MirGlobal.isUserLoggedIn(anId)) {
+ unlockArticle(anId, aUserId, false);
+ }
}
- public EntityList getContent(String whereClause, String orderBy,int offset, int limit) throws ModuleExc, ModuleFailure {
+ /**
+ * Locks an article. Forced (that is, without checking wether it's already locked)
+ * if necessary.
+ *
+ * @param anId The article number
+ * @param aUserId The locking user
+ * @param aForce Should it e forced?
+ * @return
+ */
+ public boolean lockArticle(String anId, String aUserId, boolean aForce) {
try {
- return theStorage.selectByWhereClause(whereClause, orderBy, offset, limit);
+ String query =
+ "update content set to_locking_user=" + JDBCStringRoutines.escapeStringLiteral(aUserId) +
+ " where id = " + JDBCStringRoutines.escapeStringLiteral(anId);
+
+ if (!aForce)
+ query = query + " and to_locking_user is null";
+
+ return storage.executeUpdate(query) > 0;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ }
+
+ /**
+ * Unlocks an article. Forced (that is, without checking wether it's locked by
+ * the person that unlocks it) if necessary.
+ *
+ * @param anId The article number
+ * @param aUserId The user that unlocks
+ * @param aForce Should it e forced?
+ * @return <code>true</code> if successfull, <code>false</code> if not
+ */
+ public boolean unlockArticle(String anId, String aUserId, boolean aForce) {
+ try {
+ String query =
+ "update content set to_locking_user=null" +
+ " where id = " + JDBCStringRoutines.escapeStringLiteral(anId);
+
+ if (!aForce)
+ query = query + " and to_locking_user = "+JDBCStringRoutines.escapeStringLiteral(aUserId);
+
+ return storage.executeUpdate(query) > 0;
+ }
+ catch (Throwable t) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns the id of the locking user of an article. <code>null</code> otherwise.
+ *
+ * @param anId
+ * @return
+ */
+ public String queryArticleLock(String anId) {
+ try {
+ String result = storage.executeFreeSingleValueSql("select to_locking_user from content where id = " + JDBCStringRoutines.escapeStringLiteral(anId));
+
+ if (result!=null && !MirGlobal.isUserLoggedIn(result)) {
+ expireArticleLock(anId, result);
+ result = null;
+ }
+
+ return result;
}
- catch (Throwable e){
- throw new ModuleFailure(e);
+ catch (Throwable t) {
+ return null;
}
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.module;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.storage.StorageObject;
+import mircoders.storage.DatabaseImages;
public class ModuleImages extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Images");
- public ModuleImages(StorageObject theStorage) {
- if (theStorage == null)
- logger.warn("ModuleImages: StorageObject was null!");
- this.theStorage = theStorage;
-
- }
-
-// Methoden
-/*
- public SimpleList getBilderAsSimpleList() throws ModuleExc, ModuleFailure {
- try {
- return ((DatabaseImages)theStorage).getPopupData();
- }
- catch (StorageObjectFailure e) {
- throw new ModuleException(e.toString());
- }
+ public ModuleImages() {
+ super(DatabaseImages.getInstance());
}
-*/
}
import mir.module.AbstractModule;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
import mir.util.JDBCStringRoutines;
+import mir.entity.Entity;
+import mir.entity.EntityList;
+import mircoders.storage.DatabaseLanguage;
/**
* Title: mir - another content management system
public class ModuleLanguage extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Language");
- public ModuleLanguage (StorageObject theStorage) {
- if (theStorage == null)
- logger.warn("ModuleLanguage -- StorageObject was null!");
-
- this.theStorage = theStorage;
+ public ModuleLanguage () {
+ super(DatabaseLanguage.getInstance());
}
public String languageIdForCode(String aCode) throws ModuleExc, ModuleFailure {
try {
- return theStorage.executeFreeSingleValueSql("select id from language where code = '" + JDBCStringRoutines.escapeStringLiteral(aCode) + "'");
+ return storage.executeFreeSingleValueSql("select id from language where code = '" + JDBCStringRoutines.escapeStringLiteral(aCode) + "'");
+ }
+ catch (Throwable t) {
+ throw new ModuleFailure(t);
+ }
+ }
+
+ public Entity languageForCode(String aCode) throws ModuleExc, ModuleFailure {
+ try {
+ EntityList list = storage.selectByFieldValue("code", aCode);
+ if (list.size()>0) {
+ return list.elementAt(0);
+ }
+ else {
+ throw new ModuleExc("No language found for code " + aCode);
+ }
}
catch (Throwable t) {
throw new ModuleFailure(t);
package mircoders.module;
-import java.util.List;
-
import mir.entity.Entity;
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
import mir.util.JDBCStringRoutines;
import mir.util.StringRoutines;
import mircoders.storage.DatabaseMediaType;
+import java.util.List;
+
public class ModuleMediaType extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Content");
public ModuleMediaType() {
- this (DatabaseMediaType.getInstance());
- }
-
- public ModuleMediaType(StorageObject aStorage) {
- this.theStorage = aStorage;
+ super(DatabaseMediaType.getInstance());
}
public Entity findMediaTypeForMimeType(String aMimeType) throws ModuleExc, ModuleFailure {
mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'");
}
if (mediaTypes.size() == 0) {
+ mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral("*/*")+"'");
+ }
+ if (mediaTypes.size() == 0) {
throw new UnsupportedMimeTypeExc("Unsupported mimetype: " + aMimeType, aMimeType);
}
return (Entity) mediaTypes.elementAt(0);
}
+ public Entity findMediaTypeForExtension(String anExtension) throws ModuleExc, ModuleFailure {
+ EntityList mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension)+"'");
+
+ if (mediaTypes.size() == 0) {
+ try {
+ return findMediaTypeForMimeType("*/*");
+ }
+ catch (UnsupportedMimeTypeExc e) {
+ throw new UnsupportedMimeTypeExc("Unsupported media extension: " + anExtension, anExtension);
+ }
+ }
+ else {
+ return (Entity) mediaTypes.elementAt(0);
+ }
+ }
+
public static class MimeTypeExc extends ModuleExc {
private String mimeType;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
import mir.storage.StorageObject;
+import mir.util.JDBCStringRoutines;
import mircoders.storage.DatabaseMediafolder;
-
-public class ModuleMediafolder extends AbstractModule
-{
+public class ModuleMediafolder extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Mediafolder");
- public ModuleMediafolder(StorageObject aStorage)
- {
- if (aStorage == null)
- logger.warn("ModuleMediafolder: StorageObject was null!");
+ public ModuleMediafolder() {
+ super(DatabaseMediafolder.getInstance());
+ }
- theStorage = aStorage;
+ public String mediaFolderIdForName(String aName) throws ModuleExc, ModuleFailure {
+ try {
+ return storage.executeFreeSingleValueSql("select id from media_folder where name = '" + JDBCStringRoutines.escapeStringLiteral(aName) + "'");
+ }
+ catch (Throwable t) {
+ throw new ModuleFailure(t);
+ }
}
+
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.module;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.storage.StorageObject;
+import mircoders.storage.DatabaseMessages;
-/**
- * Title: ModuleMessage
- * Description:
- * Copyright: Copyright (c) 2001
- * Company: Indymedia
- * @author
- * @version 1.0
- */
-
-
-public class ModuleMessage extends AbstractModule
-{
+public class ModuleMessage extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Message");
- public ModuleMessage (StorageObject theStorage)
- {
- if (theStorage == null) logger.warn("ModuleMessage -- StorageObject was null!");
-
- this.theStorage = theStorage;
+ public ModuleMessage () {
+ super(DatabaseMessages.getInstance());
}
}
\ No newline at end of file
*/
package mircoders.module;
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
import mircoders.storage.DatabaseTopics;
public class ModuleTopics extends AbstractModule {
static LoggerWrapper logger = new LoggerWrapper("Module.Topics");
- public ModuleTopics(StorageObject theStorage) {
- this.theStorage = theStorage;
- }
-
- /**
- * Method getTopicList
- *
- * @return SimpleList of all Topics sorted by title
- *
- */
- public EntityList getTopicsList() throws ModuleExc, ModuleFailure {
- try {
- return getByWhereClause("", "title", -1);
- }
- catch (Throwable e) {
- logger.error("ModuleTopics.getTopicsList: topics could not be fetched: " + e.getMessage());
-
- throw new ModuleFailure("ModuleTopics.getTopicsList: topics could not be fetched: " + e.getMessage(), e);
- }
+ public ModuleTopics() {
+ super (DatabaseTopics.getInstance());
}
-
- /**
- * Overrides the AbstractModule.set(),
- * All dependent ContentEntities are set unproduced.
- * @param theValues Hash mit Spalte/Wert-Paaren
- * @return Id des eingef?gten Objekts
- * @exception ModuleException
- */
- public String set(Map theValues) throws ModuleExc, ModuleFailure {
- try {
- Entity theEntity = theStorage.selectById((String) theValues.get("id"));
- if (theEntity == null) {
- throw new ModuleExc("No topic with id " + theValues.get("id") + " found");
- }
- theEntity.setValues(theValues);
- theEntity.update();
-
- return theEntity.getId();
- }
- catch (Throwable e) {
- throw new ModuleFailure(e);
- }
- }
-
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
static LoggerWrapper logger = new LoggerWrapper("Module.UploadedMedia");
public ModuleUploadedMedia(StorageObject aStorage) {
- theStorage = aStorage;
+ super(aStorage);
}
}
\ No newline at end of file
package mircoders.module;
-import java.util.HashMap;
-import java.util.Map;
-
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.module.AbstractModule;
import mir.module.ModuleExc;
import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
import mir.util.JDBCStringRoutines;
import mircoders.entity.EntityUsers;
import mircoders.global.MirGlobal;
+import mircoders.storage.DatabaseUsers;
+
+import java.util.HashMap;
+import java.util.Map;
/*
{
static LoggerWrapper logger = new LoggerWrapper("Module.Users");
- public ModuleUsers(StorageObject theStorage)
- {
- if (theStorage == null)
- logger.warn("ModuleUsers(): StorageObject was null!");
-
- this.theStorage = theStorage;
+ public ModuleUsers() {
+ super(DatabaseUsers.getInstance());
}
/**
* @param password The password
* @return The authenticated user, or <code>null</code> if the user
* doesn't exist, or the supplied password is invalid.
- * @throws ModuleException
+ * @throws ModuleExc
*/
public EntityUsers getUserForLogin(String user, String password) throws ModuleExc, ModuleFailure {
EntityList userList = getByWhereClause(whereString, -1);
- if (userList != null && userList.getCount() == 1)
- return (EntityUsers) userList.elementAt(0);
- else
- return null;
+ if (userList != null && userList.getCount() == 1) {
+ EntityUsers result = (EntityUsers) userList.elementAt(0);
+
+ if (result.getFieldValue("is_disabled") == null ||
+ result.getFieldValue("is_disabled").equals("0"))
+ return result;
+ }
+
+ return null;
}
catch (Throwable t) {
throw new ModuleFailure(t);
public boolean checkUserPassword(EntityUsers aUser, String aPassword) throws ModuleExc, ModuleFailure {
try {
- return aUser.getValue("password").equals(MirGlobal.localizer().adminInterface().makePasswordDigest(aPassword));
+ return aUser.getFieldValue("password").equals(MirGlobal.localizer().adminInterface().makePasswordDigest(aPassword));
}
catch (Throwable t) {
throw new ModuleFailure(t);
}
}
- private Map digestPassword(Map aValues) throws ModuleExc, ModuleFailure {
+ private Map digestPassword(Map aValues) throws ModuleFailure {
Map result = aValues;
try {
return result;
}
+ /**
+ *
+ * @param theValues
+ * @return
+ * @throws ModuleExc
+ * @throws ModuleFailure
+ */
+
public String add (Map theValues) throws ModuleExc, ModuleFailure {
try {
return super.add(digestPassword(theValues));
}
/**
- * Standardfunktion, um einen Datensatz via StorageObject zu aktualisieren
- * @param theValues Hash mit Spalte/Wert-Paaren
- * @return Id des eingef?gten Objekts
- * @exception ModuleException
+ *
+ * @param theValues
+ * @return
+ * @throws ModuleExc
+ * @throws ModuleFailure
*/
public String set (Map theValues) throws ModuleExc, ModuleFailure {
try {
throw new ModuleFailure(t);
}
}
+
+ public void recordLogin(EntityUsers aUser) throws ModuleExc, ModuleFailure {
+ try {
+ String sql = "update webdb_users set lastlogin=now() where id = " + aUser.getId();
+
+ storage.executeUpdate(sql);
+ }
+ catch (Throwable t) {
+// no propagation of this error for now, to allow mir to still function
+// with older db schemas
+// throw new ModuleFailure(t);
+ }
+ }
}
\ No newline at end of file
*/
package mircoders.pdf;
+import gnu.regexp.RE;
+import gnu.regexp.REException;
+import gnu.regexp.REMatch;
+import gnu.regexp.REMatchEnumeration;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
-import java.util.*;
+import java.util.Iterator;
+import java.util.Vector;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.EntityBrowser;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.util.DateTimeFunctions;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityImages;
+import mircoders.storage.DatabaseImages;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-import gnu.regexp.REMatch;
-import gnu.regexp.REMatchEnumeration;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.*;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.util.DateTimeFunctions;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityImages;
-import mircoders.storage.*;
public class PDFGenerator{
public PDFGenerator(ByteArrayOutputStream out){
logger = new LoggerWrapper("PDFGenerator");
- try {
- configuration = MirPropertiesConfiguration.instance();
- }
- catch (MirPropertiesConfiguration.PropertiesConfigExc e) {
- throw new RuntimeException("Can't get configuration: " + e.getMessage());
- }
+ configuration = MirPropertiesConfiguration.instance();
localImageDir=configuration.getString("Producer.Image.Path");
try {
try {
ColumnText ict = new ColumnText(cb);
- String theTitle = entityContent.getValue("title");
- String theCreator = entityContent.getValue("creator");
+ String theTitle = entityContent.getFieldValue("title");
+ String theCreator = entityContent.getFieldValue("creator");
Phrase titleP=new Phrase(" - " + theTitle,new Font(indexFontFamily,indexFontSize,Font.BOLD));
Phrase creatorP=new Phrase( " :: " + theCreator,new Font(indexFontFamily,indexFontSize));
float toYPosition = currentYPosition - indexLineHeight;
while (images.hasNext()){
EntityImages currentImage=(EntityImages) images.next();
- float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();
- float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();
+ float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue();
+ float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue();
if (img_height>maxImageHeight){
img_width=(new Float((new Float(img_width*(maxImageHeight/img_height))).intValue())).floatValue();
img_height=maxImageHeight;
img_width=maxImageWidth;
}
- String img_title=currentImage.getValue("title");
- String img_path=currentImage.getValue("publish_path");
+ String img_title=currentImage.getFieldValue("title");
+ String img_path=currentImage.getFieldValue("publish_path");
if ((status & ColumnText.NO_MORE_TEXT) == 0){
// there is still text, so add an image which will have text wrapped around it, then add the text which
* source
*/
- Iterator images = new EntityBrowser(
- DatabaseImages.getInstance(),
- "exists (select * from content_x_media where content_id=" + entityContent.getId() + " and media_id=id)",
- "id desc", 30, -1, 0);
+ Vector extraTables = new Vector();
+ extraTables.add("content_x_media cxm");
+ Iterator images = new EntityBrowser(
+ DatabaseImages.getInstance(), "i", extraTables,
+ "cxm.content_id="+entityContent.getId()+"and cxm.media_id=i.id",
+ "i.id desc", 30, -1, 0);
- String isHTML = entityContent.getValue("is_html");
- String theTitle = entityContent.getValue("title");
- String theCreator = entityContent.getValue("creator");
+ String isHTML = entityContent.getFieldValue("is_html");
+ String theTitle = entityContent.getFieldValue("title");
+ String theCreator = entityContent.getFieldValue("creator");
String theDate = DateTimeFunctions.advancedDateFormat(
configuration.getString("RDF.Meta.DateFormat"),
- StringUtil.convertMirInternalDateToDate(entityContent.getValue("webdb_create")),
+ StringUtil.convertMirInternalDateToDate(entityContent.getFieldValue("webdb_create")),
configuration.getString("Mir.DefaultTimezone"));
- String theDescriptionRaw = entityContent.getValue("description");
- String theContentRaw = entityContent.getValue("content_data");
- String theSource = configuration.getString("Producer.ProductionHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getValue("publish_path") + entityContent.getValue("id") + ".shtml";
+ String theDescriptionRaw = entityContent.getFieldValue("description");
+ String theContentRaw = entityContent.getFieldValue("content_data");
+ String theSource = configuration.getString("Producer.PublicationHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getFieldValue("publish_path") + entityContent.getFieldValue("id") + ".shtml";
try {
RE nobackslashr = new RE("\r");
theContent= nobackslashr.substituteAll(theContentRaw,"");
+ theDescription= nobackslashr.substituteAll(theDescriptionRaw,"");
RE HxTag = new RE("</?h[1-6][^>]*>",RE.REG_ICASE);
theContent = HxTag.substituteAll(theContent,"\n\n");
+ theDescription = HxTag.substituteAll(theDescription,"\n\n");
RE ListItemTag = new RE("<li[^>]*>",RE.REG_ICASE);
theContent = ListItemTag.substituteAll(theContent,"\n * ");
+ theDescription = ListItemTag.substituteAll(theDescription,"\n * ");
RE ListTag = new RE("<(u|o)l[^>]*>",RE.REG_ICASE);
theContent = ListTag.substituteAll(theContent,"\n");
+ theDescription = ListTag.substituteAll(theDescription,"\n");
RE DivTag = new RE("</?div[^>]*>",RE.REG_ICASE);
theContent= DivTag.substituteAll(theContent,"\n");
+ theDescription= DivTag.substituteAll(theDescription,"\n");
RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
theContent= PTag.substituteAll(theContent,"\n ");
+ theDescription= PTag.substituteAll(theDescription,"\n ");
RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
theContent= PTagClose.substituteAll(theContent,"\n");
+ theDescription= PTagClose.substituteAll(theDescription,"\n");
RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
theContent= BRTag.substituteAll(theContent,"\n");
+ theDescription= BRTag.substituteAll(theDescription,"\n");
RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>",RE.REG_ICASE);
REMatchEnumeration atags= ATagAll.getMatchEnumeration(theContent);
}
theContent=theContentCopy;
+ REMatchEnumeration atags2= ATagAll.getMatchEnumeration(theDescription);
+ String theDescriptionCopy=theDescription;
+ while (atags2.hasMoreMatches()){
+ REMatch atag = atags2.nextMatch();
+ String atagString=atag.toString();
+ String atagStringHref=atag.toString(1);
+ String atagStringText=atag.toString(2);
+ int begin=theDescriptionCopy.indexOf(atagString);
+ theDescriptionCopy=theDescriptionCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theDescriptionCopy.substring(begin+atagString.length());
+ }
+ theDescription=theDescriptionCopy;
+
+
RE noTags = new RE("<[^>]*>");
theContent= noTags.substituteAll(theContent," ");
+ theDescription= noTags.substituteAll(theDescription," ");
theContent=mir.util.Translate.decode(theContent);
+ theDescription=mir.util.Translate.decode(theDescription);
RE re1 = new RE("\r?\n\r?\n");
- String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
+ String theDescription1 = re1.substituteAll(theDescription,"BREAKHERE");
RE re2 = new RE("\r?\n");
String theDescription2 = re2.substituteAll(theDescription1," ");
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.producer;
import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
import mircoders.entity.EntityContent;
-import mircoders.module.ModuleContent;
-import mircoders.storage.DatabaseContent;
-
public class ContentModifyingProducerNode implements ProducerNode {
private String contentKey;
String fieldName;
try {
- ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());
-
data = ParameterExpander.findValueForKey( aValueMap, contentKey );
if (! (data instanceof EntityAdapter)) {
value = ParameterExpander.expandExpression(aValueMap, valueExpression);
fieldName = ParameterExpander.expandExpression(aValueMap, fieldNameExpression);
- entity.setValueForProperty("is_produced", "0");
- entity.setValueForProperty(fieldName, value);
+ entity.setFieldValue("is_produced", "0");
+ entity.setFieldValue(fieldName, value);
entity.update();
aLogger.info(" Modified content " + entity.getId() + ": " + fieldName + " = " + value );
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.producer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
-import java.util.GregorianCalendar;
import java.util.Date;
+import java.util.GregorianCalendar;
import java.util.Map;
+import java.io.File;
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.producer.ProducerFailure;
import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
+import mir.util.FileFunctions;
import mircoders.entity.EntityContent;
import mircoders.search.AudioSearchTerm;
import mircoders.search.ContentSearchTerm;
public class IndexingProducerNode implements ProducerNode {
private String contentKey;
private String indexPath;
+ private File indexBasePath;
- public IndexingProducerNode(String aContentKey, String pathToIndex) {
+ public IndexingProducerNode(File anIndexBasePath, String aContentKey, String pathToIndex) {
contentKey = aContentKey;
indexPath = pathToIndex;
+ indexBasePath = anIndexBasePath;
}
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger)
IndexWriter indexWriter = null;
Object data;
Entity entity;
- String index = null;
long startTime;
long endTime;
+ File indexFile = null;
startTime = System.currentTimeMillis();
try {
- index = ParameterExpander.expandExpression(aValueMap, indexPath);
+ indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath));
data = ParameterExpander.findValueForKey(aValueMap, contentKey);
if (!(data instanceof EntityAdapter)) {
entity.getClass().getName() + " adapter", null);
}
- aLogger.info("Indexing " + (String) entity.getValue("id") + " into " +
- index);
+ aLogger.info("Indexing " + entity.getFieldValue("id") + " into " + indexFile.getAbsolutePath());
// create an index here if one did not already exist
- if (!(IndexReader.indexExists(index))) {
- aLogger.error("Didn't find existing index, so I'm making one in " +
- index);
+ if (!(IndexReader.indexExists(indexFile))) {
+ aLogger.error("Didn't find existing index, so I'm making one in " + indexFile.getAbsolutePath());
- IndexWriter indexCreator =
- new IndexWriter(index, new StandardAnalyzer(), true);
+ IndexWriter indexCreator = new IndexWriter(indexFile, new StandardAnalyzer(), true);
indexCreator.close();
}
- IndexUtil.unindexEntity((EntityContent) entity, index);
+ IndexUtil.unindexEntity((EntityContent) entity, indexFile);
- indexWriter = new IndexWriter(index, new StandardAnalyzer(), false);
+ indexWriter = new IndexWriter(indexFile, new StandardAnalyzer(), false);
Document theDoc = new Document();
//this initialization should go somewhere global like an xml file....
(new KeywordSearchTerm("id", "", "id", "", "id")).index(theDoc, entity);
- String textValue = entity.getValue("webdb_create");
+ String textValue = entity.getFieldValue("webdb_create");
Calendar calendar = GregorianCalendar.getInstance();
int year;
int month;
if (textValue!=null) {
try {
- year = Integer.parseInt(textValue.substring(0,4));
- month = Integer.parseInt(textValue.substring(5,7));
- day = Integer.parseInt(textValue.substring(8,10));
- hours = Integer.parseInt(textValue.substring(11,13));
- minutes = Integer.parseInt(textValue.substring(14,16));
+ year = Integer.parseInt(textValue.substring(0, 4));
+ month = Integer.parseInt(textValue.substring(5, 7));
+ day = Integer.parseInt(textValue.substring(8, 10));
+ hours = Integer.parseInt(textValue.substring(11, 13));
+ minutes = Integer.parseInt(textValue.substring(14, 16));
- calendar.set(year, month-1, day, hours, minutes);
+ calendar.set(year, month - 1, day, hours, minutes);
date = calendar.getTime();
- SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd hh:mm");
- formattedDate=formatter.format(date);
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd hh:mm");
+ formattedDate = formatter.format(date);
+ }
+ catch (Throwable t) {
+ aLogger.error("Error while generating content date to index: " + t.getMessage());
+ t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
}
- catch (Throwable t){
- aLogger.error("Error while generating content date to index: " + t.getMessage());
- t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- }
}
(new KeywordSearchTerm("webdb_create_formatted", "search_date",
"webdb_create_formatted", "webdb_create_formatted",
"webdb_create_formatted")).indexValue(theDoc,formattedDate);
-
+
(new UnIndexedSearchTerm("", "", "", "where", "where")).indexValue(theDoc,
- StringUtil.webdbDate2path(entity.getValue("date")) +
- entity.getValue("id") + ".shtml");
+ StringUtil.webdbDate2path(entity.getFieldValue("date")) +
+ entity.getFieldValue("id") + ".shtml");
(new TextSearchTerm("creator", "search_creator", "creator", "creator",
"creator")).index(theDoc, entity);
"creationDate", "creationDate", "creationDate")).index(theDoc, entity);
(new ContentSearchTerm("content_data", "search_content", "content", "", "")).indexValue(theDoc,
- entity.getValue("content_data") + " " + entity.getValue("description") +
- " " + entity.getValue("title"));
+ entity.getFieldValue("content_data") + " " + entity.getFieldValue("description") +
+ " " + entity.getFieldValue("title"));
(new TopicSearchTerm()).index(theDoc, entity);
if (indexWriter != null) {
try {
indexWriter.close();
- } catch (Throwable t) {
+ }
+ catch (Throwable t) {
aLogger.warn("Error while closing indexWriter: " + t.getMessage());
}
}
- try {
- FSDirectory theIndexDir = FSDirectory.getDirectory(index, false);
+ if (indexFile!=null) {
+ try {
+ FSDirectory theIndexDir = FSDirectory.getDirectory(indexFile, false);
- if (IndexReader.isLocked(theIndexDir)) {
- IndexReader.unlock(theIndexDir);
+ if (IndexReader.isLocked(theIndexDir)) {
+ IndexReader.unlock(theIndexDir);
+ }
+ }
+ catch (Throwable t) {
+ aLogger.warn("Error while unlocking index: " + t.getMessage());
}
- } catch (Throwable t) {
- aLogger.warn("Error while unlocking index: " + t.getMessage());
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.log.LoggerWrapper;
-import mir.media.MediaHelper;
-import mir.media.MirMedia;
+import mircoders.media.MediaHelper;
+import mir.media.MediaHandler;
import mir.producer.ProducerExc;
import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
Entity entity;
EntityUploadedMedia uploadedMediaEntity = null;
Entity mediaType = null;
- MirMedia currentMediaHandler;
+ MediaHandler currentMediaHandler;
try {
-
data = ParameterExpander.findValueForKey( aValueMap, mediaEntityKey );
if (!(data instanceof EntityAdapter)) {
currentMediaHandler = MediaHelper.getHandler( mediaType );
currentMediaHandler.produce(entity, mediaType);
- entity.setValueForProperty("publish_server", currentMediaHandler.getPublishHost());
- entity.setValueForProperty("icon_is_produced", "1");
- entity.setValueForProperty("is_produced", "1");
+ entity.setFieldValue("publish_server", currentMediaHandler.getPublishHost());
+ entity.setFieldValue("icon_is_produced", "1");
+ entity.setFieldValue("is_produced", "1");
entity.update();
- aLogger.info("media with id "+uploadedMediaEntity.getValue("id") + ", mediaType " + mediaType.getValue("name") + " successfully produced");
+ aLogger.info("media with id "+uploadedMediaEntity.getFieldValue("id") + ", mediaType " + mediaType.getFieldValue("name") + " successfully produced");
}
catch (Throwable t) {
String message = "Error while generating media";
try {
if (uploadedMediaEntity!=null)
- message = message + " with id "+uploadedMediaEntity.getValue("id");
+ message = message + " with id "+uploadedMediaEntity.getFieldValue("id");
if (mediaType!=null) {
- message = message + ", mediaType " + mediaType.getValue("name");
+ message = message + ", mediaType " + mediaType.getFieldValue("name");
}
}
catch (Throwable s) {
-/*\r
- * Copyright (C) 2001, 2002 The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with any library licensed under the Apache Software License,\r
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
- * (or with modified versions of the above that use the same license as the above),\r
- * and distribute linked combinations including the two. You must obey the\r
- * GNU General Public License in all respects for all of the code used other than\r
- * the above mentioned libraries. If you modify this file, you may extend this\r
- * exception to your version of the file, but you are not obligated to do so.\r
- * If you do not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.producer;\r
-\r
-import java.io.PrintWriter;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.*;\r
-\r
-import mir.entity.*;\r
-import mir.entity.EntityList;\r
-import mir.entity.adapter.EntityAdapter;\r
-import mir.log.LoggerToWriterAdapter;\r
-import mir.log.LoggerWrapper;\r
-import mir.misc.StringUtil;\r
-import mir.producer.ProducerFailure;\r
-import mir.producer.ProducerNode;\r
-import mir.util.CachingRewindableIterator;\r
-import mir.util.HTMLRoutines;\r
-import mir.util.ParameterExpander;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityImages;\r
-import mircoders.storage.*;\r
-\r
-\r
-public class PDFPreFormattingProducerNode implements ProducerNode {\r
- private String contentKey;\r
- private int numLinesBetweenImages;\r
- private float contentAreaWidthCM;\r
- private float characterWidthCM;\r
- private float pixelWidthCM;\r
- private float lineHeightCM;\r
-\r
- public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {\r
- contentKey = aContentKey;\r
- numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();\r
- contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();\r
- characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();\r
- pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();\r
- lineHeightCM=(new Float(aLineHeightCM)).floatValue();\r
-\r
- // float characterWidthCM = 0.17F;\r
- //float contentAreaWidthCM = 16;\r
- //float pixelWidthCM = .03F;\r
- //float lineHeightCM = .5F;\r
- }\r
-\r
- public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {\r
- Object data;\r
- Entity entity;\r
-\r
- try {\r
- data = ParameterExpander.findValueForKey( aValueMap, contentKey );\r
-\r
- if (! (data instanceof EntityAdapter)) {\r
- throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);\r
- }\r
-\r
- entity = ((EntityAdapter) data).getEntity();\r
- if (! (entity instanceof EntityContent)) {\r
- throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);\r
- }\r
-\r
- int currentPosition = 0;\r
-\r
- //int numLinesBetweenImages=3;\r
-\r
-\r
-\r
-\r
- int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();\r
-\r
- boolean outOfText = false;\r
-\r
- ArrayList brokenUpContent = new ArrayList();\r
-\r
- Iterator images = new EntityBrowser(\r
- DatabaseImages.getInstance(),\r
- "exists (select * from content_x_media where content_id=" + entity.getId() + " and media_id=id)",\r
- "id desc", 30, -1, 0);\r
-\r
- String theContent = ((EntityContent) entity).getValue("content_data");\r
- //remove pesky characters\r
- theContent = HTMLRoutines.encodeXML(theContent);\r
- //put in the <BR> tags so we can turn them to empty blocks\r
- theContent = StringUtil.convertNewline2Break(theContent);\r
-\r
- if (images == null){\r
- Map row = new HashMap();\r
- row.put("text",theContent);\r
- row.put("hasImage","0");\r
- brokenUpContent.add(row);\r
- }\r
- if (images != null){\r
- //need to add checks for out of content!\r
- Map row0 = new HashMap();\r
- if (numCharsInAnImagelessRow>(theContent).length()){\r
- row0.put("text",theContent);\r
- outOfText = true;\r
- }\r
- else {\r
- //break on words so we don't split html entities\r
- int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);\r
- row0.put("text",theContent.substring(0,lastSpaceAt));\r
- currentPosition=lastSpaceAt;\r
- }\r
- row0.put("hasImage","0");\r
- brokenUpContent.add(row0);\r
- aLogger.debug("CP1 is "+ currentPosition);\r
- while(images.hasNext()){\r
- Map row1 = new HashMap();\r
- Map row2 = new HashMap();\r
- EntityImages currentImage=(EntityImages) images.next();\r
- float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();\r
- float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();\r
-\r
- //oversize images must be shrunk\r
- if (img_width>250){\r
- img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();\r
- img_width=250.0F;\r
- }\r
-\r
-\r
- //calculate how much text goes in the column(use 8 pixels to pad the column)\r
- float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);\r
- float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int\r
- //add one line for image description\r
- int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();\r
-\r
- row1.put("text_widthCM",Float.toString(text_widthCM));\r
-\r
- row1.put("img_title",currentImage.getValue("title"));\r
-\r
- row1.put("img_width",Float.toString(img_width));\r
- row1.put("img_height",Float.toString(img_height));\r
-\r
- aLogger.debug("img_width " +Float.toString(img_width));\r
- aLogger.debug("img_height "+Float.toString(img_height));\r
-\r
- row1.put("img_src",currentImage.getValue("publish_path"));\r
- row1.put("hasImage","1");\r
- if (! outOfText){\r
- try {\r
- int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);\r
- row1.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
- currentPosition=lastSpaceAt;\r
- }\r
- catch (IndexOutOfBoundsException e){\r
- row1.put("text",theContent.substring(currentPosition));\r
- outOfText = true;\r
- }\r
- }\r
- aLogger.debug("CP2 is "+ currentPosition);\r
- brokenUpContent.add(row1);\r
-\r
- if (! outOfText){\r
- try {\r
- int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);\r
- row2.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
- currentPosition=lastSpaceAt;\r
- }\r
- catch (IndexOutOfBoundsException e){\r
- row2.put("text",theContent.substring(currentPosition));\r
- outOfText = true;\r
- }\r
- }\r
- row2.put("hasImage","0");\r
- brokenUpContent.add(row2);\r
-\r
- aLogger.debug("CP3 is "+ currentPosition);\r
- }\r
- Map row3 = new HashMap();\r
- if (! outOfText){\r
- row3.put("text",theContent.substring(currentPosition));\r
- row3.put("hasImage","0");\r
- brokenUpContent.add(row3);\r
- }\r
-\r
- }\r
-\r
-\r
-\r
-\r
-\r
- ParameterExpander.setValueForKey(\r
- aValueMap,\r
- "data.formatted_content",\r
- new CachingRewindableIterator(brokenUpContent.iterator())\r
- );\r
-\r
-\r
- }\r
- catch (Throwable t) {\r
- aLogger.error("Error while formatting content for PDF: " + t.getMessage());\r
- t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));\r
- }\r
- }\r
-}\r
-\r
-\r
-\r
-\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.producer;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.Entity;
+import mir.entity.EntityBrowser;
+import mir.entity.adapter.EntityAdapter;
+import mir.log.LoggerToWriterAdapter;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.producer.ProducerFailure;
+import mir.producer.ProducerNode;
+import mir.util.CachingRewindableIterator;
+import mir.util.HTMLRoutines;
+import mir.util.ParameterExpander;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityImages;
+import mircoders.storage.DatabaseImages;
+
+
+public class PDFPreFormattingProducerNode implements ProducerNode {
+ private String contentKey;
+ private int numLinesBetweenImages;
+ private float contentAreaWidthCM;
+ private float characterWidthCM;
+ private float pixelWidthCM;
+ private float lineHeightCM;
+
+ public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {
+ contentKey = aContentKey;
+ numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();
+ contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();
+ characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();
+ pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();
+ lineHeightCM=(new Float(aLineHeightCM)).floatValue();
+
+ // float characterWidthCM = 0.17F;
+ //float contentAreaWidthCM = 16;
+ //float pixelWidthCM = .03F;
+ //float lineHeightCM = .5F;
+ }
+
+ public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
+ Object data;
+ Entity entity;
+
+ try {
+ data = ParameterExpander.findValueForKey( aValueMap, contentKey );
+
+ if (! (data instanceof EntityAdapter)) {
+ throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);
+ }
+
+ entity = ((EntityAdapter) data).getEntity();
+ if (! (entity instanceof EntityContent)) {
+ throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
+ }
+
+ int currentPosition = 0;
+
+ //int numLinesBetweenImages=3;
+
+
+
+
+ int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();
+
+ boolean outOfText = false;
+
+ ArrayList brokenUpContent = new ArrayList();
+
+
+ Vector extraTables = new Vector();
+ extraTables.add("content_x_media cxm");
+ Iterator images = new EntityBrowser(
+ DatabaseImages.getInstance(), "i", extraTables,
+ "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id",
+ "i.id desc", 30, -1, 0);
+
+ String theContent = ((EntityContent) entity).getFieldValue("content_data");
+ //remove pesky characters
+ theContent = HTMLRoutines.encodeXML(theContent);
+ //put in the <BR> tags so we can turn them to empty blocks
+ theContent = StringUtil.convertNewline2Break(theContent);
+
+ if (images == null){
+ Map row = new HashMap();
+ row.put("text",theContent);
+ row.put("hasImage","0");
+ brokenUpContent.add(row);
+ }
+ if (images != null){
+ //need to add checks for out of content!
+ Map row0 = new HashMap();
+ if (numCharsInAnImagelessRow>(theContent).length()){
+ row0.put("text",theContent);
+ outOfText = true;
+ }
+ else {
+ //break on words so we don't split html entities
+ int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);
+ row0.put("text",theContent.substring(0,lastSpaceAt));
+ currentPosition=lastSpaceAt;
+ }
+ row0.put("hasImage","0");
+ brokenUpContent.add(row0);
+ aLogger.debug("CP1 is "+ currentPosition);
+ while(images.hasNext()){
+ Map row1 = new HashMap();
+ Map row2 = new HashMap();
+ EntityImages currentImage=(EntityImages) images.next();
+ float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue();
+ float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue();
+
+ //oversize images must be shrunk
+ if (img_width>250){
+ img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();
+ img_width=250.0F;
+ }
+
+
+ //calculate how much text goes in the column(use 8 pixels to pad the column)
+ float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);
+ float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int
+ //add one line for image description
+ int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();
+
+ row1.put("text_widthCM",Float.toString(text_widthCM));
+
+ row1.put("img_title",currentImage.getFieldValue("title"));
+
+ row1.put("img_width",Float.toString(img_width));
+ row1.put("img_height",Float.toString(img_height));
+
+ aLogger.debug("img_width " +Float.toString(img_width));
+ aLogger.debug("img_height "+Float.toString(img_height));
+
+ row1.put("img_src",currentImage.getFieldValue("publish_path"));
+ row1.put("hasImage","1");
+ if (! outOfText){
+ try {
+ int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);
+ row1.put("text",theContent.substring(currentPosition,lastSpaceAt));
+ currentPosition=lastSpaceAt;
+ }
+ catch (IndexOutOfBoundsException e){
+ row1.put("text",theContent.substring(currentPosition));
+ outOfText = true;
+ }
+ }
+ aLogger.debug("CP2 is "+ currentPosition);
+ brokenUpContent.add(row1);
+
+ if (! outOfText){
+ try {
+ int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);
+ row2.put("text",theContent.substring(currentPosition,lastSpaceAt));
+ currentPosition=lastSpaceAt;
+ }
+ catch (IndexOutOfBoundsException e){
+ row2.put("text",theContent.substring(currentPosition));
+ outOfText = true;
+ }
+ }
+ row2.put("hasImage","0");
+ brokenUpContent.add(row2);
+
+ aLogger.debug("CP3 is "+ currentPosition);
+ }
+ Map row3 = new HashMap();
+ if (! outOfText){
+ row3.put("text",theContent.substring(currentPosition));
+ row3.put("hasImage","0");
+ brokenUpContent.add(row3);
+ }
+
+ }
+
+
+
+
+
+ ParameterExpander.setValueForKey(
+ aValueMap,
+ "data.formatted_content",
+ new CachingRewindableIterator(brokenUpContent.iterator())
+ );
+
+
+ }
+ catch (Throwable t) {
+ aLogger.error("Error while formatting content for PDF: " + t.getMessage());
+ t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));
+ }
+ }
+}
+
+
+
+
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.producer;
import java.util.Map;
+import java.io.File;
import mir.entity.Entity;
import mir.entity.adapter.EntityAdapter;
import mir.producer.ProducerFailure;
import mir.producer.ProducerNode;
import mir.util.ParameterExpander;
+import mir.util.FileFunctions;
import mircoders.entity.EntityContent;
import mircoders.search.IndexUtil;
-
public class UnIndexingProducerNode implements ProducerNode {
private String contentKey;
private String indexPath;
+ private File indexBasePath;
-
- public UnIndexingProducerNode(String aContentKey, String pathToIndex) {
+ public UnIndexingProducerNode(File anIndexBasePath, String aContentKey, String pathToIndex) {
contentKey = aContentKey;
indexPath=pathToIndex;
+ indexBasePath = anIndexBasePath;
}
public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
Object data;
Entity entity;
- String index=null;
+ File indexFile;
long startTime;
long endTime;
startTime = System.currentTimeMillis();
try {
- index = ParameterExpander.expandExpression(aValueMap, indexPath);
+ indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath));
+
data = ParameterExpander.findValueForKey( aValueMap, contentKey );
if (! (data instanceof EntityAdapter)) {
if (! (entity instanceof EntityContent)) {
throw new ProducerFailure("UnIndexingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
}
- aLogger.info("UnIndexing " + (String) entity.getValue("id") + " out of " + index);
-
- IndexUtil.unindexEntity((EntityContent) entity,index);
+ aLogger.info("UnIndexing " + entity.getFieldValue("id") + " out of " + indexFile.getAbsolutePath());
+ IndexUtil.unindexEntity((EntityContent) entity, indexFile);
}
catch (Throwable t) {
aLogger.error("Error while unindexing content: " + t.getMessage());
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.producer.reader;
import java.util.Map;
+import java.io.File;
-import mir.entity.adapter.EntityAdapterModel;
import mir.producer.ProducerNode;
import mir.producer.reader.DefaultProducerNodeBuilders;
import mir.producer.reader.ProducerConfigExc;
import mir.producer.reader.ProducerNodeBuilderLibrary;
-import mir.util.XMLReader;
-import mir.util.XMLReaderTool;
+import mir.producer.reader.ProducerNodeBuilder;
+import mir.util.xml.XMLParserExc;
+import mir.util.xml.XMLReaderTool;
import mircoders.producer.ContentMarkingProducerNode;
import mircoders.producer.ContentModifyingProducerNode;
import mircoders.producer.IndexingProducerNode;
public class SupplementalProducerNodeBuilders {
- public static void registerBuilders(ProducerNodeBuilderLibrary aBuilderLibrary, EntityAdapterModel aModel) throws ProducerConfigExc {
+ public static void registerBuilders(ProducerNodeBuilderLibrary aBuilderLibrary, File aBasePath) throws ProducerConfigExc {
aBuilderLibrary.registerBuilder("ModifyContent", ContentModifyingProducerNodeBuilder.class);
aBuilderLibrary.registerBuilder("MarkContent", ContentMarkingProducerNodeBuilder.class);
aBuilderLibrary.registerBuilder("GenerateMedia", MediaGeneratingProducerNodeBuilder.class);
- aBuilderLibrary.registerBuilder("IndexContent",ContentIndexingProducerNodeBuilder.class);
- aBuilderLibrary.registerBuilder("UnIndexContent",ContentUnIndexingProducerNodeBuilder.class);
+ aBuilderLibrary.registerFactory("IndexContent", new ContentIndexingProducerNodeBuilder.factory(aBasePath));
+ aBuilderLibrary.registerFactory("UnIndexContent", new ContentUnIndexingProducerNodeBuilder.factory(aBasePath));
aBuilderLibrary.registerBuilder("PDFPreFormat", PDFPreFormattingProducerNodeBuilder.class);
aBuilderLibrary.registerBuilder("PDFGenerate", PDFGeneratingProducerNodeBuilder.class);
+// aBuilderLibrary.registerBuilder("ReportChangedFiles", );
}
private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
super(MARKER_SUBNODES);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(MARKER_KEY_ATTRIBUTE);
private final static String[] INDEXER_SUBNODES = {};
public static class ContentIndexingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
-
private String key;
private String pathToIndex;
+ private File indexBasePath;
+
+ private static class factory implements ProducerNodeBuilderFactory {
+ private File sourceBasePath;
- public ContentIndexingProducerNodeBuilder() {
+ public factory(File aSourceBasePath) {
+ sourceBasePath = aSourceBasePath;
+ }
+
+ public ProducerNodeBuilder makeBuilder() {
+ return new ContentIndexingProducerNodeBuilder(sourceBasePath);
+ }
+ }
+
+ public ContentIndexingProducerNodeBuilder(File anIndexBasePath) {
super(INDEXER_SUBNODES);
+
+ indexBasePath = anIndexBasePath;
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, INDEXER_REQUIRED_ATTRIBUTES, INDEXER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(INDEXER_KEY_ATTRIBUTE);
};
public ProducerNode constructNode() {
- return new IndexingProducerNode(key,pathToIndex);
+ return new IndexingProducerNode(indexBasePath, key, pathToIndex);
};
}
private final static String[] UNINDEXER_SUBNODES = {};
public static class ContentUnIndexingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
-
private String key;
private String pathToIndex;
- public ContentUnIndexingProducerNodeBuilder() {
+ private File indexBasePath;
+
+ private static class factory implements ProducerNodeBuilderFactory {
+ private File indexBasePath;
+
+ public factory(File aSourceBasePath) {
+ indexBasePath = aSourceBasePath;
+ }
+
+ public ProducerNodeBuilder makeBuilder() {
+ return new ContentUnIndexingProducerNodeBuilder(indexBasePath);
+ }
+ }
+
+ public ContentUnIndexingProducerNodeBuilder(File anIndexBasePath) {
super(UNINDEXER_SUBNODES);
+
+ indexBasePath = anIndexBasePath;
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, UNINDEXER_REQUIRED_ATTRIBUTES, UNINDEXER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(UNINDEXER_KEY_ATTRIBUTE);
};
public ProducerNode constructNode() {
- return new UnIndexingProducerNode(key,pathToIndex);
+ return new UnIndexingProducerNode(indexBasePath, key,pathToIndex);
};
}
super(CONTENT_MODIFIER_SUBNODES);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, CONTENT_MODIFIER_REQUIRED_ATTRIBUTES, CONTENT_MODIFIER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(CONTENT_MODIFIER_KEY_ATTRIBUTE);
super(MEDIA_SUBNODES);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, MEDIA_REQUIRED_ATTRIBUTES, MEDIA_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(MEDIA_KEY_ATTRIBUTE);
super(MARKER_SUBNODES);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
key = (String) anAttributes.get(MARKER_KEY_ATTRIBUTE);
}
public static class PDFGeneratingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
- private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE;
private final static String PDF_GENERATOR_ATTRIBUTE = "generator";
private final static String PDF_DESTINATION_ATTRIBUTE = "destination";
private final static String PDF_STYLESHEET_ATTRIBUTE = "stylesheet";
super(MARKER_SUBNODES);
}
- public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES);
generator = (String) anAttributes.get(PDF_GENERATOR_ATTRIBUTE);
return new PDFGeneratingProducerNode(generator,destination,stylesheet);
};
}
+
+
+ /**
+ * Builder for {@link mircoders.producer.ChangedFilesReportingProducerNode}
+ * nodes.
+ */
+/*
+ private static class ChangeReportingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder {
+ private final static String DESTINATION_FILE_ATTRIBUTE = "reportFile";
+ private final static String LOCK_FILE_ATTRIBUTE = "lockfile";
+ private final static String BASE_PATH_ATTRIBUTE = "basepath";
+ private final static String EXCLUDED_PATHS_ATTRIBUTE = "excludedpaths";
+ private final static String FLUSH_ATTRIBUTE = "flush";
+ private final static String[] REQUIRED_ATTRIBUTES = {DESTINATION_FILE_ATTRIBUTE};
+ private final static String[] OPTIONAL_ATTRIBUTES = {LOCK_FILE_ATTRIBUTE, BASE_PATH_ATTRIBUTE, EXCLUDED_PATHS_ATTRIBUTE, FLUSH_ATTRIBUTE};
+ private final static String[] SUBNODES = {};
+
+ private String reportFile;
+ private String lockFile;
+ private String basePath;
+ private String excludedPaths;
+ private String flush;
+
+ public ChangeReportingProducerNodeBuilder() {
+ super(SUBNODES);
+ }
+
+ public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc {
+ XMLReaderTool.checkAttributes(anAttributes, REQUIRED_ATTRIBUTES, OPTIONAL_ATTRIBUTES);
+
+ reportFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, DESTINATION_FILE_ATTRIBUTE, null);
+ lockFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, LOCK_FILE_ATTRIBUTE, null);
+ basePath = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BASE_PATH_ATTRIBUTE, "");
+ excludedPaths = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXCLUDED_PATHS_ATTRIBUTE, "");
+ flush = XMLReaderTool.getStringAttributeWithDefault(anAttributes, FLUSH_ATTRIBUTE, "1");
+ };
+
+ public ProducerNode constructNode() {
+ return new ChangedFilesReportingProducerNode(reportFile, lockFile, basePath, excludedPaths, flush);
+ };
+ }
+*/
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
-import java.util.Map;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
-import mir.entity.EntityList;
+import mir.entity.EntityBrowser;
import mir.storage.StorageObjectFailure;
import mircoders.entity.EntityContent;
import mircoders.storage.DatabaseContentToMedia;
+import mircoders.storage.DatabaseAudio;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
public class AudioSearchTerm extends SearchTerm{
+ public AudioSearchTerm() {
+ super(null, "search_hasAudio", "hasAudio", null, "hasAudio");
+ }
+ public void index(Document doc, Entity entity) throws StorageObjectFailure{
+ // EntityList audio = DatabaseContentToMedia.getInstance().getAudio((EntityContent) entity);
+ Vector extraTables = new Vector();
+ extraTables.add("content_x_media cxm");
+ Iterator audios = new EntityBrowser(
+ DatabaseAudio.getInstance(), "i", extraTables,
+ "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id",
+ "i.id desc", 30, -1, 0);
- public static String matchField = "hasAudio";
- public static String paramName = "search_hasAudio";
- public static String templateVariable = "hasAudio";
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
- EntityList audio = DatabaseContentToMedia.getInstance().getAudio((EntityContent) entity);
- if (audio != null && audio.size()>0){
+ if (audios != null && audios.hasNext()){
doc.add(Field.Keyword(matchField,"y"));
}
}
public void returnMeta(Map result,Document doc){
result.put(templateVariable,doc.get(matchField));
}
-
-
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
public class ContentSearchTerm extends SearchTerm{
-
- public String templateVariable;
- public String dataField;
- public String matchField;
- public String paramName;
- public String partOfEntity;
+ protected ContentSearchTerm() {
+ }
public ContentSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
matchField = aMatchField;
dataField = aDataField;
templateVariable = aTemplateVariable;
-
}
public void index(Document doc, Entity entity){
- doc.add(Field.UnStored(matchField,entity.getValue(partOfEntity)));
+ doc.add(Field.UnStored(matchField,entity.getFieldValue(partOfEntity)));
}
public void indexValue(Document doc, String value){
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
+import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
-
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
-import mir.entity.EntityList;
+import mir.entity.EntityBrowser;
import mir.storage.StorageObjectFailure;
import mircoders.entity.EntityContent;
-import mircoders.storage.DatabaseContentToMedia;
+import mircoders.entity.EntityImages;
+import mircoders.storage.DatabaseImages;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
public class ImagesSearchTerm extends SearchTerm{
+ public ImagesSearchTerm() {
+ super (null, "search_hasImages", "hasImages", "images", "images");
+ }
+ public void index(Document doc, Entity entity) throws StorageObjectFailure{
+ Vector extraTables = new Vector();
+ extraTables.add("content_x_media cxm");
- public static String matchField = "hasImages";
- public static String paramName = "search_hasImages";
- public static String dataField = "images";
- public static String templateVariable = "images";
+ Iterator images = new EntityBrowser(
+ DatabaseImages.getInstance(), "i", extraTables,
+ "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id",
+ "i.id desc", 30, -1, 0);
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
- EntityList images = DatabaseContentToMedia.getInstance().getImages((EntityContent) entity);
- if (images != null && images.size()>0){
+
+ if (images != null && images.hasNext()){
doc.add(Field.Keyword(matchField,"y"));
String imageURLString = "";
- for(int k=0;k<images.size();k++){
+ int k=0;
+ while(images.hasNext()){
if (k != 0){
imageURLString = imageURLString + ":";
}
- imageURLString = imageURLString + (images.elementAt(k)).getValue("icon_path");
+ k++;
+ imageURLString = imageURLString + ((EntityImages) images.next()).getFieldValue("icon_path");
}
doc.add(Field.UnIndexed("images",imageURLString));
}
-
-
}
public String makeTerm(HttpServletRequest req){
public void returnMeta(Map result,Document doc){
String imageURLString=doc.get(dataField);
+ List theImages = new ArrayList();
if (imageURLString != null){
- List theImages = new Vector();
StringTokenizer st = new StringTokenizer(imageURLString,":");
while (st.hasMoreTokens()) {
String imageURL=st.nextToken();
theImages.add(imageURL);
}
- result.put(templateVariable,theImages);
}
+ result.put(templateVariable,theImages);
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
import java.io.IOException;
-
-import mircoders.entity.EntityContent;
+import java.io.File;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
+import mircoders.entity.EntityContent;
-
+/**
+ * Some utility functions for article (un)indexing
+ */
public class IndexUtil {
- public static void unindexEntity (EntityContent entity,String index) throws IOException{
- IndexReader indexReader = null;
- try{
- indexReader = IndexReader.open(index);
- indexReader.delete(new Term("id",entity.getValue("id")));
- indexReader.close();
- }
- catch(Exception e){
- if (indexReader != null){
- indexReader.close();
- }
- }
- finally {
- if (indexReader != null){
- FSDirectory theIndexDir=FSDirectory.getDirectory(index,false);
- if (IndexReader.isLocked(theIndexDir)){
- IndexReader.unlock(theIndexDir);
- }
- }
- }
+ /**
+ * Unindexes an article
+ */
+ public static void unindexEntity (EntityContent anEntity, String anIndex) throws IOException{
+ unindexEntity(anEntity, new File(anIndex));
}
- public static void unindexID (String id,String index) throws IOException{
+
+ /**
+ * Unindexes an article
+ */
+ public static void unindexEntity (EntityContent anEntity, File anIndex) throws IOException{
+ unindexID(anEntity.getId(), anIndex);
+ }
+
+ /**
+ * Unindexes an article by article id
+ */
+ public static void unindexID (String id,File index) throws IOException{
IndexReader indexReader = null;
try{
indexReader = IndexReader.open(index);
}
catch(Exception e){
if (indexReader != null){
- indexReader.close();
+ indexReader.close();
}
}
- finally {
+ finally {
if (indexReader != null){
- FSDirectory theIndexDir=FSDirectory.getDirectory(index,false);
- if (IndexReader.isLocked(theIndexDir)){
- IndexReader.unlock(theIndexDir);
- }
+ FSDirectory theIndexDir=FSDirectory.getDirectory(index,false);
+ if (IndexReader.isLocked(theIndexDir)){
+ IndexReader.unlock(theIndexDir);
+ }
}
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
public class KeywordSearchTerm extends SearchTerm{
- public String templateVariable;
- public String dataField;
- public String matchField;
- public String paramName;
- public String partOfEntity;
-
-
public KeywordSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
public void index(Document doc, Entity entity){
- doc.add(Field.Keyword(matchField,entity.getValue(partOfEntity)));
+ doc.add(Field.Keyword(matchField,entity.getFieldValue(partOfEntity)));
}
public void indexValue(Document doc, String value){
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
public class MediaSearchTerm extends SearchTerm{
- public static String matchField = "";
- public static String paramName = "search_hasMedia";
- public static String templateVariable = "";
+ public MediaSearchTerm() {
+ super(null, "search_hasMedia", "", null, "");
+ }
public void index(Document doc, Entity entity) throws StorageObjectFailure{
- // only use this term for doing alternate queries on media
+ // only use this term for doing alternate queries on media
return;
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
-
import mir.entity.Entity;
-
import org.apache.lucene.document.Document;
abstract public class SearchTerm {
+ protected String partOfEntity;
+ protected String paramName;
+ protected String matchField;
+ protected String dataField;
+ protected String templateVariable;
- public static String partOfEntity;
- public static String paramName;
- public static String matchField;
- public static String dataField;
- public static String templateVariable;
-
- public SearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
+ public SearchTerm(String anEntityPart, String aParamName, String aMatchField, String aDataField, String aTemplateVariable){
//for more reusable SearchTerm types
partOfEntity = anEntityPart;
paramName = aParamName;
public class TextSearchTerm extends SearchTerm{
-
- public String templateVariable;
- public String dataField;
- public String matchField;
- public String paramName;
- public String partOfEntity;
-
public TextSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
paramName = aParamName;
matchField = aMatchField;
dataField = aDataField;
templateVariable = aTemplateVariable;
-
}
public void index(Document doc, Entity entity){
- String value =entity.getValue(partOfEntity);
+ String value =entity.getFieldValue(partOfEntity);
if (value==null) value="";
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
public class TopicMatrixSearchTerm extends SearchTerm{
-
-
- public static String matchField = "topic";
- public static String paramName = "search_topicmatrix";
+ public TopicMatrixSearchTerm() {
+ super(null, "search_topicmatrix", "topic", null, null);
+ }
public void index(Document doc, Entity entity) throws StorageObjectFailure{
EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity);
if (topics != null && topics.size()>0){
for(int k=0;k<topics.size();k++){
- doc.add(Field.UnStored(matchField,(topics.elementAt(k)).getValue("title")));
+ doc.add(Field.UnStored(matchField,(topics.elementAt(k)).getFieldValue("title")));
}
}
}
String queryTerm = "";
for (int x=0;x<10;x++){
String[] values = req.getParameterValues("search_topicmatrix_"+Integer.toString(x));
-
+
if (values != null && values.length > 0){
String subqueryTerm = "(";
for (int i=0;i<values.length;i++){
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
public class TopicSearchTerm extends SearchTerm{
-
-
- public static String matchField = "topic";
- public static String paramName = "search_topic";
+ public TopicSearchTerm() {
+ super(null, "search_topic", "topic", null, null);
+ }
public void index(Document doc, Entity entity) throws StorageObjectFailure{
EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity);
if (topics != null && topics.size()>0){
for(int k=0;k<topics.size();k++){
- doc.add(Field.UnStored(matchField,(topics.elementAt(k)).getValue("title")));
+ doc.add(Field.UnStored(matchField,(topics.elementAt(k)).getFieldValue("title")));
}
}
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
public class UnIndexedSearchTerm extends SearchTerm{
-
- public String templateVariable;
- public String dataField;
- public String matchField;
- public String paramName;
- public String partOfEntity;
-
public UnIndexedSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
paramName = aParamName;
templateVariable = aTemplateVariable;
}
-
public void index(Document doc, Entity entity){
- doc.add(Field.Text(dataField,entity.getValue(partOfEntity)));
+ doc.add(Field.Text(dataField,entity.getFieldValue(partOfEntity)));
}
public void indexValue(Document doc, String value){
doc.add(Field.Text(dataField, value));
}
-
public String makeTerm(HttpServletRequest req){
// it isn't indexed!
return null;
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package mircoders.search;
public class UnStoredSearchTerm extends SearchTerm{
-
- public String templateVariable;
- public String dataField;
- public String matchField;
- public String paramName;
- public String partOfEntity;
-
-
public UnStoredSearchTerm(String anEntityPart,String aParamName,String aMatchField,String aDataField, String aTemplateVariable){
partOfEntity = anEntityPart;
paramName = aParamName;
templateVariable = aTemplateVariable;
}
-
public void index(Document doc, Entity entity){
- doc.add(Field.UnStored(matchField,entity.getValue(partOfEntity)));
+ doc.add(Field.UnStored(matchField,entity.getFieldValue(partOfEntity)));
}
public void indexValue(Document doc, String value){
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two. You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries. If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
+ * the code of this program with any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two. You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries. If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
-
package mircoders.search;
+import java.util.Iterator;
import java.util.Map;
+import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
-import mir.entity.EntityList;
+import mir.entity.EntityBrowser;
import mir.storage.StorageObjectFailure;
import mircoders.entity.EntityContent;
-import mircoders.storage.DatabaseContentToMedia;
+import mircoders.storage.DatabaseVideo;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-public class VideoSearchTerm extends SearchTerm{
- public static String matchField = "hasVideo";
- public static String paramName = "search_hasVideo";
- public static String templateVariable = "hasVideo";
- public void index(Document doc, Entity entity) throws StorageObjectFailure{
- EntityList video = DatabaseContentToMedia.getInstance().getVideo((EntityContent) entity);
- if (video != null && video.size()>0){
- doc.add(Field.Keyword(matchField,"y"));
+
+public class VideoSearchTerm extends SearchTerm {
+ public VideoSearchTerm() {
+ super(null, "search_hasVideo", "hasVideo", null, "hasVideo");
+ }
+
+ public void index(Document doc, Entity entity) throws StorageObjectFailure {
+ Vector extraTables = new Vector();
+ extraTables.add("content_x_media cxm");
+
+ Iterator videos = new EntityBrowser(
+ DatabaseVideo.getInstance(), "i", extraTables,
+ "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id",
+ "i.id desc", 30, -1, 0);
+
+ if ((videos != null) && (videos.hasNext())) {
+ doc.add(Field.Keyword(matchField, "y"));
}
}
- public String makeTerm(HttpServletRequest req){
+ public String makeTerm(HttpServletRequest req) {
String wanted = req.getParameter(paramName);
- if (wanted != null && wanted.equals("y")){
+
+ if ((wanted != null) && wanted.equals("y")) {
return matchField + ":" + "\"" + wanted + "\"";
- }
- else {
+ } else {
return null;
}
}
- public void returnMeta(Map result,Document doc){
+ public void returnMeta(Map result, Document doc) {
result.put(templateVariable, doc.get(matchField));
}
-
-
}
-
-