Subversion Repositories general

Compare Revisions

Ignore whitespace Rev 1221 → Rev 1223

/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/hibernate/HibernateUtil.java
0,0 → 1,279
package ak.hostadmiral.util.hibernate;
 
import java.util.Iterator;
import java.util.Collection;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.type.Type;
import org.hibernate.classic.Session;
 
import ak.hostadmiral.util.ModelStoreException;
 
public class HibernateUtil
{
public static final int DATABASE_VERSION = 2;
 
private static Configuration configuration;
private static SessionFactory sessionFactory;
private static final ThreadLocal hibernateBean = new ThreadLocal();
private static boolean validated = false;
 
private static void validate()
throws HibernateException, ModelStoreException
{
synchronized(HibernateUtil.class) {
if(validated) return;
 
Collection versions = currentSession().find("from DatabaseVersion");
 
if(versions == null || versions.size() == 0)
throw new ModelStoreException("Database structure version not found");
 
if(versions.size() > 1)
throw new ModelStoreException(
"Too much entries in database structure version table");
 
int version = ((DatabaseVersion)versions.iterator().next()).getMajor();
if(version != DATABASE_VERSION)
throw new ModelStoreException("Expected database structure version "
+ DATABASE_VERSION + ", found " + version);
 
validated = true;
}
}
 
public static void configure(String driver, String userName, String password,
String url, String dialect)
throws HibernateException
{
Configuration c = getConfiguration();
c.setProperty("hibernate.connection.driver_class", driver);
c.setProperty("hibernate.connection.username", userName);
c.setProperty("hibernate.connection.password", password);
c.setProperty("hibernate.connection.url", url);
c.setProperty("hibernate.dialect", dialect);
}
 
public static Configuration getConfiguration()
throws HibernateException
{
if(configuration == null)
configuration = new Configuration();
 
return configuration;
}
 
public static SessionFactory getSessionFactory()
throws HibernateException
{
if(sessionFactory == null)
sessionFactory = getConfiguration().configure().buildSessionFactory();
 
return sessionFactory;
}
 
private static HibernateBean currentBean()
throws HibernateException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
if(hb == null) {
hb = new HibernateBean();
hb.session = getSessionFactory().openSession();
hibernateBean.set(hb);
}
return hb;
}
 
public static Session currentSession()
throws HibernateException
{
return currentBean().session;
}
 
public static void closeSession()
throws HibernateException, ModelStoreException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
if(hb == null)
throw new ModelStoreException("No session found for this thread");
 
hibernateBean.set(null);
hb.session.close();
}
 
public static void beginTransaction()
throws HibernateException, ModelStoreException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
if(hb != null && hb.transaction != null)
throw new ModelStoreException("Transaction is already open");
 
currentBean().transaction = currentSession().beginTransaction();
 
// validate database structure version
if(!validated) // just try to speed up by avoiding synchronization
validate();
}
 
public static boolean isTransactionOpen()
throws HibernateException, ModelStoreException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
return (hb != null) && (hb.transaction != null);
}
 
public static void commitTransaction()
throws HibernateException, ModelStoreException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
if(hb == null || hb.transaction == null)
throw new ModelStoreException("No open transaction");
 
hb.transaction.commit();
hb.transaction = null;
}
 
public static void rollbackTransaction()
throws HibernateException, ModelStoreException
{
HibernateBean hb = (HibernateBean)hibernateBean.get();
 
if(hb == null || hb.transaction == null)
throw new ModelStoreException("No open transaction");
 
hb.transaction.rollback();
hb.transaction = null;
}
 
public static List sqlQuery(String query, Object[] values)
throws HibernateException, ModelStoreException
{
Connection con = currentSession().connection();
PreparedStatement stmt;
 
try {
stmt = con.prepareStatement(query);
}
catch(SQLException ex) {
throw new ModelStoreException(ex);
}
 
try {
if(values != null) {
for(int i = 0; i < values.length; i++)
stmt.setObject(i+1, values[i]);
}
 
List res = new ArrayList();
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
res.add(rs.getObject(1));
}
return res;
}
catch(SQLException ex)
{
throw new ModelStoreException(ex);
}
finally {
try {
stmt.close();
}
catch(SQLException ex) {
ex.printStackTrace();
}
}
}
 
public static List pageableListSql(int pageSize, int pageNumber,
String query, String[] returnAliases, Class[] returnClasses,
Object[] values, Type[] types)
throws HibernateException, ModelStoreException
{
Query hq = currentSession().createSQLQuery(
query, returnAliases, returnClasses);
 
if(values != null && types != null) {
for(int i = 0; i < values.length; i++)
hq.setParameter(i, values[i], types[i]);
}
 
if(pageSize > 0) {
hq.setFirstResult(pageSize * pageNumber);
hq.setMaxResults(pageSize);
}
 
return selectFirstClassColumn(hq.list());
// FIXME: really no other way in Hibernate?
}
 
public static List pageableList(int pageSize, int pageNumber,
String query, Object[] values, Type[] types)
throws HibernateException, ModelStoreException
{
Query hq = currentSession().createQuery(query);
 
if(values != null && types != null) {
for(int i = 0; i < values.length; i++)
hq.setParameter(i, values[i], types[i]);
}
 
if(pageSize > 0) {
hq.setFirstResult(pageSize * pageNumber);
hq.setMaxResults(pageSize);
}
 
return hq.list();
}
 
protected static List selectFirstClassColumn(List list)
{
List res = new ArrayList();
 
for(Iterator i = list.iterator(); i.hasNext(); ) {
res.add(((Object[])i.next())[0]);
}
 
return res;
}
 
public static String formOrderClause(Integer[] sortingKeys, Map fieldMap)
throws ModelStoreException
{
if(sortingKeys == null || sortingKeys.length == 0) return "";
 
StringBuffer buf = new StringBuffer(" order by ");
 
for(int i = 0; i < sortingKeys.length; i++) {
if(i > 0) buf.append(",");
 
String field = (String)fieldMap.get(sortingKeys[i]);
if(field == null)
throw new ModelStoreException(
"Field for sorting key " + sortingKeys[i] + " not found");
 
buf.append(field);
}
 
return buf.toString();
}
 
static class HibernateBean
{
public Session session;
public Transaction transaction;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/hibernate/DatabaseVersion.java
0,0 → 1,40
package ak.hostadmiral.util.hibernate;
 
/**
*
* @hibernate.class table="dbversion" mutable="false"
*/
public class DatabaseVersion
{
private int major;
 
/**
*
* @hibernate.id generator-class="assigned"
*/
public int getMajor()
{
return major;
}
 
protected void setMajor(int major)
{
this.major = major;
}
 
private int minor;
 
/**
*
* @hibernate.field
*/
public int getMinor()
{
return minor;
}
 
protected void setMinor(int minor)
{
this.minor = minor;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/DigestCrypt.java
0,0 → 1,640
package ak.hostadmiral.util;
 
/****************************************************************************
* Java implementation of the unix crypt command
* Based on jdumas@zgs.com implementation,
* http://locutus.kingwoodcable.com/jfd/crypt.html
*
* Based upon C source code written by Eric Young, eay@psych.uq.oz.au
*
****************************************************************************/
 
public class DigestCrypt
{
private DigestCrypt() {}
 
private static final int ITERATIONS = 16;
 
private static String salt_chars
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890./";
 
private static final int con_salt[] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22,
0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24,
0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C,
0x3D, 0x3E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00,
};
 
private static final boolean shifts2[] =
{
false, false, true, true, true, true, true, true,
false, true, true, true, true, true, true, false
};
 
private static final int skb[][] =
{
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x00000010, 0x20000000, 0x20000010,
0x00010000, 0x00010010, 0x20010000, 0x20010010,
0x00000800, 0x00000810, 0x20000800, 0x20000810,
0x00010800, 0x00010810, 0x20010800, 0x20010810,
0x00000020, 0x00000030, 0x20000020, 0x20000030,
0x00010020, 0x00010030, 0x20010020, 0x20010030,
0x00000820, 0x00000830, 0x20000820, 0x20000830,
0x00010820, 0x00010830, 0x20010820, 0x20010830,
0x00080000, 0x00080010, 0x20080000, 0x20080010,
0x00090000, 0x00090010, 0x20090000, 0x20090010,
0x00080800, 0x00080810, 0x20080800, 0x20080810,
0x00090800, 0x00090810, 0x20090800, 0x20090810,
0x00080020, 0x00080030, 0x20080020, 0x20080030,
0x00090020, 0x00090030, 0x20090020, 0x20090030,
0x00080820, 0x00080830, 0x20080820, 0x20080830,
0x00090820, 0x00090830, 0x20090820, 0x20090830,
},
{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000, 0x02000000, 0x00002000, 0x02002000,
0x00200000, 0x02200000, 0x00202000, 0x02202000,
0x00000004, 0x02000004, 0x00002004, 0x02002004,
0x00200004, 0x02200004, 0x00202004, 0x02202004,
0x00000400, 0x02000400, 0x00002400, 0x02002400,
0x00200400, 0x02200400, 0x00202400, 0x02202400,
0x00000404, 0x02000404, 0x00002404, 0x02002404,
0x00200404, 0x02200404, 0x00202404, 0x02202404,
0x10000000, 0x12000000, 0x10002000, 0x12002000,
0x10200000, 0x12200000, 0x10202000, 0x12202000,
0x10000004, 0x12000004, 0x10002004, 0x12002004,
0x10200004, 0x12200004, 0x10202004, 0x12202004,
0x10000400, 0x12000400, 0x10002400, 0x12002400,
0x10200400, 0x12200400, 0x10202400, 0x12202400,
0x10000404, 0x12000404, 0x10002404, 0x12002404,
0x10200404, 0x12200404, 0x10202404, 0x12202404,
},
{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000, 0x00000001, 0x00040000, 0x00040001,
0x01000000, 0x01000001, 0x01040000, 0x01040001,
0x00000002, 0x00000003, 0x00040002, 0x00040003,
0x01000002, 0x01000003, 0x01040002, 0x01040003,
0x00000200, 0x00000201, 0x00040200, 0x00040201,
0x01000200, 0x01000201, 0x01040200, 0x01040201,
0x00000202, 0x00000203, 0x00040202, 0x00040203,
0x01000202, 0x01000203, 0x01040202, 0x01040203,
0x08000000, 0x08000001, 0x08040000, 0x08040001,
0x09000000, 0x09000001, 0x09040000, 0x09040001,
0x08000002, 0x08000003, 0x08040002, 0x08040003,
0x09000002, 0x09000003, 0x09040002, 0x09040003,
0x08000200, 0x08000201, 0x08040200, 0x08040201,
0x09000200, 0x09000201, 0x09040200, 0x09040201,
0x08000202, 0x08000203, 0x08040202, 0x08040203,
0x09000202, 0x09000203, 0x09040202, 0x09040203,
},
{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000, 0x00100000, 0x00000100, 0x00100100,
0x00000008, 0x00100008, 0x00000108, 0x00100108,
0x00001000, 0x00101000, 0x00001100, 0x00101100,
0x00001008, 0x00101008, 0x00001108, 0x00101108,
0x04000000, 0x04100000, 0x04000100, 0x04100100,
0x04000008, 0x04100008, 0x04000108, 0x04100108,
0x04001000, 0x04101000, 0x04001100, 0x04101100,
0x04001008, 0x04101008, 0x04001108, 0x04101108,
0x00020000, 0x00120000, 0x00020100, 0x00120100,
0x00020008, 0x00120008, 0x00020108, 0x00120108,
0x00021000, 0x00121000, 0x00021100, 0x00121100,
0x00021008, 0x00121008, 0x00021108, 0x00121108,
0x04020000, 0x04120000, 0x04020100, 0x04120100,
0x04020008, 0x04120008, 0x04020108, 0x04120108,
0x04021000, 0x04121000, 0x04021100, 0x04121100,
0x04021008, 0x04121008, 0x04021108, 0x04121108,
},
{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x10000000, 0x00010000, 0x10010000,
0x00000004, 0x10000004, 0x00010004, 0x10010004,
0x20000000, 0x30000000, 0x20010000, 0x30010000,
0x20000004, 0x30000004, 0x20010004, 0x30010004,
0x00100000, 0x10100000, 0x00110000, 0x10110000,
0x00100004, 0x10100004, 0x00110004, 0x10110004,
0x20100000, 0x30100000, 0x20110000, 0x30110000,
0x20100004, 0x30100004, 0x20110004, 0x30110004,
0x00001000, 0x10001000, 0x00011000, 0x10011000,
0x00001004, 0x10001004, 0x00011004, 0x10011004,
0x20001000, 0x30001000, 0x20011000, 0x30011000,
0x20001004, 0x30001004, 0x20011004, 0x30011004,
0x00101000, 0x10101000, 0x00111000, 0x10111000,
0x00101004, 0x10101004, 0x00111004, 0x10111004,
0x20101000, 0x30101000, 0x20111000, 0x30111000,
0x20101004, 0x30101004, 0x20111004, 0x30111004,
},
{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000, 0x08000000, 0x00000008, 0x08000008,
0x00000400, 0x08000400, 0x00000408, 0x08000408,
0x00020000, 0x08020000, 0x00020008, 0x08020008,
0x00020400, 0x08020400, 0x00020408, 0x08020408,
0x00000001, 0x08000001, 0x00000009, 0x08000009,
0x00000401, 0x08000401, 0x00000409, 0x08000409,
0x00020001, 0x08020001, 0x00020009, 0x08020009,
0x00020401, 0x08020401, 0x00020409, 0x08020409,
0x02000000, 0x0A000000, 0x02000008, 0x0A000008,
0x02000400, 0x0A000400, 0x02000408, 0x0A000408,
0x02020000, 0x0A020000, 0x02020008, 0x0A020008,
0x02020400, 0x0A020400, 0x02020408, 0x0A020408,
0x02000001, 0x0A000001, 0x02000009, 0x0A000009,
0x02000401, 0x0A000401, 0x02000409, 0x0A000409,
0x02020001, 0x0A020001, 0x02020009, 0x0A020009,
0x02020401, 0x0A020401, 0x02020409, 0x0A020409,
},
{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000, 0x00000100, 0x00080000, 0x00080100,
0x01000000, 0x01000100, 0x01080000, 0x01080100,
0x00000010, 0x00000110, 0x00080010, 0x00080110,
0x01000010, 0x01000110, 0x01080010, 0x01080110,
0x00200000, 0x00200100, 0x00280000, 0x00280100,
0x01200000, 0x01200100, 0x01280000, 0x01280100,
0x00200010, 0x00200110, 0x00280010, 0x00280110,
0x01200010, 0x01200110, 0x01280010, 0x01280110,
0x00000200, 0x00000300, 0x00080200, 0x00080300,
0x01000200, 0x01000300, 0x01080200, 0x01080300,
0x00000210, 0x00000310, 0x00080210, 0x00080310,
0x01000210, 0x01000310, 0x01080210, 0x01080310,
0x00200200, 0x00200300, 0x00280200, 0x00280300,
0x01200200, 0x01200300, 0x01280200, 0x01280300,
0x00200210, 0x00200310, 0x00280210, 0x00280310,
0x01200210, 0x01200310, 0x01280210, 0x01280310,
},
{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000, 0x04000000, 0x00040000, 0x04040000,
0x00000002, 0x04000002, 0x00040002, 0x04040002,
0x00002000, 0x04002000, 0x00042000, 0x04042000,
0x00002002, 0x04002002, 0x00042002, 0x04042002,
0x00000020, 0x04000020, 0x00040020, 0x04040020,
0x00000022, 0x04000022, 0x00040022, 0x04040022,
0x00002020, 0x04002020, 0x00042020, 0x04042020,
0x00002022, 0x04002022, 0x00042022, 0x04042022,
0x00000800, 0x04000800, 0x00040800, 0x04040800,
0x00000802, 0x04000802, 0x00040802, 0x04040802,
0x00002800, 0x04002800, 0x00042800, 0x04042800,
0x00002802, 0x04002802, 0x00042802, 0x04042802,
0x00000820, 0x04000820, 0x00040820, 0x04040820,
0x00000822, 0x04000822, 0x00040822, 0x04040822,
0x00002820, 0x04002820, 0x00042820, 0x04042820,
0x00002822, 0x04002822, 0x00042822, 0x04042822,
},
};
 
private static final int SPtrans[][] =
{
{
/* nibble 0 */
0x00820200, 0x00020000, 0x80800000, 0x80820200,
0x00800000, 0x80020200, 0x80020000, 0x80800000,
0x80020200, 0x00820200, 0x00820000, 0x80000200,
0x80800200, 0x00800000, 0x00000000, 0x80020000,
0x00020000, 0x80000000, 0x00800200, 0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200,
0x80000000, 0x00000200, 0x00020200, 0x80820000,
0x00000200, 0x80800200, 0x80820000, 0x00000000,
0x00000000, 0x80820200, 0x00800200, 0x80020000,
0x00820200, 0x00020000, 0x80000200, 0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000,
0x80020200, 0x80000000, 0x80800000, 0x00820000,
0x80820200, 0x00020200, 0x00820000, 0x80800200,
0x00800000, 0x80000200, 0x80020000, 0x00000000,
0x00020000, 0x00800000, 0x80800200, 0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200,
},
{
/* nibble 1 */
0x10042004, 0x00000000, 0x00042000, 0x10040000,
0x10000004, 0x00002004, 0x10002000, 0x00042000,
0x00002000, 0x10040004, 0x00000004, 0x10002000,
0x00040004, 0x10042000, 0x10040000, 0x00000004,
0x00040000, 0x10002004, 0x10040004, 0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004,
0x10002004, 0x00042004, 0x10042000, 0x10000004,
0x10000000, 0x00040000, 0x00002004, 0x10042004,
0x00040004, 0x10042000, 0x10002000, 0x00042004,
0x10042004, 0x00040004, 0x10000004, 0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004,
0x00002000, 0x10000000, 0x00042004, 0x10002004,
0x10042000, 0x00002000, 0x00000000, 0x10000004,
0x00000004, 0x10042004, 0x00042000, 0x10040000,
0x10040004, 0x00040000, 0x00002004, 0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000,
},
{
/* nibble 2 */
0x41000000, 0x01010040, 0x00000040, 0x41000040,
0x40010000, 0x01000000, 0x41000040, 0x00010040,
0x01000040, 0x00010000, 0x01010000, 0x40000000,
0x41010040, 0x40000040, 0x40000000, 0x41010000,
0x00000000, 0x40010000, 0x01010040, 0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000,
0x41010000, 0x01000040, 0x40010040, 0x01010000,
0x00010040, 0x00000000, 0x01000000, 0x40010040,
0x01010040, 0x00000040, 0x40000000, 0x00010000,
0x40000040, 0x40010000, 0x01010000, 0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000,
0x40010000, 0x01000000, 0x41010040, 0x40000000,
0x40010040, 0x41000000, 0x01000000, 0x41010040,
0x00010000, 0x01000040, 0x41000040, 0x00010040,
0x01000040, 0x00000000, 0x41010000, 0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000,
},
{
/* nibble 3 */
0x00100402, 0x04000400, 0x00000002, 0x04100402,
0x00000000, 0x04100000, 0x04000402, 0x00100002,
0x04100400, 0x04000002, 0x04000000, 0x00000402,
0x04000002, 0x00100402, 0x00100000, 0x04000000,
0x04100002, 0x00100400, 0x00000400, 0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400,
0x00000402, 0x00000000, 0x00100002, 0x04100400,
0x04000400, 0x04100002, 0x04100402, 0x00100000,
0x04100002, 0x00000402, 0x00100000, 0x04000002,
0x00100400, 0x04000400, 0x00000002, 0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002,
0x00000000, 0x04100002, 0x04100400, 0x00000400,
0x04000000, 0x04100402, 0x00100402, 0x00100000,
0x04100402, 0x00000002, 0x04000400, 0x00100402,
0x00100002, 0x00100400, 0x04100000, 0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400,
},
{
/* nibble 4 */
0x02000000, 0x00004000, 0x00000100, 0x02004108,
0x02004008, 0x02000100, 0x00004108, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x00004100,
0x02000108, 0x02004008, 0x02004100, 0x00000000,
0x00004100, 0x02000000, 0x00004008, 0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008,
0x00000008, 0x02000108, 0x02004108, 0x00004008,
0x02004000, 0x00000100, 0x00000108, 0x02004100,
0x02004100, 0x02000108, 0x00004008, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000,
0x00004108, 0x02000000, 0x00000100, 0x00004008,
0x02000108, 0x00000100, 0x00000000, 0x02004108,
0x02004008, 0x02004100, 0x00000108, 0x00004000,
0x00004100, 0x02004008, 0x02000100, 0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008,
},
{
/* nibble 5 */
0x20000010, 0x00080010, 0x00000000, 0x20080800,
0x00080010, 0x00000800, 0x20000810, 0x00080000,
0x00000810, 0x20080810, 0x00080800, 0x20000000,
0x20000800, 0x20000010, 0x20080000, 0x00080810,
0x00080000, 0x20000810, 0x20080010, 0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010,
0x20080810, 0x20080000, 0x20000000, 0x00000810,
0x00000010, 0x00080800, 0x00080810, 0x20000800,
0x00000810, 0x20000000, 0x20000800, 0x00080810,
0x20080800, 0x00080010, 0x00000000, 0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000,
0x00080010, 0x20080810, 0x00080800, 0x00000010,
0x20080810, 0x00080800, 0x00080000, 0x20000810,
0x20000010, 0x20080000, 0x00080810, 0x00000000,
0x00000800, 0x20000010, 0x20000810, 0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010,
},
{
/* nibble 6 */
0x00001000, 0x00000080, 0x00400080, 0x00400001,
0x00401081, 0x00001001, 0x00001080, 0x00000000,
0x00400000, 0x00400081, 0x00000081, 0x00401000,
0x00000001, 0x00401080, 0x00401000, 0x00000081,
0x00400081, 0x00001000, 0x00001001, 0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080,
0x00401001, 0x00001081, 0x00401080, 0x00000001,
0x00001081, 0x00401001, 0x00000080, 0x00400000,
0x00001081, 0x00401000, 0x00401001, 0x00000081,
0x00001000, 0x00000080, 0x00400000, 0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000,
0x00000080, 0x00400001, 0x00000001, 0x00400080,
0x00000000, 0x00400081, 0x00400080, 0x00001080,
0x00000081, 0x00001000, 0x00401081, 0x00400000,
0x00401080, 0x00000001, 0x00001001, 0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001,
},
{
/* nibble 7 */
0x08200020, 0x08208000, 0x00008020, 0x00000000,
0x08008000, 0x00200020, 0x08200000, 0x08208020,
0x00000020, 0x08000000, 0x00208000, 0x00008020,
0x00208020, 0x08008020, 0x08000020, 0x08200000,
0x00008000, 0x00208020, 0x00200020, 0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000,
0x08000000, 0x00200000, 0x08008020, 0x08200020,
0x00200000, 0x00008000, 0x08208000, 0x00000020,
0x00200000, 0x00008000, 0x08000020, 0x08208020,
0x00008020, 0x08000000, 0x00000000, 0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020,
0x08208000, 0x00000020, 0x00200020, 0x08008000,
0x08208020, 0x00200000, 0x08200000, 0x08000020,
0x00208000, 0x00008020, 0x08008020, 0x08200000,
0x00000020, 0x08208000, 0x00208020, 0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020
}
};
 
private static final int cov_2char[] =
{
0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
};
 
private static final int byteToUnsigned(byte b)
{
int value = (int)b;
 
return(value >= 0 ? value : value + 256);
}
 
private static int fourBytesToInt(byte b[], int offset)
{
int value;
 
value = byteToUnsigned(b[offset++]);
value |= (byteToUnsigned(b[offset++]) << 8);
value |= (byteToUnsigned(b[offset++]) << 16);
value |= (byteToUnsigned(b[offset++]) << 24);
 
return(value);
}
 
private static final void intToFourBytes(int iValue, byte b[], int offset)
{
b[offset++] = (byte)((iValue) & 0xff);
b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
b[offset++] = (byte)((iValue >>> 16) & 0xff);
b[offset++] = (byte)((iValue >>> 24) & 0xff);
}
 
private static final void PERM_OP(int a, int b, int n, int m, int results[])
{
int t;
 
t = ((a >>> n) ^ b) & m;
a ^= t << n;
b ^= t;
 
results[0] = a;
results[1] = b;
}
 
private static final int HPERM_OP(int a, int n, int m)
{
int t;
 
t = ((a << (16 - n)) ^ a) & m;
a = a ^ t ^ (t >>> (16 - n));
 
return(a);
}
 
private static int [] des_set_key(byte key[])
{
int schedule[] = new int[ITERATIONS * 2];
 
int c = fourBytesToInt(key, 0);
int d = fourBytesToInt(key, 4);
 
int results[] = new int[2];
 
PERM_OP(d, c, 4, 0x0f0f0f0f, results);
d = results[0]; c = results[1];
 
c = HPERM_OP(c, -2, 0xcccc0000);
d = HPERM_OP(d, -2, 0xcccc0000);
 
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
 
PERM_OP(c, d, 8, 0x00ff00ff, results);
c = results[0]; d = results[1];
 
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
 
d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
c &= 0x0fffffff;
 
int s, t;
int j = 0;
 
for(int i = 0; i < ITERATIONS; i ++)
{
if(shifts2[i])
{
c = (c >>> 2) | (c << 26);
d = (d >>> 2) | (d << 26);
}
else
{
c = (c >>> 1) | (c << 27);
d = (d >>> 1) | (d << 27);
}
 
c &= 0x0fffffff;
d &= 0x0fffffff;
 
s = skb[0][ (c ) & 0x3f ]|
skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]|
skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|
skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
((c >>> 22) & 0x38)];
 
t = skb[4][ (d ) & 0x3f ]|
skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]|
skb[6][ (d >>>15) & 0x3f ]|
skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];
 
schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
s = ((s >>> 16) | (t & 0xffff0000));
 
s = (s << 4) | (s >>> 28);
schedule[j++] = s & 0xffffffff;
}
return(schedule);
}
 
private static final int D_ENCRYPT
(
int L, int R, int S, int E0, int E1, int s[]
)
{
int t, u, v;
 
v = R ^ (R >>> 16);
u = v & E0;
v = v & E1;
u = (u ^ (u << 16)) ^ R ^ s[S];
t = (v ^ (v << 16)) ^ R ^ s[S + 1];
t = (t >>> 4) | (t << 28);
 
L ^= SPtrans[1][(t ) & 0x3f] |
SPtrans[3][(t >>> 8) & 0x3f] |
SPtrans[5][(t >>> 16) & 0x3f] |
SPtrans[7][(t >>> 24) & 0x3f] |
SPtrans[0][(u ) & 0x3f] |
SPtrans[2][(u >>> 8) & 0x3f] |
SPtrans[4][(u >>> 16) & 0x3f] |
SPtrans[6][(u >>> 24) & 0x3f];
 
return(L);
}
 
private static final int [] body(int schedule[], int Eswap0, int Eswap1)
{
int left = 0;
int right = 0;
int t = 0;
 
for(int j = 0; j < 25; j ++)
{
for(int i = 0; i < ITERATIONS * 2; i += 4)
{
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
 
t = right;
 
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
 
left &= 0xffffffff;
right &= 0xffffffff;
 
int results[] = new int[2];
 
PERM_OP(right, left, 1, 0x55555555, results);
right = results[0]; left = results[1];
 
PERM_OP(left, right, 8, 0x00ff00ff, results);
left = results[0]; right = results[1];
 
PERM_OP(right, left, 2, 0x33333333, results);
right = results[0]; left = results[1];
 
PERM_OP(left, right, 16, 0x0000ffff, results);
left = results[0]; right = results[1];
 
PERM_OP(right, left, 4, 0x0f0f0f0f, results);
right = results[0]; left = results[1];
 
int out[] = new int[2];
 
out[0] = left; out[1] = right;
 
return(out);
}
 
public static final String crypt(String salt, String original)
{
while(salt.length() < 2)
salt += "A";
 
StringBuffer buffer = new StringBuffer(" ");
 
char charZero = salt.charAt(0);
char charOne = salt.charAt(1);
 
buffer.setCharAt(0, charZero);
buffer.setCharAt(1, charOne);
 
int Eswap0 = con_salt[(int)charZero];
int Eswap1 = con_salt[(int)charOne] << 4;
 
byte key[] = new byte[8];
 
for(int i = 0; i < key.length; i ++)
key[i] = (byte)0;
 
for(int i = 0; i < key.length && i < original.length(); i ++)
{
int iChar = (int)original.charAt(i);
 
key[i] = (byte)(iChar << 1);
}
 
int schedule[] = des_set_key(key);
int out[] = body(schedule, Eswap0, Eswap1);
 
byte b[] = new byte[9];
 
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
 
for(int i = 2, y = 0, u = 0x80; i < 13; i ++)
{
for(int j = 0, c = 0; j < 6; j ++)
{
c <<= 1;
 
if(((int)b[y] & u) != 0)
c |= 1;
 
u >>>= 1;
 
if(u == 0)
{
y++;
u = 0x80;
}
buffer.setCharAt(i, (char)cov_2char[c]);
}
}
return(buffer.toString());
}
 
public static final String crypt(String original)
{
char c1 = salt_chars.charAt((int)(Math.random() * salt_chars.length()));
char c2 = salt_chars.charAt((int)(Math.random() * salt_chars.length()));
return crypt("" + c1 + c2, original);
}
 
public static void main(String args[])
{
if(args.length >= 2)
{
System.out.println
(
"[" + args[0] + "] [" + args[1] + "] => [" +
DigestCrypt.crypt(args[0], args[1]) + "]"
);
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ConfigUtils.java
0,0 → 1,81
package ak.hostadmiral.util;
 
import java.util.Map;
 
public class ConfigUtils
{
private Map params;
protected boolean returnDefValue;
 
public ConfigUtils(Map params)
{
this.params = params;
}
 
public String getString(String key, String defValue,
boolean optional, boolean mayBeEmpty)
throws ModelException
{
String s = (String)getObject(key, defValue, optional);
 
if(returnDefValue) return s;
 
if(!mayBeEmpty && s.equals("")) {
throw new ModelException("Configuration parameter '" + key + "' may not be empty");
}
 
return s;
}
 
public Integer getInteger(String key, Integer defValue,
boolean optional)
throws ModelException
{
Object value = getObject(key, defValue, optional);
 
if(returnDefValue) return defValue;
 
return new Integer((String)value);
}
 
protected synchronized Object getObject(String key, Object defValue, boolean optional)
throws ModelException
{
returnDefValue = false;
 
Object obj = params.get(key);
 
if(obj == null) {
if(optional) {
returnDefValue = true;
return defValue;
}
else
throw new ModelException("Configuration parameter '" + key + "' must be present");
}
 
if(!(obj instanceof String[])) {
throw new ModelException("Configuration parameter '" + key
+ "' expected to be an array of strings");
}
 
String[] sa = (String[])obj;
 
if(sa.length == 0) {
if(optional) {
returnDefValue = true;
return defValue;
}
else
throw new ModelException("Value of configuration parameter '"
+ key + "' must be present");
}
 
if(sa.length > 1) {
throw new ModelException("Value of configuration parameter '"
+ key + "' may not be an array");
}
 
return sa[0];
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ConfigInit.java
0,0 → 1,16
package ak.hostadmiral.util;
 
import java.util.Map;
 
public interface ConfigInit
{
/**
* This method is called by initialization from config file.
* FIMXE give more powerful structure, not just a map
*
* @param params map String -> String[] with pairs of param name -> values
* from the initializaion file
*/
public void init(Map params)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/CollectionInfo.java
0,0 → 1,97
package ak.hostadmiral.util;
 
public class CollectionInfo
{
/** total number of rows in list */
private int size;
 
public int getSize()
{
return size;
}
 
public void setSize(int size)
{
this.size = size;
recalc();
}
 
/** current selected page */
private int currentPage;
 
protected int normPage(int page)
{
if(totalPages <= 0 || page <= 0)
return 0;
else if(page < totalPages)
return page;
else
return (totalPages - 1);
}
 
public int getCurrentPage()
{
return normPage(currentPage);
}
 
public void setCurrentPage(int currentPage)
{
this.currentPage = currentPage;
}
 
/** number of rows on one page */
private int rowsPerPage;
 
public int getRowsPerPage()
{
return rowsPerPage;
}
 
public void setRowsPerPage(int rowsPerPage)
{
this.rowsPerPage = rowsPerPage;
recalc();
}
 
/** total number of pages */
private int totalPages;
 
public int getTotalPages()
{
return totalPages;
}
 
public int getFirstPage()
{
return 0;
}
 
public int getLastPage()
{
return normPage(totalPages - 1);
}
 
public int getPrevPage()
{
return normPage(currentPage - 1);
}
 
public int getNextPage()
{
return normPage(currentPage + 1);
}
 
protected void recalc()
{
if(rowsPerPage > 0)
totalPages = (size + rowsPerPage - 1) / rowsPerPage;
}
 
public void init(int size, int currentPage, int rowsPerPage)
{
this.size = size;
this.currentPage = currentPage;
this.rowsPerPage = rowsPerPage;
recalc();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ResourceAddedListener.java
0,0 → 1,6
package ak.hostadmiral.util;
 
public interface ResourceAddedListener
{
public void resourceAdded(String resourceName);
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ResourceManager.java
0,0 → 1,44
package ak.hostadmiral.util;
 
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
 
public class ResourceManager
{
private Collection resources = new ArrayList(); // Collection(String)
private Collection addedListeners = new ArrayList(); // Collection(ResourceAddedListener)
 
public void addAddedListener(ResourceAddedListener listener)
{
addedListeners.add(listener);
}
 
public void removeAddedListener(ResourceAddedListener listener)
{
addedListeners.remove(listener);
}
 
public Collection getResources()
{
return Collections.unmodifiableCollection(resources);
}
 
public void addResource(String resourceName)
{
resources.add(resourceName);
 
for(Iterator i = addedListeners.iterator(); i.hasNext(); ) {
ResourceAddedListener listener = (ResourceAddedListener)i.next();
listener.resourceAdded(resourceName);
}
}
 
private static ResourceManager resourceManager = new ResourceManager();
 
public static ResourceManager getInstance()
{
return resourceManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ModelUserException.java
0,0 → 1,28
package ak.hostadmiral.util;
 
public class ModelUserException
extends ModelException
{
private Object[] values;
 
public ModelUserException()
{
this(null, null);
}
 
public ModelUserException(String message)
{
this(message, null);
}
 
public ModelUserException(String message, Object[] values)
{
super(message);
this.values = values;
}
 
public Object[] getValues()
{
return values;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ProjectVersion.java
0,0 → 1,180
package ak.hostadmiral.util;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
 
/**
* Project version holder. Understands version from resource ak/hostadmiral/version
* in format ${Major}.${Minor}-rc${ReleaseCanditat}.${Build}${Additional},
* where ${ReleaseCanditat}, ${Build} and ${Additional} are optional.
* ${Additional} - the rest.
* Instead of "-rc${ReleaseCanditat}" "-p${Patch}" may exist.
* E.g. 1.2-rc4.1234, 2.0, 2.1.4567M, 3.3-p1.
*/
public class ProjectVersion
{
private static boolean initialized = false;
private static String version = null;
private static int major = -1;
private static int minor = -1;
private static int rcandidat = -1;
private static int patch = -1;
private static int build = -1;
private static String additional = null;
 
private static void init()
{
synchronized(ProjectVersion.class) {
// in this method not exceptions are expected,
// so throw an runtime exception if any problems
 
if(initialized) return;
 
try {
// get class loader
ClassLoader cl = ProjectVersion.class.getClassLoader();
if(cl == null) cl = ClassLoader.getSystemClassLoader();
if(cl == null)
throw new RuntimeException("Cannot get class loader, something is really wrong");
 
// load
InputStream in = cl.getResourceAsStream("ak/hostadmiral/version");
if(in == null)
throw new RuntimeException("Cannot get project version, resource not found");
 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
version = reader.readLine();
 
if(version == null || version.equals(""))
throw new RuntimeException("Cannot get project version, it's empty");
 
// parse
parse(version);
}
catch(IOException ex) {
throw new RuntimeException("Cannot get project version: " + ex.getMessage());
}
 
initialized = true;
}
}
 
private static void parse(String v)
{
Pattern pattern = Pattern.compile(
"^(\\d+)\\.(\\d+)((-rc(\\d+))|(-p(\\d+)))?(\\.(\\d+))?(.*)$");
Matcher matcher = pattern.matcher(v);
if(!matcher.matches())
throw new RuntimeException(
"Cannot get project version, it doesn't match pattern: [" + v + "]");
 
major = Integer.parseInt(matcher.group(1));
minor = Integer.parseInt(matcher.group(2));
 
if(matcher.group(4) == null)
rcandidat = -1;
else
rcandidat = Integer.parseInt(matcher.group(5));
 
if(matcher.group(6) == null)
patch = -1;
else
patch = Integer.parseInt(matcher.group(7));
 
if(matcher.group(8) == null)
build = -1;
else
build = Integer.parseInt(matcher.group(9));
 
additional = matcher.group(10);
}
 
public static String getVersion()
{
init();
return version;
}
 
public static int getMajor()
{
init();
return major;
}
 
public static int getMinor()
{
init();
return minor;
}
 
public static int getRCandidat()
{
init();
return rcandidat;
}
 
public static int getPatch()
{
init();
return patch;
}
 
public static int getBuild()
{
init();
return build;
}
 
public static String getAdditional()
{
init();
return additional;
}
 
public static boolean sufficient(int major_)
{
return (major >= major_);
}
 
public static boolean sufficient(int major_, int minor_)
{
return (major > major_) || (major == major_) && (minor >= minor_);
}
 
public static boolean sufficient(int major_, int minor_, int patch_)
{
return (major > major_) || (major == major_) && (minor > minor_)
|| (major == major_) && (minor == minor_) && (patch >= patch_);
}
 
private static String formString()
{
return ("" + major + "." + minor
+ (rcandidat >= 0 ? "-rc" + rcandidat : "")
+ (patch >= 0 ? "-p" + patch : "")
+ (build >= 0 ? "." + build : "") + additional);
}
 
private static void testParse(String v)
{
parse(v);
System.out.println("test: [" + v + "] [" + formString() + "]");
}
 
/**
* internal tests
*/
public static void main(String[] args)
throws Exception
{
System.out.println("Current version is: [" + getVersion() + "] [" + formString() + "]");
testParse("1.2-rc4.1234");
testParse("2.0");
testParse("2.1.4567M");
testParse("3.3-p1");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ModelStoreException.java
0,0 → 1,25
package ak.hostadmiral.util;
 
public class ModelStoreException
extends ModelException
{
public ModelStoreException()
{
this(null, null);
}
 
public ModelStoreException(String message)
{
this(message, null);
}
 
public ModelStoreException(Exception chainedException)
{
this(null, chainedException);
}
 
public ModelStoreException(String message, Exception chainedException)
{
super(message, chainedException);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/DigestMd5.java
0,0 → 1,29
package ak.hostadmiral.util;
 
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class DigestMd5
{
/**
* digest to encode passwords
*/
protected static MessageDigest digest = null;
 
public static String encode(String password)
{
return BinUtils.bytesToHex(digest.digest(password.getBytes()));
}
 
/**
* digest initialization
*/
static {
try {
digest = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/BinUtils.java
0,0 → 1,26
package ak.hostadmiral.util;
 
public class BinUtils
{
private static final char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
 
/**
* converts password bytes to hex string
*/
public static String bytesToHex(byte[] bytes)
{
char[] buffer = new char[bytes.length * 2];
 
for (int i = 0; i < bytes.length; i++) {
int low = (int)( bytes[i] & 0x0f);
int high = (int)((bytes[i] & 0xf0) >> 4);
 
buffer[i * 2] = hexDigits[high];
buffer[i * 2 + 1] = hexDigits[low];
}
 
return new String(buffer);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ModelSecurityException.java
0,0 → 1,10
package ak.hostadmiral.util;
 
public class ModelSecurityException
extends ModelException
{
public ModelSecurityException()
{
super("ak.hostadmiral.core.access.denied");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/UserException.java
0,0 → 1,28
package ak.hostadmiral.util;
 
public class UserException
extends Exception
{
private Object[] values;
 
public UserException()
{
this(null, null);
}
 
public UserException(String message)
{
this(message, null);
}
 
public UserException(String message, Object[] values)
{
super(message);
this.values = values;
}
 
public Object[] getValues()
{
return values;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/StringConverter.java
0,0 → 1,52
package ak.hostadmiral.util;
 
public abstract class StringConverter
{
public static boolean isEmpty(Object o)
{
if(o == null)
return true;
else if((o instanceof String) && ((String)o).equals(""))
return true;
else
return false;
}
 
public static Long parseLong(Object o)
throws NumberFormatException
{
if(o instanceof String) {
String s = (String)o;
if(s == null || s.equals(""))
return null;
else
return new Long(s);
}
else {
throw new ClassCastException("String is expected, but it is " + o.getClass());
}
}
 
public static Integer parseInteger(Object o)
throws NumberFormatException
{
if(o instanceof String) {
String s = (String)o;
if(s == null || s.equals(""))
return null;
else
return new Integer(s);
}
else {
throw new ClassCastException("String is expected, but it is " + o.getClass());
}
}
 
public static String toString(Object o)
{
if(o == null)
return null;
else
return o.toString();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/ModelException.java
0,0 → 1,44
package ak.hostadmiral.util;
 
public class ModelException
extends Exception
{
private Exception chainedException;
 
public ModelException()
{
this(null, null);
}
 
public ModelException(String message)
{
this(message, null);
}
 
public ModelException(Exception chainedException)
{
this(null, chainedException);
}
 
public ModelException(String message, Exception chainedException)
{
super(message);
this.chainedException = chainedException;
}
 
public Exception getChainedException()
{
return chainedException;
}
 
public void setChainedException(Exception chainedException)
{
this.chainedException = chainedException;
}
 
public String toString()
{
return super.toString()
+ (chainedException == null ? "" : "\n" + chainedException.toString());
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/util/FormException.java
0,0 → 1,39
package ak.hostadmiral.util;
 
public class FormException
extends UserException
{
private String property;
 
public FormException()
{
this(null, null, null);
}
 
public FormException(String message)
{
this(message, null, null);
}
 
public FormException(String message, String property)
{
this(message, property, null);
}
 
public FormException(String message, String property, Object[] values)
{
super(message, values);
this.property = property;
}
 
public String getProperty()
{
return property;
}
 
public String toString()
{
return super.toString()
+ (property == null ? "" : " for " + property);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/Mailbox.java
0,0 → 1,321
package ak.hostadmiral.core.model;
 
import java.util.Iterator;
import java.util.Collection;
import java.util.HashSet;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="mailboxes"
*/
public class Mailbox
extends GeneralModelObject
{
private String login;
private Collection passwords; // Collection(PasswordStore)
private InetDomain domain;
private User owner;
private Boolean virusCheck;
private Boolean spamCheck;
private SystemUser systemUser;
private Mailbox origin; // save original object state before any changes
 
protected Mailbox()
{
}
 
protected Mailbox(Mailbox origin)
{
super(origin);
this.login = origin.login;
 
if(origin.passwords == null)
this.passwords = null;
else
this.passwords = new HashSet(origin.passwords);
 
this.domain = origin.domain;
this.owner = origin.owner;
this.virusCheck = origin.virusCheck;
this.spamCheck = origin.spamCheck;
this.systemUser = origin.systemUser;
}
 
protected Mailbox getOrigin()
{
return origin;
}
 
protected void backupMe()
{
if(origin == null)
origin = new Mailbox(this);
}
 
protected void resetOrigin()
{
origin = null;
}
 
/**
*
* @hibernate.property
*/
public String getLogin()
{
return login;
}
 
protected void setLogin(String login)
{
this.login = login;
}
 
public void setLogin(User editor, String login)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.login = login;
}
 
protected void addPasswordStore(PasswordStore ps)
{
if(passwords == null) passwords = new HashSet();
passwords.add(ps);
}
 
public String getPassword(User editor, String digest)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
for(Iterator i = passwords.iterator(); i.hasNext(); ) {
Object o = i.next();
if(!(o instanceof PasswordStore))
throw new ModelException("It's not a password store");
 
PasswordStore ps = (PasswordStore)o;
if(ps.getDigest().equals(digest)) {
return ps.getPassword();
}
}
 
throw new ModelException("Digest " + digest + " not found");
}
 
public void setPassword(User editor, String password)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
if(password == null)
throw new NullPointerException("Null password");
 
backupMe();
 
for(Iterator i = passwords.iterator(); i.hasNext(); ) {
Object o = i.next();
if(!(o instanceof PasswordStore))
throw new ModelException("It's not a password store");
((PasswordStore)o).setNewPassword(password);
}
}
 
/**
*
* @hibernate.set cascade="all"
* @hibernate.collection-key column="obj"
* @hibernate.collection-one-to-many class="ak.hostadmiral.core.model.PasswordStoreAbstract"
*/
protected Collection getPasswords()
{
return passwords;
}
 
protected void setPasswords(Collection passwords)
{
this.passwords = passwords;
}
 
/**
*
* @hibernate.many-to-one
*/
public InetDomain getDomain()
{
return domain;
}
 
protected void setDomain(InetDomain domain)
{
this.domain = domain;
}
 
public void setDomain(User editor, InetDomain domain)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.domain = domain;
}
 
/**
*
* @hibernate.many-to-one
*/
public User getOwner()
{
return owner;
}
 
protected void setOwner(User owner)
{
this.owner = owner;
}
 
public void setOwner(User editor, User owner)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.owner = owner;
}
 
/**
*
* @hibernate.property
*/
public Boolean getVirusCheck()
{
return virusCheck;
}
 
protected void setVirusCheck(Boolean virusCheck)
{
this.virusCheck = virusCheck;
}
 
public void setVirusCheck(User editor, Boolean virusCheck)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.virusCheck = virusCheck;
}
 
/**
*
* @hibernate.property
*/
public Boolean getSpamCheck()
{
return spamCheck;
}
 
protected void setSpamCheck(Boolean spamCheck)
{
this.spamCheck = spamCheck;
}
 
public void setSpamCheck(User editor, Boolean spamCheck)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.spamCheck = spamCheck;
}
 
/**
*
* @hibernate.many-to-one
*/
public SystemUser getSystemUser()
{
return systemUser;
}
 
protected void setSystemUser(SystemUser systemUser)
{
this.systemUser = systemUser;
}
 
public void setSystemUser(User editor, SystemUser systemUser)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.systemUser = systemUser;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_MAILBOX;
}
 
public String getIdentKey()
{
return ak.hostadmiral.core.resources.CoreResources.IDENT_MAILBOX;
}
 
public Object[] getIdentParams()
{
return new Object[] { getLogin(), getDomain().getName() };
}
 
public boolean viewableBy(User user)
{
return user.isSuperuser() || user.equals(domain.getOwner()) || user.equals(owner);
}
 
public boolean editableBy(User user)
{
return user.isSuperuser()
|| (domain == null) // just created
|| user.equals(domain.getOwner());
}
 
public boolean deleteableBy(User user)
{
return user.isSuperuser() || user.equals(domain.getOwner());
}
 
protected static boolean allowedToCreate(MailboxManager manager, User editor)
throws ModelException
{
return editor.isSuperuser()
|| InetDomainManager.getInstance().areInetDomainsAvailable(editor);
}
 
protected static Mailbox createLimitedCopy(Mailbox origin)
{
Mailbox m = new Mailbox();
m.setLogin(origin.getLogin());
m.setDomain(origin.getDomain());
m.setOwner(origin.getOwner());
return m;
}
 
public String toString()
{
return "Mailbox id=[" + getId() + "] login=[" + login + "@"
+ (domain == null ? "_none_" : domain.getName()) + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAlias.java
0,0 → 1,210
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="mailaliases"
*/
public class MailAlias
extends GeneralModelObject
{
private String address;
private InetDomain domain;
private User owner;
private Collection destinations; // Collection(MailAliasDestintion)
private MailAlias origin; // save original object state before any changes
 
protected MailAlias()
{
}
 
protected MailAlias(MailAlias origin)
{
super(origin);
this.address = origin.address;
this.domain = origin.domain;
this.owner = origin.owner;
this.destinations = origin.destinations; // FIXME: or make a copy?
}
 
protected MailAlias getOrigin()
{
return origin;
}
 
protected void backupMe()
{
if(origin == null)
origin = new MailAlias(this);
}
 
protected void resetOrigin()
{
origin = null;
}
 
/**
*
* @hibernate.property
*/
public String getAddress()
{
return address;
}
 
protected void setAddress(String address)
{
this.address = address;
}
 
public void setAddress(User editor, String address)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.address = address;
}
 
/**
*
* @hibernate.many-to-one
*/
public InetDomain getDomain()
{
return domain;
}
 
protected void setDomain(InetDomain domain)
{
this.domain = domain;
}
 
public void setDomain(User editor, InetDomain domain)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.domain = domain;
}
 
/**
*
* @hibernate.many-to-one
*/
public User getOwner()
{
return owner;
}
 
protected void setOwner(User owner)
{
this.owner = owner;
}
 
public void setOwner(User editor, User owner)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.owner = owner;
}
 
/**
* @return Collection(MailAliasDestination)
*
* @hibernate.bag inverse="true" cascade="all-delete-orphan"
* @hibernate.collection-key column="alias"
* @hibernate.collection-one-to-many class="ak.hostadmiral.core.model.MailAliasDestination"
*/
protected Collection getDestinations()
{
return destinations;
}
 
/**
* @return Collection(MailAliasDestination)
*/
public Collection getDestinations(User editor)
throws ModelException
{
if(mayChangeDestinations(editor))
return destinations;
else if(viewableBy(editor))
return java.util.Collections.unmodifiableCollection(destinations);
else
throw new ModelSecurityException();
}
 
/**
* @param destinations Collection(MailAliasDestination)
*/
protected void setDestinations(Collection destinations)
{
this.destinations = destinations;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_MAIL_ALIAS;
}
 
public String getIdentKey()
{
return ak.hostadmiral.core.resources.CoreResources.IDENT_MAIL_ALIAS;
}
 
public Object[] getIdentParams()
{
return new Object[] { getAddress(), getDomain().getName() };
}
 
public boolean viewableBy(User user)
{
return user.isSuperuser() || user.equals(domain.getOwner()) || user.equals(owner);
}
 
public boolean editableBy(User user)
{
return user.isSuperuser()
|| (domain == null) // just created
|| user.equals(domain.getOwner());
}
 
public boolean mayChangeDestinations(User user)
{
return user.isSuperuser() || user.equals(domain.getOwner()) || user.equals(owner);
}
 
public boolean deleteableBy(User user)
{
return user.isSuperuser() || user.equals(domain.getOwner());
}
 
protected static boolean allowedToCreate(MailAliasManager manager, User editor)
throws ModelException
{
return editor.isSuperuser()
|| InetDomainManager.getInstance().areInetDomainsAvailable(editor);
}
 
protected static MailAlias createLimitedCopy(MailAlias origin)
{
MailAlias m = new MailAlias();
m.setAddress(origin.getAddress());
m.setDomain(origin.getDomain());
m.setOwner(origin.getOwner());
return m;
}
 
public String toString()
{
return "MailAlias id=[" + getId() + "] address=[" + address + "@"
+ (domain == null ? "_none_" : domain.getName()) + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/User.java
0,0 → 1,401
package ak.hostadmiral.core.model;
 
import java.util.Iterator;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.StringTokenizer;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="users"
*/
public class User
extends GeneralModelObject
{
public static final String DEFAULT_PASSWORD_STORE = "MD5";
 
private String login;
private Collection passwords; // Collection(PasswordStore)
private User boss;
private Boolean superuser;
private Locale locale = Locale.getDefault();
private Collection loginHistory;
private User origin; // save original object state before any changes
 
protected User()
{
}
 
protected User(User origin)
{
super(origin);
this.login = origin.login;
 
if(origin.passwords == null)
this.passwords = null;
else
this.passwords = new HashSet(origin.passwords);
 
this.boss = origin.boss;
this.superuser = origin.superuser;
this.locale = origin.locale;
 
if(origin.loginHistory == null)
this.loginHistory = null;
else
this.loginHistory = new HashSet(origin.loginHistory);
}
 
protected User getOrigin()
{
return origin;
}
 
protected void backupMe()
{
if(origin == null)
origin = new User(this);
}
 
protected void resetOrigin()
{
origin = null;
}
 
/**
*
* @hibernate.property
*/
public String getLogin()
{
return login;
}
 
protected void setLogin(String login)
{
this.login = login;
}
 
public void setLogin(User editor, String login)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.login = login;
}
 
protected void addPasswordStore(PasswordStore ps)
{
if(passwords == null) passwords = new HashSet();
passwords.add(ps);
}
 
protected PasswordStore getDefaultPasswordStore()
throws ModelException
{
if(passwords == null)
throw new ModelException("No password store");
 
for(Iterator i = passwords.iterator(); i.hasNext(); ) {
Object o = i.next();
if(!(o instanceof PasswordStore))
throw new ModelException("It's not a password store");
PasswordStore ps = (PasswordStore)o;
if(DEFAULT_PASSWORD_STORE.equals(ps.getDigest()))
return ps;
}
 
throw new ModelException("No password store for digest " + DEFAULT_PASSWORD_STORE);
}
 
public String getPassword(User editor)
throws ModelException
{
if(!partEditableBy(editor))
throw new ModelSecurityException();
 
return getDefaultPasswordStore().getPassword();
}
 
public String getPassword(User editor, String digest)
throws ModelException
{
if(!partEditableBy(editor))
throw new ModelSecurityException();
 
for(Iterator i = passwords.iterator(); i.hasNext(); ) {
Object o = i.next();
if(!(o instanceof PasswordStore))
throw new ModelException("It's not a password store");
 
PasswordStore ps = (PasswordStore)o;
if(ps.getDigest().equals(digest)) {
return ps.getPassword();
}
}
 
throw new ModelException("Digest " + digest + " not found");
}
 
public void setPassword(User editor, String password)
throws ModelException
{
if(!partEditableBy(editor))
throw new ModelSecurityException();
 
if(password == null)
throw new NullPointerException("Null password");
 
backupMe();
 
for(Iterator i = passwords.iterator(); i.hasNext(); ) {
Object o = i.next();
if(!(o instanceof PasswordStore))
throw new ModelException("It's not a password store");
((PasswordStore)o).setNewPassword(password);
}
}
 
public boolean checkPassword(String password)
throws ModelException
{
if(password == null)
throw new NullPointerException("Null password");
 
return getDefaultPasswordStore().checkPassword(password);
}
 
/**
*
* @hibernate.set cascade="all"
* @hibernate.collection-key column="obj"
* @hibernate.collection-one-to-many class="ak.hostadmiral.core.model.PasswordStoreAbstract"
*/
protected Collection getPasswords()
{
return passwords;
}
 
protected void setPasswords(Collection passwords)
{
this.passwords = passwords;
}
 
/**
*
* @hibernate.many-to-one
*/
public User getBoss()
{
return boss;
}
 
protected void setBoss(User boss)
{
this.boss = boss;
}
 
public void setBoss(User editor, User boss)
throws ModelException
{
if(!mayChangeBoss(editor))
throw new ModelSecurityException();
 
backupMe();
this.boss = boss;
}
 
/**
*
* @hibernate.property
*/
public Boolean getSuperuser()
{
return superuser;
}
 
public boolean isSuperuser()
{
return (superuser != null) && superuser.booleanValue();
}
 
protected void setSuperuser(Boolean superuser)
{
this.superuser = superuser;
}
 
public void setSuperuser(User editor, Boolean superuser)
throws ModelException
{
if(!mayChangeSuperuser(editor))
throw new ModelSecurityException();
 
backupMe();
this.superuser = superuser;
}
 
/**
*
* @hibernate.property column="locale"
*/
protected String getLocaleName()
{
return locale.toString();
}
 
protected void setLocaleName(String localeName)
{
String language = null;
String country = null;
 
if(localeName != null) {
StringTokenizer t = new StringTokenizer(localeName, "_");
if(t.hasMoreTokens()) language = t.nextToken();
if(t.hasMoreTokens()) country = t.nextToken();
}
 
if(language == null)
this.locale = Locale.getDefault();
else if(country == null)
this.locale = new Locale(language);
else
this.locale = new Locale(language, country);
}
 
public void setLocaleName(User editor, String localeName)
throws ModelException
{
if(!partEditableBy(editor))
throw new ModelSecurityException();
 
backupMe();
setLocaleName(localeName);
}
 
public Locale getLocale()
{
return locale;
}
 
public void setLocale(Locale locale)
{
this.locale = locale;
}
 
public void setLocale(User editor, Locale locale)
throws ModelException
{
if(!partEditableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.locale = locale;
}
 
/**
*
* @hibernate.set
* @hibernate.collection-key column="usr"
* @hibernate.collection-one-to-many class="ak.hostadmiral.core.model.UserLogin"
*/
protected Collection getLoginHistory()
{
return loginHistory;
}
 
public Collection getLogins()
{
return Collections.unmodifiableCollection(loginHistory);
}
 
protected void setLoginHistory(Collection loginHistory)
{
this.loginHistory = loginHistory;
}
 
protected void update(User origin)
{
this.login = origin.login;
this.boss = origin.boss;
this.superuser = origin.superuser;
this.locale = origin.locale;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_USER;
}
 
public String getIdentKey()
{
return ak.hostadmiral.core.resources.CoreResources.IDENT_USER;
}
 
public Object[] getIdentParams()
{
return new Object[] { getLogin() };
}
 
public boolean viewableBy(User user)
{
return user.isSuperuser() || user.equals(boss) || user.equals(this);
}
 
public boolean editableBy(User user)
{
return user.isSuperuser() || user.equals(boss);
}
 
public boolean deleteableBy(User user)
{
return !user.equals(this) && (user.isSuperuser() || user.equals(boss));
}
 
// editor is allowed to change some additional properties
public boolean partEditableBy(User user)
{
return user.isSuperuser() || user.equals(boss) || user.equals(this);
}
 
public boolean mayChangeBoss(User user)
{
return user.isSuperuser();
}
 
public boolean mayChangeSuperuser(User user)
{
return user.isSuperuser() && !user.equals(this);
}
 
public boolean mayViewAllLogins()
{
return isSuperuser();
}
 
protected static boolean allowedToCreate(UserManager manager, User editor)
throws ModelException
{
return editor.isSuperuser()
|| InetDomainManager.getInstance().areInetDomainsAvailable(editor);
// FIXME: or allow any user to create "subusers"?
}
 
protected static User createLimitedCopy(User origin)
{
User u = new User();
u.setLogin(origin.getLogin());
return u;
}
 
public String toString()
{
return "User id=[" + getId() + "] login=[" + login + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxManager.java
0,0 → 1,445
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Comparator;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.MailboxStore;
 
public class MailboxManager
implements
ConfigInit,
UserBeforeDeleteListener,
UserDeletingListener,
SystemUserBeforeDeleteListener,
SystemUserDeletingListener,
InetDomainBeforeDeleteListener,
InetDomainDeletingListener
{
private MailboxStore store;
private Class[] passwordStores;
 
private Collection validateListeners = new ArrayList();
private Collection createdListeners = new ArrayList();
private Collection modifiedListeners = new ArrayList();
private Collection beforeDeleteListeners = new ArrayList();
private Collection deletingListeners = new ArrayList();
private Collection deletedListeners = new ArrayList();
 
public MailboxManager()
throws ModelException
{
UserManager.getInstance().addBeforeDeleteListener(this);
UserManager.getInstance().addDeletingListener(this);
SystemUserManager.getInstance().addBeforeDeleteListener(this);
SystemUserManager.getInstance().addDeletingListener(this);
InetDomainManager.getInstance().addBeforeDeleteListener(this);
InetDomainManager.getInstance().addDeletingListener(this);
}
 
public Mailbox create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
Mailbox mailbox = new Mailbox();
setMailboxPasswordStores(mailbox);
 
return mailbox;
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return Mailbox.allowedToCreate(this, editor);
}
 
public Mailbox get(User editor, Long id)
throws ModelException
{
Mailbox mailbox = store.get(id);
 
if(!mailbox.viewableBy(editor))
throw new ModelSecurityException();
 
return mailbox;
}
 
public boolean loginExists(User editor, Mailbox mailbox, String login)
throws ModelException
{
if(mailbox.getDomain() == null)
throw new ModelException("Cannot check unique login for mailbox without domain");
 
return store.loginExists(mailbox, login);
}
 
public Mailbox findForLogin(User editor, String login)
throws ModelException
{
Mailbox mailbox = store.findForLogin(login);
 
if(!mailbox.viewableBy(editor))
throw new ModelSecurityException();
 
return mailbox;
}
 
public void save(User editor, Mailbox mailbox)
throws ModelException
{
// security check
if(!mailbox.editableBy(editor))
throw new ModelSecurityException();
 
//mailbox.setModUser(editor); // FIXME
 
boolean isNew = mailbox.isNew();
Mailbox oldMailbox = mailbox.getOrigin();
if(oldMailbox == null) oldMailbox = mailbox;
 
// validate
for(Iterator i = validateListeners.iterator(); i.hasNext(); ) {
MailboxValidateListener listener = (MailboxValidateListener)i.next();
listener.mailboxValidate(editor, mailbox, oldMailbox);
}
 
store.save(mailbox);
 
// inform listeners
if(isNew) {
for(Iterator i = createdListeners.iterator(); i.hasNext(); ) {
MailboxCreatedListener listener = (MailboxCreatedListener)i.next();
listener.mailboxCreated(editor, mailbox);
}
}
else {
for(Iterator i = modifiedListeners.iterator(); i.hasNext(); ) {
MailboxModifiedListener listener = (MailboxModifiedListener)i.next();
listener.mailboxModified(editor, mailbox, oldMailbox);
}
}
 
// reset backup
mailbox.resetOrigin();
}
 
public void addValidateListener(MailboxValidateListener listener)
{
validateListeners.add(listener);
}
 
public void removeValidateListener(MailboxValidateListener listener)
{
validateListeners.remove(listener);
}
 
public void addCreatedListener(MailboxCreatedListener listener)
{
createdListeners.add(listener);
}
 
public void removeCreatedListener(MailboxCreatedListener listener)
{
createdListeners.remove(listener);
}
 
public void addModifiedListener(MailboxModifiedListener listener)
{
modifiedListeners.add(listener);
}
 
public void removeModifiedListener(MailboxModifiedListener listener)
{
modifiedListeners.remove(listener);
}
 
public void addBeforeDeleteListener(MailboxBeforeDeleteListener listener)
{
beforeDeleteListeners.add(listener);
}
 
public void removeBeforeDeleteListener(MailboxBeforeDeleteListener listener)
{
beforeDeleteListeners.remove(listener);
}
 
public void addDeletingListener(MailboxDeletingListener listener)
{
deletingListeners.add(listener);
}
 
public void removeDeletingListener(MailboxDeletingListener listener)
{
deletingListeners.remove(listener);
}
 
public void addDeletedListener(MailboxDeletedListener listener)
{
deletedListeners.add(listener);
}
 
public void removeDeletedListener(MailboxDeletedListener listener)
{
deletedListeners.remove(listener);
}
 
public Collection beforeDelete(User editor, Mailbox mailbox, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
 
for(Iterator i = beforeDeleteListeners.iterator(); i.hasNext(); ) {
MailboxBeforeDeleteListener listener = (MailboxBeforeDeleteListener)i.next();
Collection subcascade = listener.mailboxBeforeDelete(editor, mailbox, known);
if(subcascade != null)
cascade.addAll(subcascade);
}
 
return cascade;
}
 
public void delete(User editor, Mailbox mailbox)
throws ModelException
{
// check rights
if(!mailbox.deleteableBy(editor))
throw new ModelSecurityException();
 
// inform deleting listeners
for(Iterator i = deletingListeners.iterator(); i.hasNext(); ) {
MailboxDeletingListener listener = (MailboxDeletingListener)i.next();
listener.mailboxDeleting(editor, mailbox);
}
 
// backup copy
Mailbox oldMailbox = new Mailbox(mailbox);
 
// delete it
store.delete(mailbox);
 
// inform deleted listeners
for(Iterator i = deletedListeners.iterator(); i.hasNext(); ) {
MailboxDeletedListener listener = (MailboxDeletedListener)i.next();
listener.mailboxDeleted(editor, oldMailbox);
}
}
 
public Collection listMailboxes(User editor)
throws ModelException
{
return listMailboxes(null, 0, 0, null, editor);
}
 
public Collection listMailboxes(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor)
throws ModelException
{
if(editor.isSuperuser())
return store.listAllMailboxes(info, rowsPerPage, pageNumber, sortingKeys);
else
return store.listMailboxes(info, rowsPerPage, pageNumber, sortingKeys, editor);
}
 
public boolean areMailboxesAvailable(User editor)
throws ModelException
{
if(editor.isSuperuser() || InetDomainManager.getInstance().areInetDomainsAvailable(editor))
return true;
else
return store.countMailboxesAvailable(editor) > 0;
}
 
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection mailboxes = store.listOwnMailboxes(user);
 
return iterateBeforeDelete(editor, mailboxes, known, CascadeDeleteElement.DELETE);
}
 
public void userDeleting(User editor, User user)
throws ModelException
{
Collection mailboxes = store.listOwnMailboxes(user);
 
for(Iterator i = mailboxes.iterator(); i.hasNext(); ) {
delete(editor, (Mailbox)i.next());
}
}
 
public Collection inetDomainBeforeDelete(User editor, InetDomain domain, Collection known)
throws ModelException
{
Collection mailboxes = store.listMailboxesForDomain(domain);
 
return iterateBeforeDelete(editor, mailboxes, known, CascadeDeleteElement.DELETE);
}
 
public void inetDomainDeleting(User editor, InetDomain domain)
throws ModelException
{
Collection mailboxes = store.listMailboxesForDomain(domain);
 
for(Iterator i = mailboxes.iterator(); i.hasNext(); ) {
delete(editor, (Mailbox)i.next());
}
}
 
public Collection systemUserBeforeDelete(User editor, SystemUser user, Collection known)
throws ModelException
{
Collection mailboxes = store.listMailboxesForSystemUser(user);
 
return iterateBeforeDelete(editor, mailboxes, known, CascadeDeleteElement.CHANGE);
}
 
public void systemUserDeleting(User editor, SystemUser user)
throws ModelException
{
Collection mailboxes = store.listMailboxesForSystemUser(user);
 
for(Iterator i = mailboxes.iterator(); i.hasNext(); ) {
Mailbox mailbox = (Mailbox)i.next();
mailbox.setSystemUser(null);
save(editor, mailbox);
}
}
 
private Collection iterateBeforeDelete(User editor, Collection mailboxes, Collection known, int action)
throws ModelException
{
Collection cascade = new ArrayList();
for(Iterator i = mailboxes.iterator(); i.hasNext(); ) {
Mailbox mailbox = (Mailbox)i.next();
if(known.contains(mailbox)) continue;
 
known.add(mailbox);
if(mailbox.viewableBy(editor)) {
if(action == CascadeDeleteElement.CHANGE && mailbox.editableBy(editor))
cascade.add(new CascadeDeleteElement(mailbox, CascadeDeleteElement.CHANGE, null));
else if(action == CascadeDeleteElement.DELETE && mailbox.deleteableBy(editor))
cascade.add(new CascadeDeleteElement(mailbox, CascadeDeleteElement.DELETE,
this.beforeDelete(editor, mailbox, known)));
else
cascade.add(new CascadeDeleteElement(mailbox, CascadeDeleteElement.FORBIDDEN,
null));
}
else {
cascade.add(new CascadeDeleteElement(Mailbox.createLimitedCopy(mailbox),
CascadeDeleteElement.FORBIDDEN, null));
}
}
 
return cascade;
}
 
protected void setMailboxPasswordStores(Mailbox mailbox)
throws ModelException
{
if(passwordStores == null) return;
 
try {
for(int i = 0; i < passwordStores.length; i++)
mailbox.addPasswordStore((PasswordStore)passwordStores[i].newInstance());
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
public static final Integer SORT_LOGIN = new Integer(1);
public static final Integer SORT_DOMAIN = new Integer(2);
 
public static final Comparator LOGIN_COMPARATOR = new LoginComparator();
public static final Comparator DOMAIN_COMPARATOR = new DomainComparator();
 
private static class LoginComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof Mailbox) || !(o2 instanceof Mailbox))
throw new ClassCastException("not a Mailbox");
 
Mailbox a1 = (Mailbox)o1;
Mailbox a2 = (Mailbox)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getLogin().compareToIgnoreCase(a2.getLogin());
}
 
public boolean equals(Object obj)
{
return (obj instanceof LoginComparator);
}
}
 
private static class DomainComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof Mailbox) || !(o2 instanceof Mailbox))
throw new ClassCastException("not a Mailbox");
 
Mailbox a1 = (Mailbox)o1;
Mailbox a2 = (Mailbox)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getDomain().getName().compareToIgnoreCase(a2.getDomain().getName());
}
 
public boolean equals(Object obj)
{
return (obj instanceof DomainComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
mailboxManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (MailboxStore)c.newInstance();
 
String[] passwordStoreNames = (String[])params.get("passwordStore");
if(passwordStoreNames != null) {
passwordStores = new Class[passwordStoreNames.length];
for(int i = 0; i < passwordStoreNames.length; i++) {
passwordStores[i] = Class.forName(passwordStoreNames[i]);
}
}
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static MailboxManager mailboxManager = null;
 
public static MailboxManager getInstance()
{
return mailboxManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/MailAliasDestinationHibernate.java
0,0 → 1,97
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.MailAlias;
import ak.hostadmiral.core.model.MailAliasDestination;
import ak.hostadmiral.core.model.MailAliasDestinationManager;
import ak.hostadmiral.core.model.store.MailAliasDestinationStore;
 
public class MailAliasDestinationHibernate
implements MailAliasDestinationStore
{
public MailAliasDestinationHibernate()
throws ModelStoreException
{
register();
}
 
public MailAliasDestination get(Long id)
throws ModelStoreException
{
try {
return (MailAliasDestination)HibernateUtil.currentSession()
.load(MailAliasDestination.class, id);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void save(MailAliasDestination mailAliasDestination)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(mailAliasDestination);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void delete(MailAliasDestination mailAliasDestination)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(mailAliasDestination);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailAliasesDestination(MailAlias alias)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select d from MailAliasDestination d left join fetch d.mailbox where d.alias=?",
alias, Hibernate.entity(MailAlias.class));
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(MailAliasDestinationHibernate.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/MailAliasDestination.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/UserHibernate.java
0,0 → 1,245
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserLogin;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.store.UserStore;
 
public class UserHibernate
implements UserStore
{
public UserHibernate()
throws ModelStoreException
{
initSortKeys();
register();
}
 
public User get(Long id)
throws ModelStoreException
{
try {
return (User)HibernateUtil.currentSession().load(User.class, id);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public boolean loginExists(User user, String login)
throws ModelStoreException
{
try {
if(user.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from User u where login = ?",
login, Hibernate.STRING)
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from User u where login = ? and u != ?",
new Object[] { login, user },
new Type[] { Hibernate.STRING, Hibernate.entity(User.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public User findForLogin(String login)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select u from User u left join fetch u.boss where u.login = ? and u.enabled = ?",
new Object[] { login, Boolean.TRUE },
new Type[] { Hibernate.STRING, Hibernate.BOOLEAN } );
 
if(list.size() == 0)
return null;
else
return (User)list.get(0);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public void save(User user)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(user);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public void delete(User user)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(user);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public Collection listAllUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from User").next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select u from User u left join fetch u.boss"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys), null, null);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public Collection listUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from User u where u = ? or u.boss = ?",
new Object[] { user, user},
new Type[] { Hibernate.entity(User.class), Hibernate.entity(User.class) }
).next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select u from User u left join fetch u.boss where u = ? or u.boss = ?"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys),
new Object[] { user, user},
new Type[] { Hibernate.entity(User.class), Hibernate.entity(User.class) } );
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public void saveUserLogin(UserLogin userLogin)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(userLogin);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public Collection listFailedLogins()
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select l from UserLogin l left join fetch l.user where l.success = ?",
Boolean.FALSE, Hibernate.BOOLEAN);
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public Collection listSubusers(User user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select u from User u where u.boss = ?",
user, Hibernate.entity(User.class) );
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
public Collection listUserLogins(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from UserLogin where usr = ?",
new Object[] { user },
new Type[] { Hibernate.entity(User.class) }
).next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select l from UserLogin l where usr = ?"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeysLogins),
new Object[] { user },
new Type[] { Hibernate.entity(User.class) } );
}
catch(HibernateException ex) {
throw new ModelStoreException(ex);
}
}
 
protected static Map sortKeys = new HashMap();
protected static Map sortKeysLogins = new HashMap();
private static boolean sortKeysInitialized = false;
 
private static void initSortKeys()
{
if(!sortKeysInitialized) {
sortKeys.put(UserManager.SORT_LOGIN, "u.login");
sortKeysLogins.put(UserManager.SORT_LOGINS_TIME, "l.loginTime");
sortKeysLogins.put(UserManager.SORT_LOGINS_TIME_REVERSE, "l.loginTime desc");
sortKeysInitialized = true;
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(UserHibernate.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/User.hbm.xml");
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/UserLogin.hbm.xml");
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/PasswordStoreAbstract.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/SystemUserHibernate.java
0,0 → 1,251
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.SystemUser;
import ak.hostadmiral.core.model.SystemUserManager;
import ak.hostadmiral.core.model.store.SystemUserStore;
 
public class SystemUserHibernate
implements SystemUserStore
{
public SystemUserHibernate()
throws ModelStoreException
{
initSortKeys();
register();
}
 
public SystemUser get(Long id)
throws ModelStoreException
{
try {
return (SystemUser)HibernateUtil.currentSession().load(SystemUser.class, id);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public boolean nameExists(SystemUser user, String name)
throws ModelStoreException
{
try {
if(user.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser u where name = ?",
name, Hibernate.STRING)
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser u where name = ? and u != ?",
new Object[] { name, user },
new Type[] { Hibernate.STRING, Hibernate.entity(SystemUser.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public boolean uidExists(SystemUser user, Integer uid)
throws ModelStoreException
{
try {
if(user.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser u where uid = ?",
uid, Hibernate.INTEGER)
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser u where uid = ? and u != ?",
new Object[] { uid, user },
new Type[] { Hibernate.INTEGER, Hibernate.entity(SystemUser.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public SystemUser findForName(String name)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select u from SystemUser u left join fetch u.owner where u.name=?",
name, Hibernate.STRING);
 
if(list.size() == 0)
return null;
else
return (SystemUser)list.get(0);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public SystemUser findForUid(Integer uid)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select u from SystemUser u left join fetch u.owner where u.uid=?",
uid, Hibernate.INTEGER);
 
if(list.size() == 0)
return null;
else
return (SystemUser)list.get(0);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void save(SystemUser systemUser)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(systemUser);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void delete(SystemUser systemUser)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(systemUser);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listAllSystemUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser").next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select u from SystemUser u left join fetch u.owner"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys), null, null);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listSystemUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser where owner is null or owner = ?",
user, Hibernate.entity(User.class))
.next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select u from SystemUser u left join u.owner o"
+ " where u.owner is null or u.owner = ?"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys),
new Object[] { user }, new Type[] { Hibernate.entity(User.class) } );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public int countSystemUsersAvailable(User user)
throws ModelStoreException
{
try {
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from SystemUser u left join u.owner o where o is null or o=?",
user, Hibernate.entity(User.class)).next()).intValue();
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listOwnSystemUsers(User user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select u from SystemUser u where u.owner = ?",
user, Hibernate.entity(User.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
protected static Map sortKeys = new HashMap();
private static boolean sortKeysInitialized = false;
 
private static void initSortKeys()
{
if(!sortKeysInitialized) {
sortKeys.put(SystemUserManager.SORT_UID, "u.uid");
sortKeys.put(SystemUserManager.SORT_NAME, "u.name");
sortKeysInitialized = true;
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(SystemUserManager.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/SystemUser.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/InetDomainHibernate.java
0,0 → 1,208
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.core.model.store.InetDomainStore;
 
public class InetDomainHibernate
implements InetDomainStore
{
public InetDomainHibernate()
throws ModelStoreException
{
initSortKeys();
register();
}
 
public InetDomain get(Long id)
throws ModelStoreException
{
try {
return (InetDomain)HibernateUtil.currentSession().load(
InetDomain.class, id);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public boolean nameExists(InetDomain domain, String name)
throws ModelStoreException
{
try {
if(domain.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from InetDomain d where name = ?",
name, Hibernate.STRING)
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from InetDomain d where name = ? and d != ?",
new Object[] { name, domain },
new Type[] { Hibernate.STRING, Hibernate.entity(InetDomain.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public InetDomain findForName(String name)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select d from InetDomain d left join fetch d.owner where d.name=?",
name, Hibernate.STRING);
 
if(list.size() == 0)
return null;
else
return (InetDomain)list.get(0);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void save(InetDomain domain)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(domain);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void delete(InetDomain domain)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(domain);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listAllInetDomains(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from InetDomain").next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select d from InetDomain d left join fetch d.owner"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys), null, null);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listInetDomains(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from InetDomain d where d.owner=?",
user, Hibernate.entity(User.class)).next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select d from InetDomain d where d.owner=?"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys),
new Object[] { user }, new Type[] { Hibernate.entity(User.class) } );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public int countInetDomainsAvailable(User user)
throws ModelStoreException
{
try {
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from InetDomain where owner=?",
user, Hibernate.entity(User.class)).next()).intValue();
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listOwnInetDomains(User user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select d from InetDomain d where d.owner = ?",
user, Hibernate.entity(User.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
protected static Map sortKeys = new HashMap();
private static boolean sortKeysInitialized = false;
 
private static void initSortKeys()
{
if(!sortKeysInitialized) {
sortKeys.put(InetDomainManager.SORT_NAME, "d.name");
sortKeysInitialized = true;
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(InetDomainHibernate.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/InetDomain.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/MailboxHibernate.java
0,0 → 1,289
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.SystemUser;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.Mailbox;
import ak.hostadmiral.core.model.MailboxManager;
import ak.hostadmiral.core.model.store.MailboxStore;
 
public class MailboxHibernate
implements MailboxStore
{
public MailboxHibernate()
throws ModelStoreException
{
initSortKeys();
register();
}
 
public Mailbox get(Long id)
throws ModelStoreException
{
try {
return (Mailbox)HibernateUtil.currentSession().load(Mailbox.class, id);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public boolean loginExists(Mailbox mailbox, String login)
throws ModelStoreException
{
try {
if(mailbox.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from Mailbox where login = ? and domain = ?",
new Object[] { login, mailbox.getDomain() },
new Type[] { Hibernate.STRING, Hibernate.entity(InetDomain.class) } )
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from Mailbox b where login = ? and domain = ? and b != ?",
new Object[] { login, mailbox.getDomain(), mailbox },
new Type[] { Hibernate.STRING, Hibernate.entity(InetDomain.class),
Hibernate.entity(Mailbox.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Mailbox findForLogin(String login)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select mb from Mailbox mb left join fetch mb.domain as d"
+ " left join fetch mb.owner left join fetch mb.systemUser where mb.login=?",
login, Hibernate.STRING);
 
if(list.size() == 0)
return null;
else
return (Mailbox)list.get(0);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void save(Mailbox mailbox)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(mailbox);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void delete(Mailbox mailbox)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(mailbox);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listAllMailboxes(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from Mailbox").next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableListSql(rowsPerPage, pageNumber,
"select {mb.*}, {d.*}, {o.*}, {su.*}"
+ " from mailboxes as mb"
+ " left join domains as d on mb.domain = d.id"
+ " left join users as o on mb.owner = o.id"
+ " left join systemusers as su on mb.systemUser = su.id"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeysSql),
new String[] { "mb", "d", "o", "su" },
new Class[] { Mailbox.class, InetDomain.class, User.class, SystemUser.class },
null,
null);
}
catch(HibernateException ex)
{
ex.printStackTrace();
 
throw new ModelStoreException(ex);
}
}
 
public Collection listMailboxes(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
List countlist = HibernateUtil.sqlQuery(
"select count(*) from ("
+ " select mb.id from mailboxes mb"
+ " where mb.owner=?"
+ " union"
+ " select mb.id from mailboxes mb"
+ " left join domains as d on mb.domain = d.id"
+ " where d.owner=?"
+ ") as count_table",
new Object[] { user.getId(), user.getId() });
 
info.init(((Long)countlist.get(0)).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableListSql(rowsPerPage, pageNumber,
"(select {mb.*}, {d.*}, {o.*}, {su.*}"
+ " from mailboxes as mb"
+ " left join domains as d on mb.domain = d.id"
+ " left join users as o on mb.owner = o.id"
+ " left join systemusers as su on mb.systemUser = su.id"
+ " where mb.owner=?)"
+ " union "
+ "(select {mb.*}, {d.*}, {o.*}, {su.*}"
+ " from mailboxes as mb"
+ " left join domains as d on mb.domain = d.id"
+ " left join users as o on mb.owner = o.id"
+ " left join systemusers as su on mb.systemUser = su.id"
+ " where d.owner=?)"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeysSql),
new String[] { "mb", "d", "o", "su" },
new Class[] { Mailbox.class, InetDomain.class, User.class, SystemUser.class },
new Object[] { user, user },
new Type[] { Hibernate.entity(User.class), Hibernate.entity(User.class) });
}
catch(HibernateException ex)
{
ex.printStackTrace();
 
throw new ModelStoreException(ex);
}
}
 
public int countMailboxesAvailable(User user)
throws ModelStoreException
{
try {
List countlist = HibernateUtil.sqlQuery(
"select count(*) from ("
+ " select mb.id from mailboxes mb"
+ " where mb.owner=?"
+ " union"
+ " select mb.id from mailboxes mb"
+ " left join domains as d on mb.domain = d.id"
+ " where d.owner=?"
+ ") as count_table",
new Object[] { user.getId(), user.getId() });
 
return ((Long)countlist.get(0)).intValue();
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listOwnMailboxes(User user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select mb from Mailbox mb left join fetch mb.domain"
+ " left join fetch mb.systemUser where mb.owner = ?",
user, Hibernate.entity(User.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailboxesForDomain(InetDomain domain)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select mb from Mailbox mb left join fetch mb.owner"
+ " left join fetch mb.systemUser where mb.domain = ?",
domain, Hibernate.entity(InetDomain.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailboxesForSystemUser(SystemUser user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select mb from Mailbox mb left join fetch mb.domain"
+ " left join fetch mb.owner where mb.systemUser = ?",
user, Hibernate.entity(SystemUser.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
protected static Map sortKeysSql = new HashMap();
private static boolean sortKeysInitialized = false;
 
private static void initSortKeys()
{
if(!sortKeysInitialized) {
sortKeysSql.put(MailboxManager.SORT_LOGIN, "login0_");
sortKeysSql.put(MailboxManager.SORT_DOMAIN, "name1_");
sortKeysInitialized = true;
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(MailboxHibernate.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/Mailbox.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/hibernate/MailAliasHibernate.java
0,0 → 1,276
package ak.hostadmiral.core.model.store.hibernate;
 
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
 
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
 
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.Mailbox;
import ak.hostadmiral.core.model.MailAlias;
import ak.hostadmiral.core.model.MailAliasManager;
import ak.hostadmiral.core.model.store.MailAliasStore;
 
public class MailAliasHibernate
implements MailAliasStore
{
public MailAliasHibernate()
throws ModelStoreException
{
initSortKeys();
register();
}
 
public MailAlias get(Long id)
throws ModelStoreException
{
try {
return (MailAlias)HibernateUtil.currentSession().load(MailAlias.class, id);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public boolean addressExists(MailAlias alias, String address)
throws ModelStoreException
{
try {
if(alias.getId() == null)
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from MailAlias where address = ? and domain = ?",
new Object[] { address, alias.getDomain() },
new Type[] { Hibernate.STRING, Hibernate.entity(InetDomain.class) } )
.next()).intValue() > 0;
else
return ((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from MailAlias a where address = ? and domain = ? and a != ?",
new Object[] { address, alias.getDomain(), alias },
new Type[] { Hibernate.STRING, Hibernate.entity(InetDomain.class),
Hibernate.entity(MailAlias.class) } )
.next()).intValue() > 0;
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public MailAlias findForName(String name)
throws ModelStoreException
{
try {
List list = HibernateUtil.currentSession().find(
"select a from MailAlias a left join fetch a.domain"
+ " left join fetch a.owner where a.name=?", name, Hibernate.STRING);
 
if(list.size() == 0)
return null;
else
return (MailAlias)list.get(0);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void save(MailAlias mailAlias)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().saveOrUpdate(mailAlias);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public void delete(MailAlias mailAlias)
throws ModelStoreException
{
try {
HibernateUtil.currentSession().delete(mailAlias);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listAllMailAliases(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException
{
try {
if(info != null) {
info.init(((Integer)HibernateUtil.currentSession().iterate(
"select count(*) from MailAlias").next()).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableList(rowsPerPage, pageNumber,
"select a from MailAlias a left join fetch a.domain as d"
+ " left join fetch a.owner"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeys), null, null);
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailAliases(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException
{
try {
if(info != null) {
List countlist = HibernateUtil.sqlQuery(
"select count(*) from ("
+ " select a.id from mailaliases a"
+ " where a.owner=?"
+ " union"
+ " select a.id from mailaliases a"
+ " left join domains as d on a.domain = d.id"
+ " where d.owner=?"
+ ") as count_table",
new Object[] { user.getId(), user.getId() });
 
info.init(((Long)countlist.get(0)).intValue(),
pageNumber, rowsPerPage);
}
 
return HibernateUtil.pageableListSql(rowsPerPage, pageNumber,
"(select {a.*}, {d.*}, {o.*}"
+ " from mailaliases as a"
+ " left join domains as d on a.domain = d.id"
+ " left join users as o on a.owner = o.id"
+ " where a.owner=?)"
+ " union "
+ "(select {a.*}, {d.*}, {o.*}"
+ " from mailaliases as a"
+ " left join domains as d on a.domain = d.id"
+ " left join users as o on a.owner = o.id"
+ " where d.owner=?)"
+ HibernateUtil.formOrderClause(sortingKeys, sortKeysSql),
new String[] { "a", "d", "o" },
new Class[] { MailAlias.class, InetDomain.class, User.class },
new Object[] { user, user },
new Type[] { Hibernate.entity(User.class), Hibernate.entity(User.class) });
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public int countMailAliasesAvailable(User user)
throws ModelStoreException
{
try {
List countlist = HibernateUtil.sqlQuery(
"select count(*) from ("
+ " select a.id from mailaliases a"
+ " where a.owner=?"
+ " union"
+ " select a.id from mailaliases a"
+ " left join domains as d on a.domain = d.id"
+ " where d.owner=?"
+ ") as count_table",
new Object[] { user.getId(), user.getId() });
 
return ((Long)countlist.get(0)).intValue();
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listOwnMailAliases(User user)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select a from MailAlias a left join fetch a.domain where a.owner = ?",
user, Hibernate.entity(User.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailAliasesForDomain(InetDomain domain)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select a from MailAlias a left join fetch a.owner where a.domain = ?",
domain, Hibernate.entity(InetDomain.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
public Collection listMailAliasesForMailbox(Mailbox mailbox)
throws ModelStoreException
{
try {
return HibernateUtil.currentSession().find(
"select a from MailAlias a left join fetch a.owner"
+ " left join fetch a.destinations as dest where dest.mailbox = ?",
mailbox, Hibernate.entity(Mailbox.class) );
}
catch(HibernateException ex)
{
throw new ModelStoreException(ex);
}
}
 
protected static Map sortKeys = new HashMap();
protected static Map sortKeysSql = new HashMap();
private static boolean sortKeysInitialized = false;
 
private static void initSortKeys()
{
if(!sortKeysInitialized) {
sortKeys.put(MailAliasManager.SORT_ADDRESS, "a.address");
sortKeys.put(MailAliasManager.SORT_DOMAIN, "d.name");
sortKeysSql.put(MailAliasManager.SORT_ADDRESS, "address0_");
sortKeysSql.put(MailAliasManager.SORT_DOMAIN, "name1_");
sortKeysInitialized = true;
}
}
 
private static boolean registered = false;
protected static void register()
throws ModelStoreException
{
synchronized(MailAliasHibernate.class) {
if(registered) return;
 
registered = true;
try {
HibernateUtil.getConfiguration().addResource(
"ak/hostadmiral/core/model/MailAlias.hbm.xml");
}
catch(Exception ex) {
throw new ModelStoreException(ex);
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/MailAliasStore.java
0,0 → 1,47
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.Mailbox;
import ak.hostadmiral.core.model.MailAlias;
 
public interface MailAliasStore
{
public MailAlias get(Long id)
throws ModelStoreException;
 
public boolean addressExists(MailAlias alias, String address)
throws ModelStoreException;
 
public MailAlias findForName(String name)
throws ModelStoreException;
 
public void save(MailAlias mailAlias)
throws ModelStoreException;
 
public void delete(MailAlias mailAlias)
throws ModelStoreException;
 
public Collection listAllMailAliases(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException;
 
public Collection listMailAliases(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
 
public int countMailAliasesAvailable(User user)
throws ModelStoreException;
 
public Collection listOwnMailAliases(User user)
throws ModelStoreException;
 
public Collection listMailAliasesForDomain(InetDomain domain)
throws ModelStoreException;
 
public Collection listMailAliasesForMailbox(Mailbox mailbox)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/UserStore.java
0,0 → 1,46
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserLogin;
 
public interface UserStore
{
public User get(Long id)
throws ModelStoreException;
 
public boolean loginExists(User user, String login)
throws ModelStoreException;
 
public User findForLogin(String login)
throws ModelStoreException;
 
public void save(User user)
throws ModelStoreException;
 
public void delete(User user)
throws ModelStoreException;
 
public Collection listAllUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException;
 
public Collection listUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
 
public void saveUserLogin(UserLogin userLogin)
throws ModelStoreException;
 
public Collection listFailedLogins()
throws ModelStoreException;
 
public Collection listSubusers(User user)
throws ModelStoreException;
 
public Collection listUserLogins(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/SystemUserStore.java
0,0 → 1,45
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.SystemUser;
 
public interface SystemUserStore
{
public SystemUser get(Long id)
throws ModelStoreException;
 
public boolean nameExists(SystemUser user, String name)
throws ModelStoreException;
 
public boolean uidExists(SystemUser user, Integer uid)
throws ModelStoreException;
 
public SystemUser findForName(String name)
throws ModelStoreException;
 
public SystemUser findForUid(Integer uid)
throws ModelStoreException;
 
public void save(SystemUser systemUser)
throws ModelStoreException;
 
public void delete(SystemUser systemUser)
throws ModelStoreException;
 
public Collection listAllSystemUsers(CollectionInfo info, int rowsPerPage,
int pageNumber, Integer[] sortingKeys)
throws ModelStoreException;
 
public Collection listSystemUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
 
public int countSystemUsersAvailable(User user)
throws ModelStoreException;
 
public Collection listOwnSystemUsers(User user)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/InetDomainStore.java
0,0 → 1,39
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.InetDomain;
 
public interface InetDomainStore
{
public InetDomain get(Long id)
throws ModelStoreException;
 
public boolean nameExists(InetDomain domain, String name)
throws ModelStoreException;
 
public InetDomain findForName(String name)
throws ModelStoreException;
 
public void save(InetDomain domain)
throws ModelStoreException;
 
public void delete(InetDomain domain)
throws ModelStoreException;
 
public Collection listAllInetDomains(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException;
 
public Collection listInetDomains(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
 
public int countInetDomainsAvailable(User user)
throws ModelStoreException;
 
public Collection listOwnInetDomains(User user)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/MailboxStore.java
0,0 → 1,47
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.SystemUser;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.Mailbox;
 
public interface MailboxStore
{
public Mailbox get(Long id)
throws ModelStoreException;
 
public boolean loginExists(Mailbox mailbox, String login)
throws ModelStoreException;
 
public Mailbox findForLogin(String login)
throws ModelStoreException;
 
public void save(Mailbox mailbox)
throws ModelStoreException;
 
public void delete(Mailbox mailbox)
throws ModelStoreException;
 
public Collection listAllMailboxes(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys)
throws ModelStoreException;
 
public Collection listMailboxes(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User user)
throws ModelStoreException;
 
public int countMailboxesAvailable(User user)
throws ModelStoreException;
 
public Collection listOwnMailboxes(User user)
throws ModelStoreException;
 
public Collection listMailboxesForDomain(InetDomain domain)
throws ModelStoreException;
 
public Collection listMailboxesForSystemUser(SystemUser user)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/store/MailAliasDestinationStore.java
0,0 → 1,23
package ak.hostadmiral.core.model.store;
 
import java.util.Collection;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelStoreException;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.MailAlias;
import ak.hostadmiral.core.model.MailAliasDestination;
 
public interface MailAliasDestinationStore
{
public MailAliasDestination get(Long id)
throws ModelStoreException;
 
public void save(MailAliasDestination mailAliasDestination)
throws ModelStoreException;
 
public void delete(MailAliasDestination mailAliasDestination)
throws ModelStoreException;
 
public Collection listMailAliasesDestination(MailAlias alias)
throws ModelStoreException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserManager.java
0,0 → 1,378
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Comparator;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.SystemUserStore;
 
public class SystemUserManager
implements
ConfigInit,
UserBeforeDeleteListener,
UserDeletingListener
{
private SystemUserStore store;
 
private Collection validateListeners = new ArrayList();
private Collection createdListeners = new ArrayList();
private Collection modifiedListeners = new ArrayList();
private Collection beforeDeleteListeners = new ArrayList();
private Collection deletingListeners = new ArrayList();
private Collection deletedListeners = new ArrayList();
 
public SystemUserManager()
throws ModelException
{
UserManager.getInstance().addBeforeDeleteListener(this);
UserManager.getInstance().addDeletingListener(this);
}
 
public SystemUser create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
return new SystemUser();
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return SystemUser.allowedToCreate(this, editor);
}
 
public SystemUser get(User editor, Long id)
throws ModelException
{
SystemUser user = store.get(id);
 
if(!user.viewableBy(editor))
throw new ModelSecurityException();
 
return user;
}
 
public boolean nameExists(User editor, SystemUser user, String name)
throws ModelException
{
return store.nameExists(user, name);
}
 
public boolean uidExists(User editor, SystemUser user, Integer uid)
throws ModelException
{
return store.uidExists(user, uid);
}
 
public SystemUser findForName(User editor, String name)
throws ModelException
{
SystemUser user = store.findForName(name);
 
if(user != null && !user.viewableBy(editor))
throw new ModelSecurityException();
 
return user;
}
 
public SystemUser findForUid(User editor, Integer uid)
throws ModelException
{
SystemUser user = store.findForUid(uid);
 
if(user != null && !user.viewableBy(editor))
throw new ModelSecurityException();
 
return user;
}
 
public void save(User editor, SystemUser systemUser)
throws ModelException
{
// security check
if(!systemUser.editableBy(editor))
throw new ModelSecurityException();
 
//systemUser.setModUser(editor); // FIXME
 
boolean isNew = systemUser.isNew();
SystemUser oldSystemUser = systemUser.getOrigin();
if(oldSystemUser == null) oldSystemUser = systemUser;
 
// validate
for(Iterator i = validateListeners.iterator(); i.hasNext(); ) {
SystemUserValidateListener listener = (SystemUserValidateListener)i.next();
listener.systemUserValidate(editor, systemUser, oldSystemUser);
}
 
store.save(systemUser);
 
// inform listeners
if(isNew) {
for(Iterator i = createdListeners.iterator(); i.hasNext(); ) {
SystemUserCreatedListener listener = (SystemUserCreatedListener)i.next();
listener.systemUserCreated(editor, systemUser);
}
}
else {
for(Iterator i = modifiedListeners.iterator(); i.hasNext(); ) {
SystemUserModifiedListener listener = (SystemUserModifiedListener)i.next();
listener.systemUserModified(editor, systemUser, oldSystemUser);
}
}
 
// reset backup
systemUser.resetOrigin();
}
 
public void addValidateListener(SystemUserValidateListener listener)
{
validateListeners.add(listener);
}
 
public void removeValidateListener(SystemUserValidateListener listener)
{
validateListeners.remove(listener);
}
 
public void addCreatedListener(SystemUserCreatedListener listener)
{
createdListeners.add(listener);
}
 
public void removeCreatedListener(SystemUserCreatedListener listener)
{
createdListeners.remove(listener);
}
 
public void addModifiedListener(SystemUserModifiedListener listener)
{
modifiedListeners.add(listener);
}
 
public void removeModifiedListener(SystemUserModifiedListener listener)
{
modifiedListeners.remove(listener);
}
 
public void addBeforeDeleteListener(SystemUserBeforeDeleteListener listener)
{
beforeDeleteListeners.add(listener);
}
 
public void removeBeforeDeleteListener(SystemUserBeforeDeleteListener listener)
{
beforeDeleteListeners.remove(listener);
}
 
public void addDeletingListener(SystemUserDeletingListener listener)
{
deletingListeners.add(listener);
}
 
public void removeDeletingListener(SystemUserDeletingListener listener)
{
deletingListeners.remove(listener);
}
 
public void addDeletedListener(SystemUserDeletedListener listener)
{
deletedListeners.add(listener);
}
 
public void removeDeletedListener(SystemUserDeletedListener listener)
{
deletedListeners.remove(listener);
}
 
public Collection beforeDelete(User editor, SystemUser user, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
 
for(Iterator i = beforeDeleteListeners.iterator(); i.hasNext(); ) {
SystemUserBeforeDeleteListener listener = (SystemUserBeforeDeleteListener)i.next();
Collection subcascade = listener.systemUserBeforeDelete(editor, user, known);
if(subcascade != null)
cascade.addAll(subcascade);
}
 
return cascade;
}
 
public void delete(User editor, SystemUser systemUser)
throws ModelException
{
// check rights
if(!systemUser.deleteableBy(editor))
throw new ModelSecurityException();
 
// inform deleting listeners
for(Iterator i = deletingListeners.iterator(); i.hasNext(); ) {
SystemUserDeletingListener listener = (SystemUserDeletingListener)i.next();
listener.systemUserDeleting(editor, systemUser);
}
 
// backup copy
SystemUser oldSystemUser = new SystemUser(systemUser);
 
// delete it
store.delete(systemUser);
 
// inform deleted listeners
for(Iterator i = deletedListeners.iterator(); i.hasNext(); ) {
SystemUserDeletedListener listener = (SystemUserDeletedListener)i.next();
listener.systemUserDeleted(editor, oldSystemUser);
}
}
 
public Collection listSystemUsers(User editor)
throws ModelException
{
return listSystemUsers(null, 0, 0, null, editor);
}
 
public Collection listSystemUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor)
throws ModelException
{
if(editor.isSuperuser())
return store.listAllSystemUsers(info, rowsPerPage, pageNumber, sortingKeys);
else
return store.listSystemUsers(info, rowsPerPage, pageNumber, sortingKeys, editor);
}
 
public boolean areSystemUsersAvailable(User editor)
throws ModelException
{
if(editor.isSuperuser())
return true;
else
return store.countSystemUsersAvailable(editor) > 0;
}
 
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection systemUsers = store.listOwnSystemUsers(user);
 
Collection cascade = new ArrayList();
for(Iterator i = systemUsers.iterator(); i.hasNext(); ) {
SystemUser u = (SystemUser)i.next();
if(known.contains(u)) continue;
 
known.add(u);
if(u.viewableBy(editor)) {
if(u.deleteableBy(editor))
cascade.add(new CascadeDeleteElement(u, CascadeDeleteElement.DELETE,
this.beforeDelete(editor, u, known)));
else
cascade.add(new CascadeDeleteElement(u, CascadeDeleteElement.FORBIDDEN, null));
}
else {
cascade.add(new CascadeDeleteElement(SystemUser.createLimitedCopy(u),
CascadeDeleteElement.FORBIDDEN, null));
}
}
 
return cascade;
}
 
public void userDeleting(User editor, User user)
throws ModelException
{
Collection systemUsers = store.listOwnSystemUsers(user);
 
for(Iterator i = systemUsers.iterator(); i.hasNext(); ) {
delete(editor, (SystemUser)i.next());
}
}
 
public static final Integer SORT_UID = new Integer(1);
public static final Integer SORT_NAME = new Integer(2);
 
public static final Comparator UID_COMPARATOR = new UidComparator();
public static final Comparator NAME_COMPARATOR = new NameComparator();
 
private static class UidComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof SystemUser) || !(o2 instanceof SystemUser))
throw new ClassCastException("not a SystemUser");
 
SystemUser a1 = (SystemUser)o1;
SystemUser a2 = (SystemUser)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getUid().compareTo(a2.getUid());
}
 
public boolean equals(Object obj)
{
return (obj instanceof UidComparator);
}
}
 
private static class NameComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof SystemUser) || !(o2 instanceof SystemUser))
throw new ClassCastException("not a SystemUser");
 
SystemUser a1 = (SystemUser)o1;
SystemUser a2 = (SystemUser)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getName().compareToIgnoreCase(a2.getName());
}
 
public boolean equals(Object obj)
{
return (obj instanceof NameComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
systemUserManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (SystemUserStore)c.newInstance();
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static SystemUserManager systemUserManager = null;
 
public static SystemUserManager getInstance()
{
return systemUserManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasManager.java
0,0 → 1,394
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Comparator;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.MailAliasStore;
 
public class MailAliasManager
implements
ConfigInit,
UserBeforeDeleteListener,
UserDeletingListener,
InetDomainBeforeDeleteListener,
InetDomainDeletingListener,
MailboxDeletingListener
{
private MailAliasStore store;
 
private Collection validateListeners = new ArrayList();
private Collection createdListeners = new ArrayList();
private Collection modifiedListeners = new ArrayList();
private Collection beforeDeleteListeners = new ArrayList();
private Collection deletingListeners = new ArrayList();
private Collection deletedListeners = new ArrayList();
 
public MailAliasManager()
throws ModelException
{
UserManager.getInstance().addBeforeDeleteListener(this);
UserManager.getInstance().addDeletingListener(this);
InetDomainManager.getInstance().addBeforeDeleteListener(this);
InetDomainManager.getInstance().addDeletingListener(this);
// FIXME register for mailbox before delete event? or silently delete destinations?
MailboxManager.getInstance().addDeletingListener(this);
}
 
public MailAlias create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
MailAlias alias = new MailAlias();
alias.setDestinations(new ArrayList());
return alias;
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return MailAlias.allowedToCreate(this, editor);
}
 
public MailAlias get(User editor, Long id)
throws ModelException
{
MailAlias alias = store.get(id);
 
if(!alias.viewableBy(editor))
throw new ModelSecurityException();
 
return alias;
}
 
public boolean addressExists(User editor, MailAlias alias, String address)
throws ModelException
{
if(alias.getDomain() == null)
throw new ModelException("Cannot check unique address for mail alias without domain");
 
return store.addressExists(alias, address);
}
 
public MailAlias findForName(User editor, String name)
throws ModelException
{
MailAlias alias = store.findForName(name);
 
if(!alias.viewableBy(editor))
throw new ModelSecurityException();
 
return alias;
}
 
public void save(User editor, MailAlias mailAlias)
throws ModelException
{
// FIXME: how the onwer can save new destinations if he has no right to save the alias?
 
// security check
if(!mailAlias.editableBy(editor))
throw new ModelSecurityException();
 
//mailAlias.setModUser(editor); // FIXME
 
boolean isNew = mailAlias.isNew();
MailAlias oldMailAlias = mailAlias.getOrigin();
if(oldMailAlias == null) oldMailAlias = mailAlias;
 
// validate
for(Iterator i = validateListeners.iterator(); i.hasNext(); ) {
MailAliasValidateListener listener = (MailAliasValidateListener)i.next();
listener.mailAliasValidate(editor, mailAlias, oldMailAlias);
}
 
store.save(mailAlias);
 
// inform listeners
if(isNew) {
for(Iterator i = createdListeners.iterator(); i.hasNext(); ) {
MailAliasCreatedListener listener = (MailAliasCreatedListener)i.next();
listener.mailAliasCreated(editor, mailAlias);
}
}
else {
for(Iterator i = modifiedListeners.iterator(); i.hasNext(); ) {
MailAliasModifiedListener listener = (MailAliasModifiedListener)i.next();
listener.mailAliasModified(editor, mailAlias, oldMailAlias);
}
}
 
// reset backup
mailAlias.resetOrigin();
}
 
public void addValidateListener(MailAliasValidateListener listener)
{
validateListeners.add(listener);
}
 
public void removeValidateListener(MailAliasValidateListener listener)
{
validateListeners.remove(listener);
}
 
public void addCreatedListener(MailAliasCreatedListener listener)
{
createdListeners.add(listener);
}
 
public void removeCreatedListener(MailAliasCreatedListener listener)
{
createdListeners.remove(listener);
}
 
public void addModifiedListener(MailAliasModifiedListener listener)
{
modifiedListeners.add(listener);
}
 
public void removeModifiedListener(MailAliasModifiedListener listener)
{
modifiedListeners.remove(listener);
}
 
public void addBeforeDeleteListener(MailAliasBeforeDeleteListener listener)
{
beforeDeleteListeners.add(listener);
}
 
public void removeBeforeDeleteListener(MailAliasBeforeDeleteListener listener)
{
beforeDeleteListeners.remove(listener);
}
 
public void addDeletingListener(MailAliasDeletingListener listener)
{
deletingListeners.add(listener);
}
 
public void removeDeletingListener(MailAliasDeletingListener listener)
{
deletingListeners.remove(listener);
}
 
public void addDeletedListener(MailAliasDeletedListener listener)
{
deletedListeners.add(listener);
}
 
public void removeDeletedListener(MailAliasDeletedListener listener)
{
deletedListeners.remove(listener);
}
 
public Collection beforeDelete(User editor, MailAlias mailAlias, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
 
for(Iterator i = beforeDeleteListeners.iterator(); i.hasNext(); ) {
MailAliasBeforeDeleteListener listener = (MailAliasBeforeDeleteListener)i.next();
Collection subcascade = listener.mailAliasBeforeDelete(editor, mailAlias, known);
if(subcascade != null)
cascade.addAll(subcascade);
}
 
return cascade;
}
 
public void delete(User editor, MailAlias mailAlias)
throws ModelException
{
// check rights
if(!mailAlias.deleteableBy(editor))
throw new ModelSecurityException();
 
// inform deleting listeners
for(Iterator i = deletingListeners.iterator(); i.hasNext(); ) {
MailAliasDeletingListener listener = (MailAliasDeletingListener)i.next();
listener.mailAliasDeleting(editor, mailAlias);
}
 
// backup copy
MailAlias oldMailAlias = new MailAlias(mailAlias);
 
// delete it
store.delete(mailAlias);
 
// inform deleted listeners
for(Iterator i = deletedListeners.iterator(); i.hasNext(); ) {
MailAliasDeletedListener listener = (MailAliasDeletedListener)i.next();
listener.mailAliasDeleted(editor, oldMailAlias);
}
}
 
public Collection listMailAliases(User editor)
throws ModelException
{
return listMailAliases(null, 0, 0, null, editor);
}
 
public Collection listMailAliases(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor)
throws ModelException
{
if(editor.isSuperuser())
return store.listAllMailAliases(info, rowsPerPage, pageNumber, sortingKeys);
else
return store.listMailAliases(info, rowsPerPage, pageNumber, sortingKeys, editor);
}
 
public boolean areMailAliasesAvailable(User editor)
throws ModelException
{
if(editor.isSuperuser() || InetDomainManager.getInstance().areInetDomainsAvailable(editor))
return true;
else
return store.countMailAliasesAvailable(editor) > 0;
}
 
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection mailAliases = store.listOwnMailAliases(user);
 
return iterateBeforeDelete(editor, mailAliases, known);
}
 
public void userDeleting(User editor, User user)
throws ModelException
{
Collection mailAliases = store.listOwnMailAliases(user);
 
for(Iterator i = mailAliases.iterator(); i.hasNext(); ) {
delete(editor, (MailAlias)i.next());
}
}
 
public Collection inetDomainBeforeDelete(User editor, InetDomain domain, Collection known)
throws ModelException
{
Collection mailAliases = store.listMailAliasesForDomain(domain);
 
return iterateBeforeDelete(editor, mailAliases, known);
}
 
public void inetDomainDeleting(User editor, InetDomain domain)
throws ModelException
{
Collection mailAliases = store.listMailAliasesForDomain(domain);
 
for(Iterator i = mailAliases.iterator(); i.hasNext(); ) {
delete(editor, (MailAlias)i.next());
}
}
 
private Collection iterateBeforeDelete(User editor, Collection mailAliases, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
for(Iterator i = mailAliases.iterator(); i.hasNext(); ) {
MailAlias mailAlias = (MailAlias)i.next();
if(known.contains(mailAlias)) continue;
 
known.add(mailAlias);
if(mailAlias.viewableBy(editor)) {
if(mailAlias.deleteableBy(editor))
cascade.add(new CascadeDeleteElement(mailAlias, CascadeDeleteElement.DELETE,
this.beforeDelete(editor, mailAlias, known)));
else
cascade.add(new CascadeDeleteElement(mailAlias, CascadeDeleteElement.FORBIDDEN,
null));
}
else {
cascade.add(new CascadeDeleteElement(MailAlias.createLimitedCopy(mailAlias),
CascadeDeleteElement.FORBIDDEN, null));
}
}
 
return cascade;
}
 
public void mailboxDeleting(User editor, Mailbox mailbox)
throws ModelException
{
Collection mailAliases = store.listMailAliasesForMailbox(mailbox);
 
for(Iterator i = mailAliases.iterator(); i.hasNext(); ) {
MailAlias mailAlias = (MailAlias)i.next();
System.out.println("mailboxDeleting: " + mailAlias);
 
// FIXME is it possible that editor has right to delete mailbox
// but has no right to change alias?
if(mailAlias.mayChangeDestinations(editor)) {
for(Iterator j = mailAlias.getDestinations(editor).iterator(); j.hasNext(); ) {
MailAliasDestination dest = (MailAliasDestination)j.next();
if(mailbox == dest.getMailbox()) j.remove();
}
 
save(editor, mailAlias);
}
}
}
 
public static final Integer SORT_ADDRESS = new Integer(1);
public static final Integer SORT_DOMAIN = new Integer(2);
 
public static final Comparator ADDRESS_COMPARATOR = new AddressComparator();
 
private static class AddressComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof MailAlias) || !(o2 instanceof MailAlias))
throw new ClassCastException("not a MailAlias");
 
MailAlias a1 = (MailAlias)o1;
MailAlias a2 = (MailAlias)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getAddress().compareToIgnoreCase(a2.getAddress());
}
 
public boolean equals(Object obj)
{
return (obj instanceof AddressComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
mailAliasManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (MailAliasStore)c.newInstance();
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static MailAliasManager mailAliasManager = null;
 
public static MailAliasManager getInstance()
{
return mailAliasManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasDestination.java
0,0 → 1,141
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="mailaliasdests"
*/
public class MailAliasDestination
extends GeneralModelObject
{
private MailAlias alias;
private Mailbox mailbox;
private String email;
 
protected MailAliasDestination()
{
}
 
/**
*
* @hibernate.many-to-one
*/
public MailAlias getAlias()
{
return alias;
}
 
protected void setAlias(MailAlias alias)
{
this.alias = alias;
}
 
public void setAlias(User editor, MailAlias alias)
throws ModelException
{
if(this.alias != null && !editableBy(editor))
throw new ModelSecurityException();
 
this.alias = alias;
}
 
/**
*
* @hibernate.many-to-one
*/
public Mailbox getMailbox()
{
return mailbox;
}
 
protected void setMailbox(Mailbox mailbox)
{
this.mailbox = mailbox;
}
 
public void setMailbox(User editor, Mailbox mailbox)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.mailbox = mailbox;
}
 
/**
*
* @hibernate.property
*/
public String getEmail()
{
return email;
}
 
protected void setEmail(String email)
{
this.email = email;
}
 
public void setEmail(User editor, String email)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.email = email;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_MAIL_ALIAS_DESTINATION;
}
 
public String getIdentKey()
{
if(getMailbox() == null)
return ak.hostadmiral.core.resources.CoreResources.IDENT_MAIL_ALIAS_DESTINATION_EXTERNAL;
else
return ak.hostadmiral.core.resources.CoreResources.IDENT_MAIL_ALIAS_DESTINATION_INTERNAL;
}
 
public Object[] getIdentParams()
{
if(getMailbox() == null)
return new Object[] { getEmail() };
else
return new Object[] { getMailbox().getLogin(), getMailbox().getDomain().getName() };
}
 
public boolean viewableBy(User user)
{
return alias.viewableBy(user);
}
 
public boolean editableBy(User user)
{
return alias.mayChangeDestinations(user);
}
 
public boolean deleteableBy(User user)
{
return alias.mayChangeDestinations(user);
}
 
protected static boolean allowedToCreate(MailAliasDestinationManager manager, User editor)
throws ModelException
{
return true;
}
 
public String toString()
{
return "MailAliasDestination id=[" + getId() + "] alias=["
+ (alias == null ? "_none_" : alias.getAddress() + "@"
+ (alias.getDomain() == null ? "_none_" : alias.getDomain().getName()))
+ "] mailbox=[" + (mailbox == null ? "_none_" : mailbox.getLogin() + "@"
+ (mailbox.getDomain() == null ? "_none_" : mailbox.getDomain().getName()))
+ "] email=[" + (email == null ? "_none_" : email) + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/PasswordStore.java
0,0 → 1,44
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
/**
* A password store must implement java.lang.Cloneable interface.
*/
public interface PasswordStore
{
/**
* returns digest name, e.g. "MD5"
*/
public String getDigest();
 
/**
* returns true if the store is able to return the original password
*/
public boolean getReversable();
 
/**
* to store to persistent store
*/
public String getPassword();
 
/**
* to store from persistent store
*/
public void setPassword(String password);
 
/**
* to set by user
*/
public void setNewPassword(String password)
throws ModelException;
 
public boolean checkPassword(String password)
throws ModelException;
 
/**
* return the password in plain text if possible
*/
public String getOriginalPassword()
throws UnsupportedOperationException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/PasswordStoreAbstract.java
0,0 → 1,126
package ak.hostadmiral.core.model;
 
import java.util.Date;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.DigestMd5;
 
/**
*
* @hibernate.class table="passwords"
* @hibernate.discriminator column="digest" type="string"
*/
public abstract class PasswordStoreAbstract
implements PasswordStore, Cloneable
{
private Long id;
private Date modStamp;
private User modUser;
protected String digest;
protected String password;
 
/**
*
* @hibernate.id generator-class="native"
*/
public Long getId()
{
return id;
}
 
protected void setId(Long id)
{
this.id = id;
}
 
/**
*
* @hibernate.timestamp column="mod_stamp"
*/
public Date getModStamp()
{
return modStamp;
}
 
protected void setModStamp(Date modStamp)
{
this.modStamp = modStamp;
}
 
/**
*
* @hibernate.many-to-one column="mod_user"
*/
public User getModUser()
{
return modUser;
}
 
protected void setModUser(User modUser)
{
this.modUser = modUser;
}
 
/**
* returns digest name, e.g. "MD5"
*/
public String getDigest()
{
return digest;
}
 
/**
* to store to persistent store
*
* @hibernate.property
*/
public String getPassword()
{
return password;
}
 
/**
* to store from persistent store
*/
public void setPassword(String password)
{
this.password = password;
}
 
/**
* to set by user
*/
public void setNewPassword(String password)
throws ModelException
{
this.password = encode(password);
}
 
public boolean checkPassword(String password)
throws ModelException
{
return this.password.equals(encode(password));
}
 
protected abstract String encode(String password)
throws ModelException;
 
public Object clone()
throws CloneNotSupportedException
{
PasswordStoreAbstract theClone = (PasswordStoreAbstract)super.clone();
theClone.password = password;
return theClone;
}
 
public boolean getReversable()
{
return false;
}
 
public String getOriginalPassword()
throws UnsupportedOperationException
{
throw new UnsupportedOperationException("Not able to restore original password");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/PasswordStorePlain.java
0,0 → 1,34
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.DigestMd5;
 
/**
*
* @hibernate.subclass discriminator-value="Plain"
*/
public class PasswordStorePlain
extends PasswordStoreAbstract
{
public PasswordStorePlain()
{
digest = "Plain";
}
 
protected String encode(String password)
throws ModelException
{
return password;
}
 
public boolean getReversable()
{
return true;
}
 
public String getOriginalPassword()
throws UnsupportedOperationException
{
return password;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserManager.java
0,0 → 1,449
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.Comparator;
import java.util.Date;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.UserStore;
 
public class UserManager
implements
ConfigInit,
UserBeforeDeleteListener,
UserDeletingListener
{
private UserStore store;
private Class[] passwordStores;
 
private Collection validateListeners = new ArrayList();
private Collection createdListeners = new ArrayList();
private Collection modifiedListeners = new ArrayList();
private Collection beforeDeleteListeners = new ArrayList();
private Collection deletingListeners = new ArrayList();
private Collection deletedListeners = new ArrayList();
 
// FIMXE: check that it works
private Map loggedinUsers = new WeakHashMap();
 
public UserManager()
throws ModelException
{
addBeforeDeleteListener(this);
addDeletingListener(this);
}
 
public User create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
User user = new User();
 
if(!user.mayChangeBoss(editor)) // ordinal user can create only own "subusers"
user.setBoss(editor);
 
setUserPasswordStores(user);
 
return user;
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return User.allowedToCreate(this, editor);
}
 
public User get(User editor, Long id)
throws ModelException
{
User user = store.get(id);
 
if(!user.viewableBy(editor))
throw new ModelSecurityException();
 
return user;
}
 
public User get(Long id)
throws ModelException
{
return store.get(id);
}
 
public boolean loginExists(User editor, User user, String login)
throws ModelException
{
return store.loginExists(user, login);
}
 
public User findForLogin(User editor, String login)
throws ModelException
{
User user = store.findForLogin(login);
 
if(user != null && !user.viewableBy(editor))
throw new ModelSecurityException();
 
return user;
}
 
public void save(User editor, User user)
throws ModelException
{
// security check
if(!user.editableBy(editor) && !user.partEditableBy(editor)
&& !user.mayChangeSuperuser(editor))
{
throw new ModelSecurityException();
}
 
//user.setModUser(editor); // FIXME: disabled because hb throws exception
// if user edits itself
 
boolean isNew = user.isNew();
User oldUser = user.getOrigin();
if(oldUser == null) oldUser = user;
 
// validate
for(Iterator i = validateListeners.iterator(); i.hasNext(); ) {
UserValidateListener listener = (UserValidateListener)i.next();
listener.userValidate(editor, user, oldUser);
}
 
store.save(user);
 
// update user if he is logged in
for(Iterator i = loggedinUsers.keySet().iterator(); i.hasNext(); ) {
User u = (User)i.next();
if(u.equals(user))
u.update(user);
}
 
// inform listeners
if(isNew) {
for(Iterator i = createdListeners.iterator(); i.hasNext(); ) {
UserCreatedListener listener = (UserCreatedListener)i.next();
listener.userCreated(editor, user);
}
}
else {
for(Iterator i = modifiedListeners.iterator(); i.hasNext(); ) {
UserModifiedListener listener = (UserModifiedListener)i.next();
listener.userModified(editor, user, oldUser);
}
}
 
// reset backup
user.resetOrigin();
}
 
public void addValidateListener(UserValidateListener listener)
{
validateListeners.add(listener);
}
 
public void removeValidateListener(UserValidateListener listener)
{
validateListeners.remove(listener);
}
 
public void addCreatedListener(UserCreatedListener listener)
{
createdListeners.add(listener);
}
 
public void removeCreatedListener(UserCreatedListener listener)
{
createdListeners.remove(listener);
}
 
public void addModifiedListener(UserModifiedListener listener)
{
modifiedListeners.add(listener);
}
 
public void removeModifiedListener(UserModifiedListener listener)
{
modifiedListeners.remove(listener);
}
 
public void addBeforeDeleteListener(UserBeforeDeleteListener listener)
{
beforeDeleteListeners.add(listener);
}
 
public void removeBeforeDeleteListener(UserBeforeDeleteListener listener)
{
beforeDeleteListeners.remove(listener);
}
 
public void addDeletedListener(UserDeletedListener listener)
{
deletedListeners.add(listener);
}
 
public void removeDeletedListener(UserDeletedListener listener)
{
deletedListeners.remove(listener);
}
 
public void addDeletingListener(UserDeletingListener listener)
{
deletingListeners.add(listener);
}
 
public void removeDeletingListener(UserDeletingListener listener)
{
deletingListeners.remove(listener);
}
 
public Collection beforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
 
for(Iterator i = beforeDeleteListeners.iterator(); i.hasNext(); ) {
UserBeforeDeleteListener listener = (UserBeforeDeleteListener)i.next();
Collection subcascade = listener.userBeforeDelete(editor, user, known);
if(subcascade != null)
cascade.addAll(subcascade);
}
 
return cascade;
}
 
public void delete(User editor, User user)
throws ModelException
{
// check rights
if(!user.deleteableBy(editor))
throw new ModelSecurityException();
 
// inform deleting listeners
for(Iterator i = deletingListeners.iterator(); i.hasNext(); ) {
UserDeletingListener listener = (UserDeletingListener)i.next();
listener.userDeleting(editor, user);
}
 
// backup copy
User oldUser = new User(user);
 
// delete it
store.delete(user);
 
// inform delete listeners
for(Iterator i = deletedListeners.iterator(); i.hasNext(); ) {
UserDeletedListener listener = (UserDeletedListener)i.next();
listener.userDeleted(editor, oldUser);
}
}
 
public Collection listUsers(User editor)
throws ModelException
{
return listUsers(null, 0, 0, null, editor);
}
 
public Collection listUsers(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor)
throws ModelException
{
if(editor.isSuperuser())
return store.listAllUsers(info, rowsPerPage, pageNumber, sortingKeys);
else
return store.listUsers(info, rowsPerPage, pageNumber, sortingKeys, editor);
}
 
public boolean areUsersAvailable(User editor)
throws ModelException
{
return true;
}
 
public User loginUser(String login, String password, String ip)
throws ModelException
{
User user = (login == null || password == null)
? null : store.findForLogin(login);
 
boolean success = (user == null) ? false : user.checkPassword(password);
UserLogin userLogin = new UserLogin(user, login, new Date(), Boolean.valueOf(success), ip);
 
// save login information
store.saveUserLogin(userLogin);
 
if(success) {
user = new User(user); // unbind the user from store
loggedinUsers.put(user, Boolean.TRUE);
return user;
}
else {
return null; // wrong login or password
}
}
 
public Collection listFailedLogins(User editor)
throws ModelException
{
if(!editor.mayViewAllLogins())
throw new ModelSecurityException();
 
return store.listFailedLogins();
}
 
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection subusers = store.listSubusers(user);
 
Collection cascade = new ArrayList();
for(Iterator i = subusers.iterator(); i.hasNext(); ) {
User u = (User)i.next();
if(known.contains(u)) continue;
 
known.add(u);
if(u.viewableBy(editor)) {
if(u.deleteableBy(editor))
cascade.add(new CascadeDeleteElement(u, CascadeDeleteElement.DELETE,
this.beforeDelete(editor, u, known)));
else
cascade.add(new CascadeDeleteElement(u, CascadeDeleteElement.FORBIDDEN, null));
}
else {
cascade.add(new CascadeDeleteElement(User.createLimitedCopy(u),
CascadeDeleteElement.FORBIDDEN, null));
}
}
 
return cascade;
}
 
public void userDeleting(User editor, User user)
throws ModelException
{
Collection subusers = store.listSubusers(user);
 
for(Iterator i = subusers.iterator(); i.hasNext(); ) {
delete(editor, (User)i.next());
}
}
 
protected void setUserPasswordStores(User user)
throws ModelException
{
if(passwordStores == null) return;
 
try {
for(int i = 0; i < passwordStores.length; i++)
user.addPasswordStore((PasswordStore)passwordStores[i].newInstance());
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
public Collection listUserLogins(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor, User user)
throws ModelException
{
return store.listUserLogins(info, rowsPerPage, pageNumber, sortingKeys, user);
}
 
public static final Integer SORT_LOGIN = new Integer(1);
public static final Integer SORT_LOGINS_TIME = new Integer(2);
public static final Integer SORT_LOGINS_TIME_REVERSE = new Integer(3);
 
public static final Comparator LOGIN_COMPARATOR = new LoginComparator();
public static final Comparator LOGINS_TIME_COMPARATOR = new LoginsTimeComparator();
 
private static class LoginComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof User) || !(o2 instanceof User))
throw new ClassCastException("not a User");
 
User a1 = (User)o1;
User a2 = (User)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getLogin().compareToIgnoreCase(a2.getLogin());
}
 
public boolean equals(Object obj)
{
return (obj instanceof LoginComparator);
}
}
 
private static class LoginsTimeComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof UserLogin) || !(o2 instanceof UserLogin))
throw new ClassCastException("not a UserLogin");
 
UserLogin a1 = (UserLogin)o1;
UserLogin a2 = (UserLogin)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getLoginTime().compareTo(a2.getLoginTime());
}
 
public boolean equals(Object obj)
{
return (obj instanceof LoginComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
userManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (UserStore)c.newInstance();
 
String[] passwordStoreNames = (String[])params.get("passwordStore");
if(passwordStoreNames != null) {
passwordStores = new Class[passwordStoreNames.length];
for(int i = 0; i < passwordStoreNames.length; i++) {
passwordStores[i] = Class.forName(passwordStoreNames[i]);
}
}
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static UserManager userManager = null;
 
public static UserManager getInstance()
{
return userManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserDeletedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface UserDeletedListener
{
/**
* called if some user is just deleted.
*
* @param editor who is doing the operation
* @param user the user deleted
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other UserDeletedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void userDeleted(User editor, User user)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserCreatedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface UserCreatedListener
{
/**
* called if new user is just created.
*
* @param editor who is doing the operation
* @param user the new user
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other UserCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void userCreated(User editor, User user)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainDeletedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainDeletedListener
{
/**
* called if some domain is just deleted.
*
* @param editor who is doing the operation
* @param domain the domain deleted
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other InetDomainDeletedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void inetDomainDeleted(User editor, InetDomain domain)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainCreatedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainCreatedListener
{
/**
* called if new domain is just created.
*
* @param editor who is doing the operation
* @param domain the new domain
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other InetDomainCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void inetDomainCreated(User editor, InetDomain domain)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserModifiedListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface UserModifiedListener
{
/**
* called if some user is just changed.
*
* @param editor who is doing the operation
* @param user the user in its new state
* @param oldUser copy of user as it was before the operation
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other UserCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void userModified(User editor, User user, User oldUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxDeletedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailboxDeletedListener
{
/**
* called if some mailbox is just deleted.
*
* @param editor who is doing the operation
* @param mailbox the mailbox deleted
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailboxDeletedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailboxDeleted(User editor, Mailbox mailbox)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxCreatedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailboxCreatedListener
{
/**
* called if new mailbox is just created.
*
* @param editor who is doing the operation
* @param mailbox the new mailbox
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailboxCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailboxCreated(User editor, Mailbox mailbox)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserModifiedListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserModifiedListener
{
/**
* called if some system user is just changed.
*
* @param editor who is doing the operation
* @param systemUser the system user in its new state
* @param oldSystemUser copy of system user as it was before the operation
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other SystemUserCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void systemUserModified(User editor, SystemUser systemUser, SystemUser oldSystemUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainValidateListener.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainValidateListener
{
/**
* called if domain information is about to be changed - by new or existing entry
*
* @param editor who is doing the operation
* @param inetDomain the domain in its new state
* @param oldInetDomain copy of domain as it was before the operation
* @throws ModelException in case of any validation errors, validation will be stopped
* by first exception
*/
public void inetDomainValidate(User editor, InetDomain inetDomain, InetDomain oldInetDomain)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainDeletingListener.java
0,0 → 1,17
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainDeletingListener
{
/**
* called just before some domain is deleted.
*
* @param editor who is doing the operation
* @param domain the domain is being deleting
* @throws ModelException in case of any errors, no action should be done
* until this moment in other classes
*/
public void inetDomainDeleting(User editor, InetDomain domain)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxValidateListener.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailboxValidateListener
{
/**
* called if mailbox information is about to be changed - by new or existing entry
*
* @param editor who is doing the operation
* @param mailbox the mailbox in its new state
* @param oldMailbox copy of mailbox as it was before the operation
* @throws ModelException in case of any validation errors, validation will be stopped
* by first exception
*/
public void mailboxValidate(User editor, Mailbox mailbox, Mailbox oldMailbox)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasValidateListener.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasValidateListener
{
/**
* called if mail alias information is about to be changed - by new or existing entry
*
* @param editor who is doing the operation
* @param mailAlias the mail alias in its new state
* @param oldMailAlias copy of mail alias as it was before the operation
* @throws ModelException in case of any validation errors, validation will be stopped
* by first exception
*/
public void mailAliasValidate(User editor, MailAlias mailAlias, MailAlias oldMailAlias)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxDeletingListener.java
0,0 → 1,17
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailboxDeletingListener
{
/**
* called just before some mailbox is deleted.
*
* @param editor who is doing the operation
* @param mailbox the mailbox is being deleting
* @throws ModelException in case of any errors, no action should be done
* until this moment in other classes
*/
public void mailboxDeleting(User editor, Mailbox mailbox)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasDeletingListener.java
0,0 → 1,17
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasDeletingListener
{
/**
* called just before some mail alias is deleted.
*
* @param editor who is doing the operation
* @param mailAlias the mail alias is being deleting
* @throws ModelException in case of any errors, no action should be done
* until this moment in other classes
*/
public void mailAliasDeleting(User editor, MailAlias mailAlias)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserDeletedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserDeletedListener
{
/**
* called if some system user is just deleted.
*
* @param editor who is doing the operation
* @param systemUser the system user deleted
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other SystemUserDeletedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void systemUserDeleted(User editor, SystemUser systemUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserCreatedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserCreatedListener
{
/**
* called if new system user is just created.
*
* @param editor who is doing the operation
* @param systemUser the new system user
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other SystemUserCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void systemUserCreated(User editor, SystemUser systemUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainManager.java
0,0 → 1,332
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Comparator;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.InetDomainStore;
 
public class InetDomainManager
implements
ConfigInit,
UserBeforeDeleteListener,
UserDeletingListener
{
private InetDomainStore store;
 
private Collection validateListeners = new ArrayList();
private Collection createdListeners = new ArrayList();
private Collection modifiedListeners = new ArrayList();
private Collection beforeDeleteListeners = new ArrayList();
private Collection deletingListeners = new ArrayList();
private Collection deletedListeners = new ArrayList();
 
public InetDomainManager()
throws ModelException
{
UserManager.getInstance().addBeforeDeleteListener(this);
UserManager.getInstance().addDeletingListener(this);
}
 
public InetDomain create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
return new InetDomain();
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return InetDomain.allowedToCreate(this, editor);
}
 
public InetDomain get(User editor, Long id)
throws ModelException
{
InetDomain domain = store.get(id);
 
if(!domain.viewableBy(editor))
throw new ModelSecurityException();
 
return domain;
}
 
public boolean nameExists(User editor, InetDomain domain, String name)
throws ModelException
{
return store.nameExists(domain, name);
}
 
public InetDomain findForName(User editor, String name)
throws ModelException
{
InetDomain domain = store.findForName(name);
 
if(domain != null && !domain.viewableBy(editor))
throw new ModelSecurityException();
 
return domain;
}
 
public void save(User editor, InetDomain domain)
throws ModelException
{
// security check
if(!domain.editableBy(editor))
throw new ModelSecurityException();
 
//domain.setModUser(editor); // FIXME
 
boolean isNew = domain.isNew();
InetDomain oldDomain = domain.getOrigin();
if(oldDomain == null) oldDomain = domain;
 
// validate
for(Iterator i = validateListeners.iterator(); i.hasNext(); ) {
InetDomainValidateListener listener = (InetDomainValidateListener)i.next();
listener.inetDomainValidate(editor, domain, oldDomain);
}
 
store.save(domain);
 
// inform listeners
if(isNew) {
for(Iterator i = createdListeners.iterator(); i.hasNext(); ) {
InetDomainCreatedListener listener = (InetDomainCreatedListener)i.next();
listener.inetDomainCreated(editor, domain);
}
}
else {
for(Iterator i = modifiedListeners.iterator(); i.hasNext(); ) {
InetDomainModifiedListener listener = (InetDomainModifiedListener)i.next();
listener.inetDomainModified(editor, domain, oldDomain);
}
}
 
// reset backup
domain.resetOrigin();
}
 
public void addValidateListener(InetDomainValidateListener listener)
{
validateListeners.add(listener);
}
 
public void removeValidateListener(InetDomainValidateListener listener)
{
validateListeners.remove(listener);
}
 
public void addCreatedListener(InetDomainCreatedListener listener)
{
createdListeners.add(listener);
}
 
public void removeCreatedListener(InetDomainCreatedListener listener)
{
createdListeners.remove(listener);
}
 
public void addModifiedListener(InetDomainModifiedListener listener)
{
modifiedListeners.add(listener);
}
 
public void removeModifiedListener(InetDomainModifiedListener listener)
{
modifiedListeners.remove(listener);
}
 
public void addBeforeDeleteListener(InetDomainBeforeDeleteListener listener)
{
beforeDeleteListeners.add(listener);
}
 
public void removeBeforeDeleteListener(InetDomainBeforeDeleteListener listener)
{
beforeDeleteListeners.remove(listener);
}
 
public void addDeletingListener(InetDomainDeletingListener listener)
{
deletingListeners.add(listener);
}
 
public void removeDeletingListener(InetDomainDeletingListener listener)
{
deletingListeners.remove(listener);
}
 
public void addDeletedListener(InetDomainDeletedListener listener)
{
deletedListeners.add(listener);
}
 
public void removeDeletedListener(InetDomainDeletedListener listener)
{
deletedListeners.remove(listener);
}
 
public Collection beforeDelete(User editor, InetDomain domain, Collection known)
throws ModelException
{
Collection cascade = new ArrayList();
 
for(Iterator i = beforeDeleteListeners.iterator(); i.hasNext(); ) {
InetDomainBeforeDeleteListener listener = (InetDomainBeforeDeleteListener)i.next();
Collection subcascade = listener.inetDomainBeforeDelete(editor, domain, known);
if(subcascade != null)
cascade.addAll(subcascade);
}
 
return cascade;
}
 
public void delete(User editor, InetDomain domain)
throws ModelException
{
// check rights
if(!domain.deleteableBy(editor))
throw new ModelSecurityException();
 
// inform deleting listeners
for(Iterator i = deletingListeners.iterator(); i.hasNext(); ) {
InetDomainDeletingListener listener = (InetDomainDeletingListener)i.next();
listener.inetDomainDeleting(editor, domain);
}
 
// backup copy
InetDomain oldDomain = new InetDomain(domain);
 
// delete it
store.delete(domain);
 
// inform deleted listeners
for(Iterator i = deletedListeners.iterator(); i.hasNext(); ) {
InetDomainDeletedListener listener = (InetDomainDeletedListener)i.next();
listener.inetDomainDeleted(editor, oldDomain);
}
}
 
public Collection listInetDomains(User editor)
throws ModelException
{
return listInetDomains(null, 0, 0, null, editor);
}
 
public Collection listInetDomains(CollectionInfo info, int rowsPerPage, int pageNumber,
Integer[] sortingKeys, User editor)
throws ModelException
{
if(editor.isSuperuser())
return store.listAllInetDomains(info, rowsPerPage, pageNumber, sortingKeys);
else
return store.listInetDomains(info, rowsPerPage, pageNumber, sortingKeys, editor);
}
 
public boolean areInetDomainsAvailable(User editor)
throws ModelException
{
if(editor.isSuperuser())
return true;
else
return store.countInetDomainsAvailable(editor) > 0;
}
 
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException
{
Collection domains = store.listOwnInetDomains(user);
 
Collection cascade = new ArrayList();
for(Iterator i = domains.iterator(); i.hasNext(); ) {
InetDomain d = (InetDomain)i.next();
if(known.contains(d)) continue;
 
known.add(d);
if(d.viewableBy(editor)) {
if(d.deleteableBy(editor))
cascade.add(new CascadeDeleteElement(d, CascadeDeleteElement.DELETE,
this.beforeDelete(editor, d, known)));
else
cascade.add(new CascadeDeleteElement(d, CascadeDeleteElement.FORBIDDEN, null));
}
else {
cascade.add(new CascadeDeleteElement(InetDomain.createLimitedCopy(d),
CascadeDeleteElement.FORBIDDEN, null));
}
}
 
return cascade;
}
 
public void userDeleting(User editor, User user)
throws ModelException
{
Collection domains = store.listOwnInetDomains(user);
 
for(Iterator i = domains.iterator(); i.hasNext(); ) {
delete(editor, (InetDomain)i.next());
}
}
 
public static final Integer SORT_NAME = new Integer(1);
 
public static final Comparator NAME_COMPARATOR = new NameComparator();
 
private static class NameComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof InetDomain) || !(o2 instanceof InetDomain))
throw new ClassCastException("not a InetDomain");
 
InetDomain a1 = (InetDomain)o1;
InetDomain a2 = (InetDomain)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getName().compareToIgnoreCase(a2.getName());
}
 
public boolean equals(Object obj)
{
return (obj instanceof NameComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
inetDomainManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (InetDomainStore)c.newInstance();
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static InetDomainManager inetDomainManager = null;
 
public static InetDomainManager getInstance()
{
return inetDomainManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasDeletedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasDeletedListener
{
/**
* called if some mail alias is just deleted.
*
* @param editor who is doing the operation
* @param mailAlias the mail alias deleted
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailAliasDeletedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailAliasDeleted(User editor, MailAlias mailAlias)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasCreatedListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasCreatedListener
{
/**
* called if new mail alias is just created.
*
* @param editor who is doing the operation
* @param mailAlias the new mail alias
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailAliasCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailAliasCreated(User editor, MailAlias mailAlias)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainModifiedListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainModifiedListener
{
/**
* called if some domain is just changed.
*
* @param editor who is doing the operation
* @param domain the domain in its new state
* @param oldDomain copy of domain as it was before the operation
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other InetDomainCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void inetDomainModified(User editor, InetDomain domain, InetDomain oldDomain)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserValidateListener.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface UserValidateListener
{
/**
* called if user information is about to be changed - by new or existing entry
*
* @param editor who is doing the operation
* @param user the user in its new state
* @param oldUser copy of user as it was before the operation
* @throws ModelException in case of any validation errors, validation will be stopped
* by first exception
*/
public void userValidate(User editor, User user, User oldUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserDeletingListener.java
0,0 → 1,17
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface UserDeletingListener
{
/**
* called just before some user is deleted.
*
* @param editor who is doing the operation
* @param user the user is being deleting
* @throws ModelException in case of any errors, no action should be done
* until this moment in other classes
*/
public void userDeleting(User editor, User user)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxModifiedListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailboxModifiedListener
{
/**
* called if some mailbox is just changed.
*
* @param editor who is doing the operation
* @param mailbox the mailbox in its new state
* @param oldMailbox copy of mailbox as it was before the operation
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailboxCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailboxModified(User editor, Mailbox mailbox, Mailbox oldMailbox)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasModifiedListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasModifiedListener
{
/**
* called if some mail alias is just changed.
*
* @param editor who is doing the operation
* @param mailAlias the mail alias in its new state
* @param oldMailAlias copy of mail alias as it was before the operation
* @throws ModelException in case of any *fatal* errors,
* Note: throw it on fatal errors only, because database transaction
* will be rolled back but any other MailAliasCreatedListeners might be already called
* and (possible) they will not restore their original state.
*/
public void mailAliasModified(User editor, MailAlias mailAlias, MailAlias oldMailAlias)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserValidateListener.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserValidateListener
{
/**
* called if system user information is about to be changed - by new or existing entry
*
* @param editor who is doing the operation
* @param systemUser the user in its new state
* @param oldSystemUser copy of user as it was before the operation
* @throws ModelException in case of any validation errors, validation will be stopped
* by first exception
*/
public void systemUserValidate(User editor, SystemUser systemUser, SystemUser oldSystemUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserDeletingListener.java
0,0 → 1,17
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserDeletingListener
{
/**
* called just before some system user is deleted.
*
* @param editor who is doing the operation
* @param systemUser the system user is being deleting
* @throws ModelException in case of any errors, no action should be done
* until this moment in other classes
*/
public void systemUserDeleting(User editor, SystemUser systemUser)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailboxBeforeDeleteListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
public interface MailboxBeforeDeleteListener
{
/**
* called if some mailbox is about to be deleted.
*
* @param editor who is doing the operation
* @param mailbox the mailbox to delete
* @param known Collection(Object) - already known objects which are touched by current operation,
* to avoid loops
* @return Collection(CascadeDeleteElement) - object which are touched by deleting the mailbox
*/
public Collection mailboxBeforeDelete(User editor, Mailbox mailbox, Collection known)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasBeforeDeleteListener.java
0,0 → 1,20
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
public interface MailAliasBeforeDeleteListener
{
/**
* called if some mail alias is about to be deleted.
*
* @param editor who is doing the operation
* @param alias the mail alias to delete
* @param known Collection(Object) - already known objects which are touched by current operation,
* to avoid loops
* @return Collection(CascadeDeleteElement)
* - object which are touched by deleting the mail alias
*/
public Collection mailAliasBeforeDelete(User editor, MailAlias mailAlias, Collection known)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomainBeforeDeleteListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
public interface InetDomainBeforeDeleteListener
{
/**
* called if some domain is about to be deleted.
*
* @param editor who is doing the operation
* @param domain the domain to delete
* @param known Collection(Object) - already known objects which are touched by current operation,
* to avoid loops
* @return Collection(CascadeDeleteElement) - object which are touched by deleting the domain
*/
public Collection inetDomainBeforeDelete(User editor, InetDomain domain, Collection known)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserBeforeDeleteListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
public interface UserBeforeDeleteListener
{
/**
* called if some user is about to be deleted.
*
* @param editor who is doing the operation
* @param user the user to delete
* @param known Collection(Object) - already known objects which are touched by current operation,
* to avoid loops
* @return Collection(CascadeDeleteElement) - object which are touched by deleting the user
*/
public Collection userBeforeDelete(User editor, User user, Collection known)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUserBeforeDeleteListener.java
0,0 → 1,19
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
public interface SystemUserBeforeDeleteListener
{
/**
* called if some system user is about to be deleted.
*
* @param editor who is doing the operation
* @param user the user to delete
* @param known Collection(Object) - already known objects which are touched by current operation,
* to avoid loops
* @return Collection(CascadeDeleteElement) - object which are touched by deleting the user
*/
public Collection systemUserBeforeDelete(User editor, SystemUser user, Collection known)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/GeneralModelObject.java
0,0 → 1,146
package ak.hostadmiral.core.model;
 
import java.util.Date;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
public abstract class GeneralModelObject
implements ModelObject
{
private Long id;
private Boolean enabled;
private String comment;
private Date modStamp;
private User modUser;
 
protected GeneralModelObject()
{
}
 
protected GeneralModelObject(GeneralModelObject origin)
{
this.id = origin.id;
this.enabled = origin.enabled;
this.comment = origin.comment;
this.modStamp = origin.modStamp;
this.modUser = origin.modUser;
}
 
/**
* @return true if the object is not yet saved in DB
*/
public boolean isNew()
{
return (id == null);
}
 
/**
*
* @hibernate.id generator-class="native"
*/
public Long getId()
{
return id;
}
 
protected void setId(Long id)
{
this.id = id;
}
 
/**
*
* @hibernate.property
*/
public Boolean getEnabled()
{
return enabled;
}
 
protected void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
 
public void setEnabled(User editor, Boolean enabled)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.enabled = enabled;
}
 
/**
*
* @hibernate.property
*/
public String getComment()
{
return comment;
}
 
protected void setComment(String comment)
{
this.comment = comment;
}
 
public void setComment(User editor, String comment)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.comment = comment;
}
 
/**
*
* @hibernate.timestamp column="mod_stamp"
*/
public Date getModStamp()
{
return modStamp;
}
 
protected void setModStamp(Date modStamp)
{
this.modStamp = modStamp;
}
 
/**
*
* @hibernate.many-to-one column="mod_user"
*/
public User getModUser()
{
return modUser;
}
 
protected void setModUser(User modUser)
{
this.modUser = modUser;
}
 
public String toString()
{
return getClass().getName() + " [" + getId() + "]";
}
 
public boolean equals(Object o)
{
if(o == null) return false;
if(!getClass().isInstance(o)) return false;
 
ModelObject u = (ModelObject)o;
return (getId() != null) && (u.getId() != null) && (getId().equals(u.getId()));
}
 
public int hashCode()
{
if(getId() == null)
return 0;
else
return getId().hashCode();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/InetDomain.java
0,0 → 1,139
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="domains"
*/
public class InetDomain
extends GeneralModelObject
{
private String name;
private User owner;
private InetDomain origin; // save original object state before any changes
 
protected InetDomain()
{
}
 
protected InetDomain(InetDomain origin)
{
super(origin);
this.name = origin.name;
this.owner = origin.owner;
}
 
protected InetDomain getOrigin()
{
return origin;
}
 
protected void backupMe()
{
if(origin == null)
origin = new InetDomain(this);
}
 
protected void resetOrigin()
{
origin = null;
}
 
/**
*
* @hibernate.property
*/
public String getName()
{
return name;
}
 
protected void setName(String name)
{
this.name = name;
}
 
public void setName(User editor, String name)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.name = name;
}
 
/**
*
* @hibernate.many-to-one
*/
public User getOwner()
{
return owner;
}
 
protected void setOwner(User owner)
{
this.owner = owner;
}
 
public void setOwner(User editor, User owner)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
backupMe();
this.owner = owner;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_DOMAIN;
}
 
public String getIdentKey()
{
return ak.hostadmiral.core.resources.CoreResources.IDENT_DOMAIN;
}
 
public Object[] getIdentParams()
{
return new Object[] { getName() };
}
 
public boolean viewableBy(User user)
{
return user.isSuperuser() || user.equals(owner);
}
 
public boolean editableBy(User user)
{
return user.isSuperuser();
}
 
public boolean deleteableBy(User user)
{
return user.isSuperuser();
}
 
protected static boolean allowedToCreate(InetDomainManager manager, User editor)
throws ModelException
{
return editor.isSuperuser();
}
 
protected static InetDomain createLimitedCopy(InetDomain origin)
{
InetDomain d = new InetDomain();
d.setName(origin.getName());
return d;
}
 
public String toString()
{
return "InetDomain id=[" + getId() + "] name=[" + name + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/SystemUser.java
0,0 → 1,164
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
 
/**
*
* @hibernate.class table="systemusers"
*/
public class SystemUser
extends GeneralModelObject
{
/** user id in the OS */
private Integer uid;
private String name;
private User owner;
private SystemUser origin; // save original object state before any changes
 
protected SystemUser()
{
}
 
protected SystemUser(SystemUser origin)
{
super(origin);
this.uid = origin.uid;
this.name = origin.name;
this.owner = origin.owner;
}
 
protected SystemUser getOrigin()
{
return origin;
}
 
protected void backupMe()
{
if(origin == null)
origin = new SystemUser(this);
}
 
protected void resetOrigin()
{
origin = null;
}
 
/**
*
* @hibernate.property
*/
public Integer getUid()
{
return uid;
}
 
protected void setUid(Integer uid)
{
this.uid = uid;
}
 
public void setUid(User editor, Integer uid)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.uid = uid;
}
 
/**
*
* @hibernate.property
*/
public String getName()
{
return name;
}
 
protected void setName(String name)
{
this.name = name;
}
 
public void setName(User editor, String name)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.name = name;
}
 
/**
*
* @hibernate.many-to-one
*/
public User getOwner()
{
return owner;
}
 
protected void setOwner(User owner)
{
this.owner = owner;
}
 
public void setOwner(User editor, User owner)
throws ModelException
{
if(!editableBy(editor))
throw new ModelSecurityException();
 
this.owner = owner;
}
 
public String getTypeKey()
{
return ak.hostadmiral.core.resources.CoreResources.TYPE_SYSTEM_USER;
}
 
public String getIdentKey()
{
return ak.hostadmiral.core.resources.CoreResources.IDENT_SYSTEM_USER;
}
 
public Object[] getIdentParams()
{
return new Object[] { getName(), getUid() };
}
 
public boolean viewableBy(User user)
{
return user.isSuperuser() || (owner == null) || user.equals(owner);
}
 
public boolean editableBy(User user)
{
return user.isSuperuser();
}
 
public boolean deleteableBy(User user)
{
return user.isSuperuser();
}
 
protected static boolean allowedToCreate(SystemUserManager manager, User editor)
throws ModelException
{
return editor.isSuperuser();
}
 
protected static SystemUser createLimitedCopy(SystemUser origin)
{
SystemUser u = new SystemUser();
u.setUid(origin.getUid());
u.setName(origin.getName());
return u;
}
 
public String toString()
{
return "SystemUser id=[" + getId() + "] uid=[" + uid + "] name=[" + name + "]";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/MailAliasDestinationManager.java
0,0 → 1,136
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Comparator;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.core.model.store.MailAliasDestinationStore;
 
public class MailAliasDestinationManager
implements
ConfigInit
{
// FIXME create, delete and modify listeners are not implemented, bacause
// all operations are done via MailAliasManager. Do we need them?
 
private MailAliasDestinationStore store;
 
public MailAliasDestinationManager()
throws ModelException
{
}
 
public MailAliasDestination create(User editor)
throws ModelException
{
if(!allowedToCreate(editor)) throw new ModelSecurityException();
 
return new MailAliasDestination();
}
 
public boolean allowedToCreate(User editor)
throws ModelException
{
return MailAliasDestination.allowedToCreate(this, editor);
}
 
public MailAliasDestination get(User editor, Long id)
throws ModelException
{
MailAliasDestination dest = store.get(id);
 
if(!dest.viewableBy(editor))
throw new ModelSecurityException();
 
return dest;
}
 
public void save(User editor, MailAliasDestination mailAliasDestination)
throws ModelException
{
if(!mailAliasDestination.editableBy(editor))
throw new ModelSecurityException();
 
//mailAliasDestination.setModUser(editor); // FIXME
// FIXME: the mod_user is not set when changing a destination as element of collection
 
store.save(mailAliasDestination);
}
 
public void delete(User editor, MailAliasDestination mailAliasDestination)
throws ModelException
{
if(!mailAliasDestination.deleteableBy(editor))
throw new ModelSecurityException();
 
store.delete(mailAliasDestination);
}
 
public Collection listMailAliasesDestination(MailAlias alias)
throws ModelException
{
return store.listMailAliasesDestination(alias);
}
 
public boolean areMailAliasesDestinationsAvailable(User editor)
throws ModelException
{
return true;
}
 
public static final Comparator EMAIL_COMPARATOR = new EmailComparator();
 
private static class EmailComparator
implements Comparator
{
public int compare(Object o1, Object o2)
{
if(!(o1 instanceof MailAliasDestination) || !(o2 instanceof MailAliasDestination))
throw new ClassCastException("not a MailAliasDestination");
 
MailAliasDestination a1 = (MailAliasDestination)o1;
MailAliasDestination a2 = (MailAliasDestination)o2;
 
if(a1 == null && a2 == null)
return 0;
else if(a1 == null && a2 != null)
return -1;
else if(a1 != null && a2 == null)
return 1;
else
return a1.getEmail().compareToIgnoreCase(a2.getEmail());
}
 
public boolean equals(Object obj)
{
return (obj instanceof EmailComparator);
}
}
 
public void init(Map params)
throws ModelException
{
try {
mailAliasDestinationManager = this;
 
Class c = Class.forName(((String[])params.get("store"))[0]);
store = (MailAliasDestinationStore)c.newInstance();
}
catch(Exception ex) {
throw new ModelException(ex);
}
}
 
private static MailAliasDestinationManager mailAliasDestinationManager = null;
 
public static MailAliasDestinationManager getInstance()
{
return mailAliasDestinationManager;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/UserLogin.java
0,0 → 1,114
package ak.hostadmiral.core.model;
 
import java.util.Date;
 
/**
*
* @hibernate.class table="userlogins"
*/
public class UserLogin
{
private Long id;
private User user;
private String login;
private Date loginTime;
private Boolean success;
private String ip;
 
protected UserLogin()
{
}
 
protected UserLogin(User user, String login, Date loginTime, Boolean success, String ip)
{
this.user = user;
this.login = login;
this.loginTime = loginTime;
this.success = success;
this.ip = ip;
}
 
/**
*
* @hibernate.id generator-class="native"
*/
public Long getId()
{
return id;
}
 
protected void setId(Long id)
{
this.id = id;
}
 
/**
*
* @hibernate.many-to-one column="usr"
*/
public User getUser()
{
return user;
}
 
protected void setUser(User user)
{
this.user = user;
}
 
/**
*
* @hibernate.property
*/
public String getLogin()
{
return login;
}
 
protected void setLogin(String login)
{
this.login = login;
}
 
/**
*
* @hibernate.property
*/
public Date getLoginTime()
{
return loginTime;
}
 
protected void setLoginTime(Date loginTime)
{
this.loginTime = loginTime;
}
 
/**
*
* @hibernate.property
*/
public Boolean getSuccess()
{
return success;
}
 
protected void setSuccess(Boolean success)
{
this.success = success;
}
 
/**
*
* @hibernate.property
*/
public String getIp()
{
return ip;
}
 
protected void setIp(String ip)
{
this.ip = ip;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/PasswordStoreCrypt.java
0,0 → 1,33
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.DigestCrypt;
 
/**
*
* @hibernate.subclass discriminator-value="crypt"
*/
public class PasswordStoreCrypt
extends PasswordStoreAbstract
{
public PasswordStoreCrypt()
{
digest = "crypt";
}
 
protected String encode(String password)
throws ModelException
{
return DigestCrypt.crypt(password);
}
 
public boolean checkPassword(String password)
throws ModelException
{
if(this.password == null || this.password.length() < 3) return false;
 
String salt = this.password.substring(0, 2);
String crypted = DigestCrypt.crypt(salt, password);
return crypted.equals(this.password);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/PasswordStoreMd5.java
0,0 → 1,23
package ak.hostadmiral.core.model;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.DigestMd5;
 
/**
*
* @hibernate.subclass discriminator-value="MD5"
*/
public class PasswordStoreMd5
extends PasswordStoreAbstract
{
public PasswordStoreMd5()
{
digest = "MD5";
}
 
protected String encode(String password)
throws ModelException
{
return DigestMd5.encode(password);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/TransactionController.java
0,0 → 1,34
package ak.hostadmiral.core.model;
 
import java.util.Map;
import java.util.HashMap;
import ak.hostadmiral.util.ModelException;
 
// FIXME: implement it
public class TransactionController
{
private static TransactionController transactionController = null;
 
public static TransactionController getInstance()
{
return transactionController;
}
 
private Map listeners = new HashMap();
 
public void beginTransaction(Object transaction)
{
}
 
public void commitTransaction(Object transaction)
{
}
 
public void rollbackTransaction(Object transaction)
{
}
 
public void addObject(Object transaction, Object object)
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/TransactionListener.java
0,0 → 1,43
package ak.hostadmiral.core.model;
 
import java.util.Collection;
import ak.hostadmiral.util.ModelException;
 
/**
* One could implement this interface to receive transaction start, commit and
* rollback events.
* An object will be informed about this events if it actualy interacts with the
* transaction, e.g. if it is registered as listener for object modifications.
*/
public interface TransactionListener
{
/**
* called when this object first time interacts with given transaction,
* before any other callbacks of this object in the transaction
*
* @param id some transaction identifier, the same for all transaction* methods
* @throws ModelException if transaction must be aborted immediately
*/
public void transactionBegin(Object id)
throws ModelException;
 
/**
* called when transaction is commited
*
* @param id some transaction identifier, the same as in corresponding transactionBegin
* method call
* @throws ModelException logged, but ignored
*/
public void transactionCommited(Object id)
throws ModelException;
 
/**
* called when transaction is rolled back
*
* @param id some transaction identifier, the same as in corresponding transactionBegin
* method call
* @throws ModelException logged, but ignored
*/
public void transactionRolledBack(Object id)
throws ModelException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/ModelObject.java
0,0 → 1,18
package ak.hostadmiral.core.model;
 
public interface ModelObject
{
public Long getId();
 
public String getTypeKey();
 
public String getIdentKey();
 
public Object[] getIdentParams();
 
public boolean viewableBy(User user);
 
public boolean editableBy(User user);
 
public boolean deleteableBy(User user);
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/model/CascadeDeleteElement.java
0,0 → 1,55
package ak.hostadmiral.core.model;
 
import java.util.Collection;
 
public class CascadeDeleteElement
{
public static final int FORBIDDEN = 1;
public static final int DELETE = 2;
public static final int CHANGE = 3;
 
private ModelObject object;
private int effect;
private Collection cascade; // Collection(CascadeDeleteElement)
 
public CascadeDeleteElement()
{
}
 
public CascadeDeleteElement(ModelObject object, int effect, Collection cascade)
{
this.object = object;
this.effect = effect;
this.cascade = cascade;
}
 
public ModelObject getObject()
{
return object;
}
 
public void setObject(ModelObject object)
{
this.object = object;
}
 
public int getEffect()
{
return effect;
}
 
public void setEffect(int effect)
{
this.effect = effect;
}
 
public Collection getCascade()
{
return cascade;
}
 
public void setCascade(Collection cascade)
{
this.cascade = cascade;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/LoginFilter.java
0,0 → 1,193
package ak.hostadmiral.core.servlet;
 
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.Principal;
import java.security.AccessControlException;
 
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.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
 
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.core.servlet.LoginInfo;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
 
/**
* Ensures that user is logged in to the system to process its request.
*/
public class LoginFilter
implements Filter
{
private static final Logger logger = Logger.getLogger(LoginFilter.class);
 
private FilterConfig filterConfig;
private String loginUrl;
private String loginServlet;
private List passUrls = new ArrayList();
private List passMasks = new ArrayList();
 
public void init(FilterConfig filterConfig)
throws ServletException
{
// get config
this.filterConfig = filterConfig;
 
if(filterConfig == null)
throw new ServletException("No configuration for the filter");
 
// get login url
loginUrl = filterConfig.getInitParameter("loginUrl");
 
if(loginUrl == null)
throw new ServletException("No login URL specified");
 
// ensure it's absolute path
if(!loginUrl.startsWith("/"))
loginUrl = "/" + loginUrl;
 
// get servlet part ot the url
int qPos = loginUrl.indexOf("?");
 
if(qPos < 0)
loginServlet = loginUrl;
else
loginServlet = loginUrl.substring(0, qPos);
 
// get pass through URLs
String passUrlsStr = filterConfig.getInitParameter("passUrls");
if(passUrlsStr != null) {
String[] urls = passUrlsStr.split("\\s*;\\s*");
 
for(int i = 0; i < urls.length; i++) {
if(urls[i].endsWith("*")) {
passMasks.add(urls[i].substring(0, urls[i].length()-1));
}
else {
passUrls.add(urls[i]);
}
}
}
 
// avoid loop
if(!isPassThrough(loginServlet)) {
passUrls.add(loginServlet);
}
}
 
private boolean isPassThrough(String url)
{
for(int i = 0; i < passUrls.size(); i++) {
if(url.equals((String)passUrls.get(i))) return true;
}
 
for(int i = 0; i < passMasks.size(); i++) {
if(url.startsWith((String)passMasks.get(i))) return true;
}
 
return false;
}
 
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
boolean processNext;
 
if(!(request instanceof HttpServletRequest))
throw new ServletException("Do not know how to handle non-HTTP requests");
if(!(response instanceof HttpServletResponse))
throw new ServletException("Do not know how to handle non-HTTP responses");
 
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
 
logger.debug("Requested " + httpRequest.getServletPath());
 
if(isPassThrough(httpRequest.getServletPath())) {
processNext = true;
logger.debug("pass through");
}
else {
try {
HttpSession session = httpRequest.getSession(false);
 
if(session == null)
throw new AccessControlException("No session");
 
Object userObj = session.getAttribute(SessionKeys.USER);
if(userObj == null) {
// try to relogin
Object loginInfoObj = session.getAttribute(SessionKeys.LOGIN_INFO);
if(loginInfoObj == null)
throw new AccessControlException("No user");
 
if(!(loginInfoObj instanceof LoginInfo))
throw new ServletException(
"Wrong type of login info information: "
+ loginInfoObj.getClass().getName());
 
try {
userObj = UserManager.getInstance().get(((LoginInfo)loginInfoObj).getId());
}
catch(ModelException ex) {
throw new AccessControlException("No user");
}
 
if(userObj == null)
throw new AccessControlException("No user");
 
session.setAttribute(SessionKeys.USER, userObj);
logger.debug("User re-logined: " + userObj);
}
else {
if(!(userObj instanceof User))
throw new ServletException(
"Wrong type of user information: " + userObj.getClass().getName());
 
logger.debug("User found - OK");
}
 
processNext = true;
}
catch(AccessControlException ex) {
String redirectUrl;
try {
redirectUrl = httpRequest.getContextPath() + loginUrl
+ BackPath.findBackPath(httpRequest).getForwardParams();
}
catch(Exception ex2) {
logger.error("Cannot get forward redirect", ex2);
redirectUrl = httpRequest.getContextPath() + loginUrl;
}
 
logger.info("Redirect because of '" + ex.getMessage() + "' to " + redirectUrl);
httpResponse.sendRedirect(httpResponse.encodeRedirectURL(redirectUrl));
 
processNext = false;
}
}
 
if(processNext) { // no problems found
chain.doFilter(request, response);
}
}
 
public void destroy()
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/HibernateFilter.java
0,0 → 1,91
package ak.hostadmiral.core.servlet;
 
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.Principal;
import java.security.AccessControlException;
 
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.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
 
import org.hibernate.HibernateException;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
 
public class HibernateFilter
implements Filter
{
private static final Logger logger = Logger.getLogger(HibernateFilter.class);
 
private FilterConfig filterConfig;
 
public void init(FilterConfig filterConfig)
throws ServletException
{
this.filterConfig = filterConfig;
}
 
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
try {
logger.info("begin transaction");
HibernateUtil.beginTransaction();
 
chain.doFilter(request, response);
 
if(HibernateUtil.isTransactionOpen()) {
if(Boolean.TRUE.equals(request.getAttribute("TRANSACTION_FAILED"))) {
logger.info("rollback transaction because it is marked as failed");
HibernateUtil.rollbackTransaction();
}
else {
logger.info("commit transaction");
HibernateUtil.commitTransaction();
}
}
}
catch(Exception ex) {
logger.error("exception by program execution", ex);
try {
if(HibernateUtil.isTransactionOpen()) {
logger.info("rollback transaction because of exception");
HibernateUtil.rollbackTransaction();
}
}
catch(Exception ex2) {
logger.error("cannot rollback transaction", ex2);
}
 
if(ex instanceof ServletException)
throw (ServletException)ex;
else
throw new ServletException("Internal server error");
}
 
try {
HibernateUtil.closeSession();
}
catch(Exception ex) {
logger.error("cannot close session", ex);
}
}
 
public void destroy()
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/SessionKeys.java
0,0 → 1,7
package ak.hostadmiral.core.servlet;
 
public abstract class SessionKeys
{
public static final String USER = "user";
public static final String LOGIN_INFO = LoginInfo.class.getName();
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/LoginInfo.java
0,0 → 1,19
package ak.hostadmiral.core.servlet;
 
import java.io.Serializable;
 
public class LoginInfo
implements Serializable
{
private Long id;
 
public LoginInfo(Long id)
{
this.id = id;
}
 
public Long getId()
{
return id;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/ConfigServlet.java
0,0 → 1,39
package ak.hostadmiral.core.servlet;
 
import java.io.IOException;
 
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
 
import org.apache.log4j.Logger;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.core.config.Configurator;
 
public class ConfigServlet
extends GenericServlet
{
private static final Logger logger = Logger.getLogger(ConfigServlet.class);
 
public void init()
throws ServletException
{
try {
Configurator.getInstance().setDefaultStream(getServletContext().getResourceAsStream(
"/WEB-INF/conf/hostadmiral_config.xml.default"));
Configurator.getInstance().setUserStream(getServletContext().getResourceAsStream(
"/WEB-INF/conf/hostadmiral_config.xml"));
Configurator.getInstance().configure();
}
catch(ModelException ex) {
throw new ServletException(ex);
}
}
 
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/ProfilerFilter.java
0,0 → 1,47
package ak.hostadmiral.core.servlet;
 
import java.io.IOException;
import java.net.URLEncoder;
 
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.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
 
/**
* Prints out time of request execution.
*/
public class ProfilerFilter
implements Filter
{
private static final Logger logger = Logger.getLogger(ProfilerFilter.class);
 
public void init(FilterConfig filterConfig)
throws ServletException
{
}
 
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
logger.debug("begin");
 
long t1 = System.currentTimeMillis();
chain.doFilter(request, response);
long t2 = System.currentTimeMillis();
 
logger.info((t2 - t1) + " ms");
}
 
public void destroy()
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/servlet/EncodingFilter.java
0,0 → 1,37
package ak.hostadmiral.core.servlet;
 
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;
 
public class EncodingFilter
implements Filter
{
public static final String ENCODING = "UTF-8";
 
private FilterConfig filterConfig;
 
public void init(FilterConfig filterConfig)
throws ServletException
{
this.filterConfig = filterConfig;
}
 
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
if(request.getCharacterEncoding() == null)
request.setCharacterEncoding(ENCODING);
 
chain.doFilter(request, response);
}
 
public void destroy()
{
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/config/Configurator.java
0,0 → 1,182
package ak.hostadmiral.core.config;
 
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.SAXException;
 
import org.apache.log4j.Logger;
import org.apache.commons.digester.Digester;
import org.hibernate.HibernateException;
 
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.hibernate.HibernateUtil;
import ak.hostadmiral.core.model.*;
 
public class Configurator
{
public static final int CONFIG_VERSION = 1;
 
private static final Logger logger = Logger.getLogger(Configurator.class);
 
private InputStream defaultStream;
private InputStream userStream;
 
public void setDefaultStream(InputStream defaultStream)
{
this.defaultStream = defaultStream;
}
 
public void setUserStream(InputStream userStream)
{
this.userStream = userStream;
}
 
private void checkConfigVersion(String name, ConfigRoot config)
throws ModelException
{
if(config.getVersionMajor() == 0)
throw new ModelException("Cannot get version of " + name + " config");
 
if(config.getVersionMajor() != CONFIG_VERSION)
throw new ModelException("Version " + CONFIG_VERSION + " of " + name
+ " config is required but " + config.getVersionMajor() + " found");
}
 
public void configure()
throws ModelException
{
ConfigRoot config;
try {
// get config
ConfigRoot defaultConfig = readConfig(defaultStream);
logger.debug("default:\n" + defaultConfig);
checkConfigVersion("default", defaultConfig);
 
ConfigRoot userConfig = readConfig(userStream);
logger.debug("user:\n" + userConfig);
checkConfigVersion("user", userConfig);
 
config = defaultConfig.merge(userConfig);
logger.info("result config:\n" + config);
}
catch(Exception ex) {
throw new ModelException("Cannot read config: " + ex);
}
 
// init data source
ConfigDataSource cs = config.getDataSource();
try {
HibernateUtil.configure(cs.getDriver(), cs.getUserName(), cs.getPassword(),
cs.getUrl(), cs.getDialect());
}
catch(HibernateException ex) {
throw new ModelException("Cannot init data source: " + ex);
}
 
// init classes
for(Iterator i = config.getInitialization().iterator(); i.hasNext(); ) {
ConfigInitialization ci = (ConfigInitialization)i.next();
 
if(ci.getIgnore()) continue;
 
// get class
Class c = null;
try {
c = Class.forName(ci.getClassName());
}
catch(ClassCastException ex) {
logger.error("Class " + ci.getClassName() + " has wrong type", ex);
}
catch(Exception ex) {
logger.error("Cannot get class " + ci.getClassName(), ex);
}
if(c == null) continue;
 
if(ConfigInit.class.isAssignableFrom(c)) {
ConfigInit o = null;
try {
o = (ConfigInit)c.newInstance();
}
catch(Exception ex) {
logger.error("Cannot get instance of class " + c.getClass().getName(), ex);
}
if(o == null) continue;
 
Map params = new HashMap();
for(Iterator j = ci.getInitParam().iterator(); j.hasNext(); ) {
ConfigInitParam p = (ConfigInitParam)j.next();
params.put(p.getName(), (String[])p.getValues().toArray(new String[0]));
}
 
try {
o.init(params);
}
catch(ModelException ex) {
logger.error("Cannot initialize instance of class "
+ c.getClass().getName(), ex);
}
}
else {
logger.error("Class " + c.getClass().getName()
+ " does not implement ak.hostadmiral.util.ConfigInit interface");
}
}
}
 
private ConfigRoot readConfig(InputStream in)
throws IOException, SAXException
{
return (ConfigRoot)createDigester().parse(in);
}
 
private Digester createDigester()
{
Digester digester = new Digester();
digester.setValidating(false);
 
digester.addObjectCreate("hostadmiral", ConfigRoot.class);
digester.addSetProperties("hostadmiral/version", "major", "versionMajor");
digester.addSetProperties("hostadmiral/version", "minor", "versionMinor");
 
digester.addObjectCreate("hostadmiral/datasource", ConfigDataSource.class);
digester.addBeanPropertySetter("hostadmiral/datasource/type", "type");
digester.addBeanPropertySetter("hostadmiral/datasource/settings/driver", "driver");
digester.addBeanPropertySetter("hostadmiral/datasource/settings/username", "userName");
digester.addBeanPropertySetter("hostadmiral/datasource/settings/password", "password");
digester.addBeanPropertySetter("hostadmiral/datasource/settings/url", "url");
digester.addBeanPropertySetter("hostadmiral/datasource/settings/dialect", "dialect");
digester.addSetNext("hostadmiral/datasource", "setDataSource");
 
digester.addObjectCreate("hostadmiral/initializations/initialization",
ConfigInitialization.class);
digester.addBeanPropertySetter("hostadmiral/initializations/initialization/class",
"className");
digester.addBeanPropertySetter("hostadmiral/initializations/initialization/ignore",
"ignore");
digester.addSetNext("hostadmiral/initializations/initialization", "addInitialization");
 
digester.addObjectCreate("hostadmiral/initializations/initialization/init-param",
ConfigInitParam.class);
digester.addBeanPropertySetter(
"hostadmiral/initializations/initialization/init-param/param-name", "name");
digester.addBeanPropertySetter(
"hostadmiral/initializations/initialization/init-param/param-value", "value");
digester.addSetNext("hostadmiral/initializations/initialization/init-param",
"addInitParam");
 
return digester;
}
 
private static Configurator configurator;
 
public static Configurator getInstance()
{
if(configurator == null) configurator = new Configurator();
 
return configurator;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/config/ConfigInitParam.java
0,0 → 1,43
package ak.hostadmiral.core.config;
 
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
 
public class ConfigInitParam
{
private String name;
private List values = new ArrayList();
 
public String getName()
{
return name;
}
 
public void setName(String name)
{
this.name = name;
}
 
public List getValues()
{
return values;
}
 
public void setValue(String value)
{
values.add(value);
}
 
public String toString()
{
StringBuffer valuesStr = new StringBuffer();
for(Iterator i = values.iterator(); i.hasNext(); ) {
String s = (String)i.next();
if(valuesStr.length() > 0) valuesStr.append(";\n\t\t\t\t");
valuesStr.append(s);
}
 
return "\t\t\t" + name + "=" + valuesStr + "\n";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/config/ConfigRoot.java
0,0 → 1,87
package ak.hostadmiral.core.config;
 
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import ak.hostadmiral.util.ModelException;
 
public class ConfigRoot
{
private int versionMajor;
private int versionMinor;
private ConfigDataSource dataSource;
private List initializations = new ArrayList(); // List(ConfigInitialization)
 
public int getVersionMajor()
{
return versionMajor;
}
 
public void setMajor(String major)
{
this.versionMajor = Integer.parseInt(major);
}
 
public int getVersionMinor()
{
return versionMinor;
}
 
public void setMinor(String minor)
{
this.versionMinor = Integer.parseInt(minor);
}
 
public ConfigDataSource getDataSource()
{
return dataSource;
}
 
public void setDataSource(ConfigDataSource dataSource)
{
this.dataSource = dataSource;
}
 
public List getInitialization()
{
return initializations;
}
 
public void addInitialization(ConfigInitialization initialization)
{
initializations.add(initialization);
}
 
public ConfigRoot merge(ConfigRoot second)
throws ModelException
{
if(second == null) return this;
 
if(this.versionMajor != second.versionMajor)
throw new ModelException("First config has version " + this.versionMajor
+ ", second - " + second.versionMajor);
 
this.dataSource = dataSource.merge(second.dataSource);
 
for(Iterator i = second.initializations.iterator(); i.hasNext(); ) {
ConfigInitialization ci = (ConfigInitialization)i.next();
 
this.initializations.remove(ci);
this.initializations.add(ci);
}
 
return this;
}
 
public String toString()
{
StringBuffer initStr = new StringBuffer();
for(Iterator i = initializations.iterator(); i.hasNext(); ) {
ConfigInitialization ci = (ConfigInitialization)i.next();
initStr.append(ci);
}
 
return "hostadmiral config v" + versionMajor + "." + versionMinor + "\n"
+ dataSource + "\n\tinitializations:\n" + initStr.toString() + "end of config";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/config/ConfigInitialization.java
0,0 → 1,77
package ak.hostadmiral.core.config;
 
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
 
public class ConfigInitialization
{
private String className;
private boolean ignore = false;
private List params = new ArrayList(); // List(ConfigInitParam)
 
public String getClassName()
{
return className;
}
 
public void setClassName(String className)
{
this.className = className;
}
 
public boolean getIgnore()
{
return ignore;
}
 
public void setIgnore(boolean ignore)
{
this.ignore = ignore;
}
 
public void setIgnore(String ignore)
{
this.ignore = Boolean.valueOf(ignore).booleanValue();
}
 
public List getInitParam()
{
return params;
}
 
public void addInitParam(ConfigInitParam param)
{
params.add(param);
}
 
public boolean equals(Object obj)
{
if(!(obj instanceof ConfigInitialization)) return false;
 
ConfigInitialization second = (ConfigInitialization)obj;
 
return (this.className != null && second.className != null
&& this.className.equals(second.className));
}
 
public int hashCode()
{
if(className == null)
return 0;
else
return className.hashCode();
}
 
public String toString()
{
StringBuffer paramsStr = new StringBuffer();
for(Iterator i = params.iterator(); i.hasNext(); ) {
ConfigInitParam p = (ConfigInitParam)i.next();
paramsStr.append(p);
}
 
return "\t\t" + className + (ignore ? " (ignore)" : "") + ":\n"
+ paramsStr.toString() + "\n";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/config/ConfigDataSource.java
0,0 → 1,96
package ak.hostadmiral.core.config;
 
public class ConfigDataSource
{
private String type;
private String driver;
private String userName;
private String password;
private String url;
private String dialect;
 
public String getType()
{
return type;
}
 
public void setType(String type)
{
this.type = type;
}
 
public String getDriver()
{
return driver;
}
 
public void setDriver(String driver)
{
this.driver = driver;
}
 
public String getUserName()
{
return userName;
}
 
public void setUserName(String userName)
{
this.userName = userName;
}
 
public String getPassword()
{
return password;
}
 
public void setPassword(String password)
{
this.password = password;
}
 
public String getUrl()
{
return url;
}
 
public void setUrl(String url)
{
this.url = url;
}
 
public String getDialect()
{
return dialect;
}
 
public void setDialect(String dialect)
{
this.dialect = dialect;
}
 
public ConfigDataSource merge(ConfigDataSource second)
{
if(second == null) return this;
 
if(second.type != null) this.type = second.type;
if(second.driver != null) this.driver = second.driver;
if(second.userName != null) this.userName = second.userName;
if(second.password != null) this.password = second.password;
if(second.url != null) this.url = second.url;
if(second.dialect != null) this.dialect = second.dialect;
 
return this;
}
 
public String toString()
{
return "\tdata source: " + type + "\n"
+ "\t\tdriver: " + driver + "\n"
+ "\t\tuserName: " + userName + "\n"
+ "\t\tpassword: "
+ ((password == null || password.equals("")) ? "(not set)" : "(set)") + "\n"
+ "\t\turl: " + url + "\n"
+ "\t\tdialect: " + dialect + "\n";
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/LoginAction.java
0,0 → 1,70
package ak.hostadmiral.core.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.backpath.BackPath;
 
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.servlet.LoginInfo;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class LoginAction
extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
 
if("show".equals(mapping.getParameter())) {
return mapping.findForward("default");
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
User user = UserManager.getInstance().loginUser((String)theForm.get("login"),
(String)theForm.get("password"), request.getRemoteAddr());
 
if(user == null) {
Thread.sleep(1000); // FIXME: make this delay configurable
 
ActionErrors errors = new ActionErrors();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionError(CoreResources.LOGIN_FAILED));
saveErrors(request, errors);
return mapping.getInputForward();
}
else {
request.getSession().setAttribute(SessionKeys.USER, user);
request.getSession().setAttribute(SessionKeys.LOGIN_INFO,
new LoginInfo(user.getId()));
request.getSession().setAttribute(Globals.LOCALE_KEY, user.getLocale());
 
String origin = BackPath.findBackPath(request).getBackwardUrl();
if(origin == null || origin.length() <= 0) {
return mapping.findForward("default");
}
else {
response.sendRedirect(origin);
return null;
}
}
}
else {
throw new Exception("unknown mapping parameter");
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/UserUpdater.java
0,0 → 1,53
package ak.hostadmiral.core.action;
 
import java.util.Map;
import java.util.Iterator;
import javax.servlet.http.HttpSession;
 
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
 
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.servlet.sessioncontrol.SessionControl;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.UserModifiedListener;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class UserUpdater
implements
ConfigInit,
UserModifiedListener
{
private static final Logger logger = Logger.getLogger(UserUpdater.class);
 
public UserUpdater()
{
}
 
public void init(Map params)
{
UserManager.getInstance().addModifiedListener(this);
logger.info("registered for user modifications");
}
 
public void userModified(User editor, User user, User oldUser)
throws ModelException
{
logger.info("user modified: " + user);
 
for(Iterator i = SessionControl.getInstance().getSessions().iterator(); i.hasNext(); ) {
HttpSession s = (HttpSession)i.next();
User u = (User)s.getAttribute(SessionKeys.USER);
 
if(u != null) {
if(u.equals(oldUser)) {
logger.info("update user");
s.setAttribute(SessionKeys.USER, user);
s.setAttribute(Globals.LOCALE_KEY, user.getLocale());
}
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/MailAliasAction.java
0,0 → 1,318
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Iterator;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.beanutils.BeanUtils;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.strutsx.RequestUtilsX;
import ak.strutsx.ErrorHandlerX;
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.Mailbox;
import ak.hostadmiral.core.model.MailboxManager;
import ak.hostadmiral.core.model.MailAlias;
import ak.hostadmiral.core.model.MailAliasManager;
import ak.hostadmiral.core.model.MailAliasDestination;
import ak.hostadmiral.core.model.MailAliasDestinationManager;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.core.servlet.SessionKeys;
import ak.hostadmiral.core.form.MailAliasDestBean;
 
public final class MailAliasAction
extends Action
implements ErrorHandlerX
{
public static final int PAGE_SIZE = 20;
 
public void handleErrors(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("submit".equals(mapping.getParameter())) {
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
initLists(request, user);
}
}
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
if("list".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection list = MailAliasManager.getInstance().listMailAliases(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { MailAliasManager.SORT_DOMAIN, MailAliasManager.SORT_ADDRESS },
user);
 
request.setAttribute("aliases", list);
request.setAttribute("listInfo", listInfo);
request.setAttribute("allowedToCreate",
Boolean.valueOf(MailAliasManager.getInstance().allowedToCreate(user)));
 
return mapping.findForward("default");
}
else if("edit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
MailAlias alias;
Long aliasId = StringConverter.parseLong(theForm.get("id"));
List dests;
 
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "MailAliasEditForm");
 
if(aliasId == null) {
alias = MailAliasManager.getInstance().create(user);
dests = new ArrayList();
showForm.set("enabled", Boolean.TRUE);
}
else {
alias = MailAliasManager.getInstance().get(user, aliasId);
dests = new ArrayList(MailAliasDestinationManager.getInstance()
.listMailAliasesDestination(alias));
MailAliasDestBean[] d = new MailAliasDestBean[dests.size()];
 
// FIXME: sort dests here
 
for(int i = 0; i < dests.size(); i++) {
d[i] = new MailAliasDestBean((MailAliasDestination)dests.get(i));
}
showForm.set("dests", d);
 
showForm.set("address", alias.getAddress());
if(alias.getDomain() != null)
showForm.set("domain", StringConverter.toString(alias.getDomain().getId()));
if(alias.getOwner() != null)
showForm.set("owner", StringConverter.toString(alias.getOwner().getId()));
showForm.set("enabled", alias.getEnabled());
showForm.set("comment", alias.getComment());
}
 
initLists(request, user);
request.setAttribute("alias", alias);
request.setAttribute("dests", dests);
if(alias.editableBy(user))
return mapping.findForward("default");
else if(alias.mayChangeDestinations(user))
return mapping.findForward("editdests");
else
return mapping.findForward("view");
}
else if("deleting".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long aliasId = StringConverter.parseLong(theForm.get("id"));
MailAlias alias = MailAliasManager.getInstance().get(user, aliasId);
 
request.setAttribute("action", "/mail/alias/delete.do");
request.setAttribute("object", alias);
request.setAttribute("cascade",
MailAliasManager.getInstance().beforeDelete(user, alias, new HashSet()));
 
return mapping.findForward("default");
}
else if("delete".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long aliasId = StringConverter.parseLong(theForm.get("id"));
MailAlias alias = MailAliasManager.getInstance().get(user, aliasId);
 
MailAliasManager.getInstance().delete(user, alias);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long aliasId = StringConverter.parseLong(theForm.get("id"));
MailAlias alias = (aliasId == null)
? MailAliasManager.getInstance().create(user)
: MailAliasManager.getInstance().get(user, aliasId);
MailAliasDestBean[] dests = (MailAliasDestBean[])theForm.get("dests");
 
// submit
if(request.getParameter("submit") != null) {
// FIXME: if empty element of select box is active, it will be changed
// by submit
 
// validate required fields, because it cannot be done in general case
if(StringConverter.isEmpty(theForm.get("address"))) {
handleErrors(mapping, form, request, response);
throw new UserException("ak.hostadmiral.core.mail.alias.edit.address.empty");
}
if(StringConverter.isEmpty(theForm.get("domain"))) {
handleErrors(mapping, form, request, response);
throw new UserException("ak.hostadmiral.core.mail.alias.edit.domain.wrong");
}
if(StringConverter.isEmpty(theForm.get("owner"))) {
handleErrors(mapping, form, request, response);
throw new UserException("ak.hostadmiral.core.mail.alias.edit.owner.wrong");
}
 
alias.setDomain(user, InetDomainManager.getInstance().get(user,
StringConverter.parseLong(theForm.get("domain"))));
 
String address = (String)theForm.get("address");
if(MailAliasManager.getInstance().addressExists(user, alias, address)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_MAIL_ALIAS_ADDRESS);
}
alias.setAddress(user, address);
 
alias.setOwner(user, UserManager.getInstance().get(user,
StringConverter.parseLong(theForm.get("owner"))));
alias.setEnabled(user, (Boolean)theForm.get("enabled"));
alias.setComment(user, (String)theForm.get("comment"));
 
alias.getDestinations(user).clear();
for(int i = 0; i < dests.length; i++) {
// FIXME: validate dest id, mailbox id, email
 
// skip empty rows
if((dests[i].getMailbox() == null)
&& (dests[i].getEmail() == null || dests[i].getEmail().equals("")))
continue;
 
// get bean
Long destId = StringConverter.parseLong(dests[i].getId());
Long mailboxId = StringConverter.parseLong(dests[i].getMailbox());
MailAliasDestination dest;
if(destId == null)
dest = MailAliasDestinationManager.getInstance().create(user);
else
dest = MailAliasDestinationManager.getInstance().get(user, destId);
 
// connect
dest.setAlias(user, alias);
alias.getDestinations(user).add(dest);
 
// set mailbox or email
if(mailboxId != null) {
dest.setMailbox(user, MailboxManager.getInstance().get(user, mailboxId));
dest.setEmail(user, null);
}
else if(dests[i].getEmail() != null && !dests[i].getEmail().equals("")) {
dest.setMailbox(user, null);
dest.setEmail(user, dests[i].getEmail());
}
 
dest.setEnabled(user, dests[i].getEnabled());
dest.setComment(user, dests[i].getComment());
}
 
// update alias
MailAliasManager.getInstance().save(user, alias);
 
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
 
// add
else if(request.getParameter("add") != null) {
// FIXME: if called when no entries defined two rows are created
 
MailAliasDestBean[] newDests = new MailAliasDestBean[dests.length+1];
if(dests.length > 0)
System.arraycopy(dests, 0, newDests, 0, dests.length);
newDests[dests.length] = new MailAliasDestBean();
newDests[dests.length].setEnabled(Boolean.TRUE);
theForm.set("dests", newDests);
 
initLists(request, user);
request.setAttribute("alias", alias);
request.setAttribute("dests", newDests);
if(alias.editableBy(user))
return mapping.findForward("default");
else if(alias.mayChangeDestinations(user))
return mapping.findForward("editdests");
else
return mapping.findForward("view");
}
 
// delete
else {
Iterator iter = request.getParameterMap().keySet().iterator();
while(iter.hasNext()) {
String name = (String)iter.next();
if(name.startsWith("delete.dests[")) {
int p = name.indexOf("]");
if(p > 0) {
String index = name.substring("delete.dests[".length(), p);
try {
int n = Integer.parseInt(index);
if(n < 0 || n >= dests.length) break;
 
MailAliasDestBean[] newDests;
newDests = new MailAliasDestBean[dests.length-1];
if(n > 0)
System.arraycopy(dests, 0, newDests, 0, n);
if(n < dests.length-1)
System.arraycopy(dests, n+1, newDests,
n, dests.length-n-1);
theForm.set("dests", newDests);
request.setAttribute("dests", newDests);
break;
}
catch(NumberFormatException ex) {
}
}
}
}
 
initLists(request, user);
request.setAttribute("alias", alias);
if(alias.editableBy(user))
return mapping.findForward("default");
else if(alias.mayChangeDestinations(user))
return mapping.findForward("editdests");
else
return mapping.findForward("view");
}
}
else {
throw new Exception("unknown mapping parameter");
}
}
 
private void initLists(HttpServletRequest request, User user)
throws Exception
{
// list of mailboxes to redirect to
List mailboxes = new ArrayList(MailboxManager.getInstance().listMailboxes(user));
Collections.sort(mailboxes, MailboxManager.LOGIN_COMPARATOR);
request.setAttribute("mailboxes", mailboxes);
 
List users = new ArrayList(UserManager.getInstance().listUsers(user));
Collections.sort(users, UserManager.LOGIN_COMPARATOR);
request.setAttribute("users", users);
 
List domains = new ArrayList(InetDomainManager.getInstance().listInetDomains(user));
Collections.sort(domains, InetDomainManager.NAME_COMPARATOR);
request.setAttribute("domains", domains);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/UserAction.java
0,0 → 1,238
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.strutsx.RequestUtilsX;
import ak.strutsx.ErrorHandlerX;
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class UserAction
extends Action
implements ErrorHandlerX
{
public static final int PAGE_SIZE = 20;
 
public void handleErrors(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("submit".equals(mapping.getParameter()) || "partsubmit".equals(mapping.getParameter())) {
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
initUserList(request, user);
 
DynaActionForm theForm = (DynaActionForm)form;
Long userId;
User u;
 
try {
userId = StringConverter.parseLong(theForm.get("id"));
}
catch(NumberFormatException ex) {
userId = null;
}
 
if(userId == null)
u = UserManager.getInstance().create(user);
else
u = UserManager.getInstance().get(user, userId);
 
request.setAttribute("u", u);
}
}
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
if("list".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection list = UserManager.getInstance().listUsers(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { UserManager.SORT_LOGIN }, user);
 
request.setAttribute("users", list);
request.setAttribute("listInfo", listInfo);
request.setAttribute("allowedToCreate",
Boolean.valueOf(UserManager.getInstance().allowedToCreate(user)));
request.setAttribute("mayViewAllLogins", Boolean.valueOf(user.mayViewAllLogins()));
 
return mapping.findForward("default");
}
else if("edit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u;
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "UserEditForm");
 
if(userId == null) {
u = UserManager.getInstance().create(user);
showForm.set("enabled", Boolean.TRUE);
}
else {
u = UserManager.getInstance().get(user, userId);
showForm.set("login", u.getLogin());
if(u.getBoss() != null)
showForm.set("boss", StringConverter.toString(u.getBoss().getId()));
showForm.set("superuser", u.getSuperuser());
showForm.set("locale", u.getLocale().toString());
showForm.set("enabled", u.getEnabled());
showForm.set("comment", u.getComment());
}
 
initUserList(request, user);
request.setAttribute("u", u);
if(u.editableBy(user))
return mapping.findForward("default");
else
return mapping.findForward("view");
}
else if("partedit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u = UserManager.getInstance().get(user, userId);
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "UserPartEditForm");
 
showForm.set("locale", u.getLocale().toString());
initUserList(request, user);
request.setAttribute("u", u);
return mapping.findForward("default");
}
else if("deleting".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u = UserManager.getInstance().get(user, userId);
 
request.setAttribute("action", "/user/delete.do");
request.setAttribute("object", u);
request.setAttribute("cascade",
UserManager.getInstance().beforeDelete(user, u, new HashSet()));
 
return mapping.findForward("default");
}
else if("delete".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u = UserManager.getInstance().get(user, userId);
request.setAttribute("u", u);
 
if(u.equals(user)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.DELETE_ME_SELF);
}
 
// FIXME: invalidate session of deleted user if it is logged in
// FIXME: if two admins delete each other at the same time
 
UserManager.getInstance().delete(user, u);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u;
String password = (String)theForm.get("password");
 
if(userId == null) {
if(password == null || password.equals("")) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.PASSWORD_REQUIRED);
}
 
u = UserManager.getInstance().create(user);
}
else {
u = UserManager.getInstance().get(user, userId);
}
request.setAttribute("u", u);
 
String login = (String)theForm.get("login");
if(UserManager.getInstance().loginExists(user, u, login)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_USER_LOGIN);
}
u.setLogin(user, login);
 
if(u.mayChangeBoss(user)) {
Long bossId = StringConverter.parseLong(theForm.get("boss"));
if(bossId == null)
u.setBoss(user, null);
else
u.setBoss(user, UserManager.getInstance().get(user, bossId));
}
 
if(u.editableBy(user)) {
u.setLocaleName(user, (String)theForm.get("locale"));
u.setEnabled(user, (Boolean)theForm.get("enabled"));
u.setComment(user, (String)theForm.get("comment"));
}
 
if(u.mayChangeSuperuser(user))
u.setSuperuser(user, (Boolean)theForm.get("superuser"));
 
if(password != null && !password.equals("")
&& u.editableBy(user) // more strong condition, because normal
&& u.partEditableBy(user)) // user have to enter first the old password
{
u.setPassword(user, password);
}
 
UserManager.getInstance().save(user, u);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("partsubmit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u = UserManager.getInstance().get(user, userId);
 
u.setLocaleName(user, (String)theForm.get("locale"));
UserManager.getInstance().save(user, u);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else {
throw new Exception("unknown mapping parameter");
}
}
 
private void initUserList(HttpServletRequest request, User user)
throws Exception
{
List list = new ArrayList(UserManager.getInstance().listUsers(user));
Collections.sort(list, UserManager.LOGIN_COMPARATOR);
request.setAttribute("users", list);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/FailedLoginsAction.java
0,0 → 1,38
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class FailedLoginsAction
extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
List logins = new ArrayList(UserManager.getInstance().listFailedLogins(user));
 
Collections.sort(logins, UserManager.LOGINS_TIME_COMPARATOR);
Collections.reverse(logins);
request.setAttribute("logins", logins);
 
return mapping.findForward("default");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/SystemUserAction.java
0,0 → 1,174
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.strutsx.RequestUtilsX;
import ak.strutsx.ErrorHandlerX;
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.SystemUser;
import ak.hostadmiral.core.model.SystemUserManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class SystemUserAction
extends Action
implements ErrorHandlerX
{
public static final int PAGE_SIZE = 20;
 
public void handleErrors(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("submit".equals(mapping.getParameter())) {
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
initUserList(request, user);
}
}
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
if("list".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection list = SystemUserManager.getInstance().listSystemUsers(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { SystemUserManager.SORT_NAME }, user);
 
request.setAttribute("users", list);
request.setAttribute("listInfo", listInfo);
request.setAttribute("allowedToCreate",
Boolean.valueOf(SystemUserManager.getInstance().allowedToCreate(user)));
 
return mapping.findForward("default");
}
else if("edit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
SystemUser u;
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "SystemUserEditForm");
 
if(userId == null) {
u = SystemUserManager.getInstance().create(user);
showForm.set("enabled", Boolean.TRUE);
}
else {
u = SystemUserManager.getInstance().get(user, userId);
showForm.set("uid", StringConverter.toString(u.getUid()));
showForm.set("name", u.getName());
if(u.getOwner() != null)
showForm.set("owner", StringConverter.toString(u.getOwner().getId()));
showForm.set("enabled", u.getEnabled());
showForm.set("comment", u.getComment());
}
 
initUserList(request, user);
request.setAttribute("u", u);
if(u.editableBy(user))
return mapping.findForward("default");
else
return mapping.findForward("view");
}
else if("deleting".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
SystemUser u = SystemUserManager.getInstance().get(user, userId);
 
request.setAttribute("action", "/user/system/delete.do");
request.setAttribute("object", u);
request.setAttribute("cascade",
SystemUserManager.getInstance().beforeDelete(user, u, new HashSet()));
 
return mapping.findForward("default");
}
else if("delete".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
SystemUser u = SystemUserManager.getInstance().get(user, userId);
 
SystemUserManager.getInstance().delete(user, u);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
SystemUser u;
 
if(userId == null) {
u = SystemUserManager.getInstance().create(user);
}
else {
u = SystemUserManager.getInstance().get(user, userId);
}
 
Integer uid = StringConverter.parseInteger(theForm.get("uid"));
if(SystemUserManager.getInstance().uidExists(user, u, uid)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_SYSTEM_USER_UID);
}
u.setUid(user, uid);
 
String name = (String)theForm.get("name");
if(SystemUserManager.getInstance().nameExists(user, u, name)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_SYSTEM_USER_NAME);
}
u.setName(user, name);
 
Long ownerId = StringConverter.parseLong(theForm.get("owner"));
if(ownerId == null)
u.setOwner(user, null);
else
u.setOwner(user, UserManager.getInstance().get(user, ownerId));
 
u.setEnabled(user, (Boolean)theForm.get("enabled"));
u.setComment(user, (String)theForm.get("comment"));
 
SystemUserManager.getInstance().save(user, u);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else {
throw new Exception("unknown mapping parameter");
}
}
 
private void initUserList(HttpServletRequest request, User user)
throws Exception
{
List list = new ArrayList(UserManager.getInstance().listUsers(user));
Collections.sort(list, UserManager.LOGIN_COMPARATOR);
request.setAttribute("users", list);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/IndexAction.java
0,0 → 1,40
package ak.hostadmiral.core.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
 
import ak.hostadmiral.util.ProjectVersion;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.SystemUserManager;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.core.model.MailboxManager;
import ak.hostadmiral.core.model.MailAliasManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class IndexAction
extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
request.setAttribute("showSystemUsers",
Boolean.valueOf(SystemUserManager.getInstance().areSystemUsersAvailable(user)));
request.setAttribute("showInetDomains",
Boolean.valueOf(InetDomainManager.getInstance().areInetDomainsAvailable(user)));
request.setAttribute("showMailboxes",
Boolean.valueOf(MailboxManager.getInstance().areMailboxesAvailable(user)));
request.setAttribute("showMailAliases",
Boolean.valueOf(MailAliasManager.getInstance().areMailAliasesAvailable(user)));
 
return mapping.findForward("success");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/InetDomainAction.java
0,0 → 1,163
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.strutsx.RequestUtilsX;
import ak.strutsx.ErrorHandlerX;
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class InetDomainAction
extends Action
implements ErrorHandlerX
{
public static final int PAGE_SIZE = 20;
 
public void handleErrors(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("submit".equals(mapping.getParameter())) {
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
initUserList(request, user);
}
}
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
if("list".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection list = InetDomainManager.getInstance().listInetDomains(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { InetDomainManager.SORT_NAME }, user);
 
request.setAttribute("domains", list);
request.setAttribute("listInfo", listInfo);
request.setAttribute("allowedToCreate",
Boolean.valueOf(InetDomainManager.getInstance().allowedToCreate(user)));
 
return mapping.findForward("default");
}
else if("edit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long domainId = StringConverter.parseLong(theForm.get("id"));
InetDomain domain;
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "InetDomainEditForm");
 
if(domainId == null) {
domain = InetDomainManager.getInstance().create(user);
showForm.set("enabled", Boolean.TRUE);
}
else {
domain = InetDomainManager.getInstance().get(user, domainId);
showForm.set("name", domain.getName());
if(domain.getOwner() != null)
showForm.set("owner", StringConverter.toString(domain.getOwner().getId()));
showForm.set("enabled", domain.getEnabled());
showForm.set("comment", domain.getComment());
}
 
initUserList(request, user);
request.setAttribute("domain", domain);
if(domain.editableBy(user))
return mapping.findForward("default");
else
return mapping.findForward("view");
}
else if("deleting".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long domainId = StringConverter.parseLong(theForm.get("id"));
InetDomain domain = InetDomainManager.getInstance().get(user, domainId);
 
request.setAttribute("action", "/domain/delete.do");
request.setAttribute("object", domain);
request.setAttribute("cascade",
InetDomainManager.getInstance().beforeDelete(user, domain, new HashSet()));
 
return mapping.findForward("default");
}
else if("delete".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long domainId = StringConverter.parseLong(theForm.get("id"));
InetDomain domain = InetDomainManager.getInstance().get(user, domainId);
 
InetDomainManager.getInstance().delete(user, domain);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long domainId = StringConverter.parseLong(theForm.get("id"));
InetDomain domain;
 
if(domainId == null) {
domain = InetDomainManager.getInstance().create(user);
}
else {
domain = InetDomainManager.getInstance().get(user, domainId);
}
 
String name = (String)theForm.get("name");
if(InetDomainManager.getInstance().nameExists(user, domain, name)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_DOMAIN_NAME);
}
domain.setName(user, name);
 
domain.setOwner(user, UserManager.getInstance().get(user,
StringConverter.parseLong(theForm.get("owner"))));
 
domain.setEnabled(user, (Boolean)theForm.get("enabled"));
domain.setComment(user, (String)theForm.get("comment"));
 
InetDomainManager.getInstance().save(user, domain);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else {
throw new Exception("unknown mapping parameter");
}
}
 
private void initUserList(HttpServletRequest request, User user)
throws Exception
{
List list = new ArrayList(UserManager.getInstance().listUsers(user));
Collections.sort(list, UserManager.LOGIN_COMPARATOR);
request.setAttribute("users", list);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/ChangePasswordAction.java
0,0 → 1,53
package ak.hostadmiral.core.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.backpath.BackPath;
 
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class ChangePasswordAction
extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("first".equals(mapping.getParameter())) {
return mapping.findForward("default");
}
else {
DynaActionForm theForm = (DynaActionForm)form;
 
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
if(user.checkPassword((String)theForm.get("oldpassword"))) {
user.setPassword(user, (String)theForm.get("password"));
UserManager.getInstance().save(user, user);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else {
ActionErrors errors = new ActionErrors();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionError(CoreResources.OLD_PASSWORD_WRONG));
saveErrors(request, errors);
return mapping.getInputForward();
}
}
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/UserLoginsAction.java
0,0 → 1,49
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Collections;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class UserLoginsAction
extends Action
{
public static final int PAGE_SIZE = 20;
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
 
DynaActionForm theForm = (DynaActionForm)form;
Long userId = StringConverter.parseLong(theForm.get("id"));
User u = UserManager.getInstance().get(user, userId);
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection logins = UserManager.getInstance().listUserLogins(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { UserManager.SORT_LOGINS_TIME_REVERSE }, user, u);
 
request.setAttribute("u", u);
request.setAttribute("logins", logins);
request.setAttribute("listInfo", listInfo);
 
return mapping.findForward("default");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/MailboxAction.java
0,0 → 1,205
package ak.hostadmiral.core.action;
 
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
import ak.strutsx.RequestUtilsX;
import ak.strutsx.ErrorHandlerX;
import ak.backpath.BackPath;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.CollectionInfo;
import ak.hostadmiral.core.resources.CoreResources;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.Mailbox;
import ak.hostadmiral.core.model.MailboxManager;
import ak.hostadmiral.core.model.SystemUserManager;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public final class MailboxAction
extends Action
implements ErrorHandlerX
{
public static final int PAGE_SIZE = 20;
 
public void handleErrors(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if("submit".equals(mapping.getParameter())) {
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
initLists(request, user);
}
}
 
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
User user = (User)request.getSession().getAttribute(SessionKeys.USER);
if("list".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long page = StringConverter.parseLong(theForm.get("pg"));
CollectionInfo listInfo = new CollectionInfo();
Collection list = MailboxManager.getInstance().listMailboxes(
listInfo, PAGE_SIZE, (page == null) ? 0 : page.intValue(),
new Integer[] { MailboxManager.SORT_DOMAIN, MailboxManager.SORT_LOGIN }, user);
 
request.setAttribute("mailboxes", list);
request.setAttribute("listInfo", listInfo);
request.setAttribute("allowedToCreate",
Boolean.valueOf(MailboxManager.getInstance().allowedToCreate(user)));
 
return mapping.findForward("default");
}
else if("edit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long boxId = StringConverter.parseLong(theForm.get("id"));
Mailbox mailbox;
DynaActionForm showForm = (DynaActionForm)RequestUtilsX.populateActionForm(
this, request, "MailboxEditForm");
 
if(boxId == null) {
mailbox = MailboxManager.getInstance().create(user);
showForm.set("enabled", Boolean.TRUE);
showForm.set("viruscheck", Boolean.TRUE);
showForm.set("spamcheck", Boolean.TRUE);
}
else {
mailbox = MailboxManager.getInstance().get(user, boxId);
showForm.set("login", mailbox.getLogin());
if(mailbox.getDomain() != null)
showForm.set("domain", StringConverter.toString(mailbox.getDomain().getId()));
if(mailbox.getOwner() != null)
showForm.set("owner", StringConverter.toString(mailbox.getOwner().getId()));
showForm.set("viruscheck", mailbox.getVirusCheck());
showForm.set("spamcheck", mailbox.getSpamCheck());
if(mailbox.getSystemUser() != null)
showForm.set("systemuser", StringConverter.toString(mailbox.getSystemUser().getId()));
showForm.set("enabled", mailbox.getEnabled());
showForm.set("comment", mailbox.getComment());
}
 
initLists(request, user);
request.setAttribute("mailbox", mailbox);
if(mailbox.editableBy(user))
return mapping.findForward("default");
else
return mapping.findForward("view");
}
else if("deleting".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long boxId = StringConverter.parseLong(theForm.get("id"));
Mailbox mailbox = MailboxManager.getInstance().get(user, boxId);
 
request.setAttribute("action", "/mail/box/delete.do");
request.setAttribute("object", mailbox);
request.setAttribute("cascade",
MailboxManager.getInstance().beforeDelete(user, mailbox, new HashSet()));
 
return mapping.findForward("default");
}
else if("delete".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long boxId = StringConverter.parseLong(theForm.get("id"));
Mailbox mailbox = MailboxManager.getInstance().get(user, boxId);
 
MailboxManager.getInstance().delete(user, mailbox);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else if("submit".equals(mapping.getParameter())) {
DynaActionForm theForm = (DynaActionForm)form;
Long boxId = StringConverter.parseLong(theForm.get("id"));
Mailbox mailbox;
String password = (String)theForm.get("password");
 
if(boxId == null) {
if(password == null || password.equals("")) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.PASSWORD_REQUIRED);
}
 
mailbox = MailboxManager.getInstance().create(user);
 
// FIXME: create an user as owner of the new mailbox here,
// create a mail alias with the same name
}
else {
mailbox = MailboxManager.getInstance().get(user, boxId);
}
 
mailbox.setDomain(user, InetDomainManager.getInstance().get(user,
StringConverter.parseLong(theForm.get("domain"))));
 
String login = (String)theForm.get("login");
if(MailboxManager.getInstance().loginExists(user, mailbox, login)) {
handleErrors(mapping, form, request, response);
throw new UserException(CoreResources.NONUNIQUE_MAILBOX_LOGIN);
}
mailbox.setLogin(user, login);
 
mailbox.setOwner(user, UserManager.getInstance().get(user,
StringConverter.parseLong(theForm.get("owner"))));
mailbox.setVirusCheck(user, (Boolean)theForm.get("viruscheck"));
mailbox.setSpamCheck(user, (Boolean)theForm.get("spamcheck"));
 
Long systemUserId = StringConverter.parseLong(theForm.get("systemuser"));
if(systemUserId == null) {
mailbox.setSystemUser(user, null);
}
else {
mailbox.setSystemUser(user, SystemUserManager.getInstance().get(user, systemUserId));
}
 
if(password != null && !password.equals(""))
mailbox.setPassword(user, password);
 
mailbox.setEnabled(user, (Boolean)theForm.get("enabled"));
mailbox.setComment(user, (String)theForm.get("comment"));
 
MailboxManager.getInstance().save(user, mailbox);
response.sendRedirect(BackPath.findBackPath(request).getBackwardUrl());
return null;
}
else {
throw new Exception("unknown mapping parameter");
}
}
 
private void initLists(HttpServletRequest request, User user)
throws Exception
{
List users = new ArrayList(UserManager.getInstance().listUsers(user));
Collections.sort(users, UserManager.LOGIN_COMPARATOR);
request.setAttribute("users", users);
 
List systemUsers = new ArrayList(SystemUserManager.getInstance().listSystemUsers(user));
Collections.sort(systemUsers, SystemUserManager.UID_COMPARATOR);
request.setAttribute("systemusers", systemUsers);
 
List domains = new ArrayList(InetDomainManager.getInstance().listInetDomains(user));
Collections.sort(domains, InetDomainManager.NAME_COMPARATOR);
request.setAttribute("domains", domains);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/GeneralExceptionHandler.java
0,0 → 1,131
package ak.hostadmiral.core.action;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.config.ExceptionConfig;
 
import org.apache.log4j.Logger;
 
import ak.strutsx.ErrorHandlerX;
 
import ak.hostadmiral.util.UserException;
import ak.hostadmiral.util.ModelUserException;
import ak.hostadmiral.util.ModelSecurityException;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.FormException;
 
public final class GeneralExceptionHandler
extends ExceptionHandler
{
private static final Logger logger = Logger.getLogger(GeneralExceptionHandler.class);
 
public ActionForward execute(Exception ex, ExceptionConfig config,
ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
if(ex instanceof UserException) {
return handleUserException((UserException)ex,
config, mapping, formInstance, request, response);
}
else if(ex instanceof ModelUserException) {
return handleModelUserException((ModelUserException)ex,
config, mapping, formInstance, request, response);
}
else if(ex instanceof ModelSecurityException) {
logger.error("security exception", ex);
Exception subex = ((ModelSecurityException)ex).getChainedException();
if(subex != null && subex instanceof ModelException)
logChainedException((ModelSecurityException)subex);
 
return mapping.findForward("accessDenied");
}
else if(ex instanceof ModelException) {
logger.error("model exception", ex);
Exception subex = ((ModelException)ex).getChainedException();
if(subex != null && subex instanceof ModelException)
logChainedException((ModelException)subex);
 
return mapping.findForward("generalError");
}
else {
logger.error("unhandled exception", ex);
return mapping.findForward("generalError");
}
}
 
protected void logChainedException(ModelException ex)
{
logger.error("chained exception", ex);
 
Exception subex = ex.getChainedException();
if(subex != null && subex instanceof ModelException)
logChainedException((ModelException)subex);
}
 
protected ActionForward handleUserException(UserException ex, ExceptionConfig config,
ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
logger.info("user exception handle:" + ex.getMessage());
 
request.setAttribute("TRANSACTION_FAILED", Boolean.TRUE);
 
// try to get property for this exception if any
String property = ActionMessages.GLOBAL_MESSAGE;
if(ex instanceof FormException) {
FormException formEx = (FormException)ex;
if(formEx.getProperty() != null)
property = formEx.getProperty();
}
 
// create new error message
ActionErrors errors = (ActionErrors)request.getAttribute(Globals.ERROR_KEY);
if(errors == null) {
errors = new ActionErrors();
request.setAttribute(Globals.ERROR_KEY, errors);
}
errors.add(property, new ActionError(ex.getMessage(), ex.getValues()));
 
// find forward
if(mapping.getInput() == null)
return mapping.findForward("error");
else
return mapping.getInputForward();
}
 
protected ActionForward handleModelUserException(ModelUserException ex, ExceptionConfig config,
ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
logger.info("model user exception handle:" + ex.getMessage());
 
request.setAttribute("TRANSACTION_FAILED", Boolean.TRUE);
 
// create new error message
ActionErrors errors = (ActionErrors)request.getAttribute(Globals.ERROR_KEY);
if(errors == null) {
errors = new ActionErrors();
request.setAttribute(Globals.ERROR_KEY, errors);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionError(ex.getMessage(), ex.getValues()));
 
// find forward
if(mapping.getInput() == null)
return mapping.findForward("error");
else
return mapping.getInputForward();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/ActionUtils.java
0,0 → 1,15
package ak.hostadmiral.core.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import ak.hostadmiral.util.ProjectVersion;
 
public final class ActionUtils
{
public static void prepare(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
request.setAttribute("projectVersion", ProjectVersion.getVersion());
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/action/LogoutAction.java
0,0 → 1,28
package ak.hostadmiral.core.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
 
public final class LogoutAction
extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
ActionUtils.prepare(request, response);
if(request.getSession() != null)
request.getSession().invalidate();
 
return mapping.findForward("default");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/resources/CoreMessages.properties
0,0 → 1,58
ak.hostadmiral.core.type.user=user
ak.hostadmiral.core.type.systemUser=system user
ak.hostadmiral.core.type.domain=domain
ak.hostadmiral.core.type.mailbox=mailbox
ak.hostadmiral.core.type.mailAlias=mail alias
ak.hostadmiral.core.type.mailAliasDestination=mail alias destination
 
ak.hostadmiral.core.ident.user={0}
ak.hostadmiral.core.ident.systemUser={0} ({1})
ak.hostadmiral.core.ident.domain={0}
ak.hostadmiral.core.ident.mailbox={0}@{1}
ak.hostadmiral.core.ident.mailAlias={0}@{1}
ak.hostadmiral.core.ident.mailAliasDestination.external={0}
ak.hostadmiral.core.ident.mailAliasDestination.internal={0}@{1}
 
ak.hostadmiral.core.access.denied=Access to the object denied
ak.hostadmiral.core.login.failed=Wrong login or password or the user is disabled
ak.hostadmiral.core.login.required=You have to enter the login
ak.hostadmiral.core.password.required=You have to enter the password
ak.hostadmiral.core.oldpassword.required=You have to enter the old password
ak.hostadmiral.core.oldpassword.wrong=Wrong old password
ak.hostadmiral.core.password.dontMatch=The passwords you entered doesn't match
 
ak.hostadmiral.core.user.login.nonunique=The user login already exists
ak.hostadmiral.core.user.id.wrong=Please select an user from the list
ak.hostadmiral.core.user.deletemeself=Can not delete the user you are logged in
ak.hostadmiral.core.user.boss.id.wrong=Please select a boss from the list
ak.hostadmiral.core.user.locale.wrong=Please select a locale from the list
ak.hostadmiral.core.user.system.uid.nonunique=The UID already exists
ak.hostadmiral.core.user.system.name.nonunique=The user name already exists
ak.hostadmiral.core.domain.name.nonunique=The domain name already exists
ak.hostadmiral.core.mailbox.login.nonunique=The mailbox login already exists in the domain
ak.hostadmiral.core.mail.alias.address.nonunique=The address already exists in the domain
 
ak.hostadmiral.core.mailbox.edit.id.wrong=Please select a mailbox from the list
ak.hostadmiral.core.mailbox.edit.login.empty=You have to enter the login
ak.hostadmiral.core.mailbox.edit.domain.wrong=Please select a domain from the list
ak.hostadmiral.core.mailbox.edit.owner.wrong=Please select an owner from the list
ak.hostadmiral.core.mailbox.edit.systemuser.wrong=Please select a system user from the list
 
ak.hostadmiral.core.mail.alias.edit.id.wrong=Please select a mail alias from the list
ak.hostadmiral.core.mail.alias.edit.dest.id.wrong=Wrong ID
ak.hostadmiral.core.mail.alias.edit.mailbox.id.wrong=Please select a mailbox from the list
ak.hostadmiral.core.mail.alias.edit.email.wrong=Please enter an email
ak.hostadmiral.core.mail.alias.edit.address.empty=Please enter an address
ak.hostadmiral.core.mail.alias.edit.domain.wrong=Please select a domain from the list
ak.hostadmiral.core.mail.alias.edit.owner.wrong=Please select an owner from the list
 
ak.hostadmiral.core.user.system.edit.id.wrong=Please select an user from the list
ak.hostadmiral.core.user.system.edit.uid.wrong=Please enter the UID
ak.hostadmiral.core.user.system.edit.name.required=Please enter name of the user
ak.hostadmiral.core.user.system.edit.owner.wrong=Please select an owner from the list
 
ak.hostadmiral.core.domain.edit.id.wrong=Please select a domain from the list
ak.hostadmiral.core.domain.edit.owner.wrong=Please select an owner from the list
ak.hostadmiral.core.domain.edit.name.empty=Please enter domain name
 
ak.hostadmiral.core.mail.alias.edit.id.wrong=Please select an alias from the list
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/resources/PageMessages.properties
0,0 → 1,297
ak.hostadmiral.page.general.errors=There are errors in you input
ak.hostadmiral.page.general.version=Project version
ak.hostadmiral.page.general.page.wrong=Wrong page number: {0}
 
ak.hostadmiral.page.error.title=Host Admiral - error
ak.hostadmiral.page.error.back=back
 
ak.hostadmiral.page.generalError.title=Host Admiral - error
ak.hostadmiral.page.generalError.message=There is internal server error occured. Please go back and try again. If the error occurs again continue with the start page.
ak.hostadmiral.page.generalError.index=start page
ak.hostadmiral.page.generalError.back=back
 
ak.hostadmiral.page.accessDenied.title=Host Admiral - access denied
ak.hostadmiral.page.accessDenied.message=You have no permission to execute requested action.
ak.hostadmiral.page.accessDenied.index=start page
ak.hostadmiral.page.accessDenied.back=back
 
ak.hostadmiral.page.index.title=Host Admiral
ak.hostadmiral.page.index.password_change=change password
ak.hostadmiral.page.index.user_list=users
ak.hostadmiral.page.index.system_user_list=system users
ak.hostadmiral.page.index.domain_list=domains
ak.hostadmiral.page.index.mail_alias_list=mail aliases
ak.hostadmiral.page.index.mail_box_list=mail boxes
ak.hostadmiral.page.index.logout=logout
ak.hostadmiral.page.index.login=Logged in as
ak.hostadmiral.page.index.locale=Locale
 
ak.hostadmiral.page.system.login.title=Host Admiral - login
ak.hostadmiral.page.system.login.login=Login
ak.hostadmiral.page.system.login.password=Password
ak.hostadmiral.page.system.login.submit=Login
ak.hostadmiral.page.system.login.reset=Reset
 
ak.hostadmiral.page.system.logout.title=Host Admiral - logout
ak.hostadmiral.page.system.logout.message=You are logged out sucessfully. See you later!
ak.hostadmiral.page.system.logout.login=start new session
ak.hostadmiral.page.system.logout.back=return to system
 
ak.hostadmiral.page.deleting.title=Delete an object from system
ak.hostadmiral.page.deleting.delete=delete
ak.hostadmiral.page.deleting.back=back
 
ak.hostadmiral.page.user.password.change.title=Host Admiral - change password
ak.hostadmiral.page.user.password.change.old_password=Old password
ak.hostadmiral.page.user.password.change.new_password=New password
ak.hostadmiral.page.user.password.change.new_password_again=New password again
ak.hostadmiral.page.user.password.change.submit=submit
ak.hostadmiral.page.user.password.change.back=back
 
ak.hostadmiral.page.user.list.title=Host Admiral - users - list
ak.hostadmiral.page.user.list.login=Login
ak.hostadmiral.page.user.list.boss=Boss
ak.hostadmiral.page.user.list.superuser=Superuser
ak.hostadmiral.page.user.list.enabled=Enabled
ak.hostadmiral.page.user.list.delete=delete
ak.hostadmiral.page.user.list.edit=edit
ak.hostadmiral.page.user.list.partedit=edit
ak.hostadmiral.page.user.list.view=view
ak.hostadmiral.page.user.list.add=add new user
ak.hostadmiral.page.user.list.back=back
ak.hostadmiral.page.user.list.logins.failed=failed logins
 
ak.hostadmiral.page.user.failedLogins.title=Host Admiral - users - failed logins
ak.hostadmiral.page.user.failedLogins.login=Login
ak.hostadmiral.page.user.failedLogins.user.exists=User Exists
ak.hostadmiral.page.user.failedLogins.time=Login Time
ak.hostadmiral.page.user.failedLogins.success=Success
ak.hostadmiral.page.user.failedLogins.ip=IP
ak.hostadmiral.page.user.failedLogins.back=back
 
ak.hostadmiral.page.user.logins.title=Host Admiral - user - logins
ak.hostadmiral.page.user.logins.login=Logins of user
ak.hostadmiral.page.user.logins.time=Login Time
ak.hostadmiral.page.user.logins.success=Success
ak.hostadmiral.page.user.logins.ip=IP
ak.hostadmiral.page.user.logins.back=back
 
ak.hostadmiral.page.user.edit.title=Host Admiral - user - edit
ak.hostadmiral.page.user.edit.login=Login
ak.hostadmiral.page.user.edit.password=Password
ak.hostadmiral.page.user.edit.password_again=Password again
ak.hostadmiral.page.user.edit.boss=Boss
ak.hostadmiral.page.user.edit.boss.empty=-- no boss --
ak.hostadmiral.page.user.edit.superuser=Superuser
ak.hostadmiral.page.user.edit.superuser.true=yes
ak.hostadmiral.page.user.edit.superuser.false=no
ak.hostadmiral.page.user.edit.locale=Locale
ak.hostadmiral.page.user.edit.enabled=Enabled
ak.hostadmiral.page.user.edit.comment=Comment
ak.hostadmiral.page.user.edit.submit=submit
ak.hostadmiral.page.user.edit.back=back
ak.hostadmiral.page.user.edit.logins=login history
 
ak.hostadmiral.page.user.view.title=Host Admiral - user - view
ak.hostadmiral.page.user.view.login=Login
ak.hostadmiral.page.user.view.boss=Boss
ak.hostadmiral.page.user.view.boss.empty=[no boss]
ak.hostadmiral.page.user.view.superuser=Superuser
ak.hostadmiral.page.user.view.superuser.true=yes
ak.hostadmiral.page.user.view.superuser.false=no
ak.hostadmiral.page.user.view.locale=Locale
ak.hostadmiral.page.user.view.enabled=Enabled
ak.hostadmiral.page.user.view.enabled.true=yes
ak.hostadmiral.page.user.view.enabled.false=no
ak.hostadmiral.page.user.view.comment=Comment
ak.hostadmiral.page.user.view.back=back
ak.hostadmiral.page.user.view.logins=login history
 
ak.hostadmiral.page.user.partedit.title=Host Admiral - user - edit
ak.hostadmiral.page.user.partedit.login=Login
ak.hostadmiral.page.user.partedit.boss=Boss
ak.hostadmiral.page.user.partedit.boss.empty=[no boss]
ak.hostadmiral.page.user.partedit.superuser=Superuser
ak.hostadmiral.page.user.partedit.superuser.true=yes
ak.hostadmiral.page.user.partedit.superuser.false=no
ak.hostadmiral.page.user.partedit.locale=Locale
ak.hostadmiral.page.user.partedit.enabled=Enabled
ak.hostadmiral.page.user.partedit.enabled.true=yes
ak.hostadmiral.page.user.partedit.enabled.false=no
ak.hostadmiral.page.user.partedit.comment=Comment
ak.hostadmiral.page.user.partedit.submit=submit
ak.hostadmiral.page.user.partedit.back=back
ak.hostadmiral.page.user.partedit.logins=login history
 
ak.hostadmiral.page.user.system.list.title=Host Admiral - system users - list
ak.hostadmiral.page.user.system.list.uid=System ID
ak.hostadmiral.page.user.system.list.name=User name
ak.hostadmiral.page.user.system.list.owner=Owner
ak.hostadmiral.page.user.system.list.enabled=Enabled
ak.hostadmiral.page.user.system.list.delete=delete
ak.hostadmiral.page.user.system.list.edit=edit
ak.hostadmiral.page.user.system.list.view=view
ak.hostadmiral.page.user.system.list.add=add new user
ak.hostadmiral.page.user.system.list.back=back
 
ak.hostadmiral.page.user.system.edit.title=Host Admiral - system user - edit
ak.hostadmiral.page.user.system.edit.uid=System ID
ak.hostadmiral.page.user.system.edit.name=User name
ak.hostadmiral.page.user.system.edit.owner=Owner
ak.hostadmiral.page.user.system.edit.owner.empty=-- common user --
ak.hostadmiral.page.user.system.edit.enabled=Enabled
ak.hostadmiral.page.user.system.edit.comment=Comment
ak.hostadmiral.page.user.system.edit.submit=submit
ak.hostadmiral.page.user.system.edit.back=back
 
ak.hostadmiral.page.user.system.view.title=Host Admiral - system user - view
ak.hostadmiral.page.user.system.view.uid=System ID
ak.hostadmiral.page.user.system.view.name=User name
ak.hostadmiral.page.user.system.view.owner=Owner
ak.hostadmiral.page.user.system.view.owner.empty=[common user]
ak.hostadmiral.page.user.system.view.enabled=Enabled
ak.hostadmiral.page.user.system.view.enabled.true=yes
ak.hostadmiral.page.user.system.view.enabled.false=no
ak.hostadmiral.page.user.system.view.comment=Comment
ak.hostadmiral.page.user.system.view.back=back
 
ak.hostadmiral.page.domain.list.title=Host Admiral - domains - list
ak.hostadmiral.page.domain.list.name=Name
ak.hostadmiral.page.domain.list.owner=Owner
ak.hostadmiral.page.domain.list.enabled=Enabled
ak.hostadmiral.page.domain.list.delete=delete
ak.hostadmiral.page.domain.list.view=view
ak.hostadmiral.page.domain.list.edit=edit
ak.hostadmiral.page.domain.list.add=add new domain
ak.hostadmiral.page.domain.list.back=back
 
ak.hostadmiral.page.domain.edit.title=Host Admiral - domain - edit
ak.hostadmiral.page.domain.edit.name=Name
ak.hostadmiral.page.domain.edit.owner=Owner
ak.hostadmiral.page.domain.edit.owner.empty=-- please select --
ak.hostadmiral.page.domain.edit.enabled=Enabled
ak.hostadmiral.page.domain.edit.comment=Comment
ak.hostadmiral.page.domain.edit.submit=submit
ak.hostadmiral.page.domain.edit.back=back
 
ak.hostadmiral.page.domain.view.title=Host Admiral - domain - view
ak.hostadmiral.page.domain.view.name=Name
ak.hostadmiral.page.domain.view.owner=Owner
ak.hostadmiral.page.domain.view.enabled=Enabled
ak.hostadmiral.page.domain.view.enabled.true=yes
ak.hostadmiral.page.domain.view.enabled.false=no
ak.hostadmiral.page.domain.view.comment=Comment
ak.hostadmiral.page.domain.view.back=back
 
ak.hostadmiral.page.mail.box.list.title=Host Admiral - mail boxes - list
ak.hostadmiral.page.mail.box.list.login=Box
ak.hostadmiral.page.mail.box.list.domain=Domain
ak.hostadmiral.page.mail.box.list.owner=Owner
ak.hostadmiral.page.mail.box.list.enabled=Enabled
ak.hostadmiral.page.mail.box.list.edit=edit
ak.hostadmiral.page.mail.box.list.view=view
ak.hostadmiral.page.mail.box.list.delete=delete
ak.hostadmiral.page.mail.box.list.add=add new mail box
ak.hostadmiral.page.mail.box.list.back=back
 
ak.hostadmiral.page.mail.box.edit.title=Host Admiral - mail box - edit
ak.hostadmiral.page.mail.box.edit.login=Box
ak.hostadmiral.page.mail.box.edit.password=Password
ak.hostadmiral.page.mail.box.edit.password_again=Password again
ak.hostadmiral.page.mail.box.edit.domain=Domain
ak.hostadmiral.page.mail.box.edit.domain.empty=-- please select --
ak.hostadmiral.page.mail.box.edit.owner=Owner
ak.hostadmiral.page.mail.box.edit.owner.empty=-- create a new user --
ak.hostadmiral.page.mail.box.edit.systemuser=System user
ak.hostadmiral.page.mail.box.edit.systemuser.empty=-- default --
ak.hostadmiral.page.mail.box.edit.viruscheck=check mails for viruses
ak.hostadmiral.page.mail.box.edit.spamcheck=check mails for spam
ak.hostadmiral.page.mail.box.edit.enabled=Enabled
ak.hostadmiral.page.mail.box.edit.comment=Comment
ak.hostadmiral.page.mail.box.edit.submit=submit
ak.hostadmiral.page.mail.box.edit.back=back
 
ak.hostadmiral.page.mail.box.view.title=Host Admiral - mail box - view
ak.hostadmiral.page.mail.box.view.login=Box
ak.hostadmiral.page.mail.box.view.domain=Domain
ak.hostadmiral.page.mail.box.view.owner=Owner
ak.hostadmiral.page.mail.box.view.systemuser=System user
ak.hostadmiral.page.mail.box.view.systemuser.empty=[default user]
ak.hostadmiral.page.mail.box.view.viruscheck=check mails for viruses
ak.hostadmiral.page.mail.box.view.viruscheck.true=yes
ak.hostadmiral.page.mail.box.view.viruscheck.false=no
ak.hostadmiral.page.mail.box.view.spamcheck=check mails for spam
ak.hostadmiral.page.mail.box.view.spamcheck.true=yes
ak.hostadmiral.page.mail.box.view.spamcheck.false=no
ak.hostadmiral.page.mail.box.view.enabled=Enabled
ak.hostadmiral.page.mail.box.view.enabled.true=yes
ak.hostadmiral.page.mail.box.view.enabled.false=no
ak.hostadmiral.page.mail.box.view.comment=Comment
ak.hostadmiral.page.mail.box.view.back=back
 
ak.hostadmiral.page.mail.alias.list.title=Host Admiral - mail aliases - list
ak.hostadmiral.page.mail.alias.list.alias=Alias
ak.hostadmiral.page.mail.alias.list.domain=Domain
ak.hostadmiral.page.mail.alias.list.owner=Owner
ak.hostadmiral.page.mail.alias.list.enabled=Enabled
ak.hostadmiral.page.mail.alias.list.edit=edit
ak.hostadmiral.page.mail.alias.list.editdests=edit
ak.hostadmiral.page.mail.alias.list.view=view
ak.hostadmiral.page.mail.alias.list.delete=delete
ak.hostadmiral.page.mail.alias.list.back=back
ak.hostadmiral.page.mail.alias.list.add=add new mail alias
 
ak.hostadmiral.page.mail.alias.edit.title=Host Admiral - mail alias - edit
ak.hostadmiral.page.mail.alias.edit.address=Address
ak.hostadmiral.page.mail.alias.edit.domain=Domain
ak.hostadmiral.page.mail.alias.edit.domain.empty=-- please select --
ak.hostadmiral.page.mail.alias.edit.owner=Owner
ak.hostadmiral.page.mail.alias.edit.owner.empty=-- please select --
ak.hostadmiral.page.mail.alias.edit.enabled=Enabled
ak.hostadmiral.page.mail.alias.edit.comment=Comment
ak.hostadmiral.page.mail.alias.edit.header.tomailbox=To mailbox
ak.hostadmiral.page.mail.alias.edit.header.toexternal=or to external email
ak.hostadmiral.page.mail.alias.edit.header.enabled=Enabled
ak.hostadmiral.page.mail.alias.edit.header.comment=Comment
ak.hostadmiral.page.mail.alias.edit.external=external redirect
ak.hostadmiral.page.mail.alias.edit.add=add new destination
ak.hostadmiral.page.mail.alias.edit.delete=delete
ak.hostadmiral.page.mail.alias.edit.submit=submit
ak.hostadmiral.page.mail.alias.edit.back=back
 
ak.hostadmiral.page.mail.alias.editdest.title=Host Admiral - mail alias - edit
ak.hostadmiral.page.mail.alias.editdest.address=Address
ak.hostadmiral.page.mail.alias.editdest.domain=Domain
ak.hostadmiral.page.mail.alias.editdest.owner=Owner
ak.hostadmiral.page.mail.alias.editdest.enabled=Enabled
ak.hostadmiral.page.mail.alias.editdest.enabled.true=yes
ak.hostadmiral.page.mail.alias.editdest.enabled.false=no
ak.hostadmiral.page.mail.alias.editdest.comment=Comment
ak.hostadmiral.page.mail.alias.editdest.header.tomailbox=To mailbox
ak.hostadmiral.page.mail.alias.editdest.header.toexternal=or to external email
ak.hostadmiral.page.mail.alias.editdest.header.enabled=Enabled
ak.hostadmiral.page.mail.alias.editdest.header.comment=Comment
ak.hostadmiral.page.mail.alias.editdest.external=external redirect
ak.hostadmiral.page.mail.alias.editdest.add=add new destination
ak.hostadmiral.page.mail.alias.editdest.delete=delete
ak.hostadmiral.page.mail.alias.editdest.submit=submit
ak.hostadmiral.page.mail.alias.editdest.back=back
 
ak.hostadmiral.page.mail.alias.view.title=Host Admiral - mail alias - view
ak.hostadmiral.page.mail.alias.view.address=Address
ak.hostadmiral.page.mail.alias.view.domain=Domain
ak.hostadmiral.page.mail.alias.view.owner=Owner
ak.hostadmiral.page.mail.alias.view.enabled=Enabled
ak.hostadmiral.page.mail.alias.view.enabled.true=yes
ak.hostadmiral.page.mail.alias.view.enabled.false=no
ak.hostadmiral.page.mail.alias.view.comment=Comment
ak.hostadmiral.page.mail.alias.view.header.tomailbox=To mailbox
ak.hostadmiral.page.mail.alias.view.header.toexternal=or to external email
ak.hostadmiral.page.mail.alias.view.header.enabled=Enabled
ak.hostadmiral.page.mail.alias.view.dest.enabled.true=yes
ak.hostadmiral.page.mail.alias.view.dest.enabled.false=no
ak.hostadmiral.page.mail.alias.view.header.comment=Comment
ak.hostadmiral.page.mail.alias.view.external=external redirect
ak.hostadmiral.page.mail.alias.view.back=back
 
org.apache.struts.taglib.bean.format.sql.timestamp=dd-MM-yyyy HH:mm:ss.SSS
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/resources/PageMessages_ru.properties
0,0 → 1,3
ak.hostadmiral.page.index.title=Начальник Камчатки
 
org.apache.struts.taglib.bean.format.sql.timestamp=dd MMM yyyy HH:mm:ss.SSS
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/resources/CoreResources.java
0,0 → 1,40
package ak.hostadmiral.core.resources;
 
public abstract class CoreResources
{
public static final String LOGIN_FAILED = "ak.hostadmiral.core.login.failed";
public static final String OLD_PASSWORD_WRONG = "ak.hostadmiral.core.oldpassword.wrong";
public static final String PASSWORD_REQUIRED = "ak.hostadmiral.core.password.required";
public static final String PASSWORDS_DONT_MATCH = "ak.hostadmiral.core.password.dontMatch";
 
public static final String DELETE_ME_SELF = "ak.hostadmiral.core.user.deletemeself";
public static final String NONUNIQUE_USER_LOGIN = "ak.hostadmiral.core.user.login.nonunique";
public static final String NONUNIQUE_SYSTEM_USER_UID
= "ak.hostadmiral.core.user.system.uid.nonunique";
public static final String NONUNIQUE_SYSTEM_USER_NAME
= "ak.hostadmiral.core.user.system.name.nonunique";
public static final String NONUNIQUE_DOMAIN_NAME
= "ak.hostadmiral.core.domain.name.nonunique";
public static final String NONUNIQUE_MAILBOX_LOGIN
= "ak.hostadmiral.core.mailbox.login.nonunique";
public static final String NONUNIQUE_MAIL_ALIAS_ADDRESS
= "ak.hostadmiral.core.mail.alias.address.nonunique";
 
public static final String TYPE_USER = "ak.hostadmiral.core.type.user";
public static final String TYPE_SYSTEM_USER = "ak.hostadmiral.core.type.systemUser";
public static final String TYPE_DOMAIN = "ak.hostadmiral.core.type.domain";
public static final String TYPE_MAILBOX = "ak.hostadmiral.core.type.mailbox";
public static final String TYPE_MAIL_ALIAS = "ak.hostadmiral.core.type.mailAlias";
public static final String TYPE_MAIL_ALIAS_DESTINATION
= "ak.hostadmiral.core.type.mailAliasDestination";
 
public static final String IDENT_USER = "ak.hostadmiral.core.ident.user";
public static final String IDENT_SYSTEM_USER = "ak.hostadmiral.core.ident.systemUser";
public static final String IDENT_DOMAIN = "ak.hostadmiral.core.ident.domain";
public static final String IDENT_MAILBOX = "ak.hostadmiral.core.ident.mailbox";
public static final String IDENT_MAIL_ALIAS = "ak.hostadmiral.core.ident.mailAlias";
public static final String IDENT_MAIL_ALIAS_DESTINATION_EXTERNAL
= "ak.hostadmiral.core.ident.mailAliasDestination.external";
public static final String IDENT_MAIL_ALIAS_DESTINATION_INTERNAL
= "ak.hostadmiral.core.ident.mailAliasDestination.internal";
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/Locales.java
0,0 → 1,18
package ak.hostadmiral.core;
 
import java.util.Locale;
 
// FIXME: make this list as text file or build it directly from resources
public abstract class Locales
{
private static final Locale[] locales = {
new Locale("en"),
new Locale("de"),
new Locale("ru")
};
 
public static Locale[] getLocales()
{
return locales;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/LocaleOptionsTag.java
0,0 → 1,50
// based on jakarta struts taglib
package ak.hostadmiral.core.taglib;
 
import java.util.Locale;
import javax.servlet.jsp.JspException;
 
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.taglib.html.SelectTag;
import org.apache.struts.taglib.html.OptionsTag;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ResponseUtils;
 
import ak.hostadmiral.core.Locales;
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public class LocaleOptionsTag extends OptionsTag
{
protected static MessageResources pageMessages =
MessageResources.getMessageResources("ak.hostadmiral.core.resources.PageMessages");
 
public int doEndTag() throws JspException
{
SelectTag selectTag = (SelectTag) pageContext.getAttribute(Constants.SELECT_KEY);
if (selectTag == null) {
throw new JspException(messages.getMessage("optionsTag.select"));
}
 
User user = (User)pageContext.getSession().getAttribute(SessionKeys.USER);
if(user == null) throw new JspException("no user found");
Locale userLocale = user.getLocale();
 
StringBuffer sb = new StringBuffer();
Locale[] locales = Locales.getLocales();
for(int i = 0; i < locales.length; i++) {
Locale locale = locales[i];
String stringValue = locale.toString();
String label = locale.getDisplayLanguage(userLocale);
String country = locale.getDisplayCountry(userLocale);
 
if(country != null && !country.equals(""))
label += " / " + country; // FIXME: move the slash to JSP?
 
addOption(sb, stringValue, label, selectTag.isMatched(stringValue));
}
 
ResponseUtils.write(pageContext, sb.toString());
return EVAL_PAGE;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/RightTagBase.java
0,0 → 1,65
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
 
import org.apache.struts.util.RequestUtils;
 
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.ModelObject;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public abstract class RightTagBase
extends TagSupport
{
protected User user;
protected ModelObject object;
 
protected String name;
 
public String getName()
{
return name;
}
 
public void setName(String name)
{
this.name = name;
}
 
public void release()
{
super.release();
name = null;
user = null;
}
 
public int doStartTag()
throws JspException
{
user = (User)RequestUtils.lookup(pageContext, SessionKeys.USER, "session");
 
Object obj = RequestUtils.lookup(pageContext, name, null);
if(obj == null)
throw new JspException(name + " is null");
if(!(obj instanceof ModelObject))
throw new JspException(name + " must be a ModelObject, but is " + obj.getClass());
 
object = (ModelObject)obj;
 
if(condition())
return EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
 
public int doEndTag()
throws JspException
{
return EVAL_PAGE;
}
 
protected abstract boolean condition()
throws JspException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/EditableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class EditableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return object.editableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/NotEditableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class NotEditableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return !object.editableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/MethodTagBase.java
0,0 → 1,63
package ak.hostadmiral.core.taglib.permission;
 
import java.lang.reflect.Method;
import javax.servlet.jsp.JspException;
 
import ak.hostadmiral.core.model.User;
import org.apache.struts.util.RequestUtils;
 
public abstract class MethodTagBase
extends RightTagBase
{
protected String method;
 
public String getMethod()
{
return method;
}
 
public void setMethod(String method)
{
this.method = method;
}
 
public void release()
{
super.release();
method = null;
}
 
protected boolean condition()
throws JspException
{
Method m;
Object value;
 
// find method
try {
m = object.getClass().getMethod(method, new Class[] { User.class } );
}
catch(NoSuchMethodException ex) {
throw new JspException("Method " + method
+ " with parameter of type user not found");
}
 
// invoke it
try {
value = m.invoke(object, new Object[] { user } );
}
catch(Exception ex) {
throw new JspException("Cannot call " + method + ": " + ex.getMessage());
}
 
// check value type
if(!(value instanceof Boolean))
throw new JspException("Return type of method " + method
+ " must be java.lang.Boolean");
 
return condition(((Boolean)value).booleanValue());
}
 
protected abstract boolean condition(boolean value)
throws JspException;
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/NoRightsTag.java
0,0 → 1,15
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
import org.apache.struts.util.RequestUtils;
 
public class NoRightsTag
extends MethodTagBase
{
protected boolean condition(boolean value)
throws JspException
{
return !value;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/ViewableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class ViewableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return object.viewableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/NotViewableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class NotViewableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return !object.viewableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/RightsTag.java
0,0 → 1,15
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
import org.apache.struts.util.RequestUtils;
 
public class RightsTag
extends MethodTagBase
{
protected boolean condition(boolean value)
throws JspException
{
return value;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/DeleteableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class DeleteableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return object.deleteableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/permission/NotDeleteableTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.permission;
 
import javax.servlet.jsp.JspException;
 
public class NotDeleteableTag
extends RightTagBase
{
protected boolean condition()
throws JspException
{
return !object.deleteableBy(user);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/CountryTag.java
0,0 → 1,30
package ak.hostadmiral.core.taglib;
 
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
 
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public class CountryTag
extends TagSupport
{
public int doStartTag()
throws JspException
{
User user = (User)pageContext.getSession().getAttribute(SessionKeys.USER);
 
if(user == null)
throw new JspException("no user found");
 
try {
pageContext.getOut().print(user.getLocale().getDisplayCountry(user.getLocale()));
}
catch(IOException ex) {
throw new JspException("Cannot write out: " + ex.getMessage());
}
 
return SKIP_BODY;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/LanguageTag.java
0,0 → 1,30
package ak.hostadmiral.core.taglib;
 
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
 
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.servlet.SessionKeys;
 
public class LanguageTag
extends TagSupport
{
public int doStartTag()
throws JspException
{
User user = (User)pageContext.getSession().getAttribute(SessionKeys.USER);
 
if(user == null)
throw new JspException("no user found");
 
try {
pageContext.getOut().print(user.getLocale().getDisplayLanguage(user.getLocale()));
}
catch(IOException ex) {
throw new JspException("Cannot write out: " + ex.getMessage());
}
 
return SKIP_BODY;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/ModelObjectOptionsTag.java
0,0 → 1,71
// based on jakarta struts taglib
package ak.hostadmiral.core.taglib;
 
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
 
import javax.servlet.jsp.JspException;
 
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.taglib.html.SelectTag;
import org.apache.struts.taglib.html.OptionsTag;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ResponseUtils;
 
import ak.hostadmiral.core.model.ModelObject;
 
public class ModelObjectOptionsTag extends OptionsTag
{
protected static MessageResources coreMessages =
MessageResources.getMessageResources("ak.hostadmiral.core.resources.CoreMessages");
 
public int doEndTag() throws JspException
{
SelectTag selectTag = (SelectTag) pageContext.getAttribute(Constants.SELECT_KEY);
if (selectTag == null) {
throw new JspException(messages.getMessage("optionsTag.select"));
}
StringBuffer sb = new StringBuffer();
 
if (collection != null) {
Iterator collIterator = getIterator(collection, null);
while (collIterator.hasNext()) {
Object bean = collIterator.next();
Object value = null;
 
if(!(bean instanceof ModelObject))
throw new JspException("Not a ModelObject");
 
ModelObject model = (ModelObject)bean;
 
try {
value = PropertyUtils.getProperty(bean, property);
if (value == null) {
value = "";
}
} catch (IllegalAccessException e) {
throw new JspException(
messages.getMessage("getter.access", property, collection));
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
throw new JspException(
messages.getMessage("getter.result", property, t.toString()));
} catch (NoSuchMethodException e) {
throw new JspException(
messages.getMessage("getter.method", property, collection));
}
 
String identKey = model.getIdentKey();
Object[] identParams = model.getIdentParams();
String label = coreMessages.getMessage(identKey, identParams);
String stringValue = value.toString();
 
addOption(sb, stringValue, label, selectTag.isMatched(stringValue));
}
}
 
ResponseUtils.write(pageContext, sb.toString());
return EVAL_PAGE;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/CurrentPageTag.java
0,0 → 1,45
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.struts.util.ResponseUtils;
import org.apache.struts.util.RequestUtils;
import ak.hostadmiral.util.CollectionInfo;
 
public class CurrentPageTag
extends TagSupport
{
protected String infoBean = null;
 
public String getInfoBean()
{
return this.infoBean;
}
 
public void setInfoBean(String infoBean)
{
this.infoBean = infoBean;
}
 
protected String infoProperty = null;
 
public String getInfoProperty()
{
return this.infoProperty;
}
 
public void setInfoProperty(String infoProperty)
{
this.infoProperty = infoProperty;
}
 
public int doStartTag() throws JspException
{
CollectionInfo info = (CollectionInfo)
RequestUtils.lookup(pageContext, infoBean, infoProperty, null);
 
ResponseUtils.write(pageContext, Integer.toString(info.getCurrentPage() + 1));
 
return SKIP_BODY;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/HasFirstPageTag.java
0,0 → 1,16
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class HasFirstPageTag
extends ExistTagBase
{
protected boolean condition()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
return (info != null) && (info.getTotalPages() > 0);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NoFirstPageTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class NoFirstPageTag
extends HasFirstPageTag
{
protected boolean condition()
throws JspException
{
return !super.condition();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/FirstPageTag.java
0,0 → 1,14
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class FirstPageTag
extends PageTagBase
{
protected int getDisplayPage()
throws JspException
{
return 0;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/ExistTagBase.java
0,0 → 1,64
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.struts.util.RequestUtils;
import ak.hostadmiral.util.CollectionInfo;
 
public abstract class ExistTagBase
extends TagSupport
{
protected String infoBean = null;
 
public String getInfoBean()
{
return this.infoBean;
}
 
public void setInfoBean(String infoBean)
{
this.infoBean = infoBean;
}
 
protected String infoProperty = null;
 
public String getInfoProperty()
{
return this.infoProperty;
}
 
public void setInfoProperty(String infoProperty)
{
this.infoProperty = infoProperty;
}
 
public int doStartTag() throws JspException
{
if(condition())
return EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
 
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
 
protected abstract boolean condition() throws JspException;
 
protected CollectionInfo getCollectionInfo()
throws JspException
{
return (CollectionInfo)
RequestUtils.lookup(pageContext, infoBean, infoProperty, null);
}
 
public void release()
{
super.release();
infoBean = null;
infoProperty = null;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/PageLinkTag.java
0,0 → 1,64
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.apache.struts.taglib.html.LinkTag;
import ak.backpath.BackPath;
import ak.hostadmiral.util.CollectionInfo;
 
public class PageLinkTag
extends LinkTag
{
public static String BACKPATH_KEY = BackPath.DEFAULT_KEY + "_list";
public static String PAGE_PARAM_NAME = "pg";
 
protected PageIterateTag parent;
 
protected void findParent()
throws JspException
{
Tag p = getParent();
 
while(p != null && !(p instanceof PageIterateTag))
p = p.getParent();
 
if(p == null)
throw new JspException("This tag must be inside PageIterateTag");
 
parent = (PageIterateTag)p;
}
 
protected BackPath findBackPath()
throws JspException
{
try {
return BackPath.findBackPath((HttpServletRequest)pageContext.getRequest(),
BACKPATH_KEY, BackPath.DEFAULT_PARAM,
new String[] { "backpath", PAGE_PARAM_NAME },
BackPath.DEFAULT_ZIP);
}
catch(Exception ex) {
throw new JspException(ex);
}
}
 
protected String calculateURL()
throws JspException
{
String urlStr = findBackPath().getCurrentUrl();
if(urlStr == null) return "/";
 
StringBuffer url = new StringBuffer(urlStr);
boolean hasParams = (url.indexOf("?") > 0);
 
findParent();
 
if(hasParams)
url.append("&amp;").append(PAGE_PARAM_NAME + "=").append(parent.getDisplayPage());
else
url.append("?").append(PAGE_PARAM_NAME + "=").append(parent.getDisplayPage());
 
return url.toString();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/PageIterateTag.java
0,0 → 1,119
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;
import ak.hostadmiral.util.CollectionInfo;
 
public class PageIterateTag
extends BodyTagSupport
{
protected String infoBean = null;
 
public String getInfoBean()
{
return this.infoBean;
}
 
public void setInfoBean(String infoBean)
{
this.infoBean = infoBean;
}
 
protected String infoProperty = null;
 
public String getInfoProperty()
{
return this.infoProperty;
}
 
public void setInfoProperty(String infoProperty)
{
this.infoProperty = infoProperty;
}
 
protected int max = 0;
 
public String getMax()
{
return Integer.toString(this.max);
}
 
public void setMax(String max)
{
this.max = Integer.parseInt(max);
}
 
protected int displayPage;
 
public int getDisplayPage()
{
return this.displayPage;
}
 
protected CollectionInfo collectionInfo;
 
public CollectionInfo getCollectionInfo()
{
return this.collectionInfo;
}
 
public int doStartTag() throws JspException
{
collectionInfo = findCollectionInfo();
displayPage = (max == 0) ? 0
: Math.max(0, collectionInfo.getCurrentPage() - max/2);
 
if(collectionInfo == null) return SKIP_BODY;
 
if(collectionInfo.getTotalPages() > 0)
return EVAL_BODY_TAG;
else
return SKIP_BODY;
}
 
public int doAfterBody() throws JspException
{
// Render the output from this iteration to the output stream
if(bodyContent != null) {
ResponseUtils.writePrevious(pageContext, bodyContent.getString());
bodyContent.clearBody();
}
 
displayPage++;
 
if(max == 0 && displayPage < collectionInfo.getTotalPages()) {
return EVAL_BODY_TAG;
}
else if(max > 0 && displayPage < collectionInfo.getTotalPages()
&& displayPage < collectionInfo.getCurrentPage() + max/2)
{
return EVAL_BODY_TAG;
}
else {
return SKIP_BODY;
}
}
 
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
 
protected CollectionInfo findCollectionInfo()
throws JspException
{
return (CollectionInfo)
RequestUtils.lookup(pageContext, infoBean, infoProperty, null);
}
 
public void release()
{
super.release();
infoBean = null;
infoProperty = null;
max = 0;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/HasLastPageTag.java
0,0 → 1,16
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class HasLastPageTag
extends ExistTagBase
{
protected boolean condition()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
return (info != null) && (info.getTotalPages() > 0);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NoLastPageTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class NoLastPageTag
extends HasLastPageTag
{
protected boolean condition()
throws JspException
{
return !super.condition();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NotCurrentPageTag.java
0,0 → 1,22
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class NotCurrentPageTag
extends IterateSubtagBase
{
public int doStartTag() throws JspException
{
findParent();
 
if(parent.getCollectionInfo().getCurrentPage() != parent.getDisplayPage())
return EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
 
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/LastPageTag.java
0,0 → 1,19
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class LastPageTag
extends PageTagBase
{
protected int getDisplayPage()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
if(info == null)
return 0;
else
return info.getLastPage();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/DisplayPageTag.java
0,0 → 1,17
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import org.apache.struts.util.ResponseUtils;
 
public class DisplayPageTag
extends IterateSubtagBase
{
public int doStartTag() throws JspException
{
findParent();
 
ResponseUtils.write(pageContext, Integer.toString(parent.getDisplayPage() + 1));
 
return SKIP_BODY;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/IterateSubtagBase.java
0,0 → 1,25
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
 
public abstract class IterateSubtagBase
extends TagSupport
{
protected PageIterateTag parent;
 
protected void findParent()
throws JspException
{
Tag p = getParent();
 
while(p != null && !(p instanceof PageIterateTag))
p = p.getParent();
 
if(p == null)
throw new JspException("This tag must be inside PageIterateTag");
 
parent = (PageIterateTag)p;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/HasPrevPageTag.java
0,0 → 1,16
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class HasPrevPageTag
extends ExistTagBase
{
protected boolean condition()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
return (info != null) && (info.getCurrentPage() > 0);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NoPrevPageTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class NoPrevPageTag
extends HasPrevPageTag
{
protected boolean condition()
throws JspException
{
return !super.condition();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/PageTagBase.java
0,0 → 1,87
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.apache.struts.taglib.html.LinkTag;
import org.apache.struts.util.RequestUtils;
import ak.backpath.BackPath;
import ak.hostadmiral.util.CollectionInfo;
 
public abstract class PageTagBase
extends LinkTag
{
public static String BACKPATH_KEY = BackPath.DEFAULT_KEY + "_list";
public static String PAGE_PARAM_NAME = "pg";
 
protected String infoBean = null;
 
public String getInfoBean()
{
return this.infoBean;
}
 
public void setInfoBean(String infoBean)
{
this.infoBean = infoBean;
}
 
protected String infoProperty = null;
 
public String getInfoProperty()
{
return this.infoProperty;
}
 
public void setInfoProperty(String infoProperty)
{
this.infoProperty = infoProperty;
}
 
protected BackPath findBackPath()
throws JspException
{
try {
return BackPath.findBackPath((HttpServletRequest)pageContext.getRequest(),
BACKPATH_KEY, BackPath.DEFAULT_PARAM,
new String[] { "backpath", PAGE_PARAM_NAME },
BackPath.DEFAULT_ZIP);
}
catch(Exception ex) {
throw new JspException(ex);
}
}
 
protected String calculateURL()
throws JspException
{
String urlStr = findBackPath().getCurrentUrl();
if(urlStr == null) return "/";
 
StringBuffer url = new StringBuffer(urlStr);
boolean hasParams = (url.indexOf("?") > 0);
 
if(hasParams)
url.append("&amp;").append(PAGE_PARAM_NAME + "=").append(getDisplayPage());
else
url.append("?").append(PAGE_PARAM_NAME + "=").append(getDisplayPage());
 
return url.toString();
}
 
protected abstract int getDisplayPage()
throws JspException;
 
protected CollectionInfo getCollectionInfo()
throws JspException
{
return (CollectionInfo)
RequestUtils.lookup(pageContext, infoBean, infoProperty, null);
}
 
public void release()
{
super.release();
infoBean = null;
infoProperty = null;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/HasNextPageTag.java
0,0 → 1,16
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class HasNextPageTag
extends ExistTagBase
{
protected boolean condition()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
return (info != null) && (info.getCurrentPage() < info.getTotalPages() - 1);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NoNextPageTag.java
0,0 → 1,13
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class NoNextPageTag
extends HasNextPageTag
{
protected boolean condition()
throws JspException
{
return !super.condition();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/PrevPageTag.java
0,0 → 1,19
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class PrevPageTag
extends PageTagBase
{
protected int getDisplayPage()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
if(info == null)
return 0;
else
return info.getPrevPage();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/IsCurrentPageTag.java
0,0 → 1,22
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
 
public class IsCurrentPageTag
extends IterateSubtagBase
{
public int doStartTag() throws JspException
{
findParent();
 
if(parent.getCollectionInfo().getCurrentPage() == parent.getDisplayPage())
return EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
 
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/list/NextPageTag.java
0,0 → 1,19
package ak.hostadmiral.core.taglib.list;
 
import javax.servlet.jsp.JspException;
import ak.hostadmiral.util.CollectionInfo;
 
public class NextPageTag
extends PageTagBase
{
protected int getDisplayPage()
throws JspException
{
CollectionInfo info = getCollectionInfo();
 
if(info == null)
return 0;
else
return info.getNextPage();
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/taglib/WriteTag.java
0,0 → 1,50
// based on struts write tag
package ak.hostadmiral.core.taglib;
 
import javax.servlet.jsp.JspException;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;
 
public class WriteTag
extends org.apache.struts.taglib.bean.WriteTag
{
protected String defValue;
 
public String getDefault()
{
return defValue;
}
 
public void setDefault(String defValue)
{
this.defValue = defValue;
}
 
public int doStartTag()
throws JspException
{
Object value;
 
if(ignore && RequestUtils.lookup(pageContext, name, scope) == null)
value = null;
else
value = RequestUtils.lookup(pageContext, name, property, scope);
 
if(value == null) value = defValue;
 
if(value != null) {
if(filter)
ResponseUtils.write(pageContext, ResponseUtils.filter(formatValue(value)));
else
ResponseUtils.write(pageContext, formatValue(value));
}
 
return SKIP_BODY;
}
 
public void release()
{
super.release();
defValue = null;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/form/UserPasswordForm.java
0,0 → 1,30
package ak.hostadmiral.core.form;
 
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
 
import ak.hostadmiral.core.resources.CoreResources;
 
public final class UserPasswordForm
extends org.apache.struts.validator.DynaValidatorForm
{
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
{
ActionErrors errors = super.validate(mapping, request);
 
if(errors == null || errors.size() == 0) { // if no errors in simple checks
String password = (String)get("password");
String password2 = (String)get("password2");
 
if(!password.equals(password2)) {
if(errors == null) errors = new ActionErrors();
errors.add("password", new ActionError(CoreResources.PASSWORDS_DONT_MATCH));
}
}
 
return errors;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/core/form/MailAliasDestBean.java
0,0 → 1,77
package ak.hostadmiral.core.form;
 
import ak.hostadmiral.util.StringConverter;
import ak.hostadmiral.core.model.MailAliasDestination;
 
public final class MailAliasDestBean
{
private String id;
private String mailbox;
private String email;
private Boolean enabled;
private String comment;
 
public MailAliasDestBean()
{
}
 
public MailAliasDestBean(MailAliasDestination dest)
{
this.id = StringConverter.toString(dest.getId());
this.mailbox = (dest.getMailbox() == null)
? null : StringConverter.toString(dest.getMailbox().getId());
this.email = dest.getEmail();
this.enabled = dest.getEnabled();
this.comment = dest.getComment();
}
 
public String getId()
{
return id;
}
 
public void setId(String id)
{
this.id = id;
}
 
public String getMailbox()
{
return mailbox;
}
 
public void setMailbox(String mailbox)
{
this.mailbox = mailbox;
}
 
public String getEmail()
{
return email;
}
 
public void setEmail(String email)
{
this.email = email;
}
 
public Boolean getEnabled()
{
return enabled;
}
 
public void setEnabled(Boolean enabled)
{
this.enabled = enabled;
}
 
public String getComment()
{
return comment;
}
 
public void setComment(String comment)
{
this.comment = comment;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/listener/tcp/TcpListener.java
0,0 → 1,369
package ak.hostadmiral.listener.tcp;
 
import java.util.Map;
import java.util.Collection;
import java.util.Iterator;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.ConfigUtils;
import ak.hostadmiral.core.model.*;
 
import org.apache.log4j.Logger;
 
public class TcpListener
implements
ConfigInit,
UserCreatedListener,
UserModifiedListener,
UserDeletedListener,
InetDomainCreatedListener,
InetDomainModifiedListener,
InetDomainDeletedListener,
SystemUserCreatedListener,
SystemUserModifiedListener,
SystemUserDeletedListener,
MailboxCreatedListener,
MailboxModifiedListener,
MailboxDeletedListener,
MailAliasCreatedListener,
MailAliasModifiedListener,
MailAliasDeletedListener
{
private static final Logger logger = Logger.getLogger(TcpListener.class);
 
private static String hostname;
private static int port;
private static String password;
protected static Object lock = new Object();
 
public static final String PROTOCOL_NAME = "HostAdmiral_TcpListener";
public static final String PROTOCOL_VER_MAJ = "1";
public static final String PROTOCOL_VER_MIN = "0";
public static final String PASSWORD_DIGEST = "crypt";
 
public void init(Map params)
throws ModelException
{
ConfigUtils cfg = new ConfigUtils(params);
 
// save params
setHostname(cfg.getString("hostname", "127.0.0.1", true, false));
setPort(cfg.getInteger("port", null, false).intValue());
setPassword(cfg.getString("password", null, true, true));
 
// register listeners
UserManager.getInstance().addCreatedListener(this);
UserManager.getInstance().addModifiedListener(this);
UserManager.getInstance().addDeletedListener(this);
 
InetDomainManager.getInstance().addCreatedListener(this);
InetDomainManager.getInstance().addModifiedListener(this);
InetDomainManager.getInstance().addDeletedListener(this);
 
SystemUserManager.getInstance().addCreatedListener(this);
SystemUserManager.getInstance().addModifiedListener(this);
SystemUserManager.getInstance().addDeletedListener(this);
 
MailboxManager.getInstance().addCreatedListener(this);
MailboxManager.getInstance().addModifiedListener(this);
MailboxManager.getInstance().addDeletedListener(this);
 
MailAliasManager.getInstance().addCreatedListener(this);
MailAliasManager.getInstance().addModifiedListener(this);
MailAliasManager.getInstance().addDeletedListener(this);
}
 
public static String getHostname()
{
return hostname;
}
 
public static void setHostname(String hostname_)
{
hostname = hostname_;
}
 
public static int getPort()
{
return port;
}
 
public static void setPort(int port_)
{
port = port_;
}
 
public static void setPassword(String password_)
{
password = password_;
}
 
protected static String escape(String s)
{
// FIXME: any other problem characters? optimize it?
s = s.replaceAll("\\\\", "\\\\\\\\");
s = s.replaceAll("\0", "\\\\0");
s = s.replaceAll("\t", "\\\\t");
s = s.replaceAll("\n", "\\\\n");
s = s.replaceAll("\r", "\\\\r");
return s;
}
 
protected static void send(String message)
throws ModelException
{
synchronized(lock) {
try {
Socket socket = new Socket(hostname, port);
 
// send request
Writer out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
 
out.write(PROTOCOL_NAME + " " + PROTOCOL_VER_MAJ + "." + PROTOCOL_VER_MIN + "\n");
if(password != null) {
out.write("password=" + password + "\n");
}
out.write(message);
out.write("\n\n");
out.flush();
socket.shutdownOutput();
 
// get response
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
boolean headerDone = false;
boolean codeDone = false;
while((line = in.readLine()) != null) {
if(!headerDone) {
if(!line.matches("^" + PROTOCOL_NAME + " " + PROTOCOL_VER_MAJ + "\\.\\d+$"))
throw new ModelException(
"Wrong response: wrong header in [" + line + "]");
 
headerDone = true;
}
else if(!codeDone) {
if(line.length() < 3)
throw new ModelException(
"Wrong response: code too short [" + line + "]");
if(line.length() >= 4 && line.charAt(3) != ' ')
throw new ModelException(
"Wrong response: cannot get code from [" + line + "]");
 
int code;
try {
code = Integer.parseInt(line.substring(0, 3));
}
catch(NumberFormatException ex) {
throw new ModelException(
"Wrong response: cannot parse code from [" + line + "]");
}
 
String response = (line.length() >= 5) ? line.substring(4) : null;
 
if(code >= 200 && code < 300) {
logger.info("Response from backend [" + line + "]");
}
else if(code >= 400 && code < 600) {
throw new ModelException(
"Error from backend [" + line + "]");
}
 
codeDone = true;
}
else {
if(!line.equals(""))
throw new ModelException(
"Wrong response: no more lines expected [" + line + "]");
}
}
 
// done
socket.close();
}
catch(Exception ex) {
logger.error("Cannot send message over TCP", ex);
throw new ModelException("Cannot send message over TCP:" + ex.getMessage());
// FIMXE: or just throw "internal server error" message?
}
}
}
 
//=== user ====================================================================================
 
public void userCreated(User editor, User user)
throws ModelException
{
send("user\tcreate\tlogin=" + escape(user.getLogin())
+ "\tpassword=" + escape(user.getPassword(editor, PASSWORD_DIGEST))
+ "\tenabled=" + user.getEnabled()
+ "\tcomment=" + escape(user.getComment()));
}
 
public void userModified(User editor, User user, User oldUser)
throws ModelException
{
send("user\tmodify\toldLogin=" + escape(oldUser.getLogin())
+ "\tlogin=" + escape(user.getLogin())
+ "\tpassword=" + escape(user.getPassword(editor, PASSWORD_DIGEST))
+ "\tenabled=" + user.getEnabled()
+ "\tcomment=" + escape(user.getComment()));
}
 
public void userDeleted(User editor, User user)
throws ModelException
{
send("user\tdelete\tlogin=" + escape(user.getLogin()));
}
 
//=== inet domain =============================================================================
 
public void inetDomainCreated(User editor, InetDomain domain)
throws ModelException
{
send("inetDomain\tcreate\tname=" + escape(domain.getName())
+ "\tenabled=" + domain.getEnabled()
+ "\tcomment=" + escape(domain.getComment()));
}
 
public void inetDomainModified(User editor, InetDomain domain, InetDomain oldDomain)
throws ModelException
{
send("inetDomain\tmodify\toldName=" + escape(oldDomain.getName())
+ "\tname=" + escape(domain.getName())
+ "\tenabled=" + domain.getEnabled()
+ "\tcomment=" + escape(domain.getComment()));
}
 
public void inetDomainDeleted(User editor, InetDomain domain)
throws ModelException
{
send("inetDomain\tdelete\tname=" + escape(domain.getName()));
}
 
//=== system user =============================================================================
 
public void systemUserCreated(User editor, SystemUser systemUser)
throws ModelException
{
send("systemUser\tcreate\tuid=" + systemUser.getUid()
+ "\tname=" + escape(systemUser.getName())
+ "\tenabled=" + systemUser.getEnabled()
+ "\tcomment=" + escape(systemUser.getComment()));
}
 
public void systemUserModified(User editor, SystemUser systemUser, SystemUser oldSystemUser)
throws ModelException
{
send("systemUser\tmodify\toldUid=" + oldSystemUser.getUid()
+ "\toldName=" + escape(oldSystemUser.getName())
+ "\tuid=" + systemUser.getUid()
+ "\tname=" + escape(systemUser.getName())
+ "\tenabled=" + systemUser.getEnabled()
+ "\tcomment=" + escape(systemUser.getComment()));
}
 
public void systemUserDeleted(User editor, SystemUser systemUser)
throws ModelException
{
send("systemUser\tdelete\tuid=" + systemUser.getUid()
+ "\tname=" + escape(systemUser.getName()));
}
 
//=== mailbox =================================================================================
 
public void mailboxCreated(User editor, Mailbox mailbox)
throws ModelException
{
send("mailbox\tcreate\tlogin=" + escape(mailbox.getLogin())
+ "\tpassword=" + escape(mailbox.getPassword(editor, PASSWORD_DIGEST))
+ "\tdomain=" + escape(mailbox.getDomain().getName())
+ "\tvirusCheck=" + mailbox.getVirusCheck()
+ "\tspamCheck=" + mailbox.getSpamCheck()
+ "\tsystemUser=" + (mailbox.getSystemUser() == null
? "" : mailbox.getSystemUser().getUid().toString())
+ "\tenabled=" + mailbox.getEnabled()
+ "\tcomment=" + escape(mailbox.getComment()));
}
 
public void mailboxModified(User editor, Mailbox mailbox, Mailbox oldMailbox)
throws ModelException
{
send("mailbox\tmodify\toldLogin=" + escape(oldMailbox.getLogin())
+ "\toldDomain=" + escape(oldMailbox.getDomain().getName())
+ "\tlogin=" + escape(mailbox.getLogin())
+ "\tpassword=" + escape(mailbox.getPassword(editor, PASSWORD_DIGEST))
+ "\tdomain=" + escape(mailbox.getDomain().getName())
+ "\tvirusCheck=" + mailbox.getVirusCheck()
+ "\tspamCheck=" + mailbox.getSpamCheck()
+ "\tsystemUser=" + (mailbox.getSystemUser() == null
? "" : mailbox.getSystemUser().getUid().toString())
+ "\tenabled=" + mailbox.getEnabled()
+ "\tcomment=" + escape(mailbox.getComment()));
}
 
public void mailboxDeleted(User editor, Mailbox mailbox)
throws ModelException
{
send("mailbox\tdelete\tlogin=" + escape(mailbox.getLogin())
+ "\tdomain=" + escape(mailbox.getDomain().getName()));
}
 
//=== mail alias ==============================================================================
 
private String formMailAliasDestinations(User editor, MailAlias mailAlias)
throws ModelException
{
StringBuffer b = new StringBuffer();
 
Collection dests = mailAlias.getDestinations(editor);
if(dests != null) {
for(Iterator i = dests.iterator(); i.hasNext(); ) {
MailAliasDestination d = (MailAliasDestination)i.next();
b.append("\n\t");
if(d.getMailbox() != null)
b.append(escape(d.getMailbox().getLogin())).append("@").append(escape(d.getMailbox().getDomain().getName()));
else
b.append(escape(d.getEmail()));
}
}
 
return b.toString();
}
 
public void mailAliasCreated(User editor, MailAlias mailAlias)
throws ModelException
{
send("mailAlias\tcreate\taddress=" + escape(mailAlias.getAddress())
+ "\tdomain=" + escape(mailAlias.getDomain().getName())
+ "\tenabled=" + mailAlias.getEnabled()
+ "\tcomment=" + escape(mailAlias.getComment())
+ formMailAliasDestinations(editor, mailAlias));
}
 
public void mailAliasModified(User editor, MailAlias mailAlias, MailAlias oldMailAlias)
throws ModelException
{
send("mailAlias\tmodify\toldAddress=" + escape(oldMailAlias.getAddress())
+ "\toldDomain=" + escape(oldMailAlias.getDomain().getName())
+ "\taddress=" + escape(mailAlias.getAddress())
+ "\tdomain=" + escape(mailAlias.getDomain().getName())
+ "\tenabled=" + mailAlias.getEnabled()
+ "\tcomment=" + escape(mailAlias.getComment())
+ formMailAliasDestinations(editor, mailAlias));
}
 
public void mailAliasDeleted(User editor, MailAlias mailAlias)
throws ModelException
{
send("mailAlias\tdelete\taddress=" + escape(mailAlias.getAddress())
+ "\tdomain=" + escape(mailAlias.getDomain().getName()));
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/listener/uservalidatoratdomain/UserValidatorAtDomain.java
0,0 → 1,52
package ak.hostadmiral.listener.uservalidatoratdomain;
 
import java.util.Map;
import java.util.Collection;
import java.util.Iterator;
 
import ak.hostadmiral.core.model.User;
import ak.hostadmiral.core.model.UserManager;
import ak.hostadmiral.core.model.UserValidateListener;
import ak.hostadmiral.core.model.InetDomain;
import ak.hostadmiral.core.model.InetDomainManager;
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ModelUserException;
import ak.hostadmiral.util.ResourceManager;
 
public class UserValidatorAtDomain
implements
ConfigInit,
UserValidateListener
{
public void init(Map params)
{
UserManager.getInstance().addValidateListener(this);
ResourceManager.getInstance().addResource(
"ak.hostadmiral.listener.uservalidatoratdomain.UserValidatorAtDomainMessages");
}
 
public void userValidate(User editor, User user, User oldUser)
throws ModelException
{
// superuser
if(editor.isSuperuser()) return;
 
// login not changed
if(oldUser.getLogin() != null && user.getLogin().equals(oldUser.getLogin()))
return;
 
// go through all domains
Collection domains = InetDomainManager.getInstance().listInetDomains(editor);
for(Iterator i = domains.iterator(); i.hasNext(); ) {
InetDomain domain = (InetDomain)i.next();
 
if(user.getLogin().endsWith("@" + domain.getName()))
return;
}
 
// nothing found
throw new ModelUserException(
"ak.hostadmiral.listener.uservalidatoratdomain.login.wrong");
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/listener/uservalidatoratdomain/UserValidatorAtDomainMessages.properties
0,0 → 1,0
ak.hostadmiral.listener.uservalidatoratdomain.login.wrong=User login must be inside one of your domains, e.g. user@example.com
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/listener/file/FileListener.java
0,0 → 1,283
package ak.hostadmiral.listener.file;
 
import java.util.Map;
import java.util.Collection;
import java.util.Iterator;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.core.model.*;
 
import org.apache.log4j.Logger;
 
public class FileListener
implements
ConfigInit,
UserCreatedListener,
UserModifiedListener,
UserDeletedListener,
InetDomainCreatedListener,
InetDomainModifiedListener,
InetDomainDeletedListener,
SystemUserCreatedListener,
SystemUserModifiedListener,
SystemUserDeletedListener,
MailboxCreatedListener,
MailboxModifiedListener,
MailboxDeletedListener,
MailAliasCreatedListener,
MailAliasModifiedListener,
MailAliasDeletedListener
{
private static final Logger logger = Logger.getLogger(FileListener.class);
 
private static String fileName;
protected static Object lock = new Object();
 
public static final String PROTOCOL_NAME = "HostAdmiral_FileListener";
public static final String PROTOCOL_VERSION = "0.1";
 
public void init(Map params)
{
setFileName(((String[])params.get("fileName"))[0]);
 
UserManager.getInstance().addCreatedListener(this);
UserManager.getInstance().addModifiedListener(this);
UserManager.getInstance().addDeletedListener(this);
 
InetDomainManager.getInstance().addCreatedListener(this);
InetDomainManager.getInstance().addModifiedListener(this);
InetDomainManager.getInstance().addDeletedListener(this);
 
SystemUserManager.getInstance().addCreatedListener(this);
SystemUserManager.getInstance().addModifiedListener(this);
SystemUserManager.getInstance().addDeletedListener(this);
 
MailboxManager.getInstance().addCreatedListener(this);
MailboxManager.getInstance().addModifiedListener(this);
MailboxManager.getInstance().addDeletedListener(this);
 
MailAliasManager.getInstance().addCreatedListener(this);
MailAliasManager.getInstance().addModifiedListener(this);
MailAliasManager.getInstance().addDeletedListener(this);
}
 
public static String getFileName()
{
return fileName;
}
 
public static void setFileName(String fileName_)
{
fileName = fileName_;
}
 
protected static String escape(String s)
{
// FIXME: any other problem characters? optimize it?
s = s.replaceAll("\0", "\\\\0");
s = s.replaceAll("\\\\", "\\\\\\\\");
s = s.replaceAll("\t", "\\\\t");
s = s.replaceAll("\n", "\\\\n");
s = s.replaceAll("\r", "\\\\r");
return s;
}
 
protected static void send(String message)
throws ModelException
{
synchronized(lock) {
try {
Writer out = new BufferedWriter(new FileWriter(fileName));
if(PROTOCOL_NAME != null) {
out.write(PROTOCOL_NAME);
out.write(" ");
}
if(PROTOCOL_VERSION != null) {
out.write(PROTOCOL_VERSION);
out.write("\n");
}
out.write(message);
out.write("\n\n");
out.close();
}
catch(Exception ex) {
logger.error("Cannot save message to file", ex);
throw new ModelException("Cannot save message to file:" + ex.getMessage());
// FIMXE: or just throw "internal server error" message?
}
}
}
 
//=== user ====================================================================================
 
public void userCreated(User editor, User user)
throws ModelException
{
send("user\tcreate\t" + escape(user.getLogin()) + "\t"
+ escape(/* FIXME user.getPassword() */ "") + "\t"
+ user.getEnabled() + "\t"
+ escape(user.getComment()));
}
 
public void userModified(User editor, User user, User oldUser)
throws ModelException
{
send("user\tmodify\t" + escape(oldUser.getLogin()) + "\t"
+ escape(user.getLogin()) + "\t"
+ escape(/* FIXME user.getPassword() */ "") + "\t"
+ user.getEnabled() + "\t"
+ escape(user.getComment()));
}
 
public void userDeleted(User editor, User user)
throws ModelException
{
send("user\tdelete\t" + escape(user.getLogin()));
}
 
//=== inet domain =============================================================================
 
public void inetDomainCreated(User editor, InetDomain domain)
throws ModelException
{
send("inetDomain\tcreate\t" + escape(domain.getName()) + "\t"
+ domain.getEnabled() + "\t"
+ escape(domain.getComment()));
}
 
public void inetDomainModified(User editor, InetDomain domain, InetDomain oldDomain)
throws ModelException
{
send("inetDomain\tmodify\t" + escape(oldDomain.getName()) + "\t"
+ escape(domain.getName()) + "\t"
+ domain.getEnabled() + "\t"
+ escape(domain.getComment()));
}
 
public void inetDomainDeleted(User editor, InetDomain domain)
throws ModelException
{
send("inetDomain\tdelete\t" + escape(domain.getName()));
}
 
//=== system user =============================================================================
 
public void systemUserCreated(User editor, SystemUser systemUser)
throws ModelException
{
send("systemUser\tcreate\t" + systemUser.getUid() + "\t"
+ escape(systemUser.getName()) + "\t"
+ systemUser.getEnabled() + "\t"
+ escape(systemUser.getComment()));
}
 
public void systemUserModified(User editor, SystemUser systemUser, SystemUser oldSystemUser)
throws ModelException
{
send("systemUser\tmodify\t" + oldSystemUser.getUid() + "\t"
+ escape(oldSystemUser.getName()) + "\t"
+ systemUser.getUid() + "\t"
+ escape(systemUser.getName()) + "\t"
+ systemUser.getEnabled() + "\t"
+ escape(systemUser.getComment()));
}
 
public void systemUserDeleted(User editor, SystemUser systemUser)
throws ModelException
{
send("systemUser\tdelete\t" + systemUser.getUid() + "\t" + escape(systemUser.getName()));
}
 
//=== mailbox =================================================================================
 
public void mailboxCreated(User editor, Mailbox mailbox)
throws ModelException
{
send("mailbox\tcreate\t" + escape(mailbox.getLogin()) + "\t"
+ escape(/* FIXME user.getPassword() */ "") + "\t"
+ escape(mailbox.getDomain().getName()) + "\t"
+ mailbox.getVirusCheck() + "\t"
+ mailbox.getSpamCheck() + "\t"
+ (mailbox.getSystemUser() == null ? "" : mailbox.getSystemUser().getUid().toString())
+ "\t"
+ mailbox.getEnabled() + "\t"
+ escape(mailbox.getComment()));
}
 
public void mailboxModified(User editor, Mailbox mailbox, Mailbox oldMailbox)
throws ModelException
{
send("mailbox\tmodify\t" + escape(oldMailbox.getLogin()) + "\t"
+ escape(oldMailbox.getDomain().getName()) + "\t"
+ escape(mailbox.getLogin()) + "\t"
+ escape(/* FIXME user.getPassword() */ "") + "\t"
+ escape(mailbox.getDomain().getName()) + "\t"
+ mailbox.getVirusCheck() + "\t"
+ mailbox.getSpamCheck() + "\t"
+ (mailbox.getSystemUser() == null ? "" : mailbox.getSystemUser().getUid().toString())
+ "\t"
+ mailbox.getEnabled() + "\t"
+ escape(mailbox.getComment()));
}
 
public void mailboxDeleted(User editor, Mailbox mailbox)
throws ModelException
{
send("mailbox\tdelete\t" + escape(mailbox.getLogin()) + "\t"
+ escape(mailbox.getDomain().getName()));
}
 
//=== mail alias ==============================================================================
 
private String formMailAliasDestinations(User editor, MailAlias mailAlias)
throws ModelException
{
StringBuffer b = new StringBuffer();
 
Collection dests = mailAlias.getDestinations(editor);
if(dests != null) {
for(Iterator i = dests.iterator(); i.hasNext(); ) {
MailAliasDestination d = (MailAliasDestination)i.next();
b.append("\n\t");
if(d.getMailbox() != null)
b.append(escape(d.getMailbox().getLogin())).append("@").append(escape(d.getMailbox().getDomain().getName()));
else
b.append(escape(d.getEmail()));
}
}
 
return b.toString();
}
 
public void mailAliasCreated(User editor, MailAlias mailAlias)
throws ModelException
{
send(" mailAlias\tcreate\t" + escape(mailAlias.getAddress()) + "\t"
+ escape(mailAlias.getDomain().getName()) + "\t"
+ mailAlias.getEnabled() + "\t"
+ escape(mailAlias.getComment())
+ formMailAliasDestinations(editor, mailAlias));
}
 
public void mailAliasModified(User editor, MailAlias mailAlias, MailAlias oldMailAlias)
throws ModelException
{
send(" mailAlias\tmodify\t" + escape(oldMailAlias.getAddress()) + "\t"
+ escape(oldMailAlias.getDomain().getName()) + "\t"
+ escape(mailAlias.getAddress()) + "\t"
+ escape(mailAlias.getDomain().getName()) + "\t"
+ mailAlias.getEnabled() + "\t"
+ escape(mailAlias.getComment())
+ formMailAliasDestinations(editor, mailAlias));
}
 
public void mailAliasDeleted(User editor, MailAlias mailAlias)
throws ModelException
{
send(" mailAlias\tdelete\t" + escape(mailAlias.getAddress())+ "\t"
+ escape(mailAlias.getDomain().getName()));
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/listener/dummy/DummyListener.java
0,0 → 1,165
package ak.hostadmiral.listener.dummy;
 
import java.util.Map;
import ak.hostadmiral.util.ModelException;
import ak.hostadmiral.util.ConfigInit;
import ak.hostadmiral.core.model.*;
 
public class DummyListener
implements
ConfigInit,
UserCreatedListener,
UserModifiedListener,
UserDeletedListener,
InetDomainCreatedListener,
InetDomainModifiedListener,
InetDomainDeletedListener,
SystemUserCreatedListener,
SystemUserModifiedListener,
SystemUserDeletedListener,
MailboxCreatedListener,
MailboxModifiedListener,
MailboxDeletedListener,
MailAliasCreatedListener,
MailAliasModifiedListener,
MailAliasDeletedListener
{
public void init(Map params)
{
UserManager.getInstance().addCreatedListener(this);
UserManager.getInstance().addModifiedListener(this);
UserManager.getInstance().addDeletedListener(this);
 
InetDomainManager.getInstance().addCreatedListener(this);
InetDomainManager.getInstance().addModifiedListener(this);
InetDomainManager.getInstance().addDeletedListener(this);
 
SystemUserManager.getInstance().addCreatedListener(this);
SystemUserManager.getInstance().addModifiedListener(this);
SystemUserManager.getInstance().addDeletedListener(this);
 
MailboxManager.getInstance().addCreatedListener(this);
MailboxManager.getInstance().addModifiedListener(this);
MailboxManager.getInstance().addDeletedListener(this);
 
MailAliasManager.getInstance().addCreatedListener(this);
MailAliasManager.getInstance().addModifiedListener(this);
MailAliasManager.getInstance().addDeletedListener(this);
}
 
//=== user ====================================================================================
 
public void userCreated(User editor, User user)
throws ModelException
{
System.out.println("DummyListener.userCreated: "
+ user + " by " + editor);
}
 
public void userModified(User editor, User user, User oldUser)
throws ModelException
{
System.out.println("DummyListener.userModified: from " + oldUser
+ " to " + user + " by " + editor);
}
 
public void userDeleted(User editor, User user)
throws ModelException
{
System.out.println("DummyListener.userDeleted: "
+ user + " by " + editor);
}
 
//=== inet domain =============================================================================
 
public void inetDomainCreated(User editor, InetDomain domain)
throws ModelException
{
System.out.println("DummyListener.inetDomainCreated: "
+ domain + " by " + editor);
}
 
public void inetDomainModified(User editor, InetDomain domain, InetDomain oldDomain)
throws ModelException
{
System.out.println("DummyListener.inetDomainModified: from " + oldDomain
+ " to " + domain + " by " + editor);
}
 
public void inetDomainDeleted(User editor, InetDomain domain)
throws ModelException
{
System.out.println("DummyListener.inetDomainDeleted: "
+ domain + " by " + editor);
}
 
//=== system user =============================================================================
 
public void systemUserCreated(User editor, SystemUser systemUser)
throws ModelException
{
System.out.println("DummyListener.systemUserCreated: "
+ systemUser + " by " + editor);
}
 
public void systemUserModified(User editor, SystemUser systemUser, SystemUser oldSystemUser)
throws ModelException
{
System.out.println("DummyListener.systemUserModified: from " + oldSystemUser
+ " to " + systemUser + " by " + editor);
}
 
public void systemUserDeleted(User editor, SystemUser systemUser)
throws ModelException
{
System.out.println("DummyListener.systemUserDeleted: "
+ systemUser + " by " + editor);
}
 
//=== mailbox =================================================================================
 
public void mailboxCreated(User editor, Mailbox mailbox)
throws ModelException
{
System.out.println("DummyListener.mailboxCreated: "
+ mailbox + " by " + editor);
}
 
public void mailboxModified(User editor, Mailbox mailbox, Mailbox oldMailbox)
throws ModelException
{
System.out.println("DummyListener.mailboxModified: from " + oldMailbox
+ " to " + mailbox + " by " + editor);
}
 
public void mailboxDeleted(User editor, Mailbox mailbox)
throws ModelException
{
System.out.println("DummyListener.mailboxDeleted: "
+ mailbox + " by " + editor);
}
 
//=== mail alias ==============================================================================
 
public void mailAliasCreated(User editor, MailAlias mailAlias)
throws ModelException
{
System.out.println("DummyListener.mailAliasCreated: "
+ mailAlias + " by " + editor);
}
 
public void mailAliasModified(User editor, MailAlias mailAlias, MailAlias oldMailAlias)
throws ModelException
{
System.out.println("DummyListener.mailAliasModified: from " + oldMailAlias
+ " to " + mailAlias + " by " + editor);
}
 
public void mailAliasDeleted(User editor, MailAlias mailAlias)
throws ModelException
{
System.out.println("DummyListener.mailAliasDeleted: "
+ mailAlias + " by " + editor);
}
 
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/servlet/sessioncontrol/SessionBug.java
0,0 → 1,19
package ak.hostadmiral.servlet.sessioncontrol;
 
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
 
public final class SessionBug
implements HttpSessionActivationListener, Serializable
{
public void sessionDidActivate(HttpSessionEvent se)
{
SessionControl.getInstance().addSession(se.getSession());
}
 
public void sessionWillPassivate(HttpSessionEvent se)
{
SessionControl.getInstance().removeSession(se.getSession());
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/servlet/sessioncontrol/SessionControl.java
0,0 → 1,41
package ak.hostadmiral.servlet.sessioncontrol;
 
import java.util.Collections;
import java.util.Collection;
import java.util.HashSet;
 
import javax.servlet.http.HttpSession;
 
import org.apache.log4j.Logger;
 
public final class SessionControl
{
private static final Logger logger = Logger.getLogger(SessionControl.class);
 
protected Collection sessions = new HashSet(); // Collection(HttpSession)
 
public void addSession(HttpSession s)
{
logger.info("session added " + s.getId());
sessions.add(s);
s.setAttribute(SessionBug.class.getName(), new SessionBug());
}
 
public void removeSession(HttpSession s)
{
logger.info("session removed " + s.getId());
sessions.remove(s);
}
 
public Collection getSessions()
{
return Collections.unmodifiableCollection(sessions);
}
 
private static SessionControl sessionControl = new SessionControl();
 
public static SessionControl getInstance()
{
return sessionControl;
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/servlet/sessioncontrol/SessionObserver.java
0,0 → 1,18
package ak.hostadmiral.servlet.sessioncontrol;
 
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
 
public final class SessionObserver
implements HttpSessionListener
{
public void sessionCreated(HttpSessionEvent se)
{
SessionControl.getInstance().addSession(se.getSession());
}
 
public void sessionDestroyed(HttpSessionEvent se)
{
SessionControl.getInstance().removeSession(se.getSession());
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/struts/MultiPropertyMessageResources.java
0,0 → 1,71
package ak.hostadmiral.struts;
 
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.struts.util.PropertyMessageResources;
 
import ak.hostadmiral.util.ResourceManager;
import ak.hostadmiral.util.ResourceAddedListener;
 
/**
* Extention of PropertyMessageResources to work with multiple
* resource files, specified as semicolomn separated list.
* Just a hack.
*/
public class MultiPropertyMessageResources
extends PropertyMessageResources
implements ResourceAddedListener
{
private List multiLocales = new ArrayList(); // List(HashMap)
private List multiConfig = new ArrayList(); // List(String)
 
public MultiPropertyMessageResources(MultiPropertyMessageResourcesFactory factory,
String config)
{
super(factory, config);
initMultiConfig(config);
ResourceManager.getInstance().addAddedListener(this);
}
 
public MultiPropertyMessageResources(MultiPropertyMessageResourcesFactory factory,
String config, boolean returnNull)
{
super(factory, config, returnNull);
initMultiConfig(config);
ResourceManager.getInstance().addAddedListener(this);
}
 
protected synchronized void loadLocale(String localeKey)
{
for(int i = 0; i < multiConfig.size(); i++) {
config = (String)multiConfig.get(i);
locales = (HashMap)multiLocales.get(i);
super.loadLocale(localeKey);
}
}
 
protected void initMultiConfig(String cfg)
{
// from struts-config.xml
String[] strs = cfg.split("\\s*;\\s*");
 
for(int i = 0; i < strs.length; i++) {
this.multiConfig.add(strs[i]);
this.multiLocales.add(new HashMap());
}
 
// from resource manager
for(Iterator i = ResourceManager.getInstance().getResources().iterator(); i.hasNext(); ) {
this.multiConfig.add((String)i.next());
this.multiLocales.add(new HashMap());
}
}
 
public void resourceAdded(String resourceName)
{
this.multiConfig.add(resourceName);
this.multiLocales.add(new HashMap());
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/struts/MultiPropertyMessageResourcesFactory.java
0,0 → 1,13
package ak.hostadmiral.struts;
 
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.PropertyMessageResourcesFactory;
 
public class MultiPropertyMessageResourcesFactory
extends PropertyMessageResourcesFactory
{
public MessageResources createResources(String config)
{
return new MultiPropertyMessageResources(this, config, this.returnNull);
}
}
/hostadmiral/branches/hibernate3/src/ak/hostadmiral/version
0,0 → 1,0
0.1.@BUILD@
/hostadmiral/branches/hibernate3/src/ak/strutsx/taglib/EmptyTag.java
0,0 → 1,56
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx.taglib;
 
import java.util.Iterator;
import java.util.Collection;
import java.util.Map;
import javax.servlet.jsp.JspException;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.taglib.logic.ConditionalTagBase;
 
public class EmptyTag
extends ConditionalTagBase
{
protected boolean condition()
throws JspException
{
return condition(true);
}
 
protected boolean condition(boolean desired)
throws JspException
{
if(this.name == null) {
JspException e = new JspException(messages.getMessage("empty.noNameAttribute"));
RequestUtils.saveException(pageContext, e);
throw e;
}
 
boolean empty = true;
 
Object value = null;
if(this.property == null)
value = RequestUtils.lookup(pageContext, name, scope);
else
value = RequestUtils.lookup(pageContext, name, property, scope);
 
if(value != null) {
if(value instanceof String)
empty = (((String)value).length() < 1);
else if(value instanceof Collection)
empty = ((Collection)value).isEmpty();
else if(value instanceof Map)
empty = ((Map)value).isEmpty();
else if(value instanceof Iterator)
empty = !((Iterator)value).hasNext();
else
empty = false;
}
 
return (empty == desired);
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/taglib/NotEmptyTag.java
0,0 → 1,18
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx.taglib;
 
import javax.servlet.jsp.JspException;
 
public class NotEmptyTag
extends EmptyTag
{
protected boolean condition()
throws JspException
{
return condition(false);
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/taglib/RootTag.java
0,0 → 1,37
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx.taglib;
 
import java.io.IOException;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
 
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
 
public class RootTag
extends TagSupport
{
public int doStartTag()
throws JspException
{
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
 
try {
pageContext.getOut().write(request.getContextPath());
}
catch(IOException ex) {
throw new JspException("Cannot write to output" + ex);
}
 
return EVAL_BODY_INCLUDE;
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/taglib/MessageTag.java
0,0 → 1,91
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx.taglib;
 
import java.util.Locale;
 
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
 
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;
 
public class MessageTag
extends org.apache.struts.taglib.bean.MessageTag
{
protected String valuesName = null;
 
public String getValuesName()
{
return this.valuesName;
}
 
public void setValuesName(String valuesName)
{
this.valuesName = valuesName;
}
 
protected String valuesProperty = null;
 
public String getValuesProperty()
{
return this.valuesProperty;
}
 
public void setValuesProperty(String valuesProperty)
{
this.valuesProperty = valuesProperty;
}
 
public int doStartTag()
throws JspException
{
String key = this.key;
if(key == null) {
Object value = RequestUtils.lookup(pageContext, name, property, scope);
if(value != null && !(value instanceof String)) {
JspException e = new JspException(messages.getMessage("message.property", key));
RequestUtils.saveException(pageContext, e);
throw e;
}
key = (String)value;
}
 
Object[] values = null;
if(valuesName != null || valuesProperty != null) {
Object valuesObj = RequestUtils.lookup(pageContext,
(valuesName == null) ? name : valuesName, valuesProperty, scope);
if(valuesObj != null && !(valuesObj instanceof Object[])) {
JspException e = new JspException("Properties are not an array");
RequestUtils.saveException(pageContext, e);
throw e;
}
values = (Object[])valuesObj;
}
 
String message = RequestUtils.message(pageContext, this.bundle,
this.localeKey, key, values);
 
if(message == null) {
JspException e = new JspException
(messages.getMessage("message.message", "\"" + key + "\""));
RequestUtils.saveException(pageContext, e);
throw e;
}
 
ResponseUtils.write(pageContext, message);
return SKIP_BODY;
}
 
public void release()
{
super.release();
valuesName = null;
valuesProperty = null;
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/taglib/ErrorsIteratorTag.java
0,0 → 1,46
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx.taglib;
 
import javax.servlet.jsp.JspException;
 
import org.apache.struts.action.ActionErrors;
import org.apache.struts.taglib.html.ErrorsTag;
import org.apache.struts.util.RequestUtils;
 
public class ErrorsIteratorTag
extends ErrorsTag
{
protected String id = null;
 
public String getId()
{
return this.id;
}
 
public void setId(String id)
{
this.id = id;
}
 
public int doStartTag()
throws JspException
{
ActionErrors errors = RequestUtils.getActionErrors(pageContext, name);
 
if(errors != null)
pageContext.setAttribute(id, (property == null) ? errors.get() : errors.get(property));
 
return EVAL_BODY_INCLUDE;
}
 
public void release()
{
super.release();
 
id = null;
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/ResizeableDynaValidatorForm.java
0,0 → 1,91
package ak.strutsx;
 
import java.util.Iterator;
import java.util.TreeSet;
import java.lang.reflect.Array;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.validator.DynaValidatorForm;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
 
public final class ResizeableDynaValidatorForm
extends DynaValidatorForm
{
public void reset(ActionMapping mapping, HttpServletRequest request)
{
super.reset(mapping, request);
resize(mapping, request);
}
 
protected void resize(ActionMapping mapping, HttpServletRequest request)
{
String name = mapping.getName();
if (name == null) return;
 
FormBeanConfig config = mapping.getModuleConfig().findFormBeanConfig(name);
if (config == null) return;
 
FormPropertyConfig props[] = config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++) {
if(props[i].getSize() > 0) // for arrays only
resize(mapping, request, props[i]);
}
}
 
protected void resize(ActionMapping mapping, HttpServletRequest request,
FormPropertyConfig prop)
{
String nameStart = prop.getName() + "[";
 
// get all indices
TreeSet indices = new TreeSet();
for(Iterator i = request.getParameterMap().keySet().iterator(); i.hasNext(); ) {
String name = (String)i.next();
if(name.startsWith(nameStart)) {
int p = name.indexOf("]");
if(p > 0) {
String index = name.substring(nameStart.length(), p);
try {
indices.add(new Integer(index));
}
catch(NumberFormatException ex) {
}
}
}
}
 
// find last index in sequence
int lastIndex = -1;
for(Iterator i = indices.iterator(); i.hasNext(); ) {
Integer idx = (Integer)i.next();
if(idx.intValue() == lastIndex+1)
lastIndex++;
else
break;
}
 
// grow
if(lastIndex > 0) {
Class clazz = prop.getTypeClass();
Object initialValue = Array.newInstance(clazz.getComponentType(), lastIndex+1);
for (int i = 0; i < lastIndex+1; i++) {
try {
Array.set(initialValue, i, clazz.getComponentType().newInstance());
}
catch (Throwable t) {
; // Probably does not have a zero-args constructor
}
}
set(prop.getName(), initialValue);
}
}
 
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
{
ActionErrors errors = super.validate(mapping, request);
 
return errors;
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/ErrorHandlerX.java
0,0 → 1,23
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx;
 
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
 
 
public interface ErrorHandlerX {
 
public void handleErrors(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/RequestProcessorX.java
0,0 → 1,231
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx;
 
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.RequestProcessor;
import org.apache.struts.config.ForwardConfig;
 
/**
* To use this processor add
* &lt;controller processorClass="ak.strutsx.RequestProcessorX" /&gt;
* into the struts-config.xml file.
*/
public class RequestProcessorX
extends RequestProcessor
{
/**
* <p>Process an <code>HttpServletRequest</code> and create the
* corresponding <code>HttpServletResponse</code>.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a processing exception occurs
*/
public void process(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
 
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
 
// Identify the path component we will use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
 
// Select a Locale for the current user if requested
processLocale(request, response);
 
// Set the content type and no-caching headers if requested
processContent(request, response);
processNoCache(request, response);
 
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
 
// Identify the mapping for this request
ActionMapping mapping = processMapping(request, response, path);
if (mapping == null) {
return;
}
 
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
 
// Create or acquire the Action instance to process this request
// Do this here, because we need the action in case form validation is failed
Action action = null;
if (mapping.getType() != null) {
action = processActionCreate(request, response, mapping);
}
 
// Process any ActionForm bean related to this request
ActionForm form = processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, action, form, mapping)) {
return;
}
 
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
 
// no action
if (action == null) {
return;
}
 
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
 
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
 
}
 
/**
* <p>If this request was not cancelled, and the request's
* {@link ActionMapping} has not disabled validation, call the
* <code>validate()</code> method of the specified {@link ActionForm},
* and forward back to the input form if there were any errors.
* Return <code>true</code> if we should continue processing,
* or <code>false</code> if we have already forwarded control back
* to the input form.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param action The Action instance we are populating
* @param form The ActionForm instance we are populating
* @param mapping The ActionMapping we are using
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
protected boolean processValidate(HttpServletRequest request,
HttpServletResponse response,
Action action,
ActionForm form,
ActionMapping mapping)
throws IOException, ServletException {
 
if (form == null) {
return (true);
}
 
// Was this request cancelled?
if (request.getAttribute(Globals.CANCEL_KEY) != null) {
if (log.isDebugEnabled()) {
log.debug(" Cancelled transaction, skipping validation");
}
return (true);
}
 
// Has validation been turned off for this mapping?
if (!mapping.getValidate()) {
return (true);
}
 
// Call the form bean's validation method
if (log.isDebugEnabled()) {
log.debug(" Validating input form properties");
}
ActionErrors errors = form.validate(mapping, request);
if ((errors == null) || errors.isEmpty()) {
if (log.isTraceEnabled()) {
log.trace(" No errors detected, accepting input");
}
return (true);
}
 
// Form validation failed, try to inform the action
if((action != null) && (action instanceof ErrorHandlerX)) {
processValidationFailed(request, response,
(ErrorHandlerX)action, form, mapping);
}
 
// Special handling for multipart request
if (form.getMultipartRequestHandler() != null) {
if (log.isTraceEnabled()) {
log.trace(" Rolling back multipart request");
}
form.getMultipartRequestHandler().rollback();
}
 
// Has an input form been specified for this mapping?
String input = mapping.getInput();
if (input == null) {
if (log.isTraceEnabled()) {
log.trace(" Validation failed but no input form available");
}
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
getInternal().getMessage("noInput",
mapping.getPath()));
return (false);
}
 
// Save our error messages and return to the input form if possible
if (log.isDebugEnabled()) {
log.debug(" Validation failed, returning to '" + input + "'");
}
request.setAttribute(Globals.ERROR_KEY, errors);
 
if (moduleConfig.getControllerConfig().getInputForward()) {
ForwardConfig forward = mapping.findForward(input);
processForwardConfig( request, response, forward);
} else {
internalModuleRelativeForward(input, request, response);
}
 
return (false);
 
}
 
protected void
processValidationFailed(HttpServletRequest request,
HttpServletResponse response,
ErrorHandlerX errorHandler,
ActionForm form,
ActionMapping mapping)
throws IOException, ServletException {
 
try {
errorHandler.handleErrors(mapping, form, request, response);
} catch (Exception e) {
processException(request, response, e, form, mapping);
}
 
}
}
/hostadmiral/branches/hibernate3/src/ak/strutsx/RequestUtilsX.java
0,0 → 1,107
/**
* Extends and based on Apache Struts source code.
*
* Copyleft Anatoli Klassen (anatoli@aksoft.net)
*/
package ak.strutsx;
 
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.action.DynaActionFormClass;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.FormPropertyConfig;
import org.apache.struts.util.RequestUtils;
 
 
public class RequestUtilsX
extends RequestUtils
{
public static ActionForm populateActionForm(
Action action,
HttpServletRequest request,
String name)
throws ServletException {
 
ActionForm form = createActionForm(action, request, name);
RequestUtils.populate(form, request);
request.setAttribute(name, form);
return form;
}
 
public static ActionForm createActionForm(
Action action,
HttpServletRequest request,
String name) {
 
return createActionForm(name,
(ModuleConfig)request.getAttribute(Globals.MODULE_KEY), action.getServlet());
}
 
public static ActionForm createActionForm(
String name,
ModuleConfig moduleConfig,
ActionServlet servlet) {
 
FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
ActionForm instance = null;
 
// Create and return a new form bean instance
if (config.getDynamic()) {
try {
DynaActionFormClass dynaClass =
DynaActionFormClass.createDynaActionFormClass(config);
instance = (ActionForm) dynaClass.newInstance();
initializeDynaActionForm((DynaActionForm) instance, config);
if (log.isDebugEnabled()) {
log.debug(
" Creating new DynaActionForm instance "
+ "of type '"
+ config.getType()
+ "'");
log.trace(" --> " + instance);
}
} catch (Throwable t) {
log.error(servlet.getInternal().getMessage("formBean", config.getType()), t);
return (null);
}
} else {
try {
instance = (ActionForm) applicationInstance(config.getType());
if (log.isDebugEnabled()) {
log.debug(
" Creating new ActionForm instance "
+ "of type '"
+ config.getType()
+ "'");
log.trace(" --> " + instance);
}
} catch (Throwable t) {
log.error(servlet.getInternal().getMessage("formBean", config.getType()), t);
return (null);
}
}
instance.setServlet(servlet);
return (instance);
 
}
 
public static void initializeDynaActionForm(DynaActionForm instance, FormBeanConfig config) {
 
if (config == null) {
return;
}
FormPropertyConfig props[] = config.findFormPropertyConfigs();
for (int i = 0; i < props.length; i++) {
instance.set(props[i].getName(), props[i].initial());
}
 
}
}
/hostadmiral/branches/hibernate3/src/log4j.properties
0,0 → 1,11
log4j.rootLogger=warn, stdout
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
 
log4j.logger.ak=debug
log4j.logger.ak.hostadmiral=debug
 
log4j.logger.net.sf.hibernate=error
 
/hostadmiral/branches/hibernate3/src/hibernate.cfg.xml
0,0 → 1,12
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
 
<hibernate-configuration>
<session-factory name="java:comp/env/hibernate/SessionFactory">
<property name="show_sql">true</property>
<mapping resource="ak/hostadmiral/util/hibernate/DatabaseVersion.hbm.xml"/>
</session-factory>
</hibernate-configuration>