From 2cf0d6c4b8a5fcb36691cc096d8876238823c766 Mon Sep 17 00:00:00 2001 From: Peter Hormanns Date: Fri, 21 Jun 2013 17:32:38 +0200 Subject: [PATCH] transform EMailAliasModul zu SessionBean --- hsarback/build.xml | 13 +- hsarback/conf/WEB-INF/dev-web.xml | 111 ---- hsarback/conf/WEB-INF/prod-web.xml | 111 ---- hsarback/conf/WEB-INF/test-web.xml | 111 ---- .../cliClientConnector/ArgumentParser.java | 357 ------------- .../cliClientConnector/BusinessException.java | 15 - .../CLIClientConnectorServlet.java | 497 ------------------ .../cliClientConnector/ModuleModel.java | 19 - .../OidsNotFoundException.java | 25 - .../cliClientConnector/VersionModel.java | 14 - .../de/hsadmin/core/model/LoginSession.java | 93 ++++ .../de/hsadmin/core/model/QueueManager.java | 46 ++ .../model}/TechnicalException.java | 2 +- .../hsadmin/core/model/TicketValidator.java | 1 + .../de/hsadmin/core/model/Transaction.java | 1 - .../qserv/QueueStatusReceiverServlet.java | 2 +- .../de/hsadmin/core/util/ReflectionUtil.java | 2 +- .../mods/email/EMailAddressModuleImpl.java | 4 +- .../mods/email/EMailAliasModuleImpl.java | 234 ++++++++- .../de/hsadmin/remote/EMailAliasRemote.java | 199 ++++++- .../hsadmin/remote/GenericAbstractRemote.java | 2 +- 21 files changed, 571 insertions(+), 1288 deletions(-) delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/ArgumentParser.java delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/BusinessException.java delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/CLIClientConnectorServlet.java delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/ModuleModel.java delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/OidsNotFoundException.java delete mode 100644 hsarback/src/de/hsadmin/cliClientConnector/VersionModel.java create mode 100644 hsarback/src/de/hsadmin/core/model/LoginSession.java create mode 100644 hsarback/src/de/hsadmin/core/model/QueueManager.java rename hsarback/src/de/hsadmin/{cliClientConnector => core/model}/TechnicalException.java (97%) diff --git a/hsarback/build.xml b/hsarback/build.xml index 469f130..641bed3 100644 --- a/hsarback/build.xml +++ b/hsarback/build.xml @@ -23,7 +23,10 @@ - + + + + @@ -68,11 +71,9 @@ - - - - - + + + diff --git a/hsarback/conf/WEB-INF/dev-web.xml b/hsarback/conf/WEB-INF/dev-web.xml index 34ee706..87ab4f5 100644 --- a/hsarback/conf/WEB-INF/dev-web.xml +++ b/hsarback/conf/WEB-INF/dev-web.xml @@ -14,112 +14,6 @@ 1 - - CLI Client Connector - de.hsadmin.cliClientConnector.CLIClientConnectorServlet - - proxyValidateUrl - TestUmgebung - - - proxyServiceUrl - TestUmgebung - - - Components - member,pac,user,domain,emailaddress,emailalias,mysqluser,mysqldb,postgresqluser,postgresqldb,q - - - ComponentClass_member - de.hsadmin.mods.cust.Customer - - - ComponentDescription_member - Mitglieder - - - ComponentClass_pac - de.hsadmin.mods.pac.Pac - - - ComponentDescription_pac - Pakete - - - ComponentClass_user - de.hsadmin.mods.user.UnixUser - - - ComponentDescription_user - Benutzer und Postfaecher anlegen - - - ComponentClass_domain - de.hsadmin.mods.dom.Domain - - - ComponentDescription_domain - Domains aufschalten - - - ComponentClass_emailaddress - de.hsadmin.mods.email.EMailAddress - - - ComponentDescription_emailaddress - E-Mail Adressen - - - ComponentClass_emailalias - de.hsadmin.mods.email.EMailAlias - - - ComponentDescription_emailalias - E-Mail Aliases - - - ComponentClass_postgresqluser - de.hsadmin.mods.db.PgSqlUser - - - ComponentDescription_postgresqluser - PostgreSQL DB-Administrator - - - ComponentClass_postgresqldb - de.hsadmin.mods.db.PgSqlDatabase - - - ComponentDescription_postgresqldb - PostgreSQL Datenbank - - - ComponentClass_mysqluser - de.hsadmin.mods.db.MySqlUser - - - ComponentDescription_mysqluser - MySQL DB-Administrator - - - ComponentClass_mysqldb - de.hsadmin.mods.db.MySqlDatabase - - - ComponentDescription_mysqldb - MySQL Datenbank - - - ComponentClass_q - de.hsadmin.core.qserv.QueueTask - - - ComponentDescription_q - Offene Aktionen - - 1 - - XmlRpcServlet de.hsadmin.remote.HSXmlRpcServlet @@ -134,11 +28,6 @@ /queueStatus - - CLI Client Connector - /hsadmin/cli-interface/ - - XmlRpcServlet /xmlrpc/* diff --git a/hsarback/conf/WEB-INF/prod-web.xml b/hsarback/conf/WEB-INF/prod-web.xml index 9ddf170..a684d6d 100644 --- a/hsarback/conf/WEB-INF/prod-web.xml +++ b/hsarback/conf/WEB-INF/prod-web.xml @@ -14,112 +14,6 @@ 1 - - CLI Client Connector - de.hsadmin.cliClientConnector.CLIClientConnectorServlet - - proxyValidateUrl - https://@LOGIN_HOST@:@LOGIN_PORT@/cas/proxyValidate - - - proxyServiceUrl - https://@CONFIG_HOST@:@CONFIG_PORT@/hsar/backend - - - Components - member,pac,user,domain,emailaddress,emailalias,mysqluser,mysqldb,postgresqluser,postgresqldb,q - - - ComponentClass_member - de.hsadmin.mods.cust.Customer - - - ComponentDescription_member - Mitglieder - - - ComponentClass_pac - de.hsadmin.mods.pac.Pac - - - ComponentDescription_pac - Pakete - - - ComponentClass_user - de.hsadmin.mods.user.UnixUser - - - ComponentDescription_user - Benutzer und Postfaecher anlegen - - - ComponentClass_domain - de.hsadmin.mods.dom.Domain - - - ComponentDescription_domain - Domains aufschalten - - - ComponentClass_emailaddress - de.hsadmin.mods.email.EMailAddress - - - ComponentDescription_emailaddress - E-Mail Adressen - - - ComponentClass_emailalias - de.hsadmin.mods.email.EMailAlias - - - ComponentDescription_emailalias - E-Mail Aliases - - - ComponentClass_postgresqluser - de.hsadmin.mods.db.PgSqlUser - - - ComponentDescription_postgresqluser - PostgreSQL DB-Administrator - - - ComponentClass_postgresqldb - de.hsadmin.mods.db.PgSqlDatabase - - - ComponentDescription_postgresqldb - PostgreSQL Datenbank - - - ComponentClass_mysqluser - de.hsadmin.mods.db.MySqlUser - - - ComponentDescription_mysqluser - MySQL DB-Administrator - - - ComponentClass_mysqldb - de.hsadmin.mods.db.MySqlDatabase - - - ComponentDescription_mysqldb - MySQL Datenbank - - - ComponentClass_q - de.hsadmin.core.qserv.QueueTask - - - ComponentDescription_q - Offene Aktionen - - 1 - - XmlRpcServlet de.hsadmin.remote.HSXmlRpcServlet @@ -134,11 +28,6 @@ /queueStatus - - CLI Client Connector - /hsadmin/cli-interface/ - - XmlRpcServlet /xmlrpc/* diff --git a/hsarback/conf/WEB-INF/test-web.xml b/hsarback/conf/WEB-INF/test-web.xml index 4f7bf97..35a60a4 100644 --- a/hsarback/conf/WEB-INF/test-web.xml +++ b/hsarback/conf/WEB-INF/test-web.xml @@ -14,112 +14,6 @@ 1 - - CLI Client Connector - de.hsadmin.cliClientConnector.CLIClientConnectorServlet - - proxyValidateUrl - https://@LOGIN_HOST@:@LOGIN_PORT@/cas/proxyValidate - - - proxyServiceUrl - https://@CONFIG_HOST@:@CONFIG_PORT@/hsar/backend - - - Components - member,pac,user,domain,emailaddress,emailalias,mysqluser,mysqldb,postgresqluser,postgresqldb,q - - - ComponentClass_member - de.hsadmin.mods.cust.Customer - - - ComponentDescription_member - Mitglieder - - - ComponentClass_pac - de.hsadmin.mods.pac.Pac - - - ComponentDescription_pac - Pakete - - - ComponentClass_user - de.hsadmin.mods.user.UnixUser - - - ComponentDescription_user - Benutzer und Postfaecher anlegen - - - ComponentClass_domain - de.hsadmin.mods.dom.Domain - - - ComponentDescription_domain - Domains aufschalten - - - ComponentClass_emailaddress - de.hsadmin.mods.email.EMailAddress - - - ComponentDescription_emailaddress - E-Mail Adressen - - - ComponentClass_emailalias - de.hsadmin.mods.email.EMailAlias - - - ComponentDescription_emailalias - E-Mail Aliases - - - ComponentClass_postgresqluser - de.hsadmin.mods.db.PgSqlUser - - - ComponentDescription_postgresqluser - PostgreSQL DB-Administrator - - - ComponentClass_postgresqldb - de.hsadmin.mods.db.PgSqlDatabase - - - ComponentDescription_postgresqldb - PostgreSQL Datenbank - - - ComponentClass_mysqluser - de.hsadmin.mods.db.MySqlUser - - - ComponentDescription_mysqluser - MySQL DB-Administrator - - - ComponentClass_mysqldb - de.hsadmin.mods.db.MySqlDatabase - - - ComponentDescription_mysqldb - MySQL Datenbank - - - ComponentClass_q - de.hsadmin.core.qserv.QueueTask - - - ComponentDescription_q - Offene Aktionen - - 1 - - XmlRpcServlet de.hsadmin.remote.HSXmlRpcServlet @@ -134,11 +28,6 @@ /queueStatus - - CLI Client Connector - /hsadmin/cli-interface/ - - XmlRpcServlet /xmlrpc/* diff --git a/hsarback/src/de/hsadmin/cliClientConnector/ArgumentParser.java b/hsarback/src/de/hsadmin/cliClientConnector/ArgumentParser.java deleted file mode 100644 index 1f88492..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/ArgumentParser.java +++ /dev/null @@ -1,357 +0,0 @@ -package de.hsadmin.cliClientConnector; - -import java.lang.reflect.Method; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; - -import de.hsadmin.cliClientConnector.CLIClientConnectorServlet.FunctionNotKnownException; -import de.hsadmin.cliClientConnector.CLIClientConnectorServlet.UnknownModuleException; -import de.hsadmin.core.model.AbstractEntity; -import de.hsadmin.core.model.ModuleInterface; - -/** - * Parses Arguments for the CLI Client Connector Servlet - * - * @author Christof Donat - * - */ -public class ArgumentParser { - /// I am working for this Servlet instance - private CLIClientConnectorServlet master; - private DateFormat df = new SimpleDateFormat( "yyyy-MM-dd"); - - public ArgumentParser(CLIClientConnectorServlet master) { - this.master = master; - } - - private String getUsageString() { - return " [ (-W name=value|--globalWhere:name=value) ...]\n"+ - " [ (-S name=value|--globalSet:name=value) ...]\n"+ - " [ (-D displayspec|--globalDisplay=displayspec) ...]\n"+ - " [ (-c module.function|--call=module.function)\n" + - " [ (-w name=value|--where:name=value) ...]\n"+ - " [ (-s name=value|--set:name=value) ...]\n"+ - " [ (-d displayspec|--display:displayspec) ...]\n"+ - " [ oids ...] ] ]\n"+ - "\n"+ - "(" + CLIClientConnectorServlet.version + ")\n"; - } - - private ArrayList getMethodList(Object o) { - Method[] meths = o.getClass().getMethods(); - ArrayList methodlist = new ArrayList(); - - for( int i = 0; i < meths.length; i++ ) { - Method m = meths[i]; - String n = m.getName(); - if( n.startsWith("get") && !n.equals("getNew") ) { - String fn = m.getName().substring(3).toLowerCase(); - if( fn.equals("class") ) continue; - if (m.getParameterTypes().length == 0) { - methodlist.add(m); - } - } - } - - return methodlist; - } - - private Hashtable getValues(Object o, ArrayList methodlist, ArrayListfieldNames, boolean deep, ArrayList foundObjects) { - Hashtable row = new Hashtable(); - int i, j; - - if( foundObjects == null ) foundObjects = new ArrayList(); - - for( i = 0; i < methodlist.size(); i++ ) { - Method m = methodlist.get(i); - try { - String name = fieldNames.get(i); - String type = m.getReturnType().getCanonicalName(); - String val = ""; - - Object value = null; - try { - value = m.invoke(o); - } catch( Exception e ) { - e.printStackTrace(); - } - - if( value == null ) - val = ""; - else if( type.equals("java.lang.String") ) - val = (String)value; - else if( type.equals("java.lang.Integer") ) - val = String.valueOf((Integer)value); - else if( type.equals("java.lang.Long") ) - val = String.valueOf((Long)value); - else if( type.equals("java.lang.Boolean") ) - val = String.valueOf((Boolean)value); - else if( type.equals("java.util.Date") ) { - val = df.format((Date)value); - } else if( type.equals("java.util.Set") ) { - val = ""; - } else try { - AbstractEntity v = (AbstractEntity)value; - val = v.createStringKey(); - if( deep && !foundObjects.contains(v) ) { - foundObjects.add(v); - ArrayList fieldNamesDeep = new ArrayList(); - ArrayList methodlistDeep = getMethodList(v); - for( j = 0; j < methodlistDeep.size(); j++ ) { - fieldNamesDeep.add(methodlistDeep.get(j).getName().substring(3).toLowerCase()); - } - Hashtable tmp = getValues(v,methodlistDeep,fieldNamesDeep,deep,foundObjects); - Enumeration keys = tmp.keys(); - while(keys.hasMoreElements()) { - try { - String k = (String)keys.nextElement(); - row.put(name+"."+k, tmp.get(k)); - } catch( Exception e ) { - e.printStackTrace(); - } - } - } - } catch(ClassCastException e) { - val = value.toString(); - } - if (val != null) row.put(name, val); - } catch (Exception e) { - e.printStackTrace(); - } - } - return row; - } - - private String formatObjectsWithoutDisplay(int j, ArrayList fieldNames, ArrayListcolumnWidths, ArrayList > rows) { - int i; - StringBuffer rval = new StringBuffer(); - - for( i = 0; i < fieldNames.size(); i++ ) { - StringBuffer name = new StringBuffer(fieldNames.get(i)); - int fieldwidth = columnWidths.get(i); - while( name.length() < fieldwidth ) - name.append(" "); - rval.append(name.toString()+((i < fieldNames.size()-1)?" | ":"")); - } - rval.append("\n"); - for( i = 0; i < j; i++ ) - rval.append("-"); - rval.append("\n"); - - for( j = 0; j < rows.size(); j++ ) { - for( i = 0; i < fieldNames.size(); i++ ) { - StringBuffer value = new StringBuffer(rows.get(j).get(fieldNames.get(i))); - int fieldwidth = columnWidths.get(i); - while( value.length() < fieldwidth ) - value.append(" "); - rval.append(value.toString()+((i < fieldNames.size()-1)?" | ":"")); - } - rval.append("\n"); - } - return rval.toString(); - } - - private String formatObjectsWithDisplay(ArrayList > rows, String displayDef) { - StringBuffer rval = new StringBuffer(); - for( int j = 0; j < rows.size(); j++) { - String rv = displayDef; - Enumeration fNames = rows.get(j).keys(); - while( fNames.hasMoreElements() ) { - String f = (String)fNames.nextElement(); - rv = rv.replaceAll("\\$\\{"+f+"\\}", rows.get(j).get(f)); - } - rv = rv.replaceAll("\\\\n", "\n"); - rv = rv.replaceAll("\\\\t", "\t"); - rv = rv.replaceAll("\\\\(.)?", "$1"); - rval.append(rv); - } - return rval.toString(); - } - - /** - * format Objects for the output as a Human readable table - * - * @param objects - * format these objects - * - * @return humanReadableString - * a string with the human readable representation of the objects - */ - public String formatObjects(List objects, String displayDef) { - if( objects.size() == 0 ) return ""; - if( objects.get(0) == null ) return ""; - ArrayList methodlist = getMethodList(objects.get(0)); - ArrayListcolumnWidths = new ArrayList(); - ArrayListfieldNames = new ArrayList(); - ArrayList > rows = - new ArrayList >(); - int i, j; - - for( i = 0; i < methodlist.size(); i++ ) { - Method m = methodlist.get(i); - String n = m.getName(); - String fn = n.substring(3).toLowerCase(); - fieldNames.add(fn); - columnWidths.add(n.length()+3); - } - - for( j = 0; j < objects.size(); j++ ) { - Object o = objects.get(j); - Hashtable row = getValues(o,methodlist,fieldNames,(displayDef != null), null); - for( i = 0; i < fieldNames.size(); i++ ) { - String val = row.get(fieldNames.get(i)); - if( val != null && i < columnWidths.size() && val.length()+3 > columnWidths.get(i) ) - columnWidths.set(i, val.length()+3); - } - rows.add(row); - } - - if( displayDef == null ) { - j = 0; - for( i = 0; i < columnWidths.size(); i++ ) { - j += columnWidths.get(i)+2; - } - j -= 2; - - return formatObjectsWithoutDisplay(j, fieldNames, columnWidths, rows); - } else - return formatObjectsWithDisplay(rows, displayDef); - } - - /** - * The main parser function. Parses the Parameters, uses the master to call - * the functions and returns a formatet output. - * - * @param arguments - * @return humanReadableObjectsString - */ - public String parse(List arguments, ModuleInterface module) { - String rval = ""; - - String currentModule = null; - String currentFunction = null; - Map currentWhere = new Hashtable(); - Map currentSet = new Hashtable(); - ArrayList currentOIDs = new ArrayList(); - - Map globalWhere = new Hashtable(); - Map globalSet = new Hashtable(); - String display = null; - String globalDisplay = null; - - for( int i = 0; i < arguments.size(); i++ ) { - String arg = arguments.get(i); - - if( arg.equals("-c") || arg.startsWith("--call:") ) { - // call - if( currentModule != null ) { - try { - // execute the last call now - rval += formatObjects(master.callModule( - currentModule, - currentFunction, - currentWhere, - currentSet, - currentOIDs, - module),(display==null)?globalDisplay:display); - } catch (FunctionNotKnownException e) { - rval += "Function unknown: "+currentModule+'.'+currentFunction+"\n"; - } catch (UnknownModuleException e) { - rval += "Module unknown: "+currentModule+"\n"; - } - } - // reset parameters for next call - currentWhere = new HashMap(); - currentWhere.putAll(globalWhere); - currentSet = new HashMap(); - currentSet.putAll(globalSet); - currentOIDs = new ArrayList(); - display = null; - - // set the new call - boolean isShortParam = arg.equals("-c"); - String calldef = isShortParam?arguments.get(i+1):arg.substring(7); - - if( calldef != null ) { - String[] split = calldef.split("[.]", 2); - currentModule = split[0]; - currentFunction = split[1]; - } - if( isShortParam ) i++; - } else if( arg.equals("-w") || arg.startsWith("--where:") ) { - // where - boolean isShortParam = arg.equals("-w"); - String wheredef = isShortParam?arguments.get(i+1):arg.substring(8); - if( wheredef != null ) { - String[] split = wheredef.split("[=]", 2); - currentWhere.put(split[0],split[1]); - } - if( isShortParam ) i++; - } else if( arg.equals("-W") || arg.startsWith("--globalWhere:") ) { - // global where - boolean isShortParam = arg.equals("-W"); - String gwheredef = isShortParam?arguments.get(i+1):arg.substring(14); - if( gwheredef != null ) { - String[] split = gwheredef.split("[=]", 2); - globalWhere.put(split[0],split[1]); - } - if( isShortParam ) i++; - } else if( arg.equals("-s") || arg.startsWith("--set:") ) { - // set - boolean isShortParam = arg.equals("-s"); - String setdef = isShortParam?arguments.get(i+1):arg.substring(6); - if( setdef != null ) { - String[] split = setdef.split("[=]", 2); - currentSet.put(split[0],split[1]); - } - if( isShortParam ) i++; - } else if( arg.equals("-S") || arg.startsWith("--globalSet:") ) { - // global set - boolean isShortParam = arg.equals("-S"); - String gsetdef = isShortParam?arguments.get(i+1):arg.substring(12); - if( gsetdef != null ) { - String[] split = gsetdef.split("[=]", 2); - globalSet.put(split[0],split[1]); - } - if( isShortParam ) i++; - } else if( arg.equals("-d") || arg.startsWith("--display:") ) { - // display - boolean isShortParam = arg.equals("-d"); - display = isShortParam?arguments.get(i+1):arg.substring(10); - if( isShortParam ) i++; - } else if( arg.equals("-D") || arg.startsWith("--globalDisplay:") ) { - // global display - boolean isShortParam = arg.equals("-D"); - globalDisplay = isShortParam?arguments.get(i+1):arg.substring(16); - if( isShortParam ) i++; - } else if( arg.equals("-h") || arg.equals("--help") ) { - return getUsageString(); - } else if( arg.startsWith("-") ) { - return "unknown option '"+arg+"'\n"+getUsageString(); - } else currentOIDs.add(arg); - } - if( currentModule != null ) { - try { - rval += formatObjects(master.callModule( - currentModule, - currentFunction, - currentWhere, - currentSet, - currentOIDs, - module),(display==null)?globalDisplay:display); - } catch (FunctionNotKnownException e) { - rval += "Function unknown: "+currentModule+'.'+currentFunction+"\n"; - } catch (UnknownModuleException e) { - rval += "Module unknown: "+currentModule+"\n"; - } - } - return rval; - } -} diff --git a/hsarback/src/de/hsadmin/cliClientConnector/BusinessException.java b/hsarback/src/de/hsadmin/cliClientConnector/BusinessException.java deleted file mode 100644 index a89cbf2..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/BusinessException.java +++ /dev/null @@ -1,15 +0,0 @@ -package de.hsadmin.cliClientConnector; - -public class BusinessException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public BusinessException(String msg) { - super(msg); - } - - public BusinessException(Exception exc) { - super(exc.getMessage()); - } - -} \ No newline at end of file diff --git a/hsarback/src/de/hsadmin/cliClientConnector/CLIClientConnectorServlet.java b/hsarback/src/de/hsadmin/cliClientConnector/CLIClientConnectorServlet.java deleted file mode 100644 index 63e475a..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/CLIClientConnectorServlet.java +++ /dev/null @@ -1,497 +0,0 @@ -package de.hsadmin.cliClientConnector; - -import java.io.BufferedReader; -import java.io.IOException; -import java.lang.reflect.Method; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.codec.binary.Base64; - -import de.hsadmin.core.model.AbstractEntity; -import de.hsadmin.core.model.GenericModuleImpl; -import de.hsadmin.core.model.ModuleInterface; -import de.hsadmin.core.model.TicketValidator; -import de.hsadmin.core.model.Transaction; - -/** - * actually this is the core of the CLI-Client. The other CLI-Client is just a - * rather simple HTTP Client that calls this Servlet. - * - * @author Christof Donat - * - */ -public class CLIClientConnectorServlet extends HttpServlet { - - private static final long serialVersionUID = 7150004719303750077L; - public static final String version = "CLI Servlet 2.0.0 (2011/May/21 09:00 MEST)"; - - private Map> componentmap; - private Map componentDescriptions; - private ArgumentParser parser; - - /** - * Servlet initialization - */ - public void init(ServletConfig cfg) { - // init ticket validator - String validateURL = cfg.getInitParameter("proxyValidateUrl"); - String serviceURL = cfg.getInitParameter("proxyServiceUrl"); - TicketValidator.getInstance().initialize(validateURL, serviceURL); - // find components - String cstring = cfg.getInitParameter("Components"); - String[] components = cstring.split(","); - - componentmap = new HashMap>(); - componentDescriptions = new HashMap(); - for (int i = 0; i < components.length; i++) { - // get everything for this component and create an entry. - try { - // component class - String classname = cfg.getInitParameter("ComponentClass_" - + components[i]); - if (classname == null) - throw new NullPointerException( - "no class name found for Component " - + components[i]); - Class cls = Class.forName(classname); - componentmap.put(components[i], cls); - // description - String descr = cfg.getInitParameter("ComponentDescription_" - + components[i]); - if (descr != null) - componentDescriptions.put(components[i], descr); - else - componentDescriptions.put(components[i], ""); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - // TODO: get username, password from http session - parser = new ArgumentParser(this); - } - - /** - * set values to a given entity Object - * - * @param o - * the entity Object - * @param set - * Hashtable with names and values that sould be changed in o - */ - private void setValues(Object o, Map set, ModuleInterface module) { - Iterator keys = set.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - String[] ns = key.split("[.]", 2); - Object realO = o; - for (int i = 0; i < ns.length - 1; i++) { - Method[] m = realO.getClass().getMethods(); - boolean oFound = false; - for (int j = 0; j < m.length; j++) { - if (m[j].getName().toLowerCase().equals( - "get" + ns[i].toLowerCase())) { - try { - realO = m[j].invoke(realO, (Object[]) null); - oFound = (realO != null); - break; - } catch (Exception e) { - new TechnicalException(e); - } - } - } - if (!oFound) - break; - } - Method[] m = realO.getClass().getMethods(); - String value = set.get(key); - for (int j = 0; j < m.length; j++) { - if (!m[j].getName().toLowerCase().equals( - "set" + ns[ns.length - 1].toLowerCase())) - continue; - String type = m[j].getParameterTypes()[0].getCanonicalName(); - try { - if (type.equals("java.lang.String")) - m[j].invoke(realO, value); - else if (type.equals("java.lang.Integer") || type.equals("int")) - m[j].invoke(realO, Integer.parseInt(value)); - else if (type.equals("java.lang.Long") || type.equals("long")) - m[j].invoke(realO, Long.parseLong(value)); - else if (type.equals("java.lang.Boolean") || type.equals("boolean")) - m[j].invoke(realO, Boolean.valueOf(value)); - else if (type.equals("java.util.Date")) { - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY); - m[j].invoke(realO, df.parse(value)); - } else { - Method m2 = module.getClass().getMethod( - "findByString", Class.class, String.class); - Object entity = - m2.invoke(module, m[j].getParameterTypes()[0], value); - if (entity != null) - m[j].invoke(realO, entity); - else - throw new BusinessException( - "not object found for '" + value + "'"); - } - } catch (Exception e) { - throw new TechnicalException(e); // TODO: this needs to be - // more specific for - // some cases - } - } - } - } - - private String hasGetter(Class eType, String name) { - String rval = null; - String[] ns = name.split("[.]", 2); - String n1 = ns[0]; - Method meth = null; - - for (Method m : eType.getMethods()) { - String n = m.getName(); - if (n.startsWith("get")) { - String fn = m.getName().substring(3).toLowerCase(); - if (fn != "class" && fn.equals(n1)) { - meth = m; - rval = fn; - break; - } - } - } - if (meth != null) { - Class returnType = meth.getReturnType(); - if (rval != null && ns.length > 1 && meth != null) - return hasGetter(returnType, ns[1]); - if (returnType.getCanonicalName().startsWith("de.hsadmin.mods")) { - try { - if (returnType.getMethod("getName") != null) { - return rval + ".name"; - } - } catch (Exception e) { - // no method found - } - } - } - return rval; - } - - /** - * builds a query from a where clause and some objectIDs. - * - * @param eType - * The class of the Entity Object for which the string should be - * built. We need this to call the static method - * "createQueryFromStringKey" - * @param where - * Hashtable with where parameters. Only objects which match all - * where parameters are found - * @param oids - * Only objects with one of these object IDs are found - * - * @return queryString a query string that can be used to select the - * required Objects - * @throws ServletException - */ - private String buildQuery(Class eType, Map where, - ArrayList oids) throws ServletException { - String rval = ""; - - boolean first = true; - Iterator wkeys = where.keySet().iterator(); - while (wkeys.hasNext()) { - String k = (String) wkeys.next(); - String kname = hasGetter(eType, k); - String kvalue = ( (k.equals("id")) - ? ( AbstractEntity.escapeString(where.get(k)) ) - : ( "'" + AbstractEntity.escapeString(where.get(k)) + "'" ) ); - if (kname != null) { - rval += (first ? "" : " and ") - + "(obj." + AbstractEntity.escapeString(kname) + " = " + kvalue + ")"; - first = false; - } else { - throw new ServletException("illegal input (unknown field: " + k + ")"); - } - } - - String rv = ""; - if (oids != null) - try { - Method m; - m = eType.getMethod("createQueryFromStringKey", String.class); - - first = true; - for (String s : oids) { - rv += (first ? "" : " or ") + "(" - + (String) m.invoke(eType, s) + ")"; - first = false; - } - if (rv != "" && rval != "") - rval = rval + " and (" + rv + ")"; - else if (rv != "") - rval = rv; - } catch (Exception e) { - throw new TechnicalException(e); - } - - return (rval == "") ? null : rval; - } - - public class FunctionNotKnownException extends Exception { - private static final long serialVersionUID = -6330015688609717838L; - } - - public class UnknownModuleException extends Exception { - private static final long serialVersionUID = 696641072107896601L; - } - - private Object callAdd(Class cls, Map set, ModuleInterface module) { - Transaction transaction = module.getTransaction(); - transaction.beginTransaction(); - try { - Method m = module.getClass().getMethod("add", AbstractEntity.class); - Object o = cls.newInstance(); - setValues(o, set, module); - m.invoke(module, o); - transaction.commitTransaction(); - return null; - } catch (Exception e) { - transaction.rollbackTransaction(); - // TODO: this needs to be more specific, but how? - throw new TechnicalException(e); - } - } - - @SuppressWarnings("unchecked") - private List callSearch(Class cls, Map where, - ArrayList oids, ModuleInterface module) { - try { - Method m = module.getClass().getMethod("search", Class.class, - String.class, String.class); - return (List) m.invoke(module, cls, - buildQuery(cls, where, oids), null); - } catch (Exception e) { - throw new TechnicalException(e); // TODO: this needs to be more - // specific, but how? - } - } - - // / checks wheather all 'oids' are in 'list' - private void checkOids(List list, List oids) { - List oidsNotFound = new ArrayList(); - for (String id : oids) { - boolean found = false; - for (AbstractEntity e : list) { - String foundKey = e.createStringKey(); - if (foundKey.equals(id)) { - found = true; - break; - } - } - if (!found) - oidsNotFound.add(id); - } - if (oidsNotFound.size() > 0) { - throw new OidsNotFoundException(oids); - } - } - - @SuppressWarnings("unchecked") - private List callUpdate(Class cls, Map where, - ArrayList oids, Map set, - ModuleInterface module) { - // better safe than sorry - alsd hso same behavior as UNIX rm - if (where.size() == 0 && oids.size() == 0) - throw new BusinessException( - "better safe than sorry - 'update' needs a -w/--where-query or object id"); - Transaction tx = module.getTransaction(); - tx.beginTransaction(); - try { - Method m = module.getClass().getMethod("search", Class.class, - String.class, String.class); - List list = (List) m.invoke(module, cls, - buildQuery(cls, where, oids), null); - checkOids(list, oids); - Method m2 = module.getClass().getMethod("update", AbstractEntity.class); - for (int i = 0; i < list.size(); i++) { - AbstractEntity entity = list.get(i); - tx.detach(entity); - setValues(entity, set, module); - m2.invoke(module, entity); - } - tx.commitTransaction(); - } catch (Exception e) { - tx.rollbackTransaction(); - // TODO: this needs to be more specific, but how? - throw new TechnicalException(e); - } - return null; - } - - @SuppressWarnings("unchecked") - private void callDelete(Class cls, Map where, - ArrayList oids, ModuleInterface module) { - // better safe than sorry - also same behavior as UNIX rm - if (where.size() == 0 && oids.size() == 0) - throw new BusinessException( - "better safe than sorry - 'update' needs a -w/--where-query or object id"); - Transaction tx = module.getTransaction(); - tx.beginTransaction(); - try { - Method m = - module.getClass().getMethod("search", Class.class, String.class, String.class); - List list = - (List) m.invoke(module, cls, buildQuery(cls, where, oids), null); - checkOids(list, oids); - Method m2 = module.getClass().getMethod("delete", AbstractEntity.class); - for (int i = 0; i < list.size(); i++) { - Object o = list.get(i); - m2.invoke(module, o); - } - tx.commitTransaction(); - } catch (Exception e) { - tx.rollbackTransaction(); - // TODO: this needs to be more specific, but how? - throw new TechnicalException(e); - } - } - - /** - * Call one of the EntitySessions methods - * - * @param moduleName - * Defines the Entity class that will be given to the - * EntitySession - * @param function - * Defines the method that will be called. The function can be - * "add", "search", "update" and "delete". - * @param where - * Reduces the set of Entity objects which the function operates - * on to those matched by the where parameters. Only for - * "search", "update" and "delete". Will be ignored otherwise. - * @param set - * Set these values on all Objects - only for "add" and "update". - * Will be ignored otherwise. - * @param oids - * Works on Objects with these IDs. Only for "search", "update" - * and "delete". Will be ignored for "add". - * @return foundObjects - * @throws FunctionNotKnownException - */ - public List callModule(String moduleName, String function, - Map where, Map set, - ArrayList oids, ModuleInterface module) - throws FunctionNotKnownException, UnknownModuleException { - List rval = new ArrayList(); - - // handle calls to the virtual module "modules" - if (moduleName.equals("modules")) { - // only search, no manipulation is possible - if (function.equals("search")) { - Iterator m = componentDescriptions.keySet().iterator(); - while (m.hasNext()) { - String mn = (String) m.next(); - rval.add(new ModuleModel(mn, componentDescriptions.get(mn))); - } - } else if (function.equals("version")) { - rval.add(new VersionModel(version)); - } else { - throw new FunctionNotKnownException(); - } - return rval; - } - - // find the component for the named module - Class cls = componentmap.get(moduleName); - if (cls == null) - throw (new UnknownModuleException()); - - // call the appropriate methods - if (function.equals("add")) - rval.add(callAdd(cls, set, module)); - else if (function.equals("search")) { - List r = callSearch(cls, where, oids, module); - if (r != null) - return r; - } else if (function.equals("update")) { - List r = callUpdate(cls, where, oids, set, module); - if (r != null) - return callUpdate(cls, where, oids, set, module); - } else if (function.equals("delete")) { - callDelete(cls, where, oids, module); - } else - throw (new FunctionNotKnownException()); - return rval; - } - - /** - * handle put method - */ - public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException { - try { - ModuleInterface module = null; - Transaction tx = null; - // check login - String auth = req.getHeader("authorization"); - if (auth == null) { - // no login information at all - get it - resp.setHeader("WWW-Authenticate", - "Basic realm=\"CLIClientConnector\""); - resp.getOutputStream().println("login Failed."); - resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; - } else { - // parse login information - String[] a = auth.split(" ", 2); - String ticket = a[1]; - byte[] decoded = Base64.decodeBase64(ticket.trim().getBytes()); - String s = new String(decoded); - a = s.split(":", 2); - // try to log in - String login = a[0]; - ticket = a[1]; - try { - tx = new Transaction(login); - if (tx.login(login, ticket)) { - // login successful - module = new GenericModuleImpl(tx); - - // read arguments - BufferedReader read = req.getReader(); - - String tmpbuf; - ArrayList arguments = new ArrayList(); - while ((tmpbuf = read.readLine()) != null) { - arguments.add(tmpbuf); - } - - // actually handle the request and write result to output - String output = parser.parse(arguments, module); - resp.getWriter().write(output); - } else { - resp.addHeader("X-hsadmin-error", "authentication failed"); - } - } catch (Exception e) { - resp.addHeader("X-hsadmin-error", "exception: " + e.getMessage()); - } finally { - if (tx != null) { - tx.close(); - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/hsarback/src/de/hsadmin/cliClientConnector/ModuleModel.java b/hsarback/src/de/hsadmin/cliClientConnector/ModuleModel.java deleted file mode 100644 index b6bfc8b..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/ModuleModel.java +++ /dev/null @@ -1,19 +0,0 @@ -package de.hsadmin.cliClientConnector; - -public class ModuleModel { - private String name; - private String description; - - public ModuleModel(String name, String description) { - this.name = name; - this.description = description; - } - - public String getName() { - return this.name; - } - - public String getDescription() { - return this.description; - } -} diff --git a/hsarback/src/de/hsadmin/cliClientConnector/OidsNotFoundException.java b/hsarback/src/de/hsadmin/cliClientConnector/OidsNotFoundException.java deleted file mode 100644 index e56c87e..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/OidsNotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -package de.hsadmin.cliClientConnector; - -import java.util.List; - - -@SuppressWarnings("serial") -public class OidsNotFoundException - extends RuntimeException -{ - static private String oidsAsString(List oids) - { - StringBuilder oidsBuilder = new StringBuilder(); - for ( String id: oids ) - oidsBuilder.append(", " + id); - if ( oidsBuilder.length() > 0 ) - return oidsBuilder.substring(2); - throw new RuntimeException( "an empty list of missing OIDS does not make sense" ); - } - - public OidsNotFoundException(List oids) - { - super("OIDS not found: " + oidsAsString(oids)); - } - -} diff --git a/hsarback/src/de/hsadmin/cliClientConnector/VersionModel.java b/hsarback/src/de/hsadmin/cliClientConnector/VersionModel.java deleted file mode 100644 index ea18f79..0000000 --- a/hsarback/src/de/hsadmin/cliClientConnector/VersionModel.java +++ /dev/null @@ -1,14 +0,0 @@ -package de.hsadmin.cliClientConnector; - -public class VersionModel -{ - private String version; - - public VersionModel( String version) { - this.version = version; - } - - public String getVersion() { - return this.version; - } -} diff --git a/hsarback/src/de/hsadmin/core/model/LoginSession.java b/hsarback/src/de/hsadmin/core/model/LoginSession.java new file mode 100644 index 0000000..753cede --- /dev/null +++ b/hsarback/src/de/hsadmin/core/model/LoginSession.java @@ -0,0 +1,93 @@ +package de.hsadmin.core.model; + +import java.util.Set; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import de.hsadmin.core.util.Config; +import de.hsadmin.mods.cust.Customer; +import de.hsadmin.mods.pac.Pac; +import de.hsadmin.mods.user.UnixUser; + +@Stateless +public class LoginSession { + + @PersistenceContext(name="hsadmin") + private EntityManager entityManager; + + private String loginName; + + public UnixUser getLoginUser() { + String loginName = getLoginName(); + if (loginName != null && loginName.length() == 2) { + loginName = Config.getInstance().getProperty("accountprefix.hostmaster", "hsh01") + "-" + loginName; + } + if (loginName != null && loginName.length() == 3) { + loginName = Config.getInstance().getProperty("accountprefix.customer", "hsh00") + "-" + loginName; + } + Query userQuery = entityManager.createQuery("SELECT u FROM UnixUsers u WHERE u.name = :username"); + userQuery.setParameter("username", loginName); + UnixUser unixUser = (UnixUser) userQuery.getSingleResult(); + return unixUser; + } + + public String getLoginName() { + if (loginName != null) { + return loginName; + } + throw new TechnicalException("no login"); + } + + public boolean login(String user, String ticket) throws AuthenticationException { + String ticketUser = TicketValidator.getInstance().validateTicket(ticket); + if (user != null && user.equals(ticketUser)) { + loginName = ticketUser; + return true; // user himself + } + if (ticketUser != null && ticketUser.length() == 2) { + loginName = ticketUser; + return true; // 2-letter hostmaster + } + String hostmasterAccountPrefix = Config.getInstance().getProperty("accountprefix.hostmaster", "hsh01") + "-"; + if (ticketUser != null && ticketUser.startsWith(hostmasterAccountPrefix) && ticketUser.length() == 8) { + loginName = ticketUser; + return true; // hsh01 hostmaster + } + if (ticketUser != null && ticketUser.length() == 5) { + Query userQuery = entityManager.createQuery("SELECT u FROM UnixUsers u WHERE u.name = :username"); + userQuery.setParameter("username", user); + UnixUser unixUser = (UnixUser) userQuery.getSingleResult(); + String pacName = unixUser.getPac().getName(); + boolean loginOk = ticketUser.equals(pacName); + if (loginOk) { + loginName = ticketUser; + } + return loginOk; // pac-admin + } + String memberAccountPrefix = Config.getInstance().getProperty("accountprefix.customer", "hsh00") + "-"; + if (ticketUser != null && (ticketUser.length() == 3 || (ticketUser.length() >= 9 && ticketUser.startsWith(memberAccountPrefix)))) { + Query memberQuery = entityManager.createQuery("SELECT c FROM Customers c WHERE c.name = :membername"); + memberQuery.setParameter("membername", ticketUser.length() == 3 ? (memberAccountPrefix + ticketUser) : ticketUser); + Customer member = (Customer) memberQuery.getSingleResult(); + Set pacs = member.getPacs(); + for (Pac p : pacs) { + if (p.getName().equals(user)) { + loginName = ticketUser; + return true; // member as pac-admin + } + Set users = p.getUnixUser(); + for (UnixUser u : users) { + if (u.getName().equals(user)) { + loginName = ticketUser; + return true; // member as pac-user + } + } + } + } + throw new AuthenticationException("User " + ticketUser + " is not allowed to run as " + user); + } + +} diff --git a/hsarback/src/de/hsadmin/core/model/QueueManager.java b/hsarback/src/de/hsadmin/core/model/QueueManager.java new file mode 100644 index 0000000..6f6b726 --- /dev/null +++ b/hsarback/src/de/hsadmin/core/model/QueueManager.java @@ -0,0 +1,46 @@ +package de.hsadmin.core.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Stateless; + +import de.hsadmin.core.qserv.QueueTask; + +@Stateless +public class QueueManager { + + private final Map taskStores; + + public QueueManager() { + taskStores = new HashMap(); + } + + public void enqueue(String hiveName, QueueTask task) { + QueueTaskStore taskStore = taskStores.get(hiveName); + if (taskStore == null) { + taskStore = new QueueTaskStore(); + taskStores.put(hiveName, taskStore); + } + taskStore.add(task); + } + + class QueueTaskStore { + private List taskList; + QueueTaskStore() { + taskList = new ArrayList(); + } + public void clear() { + taskList = new ArrayList(); + } + void add(QueueTask t) { + taskList.add(t); + } + Iterable getTasks() { + return taskList; + } + } + +} diff --git a/hsarback/src/de/hsadmin/cliClientConnector/TechnicalException.java b/hsarback/src/de/hsadmin/core/model/TechnicalException.java similarity index 97% rename from hsarback/src/de/hsadmin/cliClientConnector/TechnicalException.java rename to hsarback/src/de/hsadmin/core/model/TechnicalException.java index 19fba68..84fb9f7 100644 --- a/hsarback/src/de/hsadmin/cliClientConnector/TechnicalException.java +++ b/hsarback/src/de/hsadmin/core/model/TechnicalException.java @@ -1,4 +1,4 @@ -package de.hsadmin.cliClientConnector; +package de.hsadmin.core.model; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; diff --git a/hsarback/src/de/hsadmin/core/model/TicketValidator.java b/hsarback/src/de/hsadmin/core/model/TicketValidator.java index 4d21b99..b394579 100644 --- a/hsarback/src/de/hsadmin/core/model/TicketValidator.java +++ b/hsarback/src/de/hsadmin/core/model/TicketValidator.java @@ -28,6 +28,7 @@ public class TicketValidator { return instance; } + // FIXME wird nicht aufgerufen public void initialize(String validateURL, String serviceURL) { proxyServiceURL = serviceURL; proxyValidateURL = validateURL; diff --git a/hsarback/src/de/hsadmin/core/model/Transaction.java b/hsarback/src/de/hsadmin/core/model/Transaction.java index 1edcee6..98188b6 100644 --- a/hsarback/src/de/hsadmin/core/model/Transaction.java +++ b/hsarback/src/de/hsadmin/core/model/Transaction.java @@ -15,7 +15,6 @@ import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Query; -import de.hsadmin.cliClientConnector.TechnicalException; import de.hsadmin.core.qserv.QueueClient; import de.hsadmin.core.qserv.QueueTask; import de.hsadmin.core.util.Config; diff --git a/hsarback/src/de/hsadmin/core/qserv/QueueStatusReceiverServlet.java b/hsarback/src/de/hsadmin/core/qserv/QueueStatusReceiverServlet.java index 4918fd0..af52c92 100644 --- a/hsarback/src/de/hsadmin/core/qserv/QueueStatusReceiverServlet.java +++ b/hsarback/src/de/hsadmin/core/qserv/QueueStatusReceiverServlet.java @@ -23,7 +23,7 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import de.hsadmin.cliClientConnector.TechnicalException; +import de.hsadmin.core.model.TechnicalException; import de.hsadmin.core.model.Transaction; import de.hsadmin.core.util.Config; diff --git a/hsarback/src/de/hsadmin/core/util/ReflectionUtil.java b/hsarback/src/de/hsadmin/core/util/ReflectionUtil.java index 4de2fb6..5f86d88 100644 --- a/hsarback/src/de/hsadmin/core/util/ReflectionUtil.java +++ b/hsarback/src/de/hsadmin/core/util/ReflectionUtil.java @@ -8,9 +8,9 @@ import java.util.List; import java.util.Set; import java.util.TreeSet; -import de.hsadmin.cliClientConnector.TechnicalException; import de.hsadmin.core.model.AbstractEntity; import de.hsadmin.core.model.AnnFieldIO; +import de.hsadmin.core.model.TechnicalException; public class ReflectionUtil { diff --git a/hsarback/src/de/hsadmin/mods/email/EMailAddressModuleImpl.java b/hsarback/src/de/hsadmin/mods/email/EMailAddressModuleImpl.java index d4a773d..d4eed01 100644 --- a/hsarback/src/de/hsadmin/mods/email/EMailAddressModuleImpl.java +++ b/hsarback/src/de/hsadmin/mods/email/EMailAddressModuleImpl.java @@ -5,9 +5,9 @@ import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; +import de.hsadmin.core.model.AbstractEntity; import de.hsadmin.core.model.AbstractModuleImpl; import de.hsadmin.core.model.AuthorisationException; -import de.hsadmin.core.model.AbstractEntity; import de.hsadmin.core.model.HSAdminException; import de.hsadmin.core.model.Transaction; import de.hsadmin.hostsharing.BasePacType; @@ -99,5 +99,5 @@ public class EMailAddressModuleImpl extends AbstractModuleImpl { attachedAddr.setTarget(target); return super.update(attachedAddr); } - + } diff --git a/hsarback/src/de/hsadmin/mods/email/EMailAliasModuleImpl.java b/hsarback/src/de/hsadmin/mods/email/EMailAliasModuleImpl.java index 2825386..9886b61 100644 --- a/hsarback/src/de/hsadmin/mods/email/EMailAliasModuleImpl.java +++ b/hsarback/src/de/hsadmin/mods/email/EMailAliasModuleImpl.java @@ -1,22 +1,44 @@ package de.hsadmin.mods.email; +import java.lang.reflect.Method; +import java.util.LinkedList; import java.util.List; +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.persistence.Entity; import javax.persistence.EntityManager; +import javax.persistence.NonUniqueResultException; +import javax.persistence.PersistenceContext; import javax.persistence.Query; import de.hsadmin.core.model.AbstractEntity; import de.hsadmin.core.model.AbstractModuleImpl; import de.hsadmin.core.model.AuthorisationException; import de.hsadmin.core.model.HSAdminException; -import de.hsadmin.core.model.Transaction; +import de.hsadmin.core.model.LoginSession; +import de.hsadmin.core.model.QueueManager; +import de.hsadmin.core.qserv.EntityProcessorFactory; +import de.hsadmin.core.qserv.NullProcessor; +import de.hsadmin.core.qserv.Processor; +import de.hsadmin.core.qserv.QueueTask; import de.hsadmin.hostsharing.BasePacType; import de.hsadmin.hostsharing.MultiOption; import de.hsadmin.mods.pac.Pac; import de.hsadmin.mods.user.UnixUser; +@Stateless public class EMailAliasModuleImpl extends AbstractModuleImpl { + @PersistenceContext(name="hsadmin") + private EntityManager entityManager; + + @EJB + private LoginSession session; + + @EJB + private QueueManager queueManager; + @Override public List search(Class entityClass, String condition, String orderBy) throws HSAdminException { @@ -28,15 +50,13 @@ public class EMailAliasModuleImpl extends AbstractModuleImpl { @Override public AbstractEntity add(AbstractEntity newEntity) throws HSAdminException { - Transaction transaction = getTransaction(); - UnixUser loginUser = transaction.getLoginUser(); + UnixUser loginUser = session.getLoginUser(); EMailAlias alias = (EMailAlias) newEntity; String name = alias.getName(); if (name.length() > 5 && (name.charAt(5) != '-') || name.length() == 6) { throw new AuthorisationException(loginUser, "add", newEntity); } - EntityManager em = getTransaction().getEntityManager(); - Query qPac = em.createQuery("SELECT obj FROM Pacs obj WHERE obj.name = :pacName"); + Query qPac = entityManager.createQuery("SELECT obj FROM Pacs obj WHERE obj.name = :pacName"); qPac.setParameter("pacName", name.substring(0, 5)); Object singleResult = qPac.getSingleResult(); Pac pac = (Pac) singleResult; @@ -52,9 +72,9 @@ public class EMailAliasModuleImpl extends AbstractModuleImpl { throw new HSAdminException("not allowed for this packet type"); } //TODO: Needs better implementation - Query qEmailAliases = em.createQuery("SELECT obj FROM EMailAliases obj WHERE obj.pac.id = :pacId"); + Query qEmailAliases = entityManager.createQuery("SELECT obj FROM EMailAliases obj WHERE obj.pac.id = :pacId"); qEmailAliases.setParameter("pacId", pac.getId()); - Query qEmailAddresses = em.createQuery("SELECT obj FROM EMailAddresses obj WHERE obj.domain.user.pac.id = :pacId"); + Query qEmailAddresses = entityManager.createQuery("SELECT obj FROM EMailAddresses obj WHERE obj.domain.user.pac.id = :pacId"); qEmailAddresses.setParameter("pacId", pac.getId()); if (qEmailAliases.getResultList().size() + qEmailAddresses.getResultList().size() >= MultiOption.EMAIL_ITEMS_PER_OPTION * pac.getQuantityByComponentName("MULTI")) { throw new HSAdminException("included email addresses/aliases exceeded"); @@ -62,5 +82,205 @@ public class EMailAliasModuleImpl extends AbstractModuleImpl { alias.setPac(pac); return super.add(newEntity); } + + public void detach(AbstractEntity attached) { + entityManager.detach(attached); + } + + // TODO extract copied code + + public AbstractEntity initialize(AbstractEntity newEntity) + throws AuthorisationException { + newEntity.initialize(entityManager, session.getLoginUser()); + return newEntity; + } + + public AbstractEntity superadd(AbstractEntity newEntity) throws HSAdminException { + UnixUser loginUser = session.getLoginUser(); + newEntity.complete(entityManager, loginUser); + entityManager.persist(newEntity); + if (!newEntity.isWriteAllowedFor(loginUser)) { + throw new AuthorisationException(loginUser, "add", newEntity); + } + EntityProcessorFactory procFact = createProcessorFactory(newEntity.getClass()); + if (procFact != null) { + Processor proc = procFact.createCreateProcessor(entityManager, newEntity); + queueProcessor(proc, loginUser, newEntity, "hinzugefuegt"); + } + return newEntity; + } + + public AbstractEntity find(Class entityClass, Object key) throws HSAdminException { + AbstractEntity entity = entityManager.find(entityClass, key); + UnixUser loginUser = session.getLoginUser(); + if (!entity.isReadAllowedFor(loginUser)) { + throw new AuthorisationException(loginUser, "add", entity); + } + return entity; + } + + public AbstractEntity findByString(Class entityClass, String key) throws HSAdminException { + Method method = null; + try { + method = entityClass.getDeclaredMethod("createQueryFromStringKey", String.class); + } catch (SecurityException e) { + throw new HSAdminException(e); + } catch (NoSuchMethodException e) { + method = null; + } + AbstractEntity entity = null; + if (method == null) { + entity = entityManager.find(entityClass, key); + } + else { + String query = null; + try { + query = (String) method.invoke(null, key); + } catch (Exception e) { + throw new HSAdminException(e); + } + List result = search(entityClass, query, null); + if (result.size() > 1) throw new NonUniqueResultException(); + if (result.size() == 0) return null; + entity = result.get(0); + } + return entity; + } + + public List supersearch(Class entityClass, String condition, String orderBy) throws HSAdminException { + UnixUser loginUser = session.getLoginUser(); + condition = restrict(entityClass, loginUser, condition); + Entity entityAnnot = entityClass.getAnnotation(Entity.class); + String queryString = "SELECT obj FROM " + entityAnnot.name() + " obj"; + if (condition != null && condition.length() > 0) { + queryString += " WHERE " + condition; + } + if (condition != null && condition.contains("AND (FALSE)")) { + return new LinkedList(); + } + if (orderBy != null) { + queryString += " "; + queryString += orderBy; + } + entityManager.clear(); + Query query = entityManager.createQuery(queryString); + setQueryParameter(query, queryString, "loginUser", loginUser); + setQueryParameter(query, queryString, "loginUserName", loginUser.getName()); + setQueryParameter(query, queryString, "loginUserPac", loginUser.getPac()); + try { + List res = query.getResultList(); + List ret = new LinkedList(); + // remove entities where login user has no access rights + for (Object entity : res) { + if (entity instanceof AbstractEntity) { + AbstractEntity returnedEntity = (AbstractEntity) entity; + if (returnedEntity.isReadAllowedFor(session.getLoginUser())) { + ret.add(returnedEntity); + } + } + } + return ret; + } catch (Exception ex) { + throw new HSAdminException(ex); + } + } + + public AbstractEntity update(AbstractEntity existingEntity) throws HSAdminException { + UnixUser loginUser = session.getLoginUser(); + existingEntity = existingEntity.merge(entityManager, loginUser); + if (!existingEntity.isWriteAllowedFor(loginUser)) { + throw new AuthorisationException(loginUser, "update", existingEntity); + } + EntityProcessorFactory procFact = createProcessorFactory(existingEntity.getClass()); + if (procFact != null) { + Processor proc = procFact.createUpdateProcessor(entityManager, existingEntity); + queueProcessor(proc, loginUser, existingEntity, "aktualisiert"); + } + return existingEntity; + } + + public void delete(AbstractEntity existingEntity) throws HSAdminException { + UnixUser loginUser = session.getLoginUser(); + existingEntity = entityManager.find(existingEntity.getClass(), existingEntity.id()); + if (!existingEntity.isWriteAllowedFor(loginUser)) { + throw new AuthorisationException(loginUser, "add", existingEntity); + } + entityManager.remove(existingEntity); + EntityProcessorFactory procFact = createProcessorFactory(existingEntity.getClass()); + if (procFact != null) { + Processor proc = procFact.createDeleteProcessor(entityManager, existingEntity); + queueProcessor(proc, loginUser, existingEntity, "geloescht"); + } + } + + protected EntityProcessorFactory createProcessorFactory(Class entityClass) + throws HSAdminException { + String procFactName = entityClass.getCanonicalName() + "ProcessorFactory"; + Class procFactClass = null; + EntityProcessorFactory procFact = null; + try { + procFactClass = Class.forName(procFactName); + if (procFactClass != null) { + procFact = (EntityProcessorFactory) procFactClass.newInstance(); + } + } catch (ClassNotFoundException e) { + // no processor defined + } catch (InstantiationException e) { + throw new HSAdminException(e); + } catch (IllegalAccessException e) { + throw new HSAdminException(e); + } + return procFact; + } + + protected void queueProcessor(Processor proc, UnixUser user, AbstractEntity entity, String action) { + if (proc == null || proc instanceof NullProcessor) { + return; + } + Entity entityInfo = entity.getClass().getAnnotation(Entity.class); + String entityTypeName = entityInfo != null ? entityInfo.name() : entity.getClass().getSimpleName(); + StringBuilder details = new StringBuilder(); + String title = entityTypeName + " (" + entity.createStringKey() + ") " + action; + QueueTask task = new QueueTask(user, title, details.toString(), proc); + entityManager.persist(task); + queueManager.enqueue(entity.getHiveName(), task); + } + + public String toString(StackTraceElement[] stackTrace) { + StringBuilder stack = new StringBuilder(); + for (StackTraceElement e : stackTrace) { + stack.append(e.getFileName() + ":" + e.getLineNumber() + "\n"); + } + return stack.toString(); + } + + /** + * apply access restriction to JPA-QL condition. + */ + private String restrict(Class entityClass, UnixUser loginUser, String condition) { + String restriction = AbstractEntity.restriction(entityClass, loginUser); + if (restriction == null) + return condition; + if (condition != null && condition.length() > 0) + condition = "(" + condition + ") AND (" + restriction + ")"; + else + condition = restriction; + return condition; + } + + public static void setQueryParameter(Query query, String queryString, + String argName, Object argValue) { + int argLen = argName.length(); + int iMax = queryString.length(); + int i = 0; + while ((i = queryString.indexOf(argName, i)) >= 0) { + if ((i + argLen) >= iMax || queryString.charAt(i + argLen) < 'A') { + query.setParameter(argName, argValue); + break; + } + ++i; + } + } + } diff --git a/hsarback/src/de/hsadmin/remote/EMailAliasRemote.java b/hsarback/src/de/hsadmin/remote/EMailAliasRemote.java index 06c67d6..5843ec7 100644 --- a/hsarback/src/de/hsadmin/remote/EMailAliasRemote.java +++ b/hsarback/src/de/hsadmin/remote/EMailAliasRemote.java @@ -1,18 +1,201 @@ package de.hsadmin.remote; +import java.lang.reflect.Constructor; import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; +import javax.ejb.EJB; + import de.hsadmin.core.model.AbstractEntity; -import de.hsadmin.core.model.Transaction; +import de.hsadmin.core.model.AuthenticationException; +import de.hsadmin.core.model.AuthorisationException; +import de.hsadmin.core.model.HSAdminException; +import de.hsadmin.core.model.LoginSession; import de.hsadmin.mods.email.EMailAlias; +import de.hsadmin.mods.email.EMailAliasModuleImpl; +import de.hsadmin.mods.user.UnixUser; -public class EMailAliasRemote extends AbstractRemote { +public class EMailAliasRemote { - @Override - protected void entity2map(Transaction tx, AbstractEntity entity, Map map) { + @EJB + private LoginSession session; + + @EJB + private EMailAliasModuleImpl module; + + public List> search(String runAsUser, String ticket, + Map whereParams) throws HSAdminException { + String user = runAsUser; + try { + if (session.login(user, ticket)) { + UnixUser unixUser = session.getLoginUser(); + List list = module.search(getEntityClass(), + buildQueryCondition(whereParams), null); + if (list == null) { + throw new HSAdminException("result list is null, runtime-error?"); + } + ArrayList> result = new ArrayList>(); + for (AbstractEntity e : list) { + HashMap entry = new HashMap(); + entity2map(e, entry); + if (e.isReadAllowedFor(unixUser)) { + result.add(entry); + } + } + return result; + } else { + throw new AuthenticationException("authentication failed"); + } + } catch (SecurityException e) { + throw new HSAdminException(e); + } catch (IllegalArgumentException e) { + throw new HSAdminException(e); + } + } + + public Map add(String runAsUser, String ticket, + Map setParams) throws HSAdminException { + String user = runAsUser; + try { + if (session.login(user, ticket)) { + Constructor constructor = + getEntityClass().getConstructor(); + AbstractEntity entity = constructor.newInstance(); + module.initialize(entity); + map2entity(setParams, entity); + AbstractEntity insertedEntity = module.add(entity); + HashMap entry = new HashMap(); + entity2map(insertedEntity, entry); + return entry; + } else { + throw new AuthenticationException("authentication failed"); + } + } catch (Exception e) { + throw new HSAdminException(e); + } + } + + public void delete(String runAsUser, String ticket, + Map whereParams) throws HSAdminException { + String user = runAsUser; + try { + if (session.login(user, ticket)) { + UnixUser unixUser = session.getLoginUser(); + String queryCondition = buildQueryCondition(whereParams); + if (queryCondition == null || queryCondition.length() == 0) { + throw new HSAdminException( + "better safe than sorry: no where parameter found"); + } + List list = module.search(getEntityClass(), + queryCondition, null); + for (AbstractEntity e : list) { + if (e.isWriteAllowedFor(unixUser)) { + module.delete(e); + } else { + throw new AuthorisationException(unixUser, "delete", e); + } + } + } else { + throw new AuthenticationException("authentication failed"); + } + } catch (SecurityException e) { + throw new HSAdminException(e); + } catch (IllegalArgumentException e) { + throw new HSAdminException(e); + } + } + + public List> update(String runAsUser, String ticket, + Map setParams, Map whereParams) + throws HSAdminException { + String user = runAsUser; + try { + if (session.login(user, ticket)) { + UnixUser unixUser = session.getLoginUser(); + ArrayList> result = new ArrayList>(); + String queryCondition = buildQueryCondition(whereParams); + if (queryCondition == null || queryCondition.length() == 0) { + throw new HSAdminException( + "better safe than sorry: no where parameter found"); + } + List list = module.search(getEntityClass(), + queryCondition, getOrderBy()); + for (AbstractEntity update : list) { + if (update.isWriteAllowedFor(unixUser)) { + module.detach(update); + map2entity(setParams, update); + update = module.update(update); + HashMap entry = new HashMap(); + entity2map(update, entry); + result.add(entry); + } else { + throw new AuthorisationException(unixUser, "update", update); + } + } + return result; + } else { + throw new AuthenticationException("authentication failed"); + } + } catch (SecurityException e) { + throw new HSAdminException(e); + } catch (IllegalArgumentException e) { + throw new HSAdminException(e); + } + } + + protected String getOrderBy() { + return "ORDER BY obj.name ASC"; + } + + protected boolean assertNotNull(String string) { + return string != null && string.length() > 0; + } + + protected boolean assertNotNull(Integer integ) { + return integ != null; + } + + protected void replaceKey(Map whereParams, String shortKey, String regularKey) { + if (whereParams.containsKey(shortKey)) { + String value = whereParams.get(shortKey); + whereParams.remove(shortKey); + whereParams.put(regularKey, value); + } + } + + protected boolean assertNotNull(Date aDate) { + return aDate != null; + } + + private String buildQueryCondition(Map whereParams) { + regularizeKeys(whereParams); + StringBuffer cond = new StringBuffer(); + Iterator keyIterator = whereParams.keySet().iterator(); + while (keyIterator.hasNext()) { + if (cond.length() > 0) { + cond.append(" AND "); + } + String field = keyIterator.next(); + String value = whereParams.get(field).replaceAll("'", "\'"); + cond.append("obj."); + cond.append(field); + cond.append(" = "); + boolean numeric = "id".equals(field); + if (!numeric) cond.append("'"); + cond.append(value); + if (!numeric) cond.append("'"); + } + return cond.toString(); + } + + + + protected void entity2map(AbstractEntity entity, Map map) { EMailAlias alias = (EMailAlias) entity; String id = Long.toString(alias.getId()); String name = alias.getName(); @@ -29,13 +212,13 @@ public class EMailAliasRemote extends AbstractRemote { map.put("target", tokenList); } - @Override + protected Class getEntityClass() { return EMailAlias.class; } - @Override - protected void map2entity(Transaction tx, Map map, AbstractEntity entity) { + + protected void map2entity(Map map, AbstractEntity entity) { EMailAlias alias = (EMailAlias) entity; String name = (String) map.get("name"); if (assertNotNull(name)) { @@ -64,7 +247,7 @@ public class EMailAliasRemote extends AbstractRemote { } } - @Override + protected void regularizeKeys(Map whereParams) { replaceKey(whereParams, "pac", "pac.name"); } diff --git a/hsarback/src/de/hsadmin/remote/GenericAbstractRemote.java b/hsarback/src/de/hsadmin/remote/GenericAbstractRemote.java index 9eb4075..e503528 100644 --- a/hsarback/src/de/hsadmin/remote/GenericAbstractRemote.java +++ b/hsarback/src/de/hsadmin/remote/GenericAbstractRemote.java @@ -5,11 +5,11 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import de.hsadmin.cliClientConnector.TechnicalException; import de.hsadmin.core.model.AbstractEntity; import de.hsadmin.core.model.AnnFieldIO; import de.hsadmin.core.model.HSAdminException; import de.hsadmin.core.model.ReadWriteAccess; +import de.hsadmin.core.model.TechnicalException; import de.hsadmin.core.model.Transaction; import de.hsadmin.core.util.ReflectionUtil;