remove deprecated cli client connector from source tree

This commit is contained in:
Peter Hormanns 2014-12-08 19:47:10 +01:00
parent 37a3153135
commit db87e7b470
15 changed files with 75 additions and 1242 deletions

View File

@ -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<Method> getMethodList(Object o) {
Method[] meths = o.getClass().getMethods();
ArrayList<Method> methodlist = new ArrayList<Method>();
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<String,String> getValues(Object o, ArrayList<Method> methodlist, ArrayList<String>fieldNames, boolean deep, ArrayList<Object> foundObjects) {
Hashtable<String,String> row = new Hashtable<String,String>();
int i, j;
if( foundObjects == null ) foundObjects = new ArrayList<Object>();
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 = "<Set>";
} else try {
AbstractEntity v = (AbstractEntity)value;
val = v.createStringKey();
if( deep && !foundObjects.contains(v) ) {
foundObjects.add(v);
ArrayList<String> fieldNamesDeep = new ArrayList<String>();
ArrayList<Method> methodlistDeep = getMethodList(v);
for( j = 0; j < methodlistDeep.size(); j++ ) {
fieldNamesDeep.add(methodlistDeep.get(j).getName().substring(3).toLowerCase());
}
Hashtable<String,String> tmp = getValues(v,methodlistDeep,fieldNamesDeep,deep,foundObjects);
Enumeration<String> 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<String> fieldNames, ArrayList<Integer>columnWidths, ArrayList<Hashtable<String,String> > 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<Hashtable<String,String> > rows, String displayDef) {
StringBuffer rval = new StringBuffer();
for( int j = 0; j < rows.size(); j++) {
String rv = displayDef;
Enumeration<String> 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<Method> methodlist = getMethodList(objects.get(0));
ArrayList<Integer>columnWidths = new ArrayList<Integer>();
ArrayList<String>fieldNames = new ArrayList<String>();
ArrayList<Hashtable<String,String> > rows =
new ArrayList<Hashtable<String,String> >();
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<String,String> 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<String> arguments, ModuleInterface module) {
String rval = "";
String currentModule = null;
String currentFunction = null;
Map<String,String> currentWhere = new Hashtable<String,String>();
Map<String,String> currentSet = new Hashtable<String,String>();
ArrayList<String> currentOIDs = new ArrayList<String>();
Map<String,String> globalWhere = new Hashtable<String,String>();
Map<String,String> globalSet = new Hashtable<String,String>();
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<String, String>();
currentWhere.putAll(globalWhere);
currentSet = new HashMap<String, String>();
currentSet.putAll(globalSet);
currentOIDs = new ArrayList<String>();
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;
}
}

View File

@ -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());
}
}

View File

@ -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<String, Class<?>> componentmap;
private Map<String, String> 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<String, Class<?>>();
componentDescriptions = new HashMap<String, String>();
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<String, String> set, ModuleInterface module) {
Iterator<String> 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<String, String> where,
ArrayList<String> oids) throws ServletException {
String rval = "";
boolean first = true;
Iterator<String> 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<String, String> 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<Object> callSearch(Class<?> cls, Map<String, String> where,
ArrayList<String> oids, ModuleInterface module) {
try {
Method m = module.getClass().getMethod("search", Class.class,
String.class, String.class);
return (List<Object>) 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<AbstractEntity> list, List<String> oids) {
List<String> oidsNotFound = new ArrayList<String>();
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<Object> callUpdate(Class<?> cls, Map<String, String> where,
ArrayList<String> oids, Map<String, String> 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<AbstractEntity> list = (List<AbstractEntity>) 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<String, String> where,
ArrayList<String> 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<AbstractEntity> list =
(List<AbstractEntity>) 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<Object> callModule(String moduleName, String function,
Map<String, String> where, Map<String, String> set,
ArrayList<String> oids, ModuleInterface module)
throws FunctionNotKnownException, UnknownModuleException {
List<Object> rval = new ArrayList<Object>();
// 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<Object> r = callSearch(cls, where, oids, module);
if (r != null)
return r;
} else if (function.equals("update")) {
List<Object> 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<String> arguments = new ArrayList<String>();
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();
}
}
}

View File

@ -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;
}
}

View File

@ -1,25 +0,0 @@
package de.hsadmin.cliClientConnector;
import java.util.List;
@SuppressWarnings("serial")
public class OidsNotFoundException
extends RuntimeException
{
static private String oidsAsString(List<String> 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<String> oids)
{
super("OIDS not found: " + oidsAsString(oids));
}
}

View File

@ -1,59 +0,0 @@
package de.hsadmin.cliClientConnector;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.persistence.RollbackException;
public class TechnicalException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TechnicalException(Throwable e) {
super(extractCauseMessage(e));
}
public TechnicalException(String errorMsg) {
super(errorMsg);
}
public TechnicalException(String errorMsg, NamingException e) {
super(errorMsg + "\n" + extractCauseMessage(e));
}
private static String extractCauseMessage(Throwable e) {
if (e.getMessage() != null && !(e instanceof RollbackException)) {
return e.getMessage();
}
else if (e instanceof InvocationTargetException || e instanceof RollbackException) {
String sqlState = null;
Throwable cause = e.getCause();
Throwable prev = null;
while (cause != null && cause != prev) {
prev = cause;
cause = prev.getCause();
if ((cause == null || cause == prev)
&& prev instanceof SQLException) {
SQLException sqlExc = (SQLException) prev;
sqlState = sqlExc.getSQLState();
cause = sqlExc.getNextException();
}
}
if (cause == null)
cause = prev;
if (cause != null)
return composeMessage(sqlState, cause.getMessage());
if (e instanceof InvocationTargetException) {
return composeMessage(sqlState, ((InvocationTargetException) e).getTargetException().getMessage());
}
}
return e.getClass() + " without detail message";
}
private static String composeMessage(String sqlState, String message) {
if (sqlState != null) return "SQLSTATE[" + sqlState + "] " + message;
return message;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,20 @@
package de.hsadmin.core.model;
public class TechnicalException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TechnicalException(String message, Throwable e) {
super(message, e);
}
public TechnicalException(String message) {
super(message);
}
public TechnicalException(Throwable e) {
super(e);
}
}

View File

@ -17,7 +17,6 @@ import javax.persistence.Query;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import de.hsadmin.cliClientConnector.TechnicalException;
import de.hsadmin.core.qserv.QueueClient;
import de.hsadmin.core.qserv.QueueTask;
import de.hsadmin.core.util.Config;

View File

@ -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;

View File

@ -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 {

View File

@ -34,20 +34,20 @@ public abstract class AbstractRemote implements IRemote {
public List<Map<String, Object>> search(String runAsUser, String ticket,
Map<String, String> whereParams) throws HSAdminException {
String user = runAsUser;
Transaction transaction = new Transaction(user);
final String user = runAsUser;
final Transaction transaction = new Transaction(user);
try {
if (transaction.login(user, ticket)) {
ModuleInterface module = new GenericModuleImpl(transaction);
UnixUser unixUser = transaction.getLoginUser();
List<AbstractEntity> list = module.search(getEntityClass(),
final ModuleInterface module = new GenericModuleImpl(transaction);
final UnixUser unixUser = transaction.getLoginUser();
final List<AbstractEntity> list = module.search(getEntityClass(),
buildQueryCondition(whereParams), null);
if (list == null) {
throw new HSAdminException("result list is null, runtime-error?");
}
ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
final ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
for (AbstractEntity e : list) {
HashMap<String, Object> entry = new HashMap<String, Object>();
final HashMap<String, Object> entry = new HashMap<String, Object>();
entity2map(transaction, e, entry);
if (e.isReadAllowedFor(unixUser)) {
result.add(entry);
@ -68,20 +68,20 @@ public abstract class AbstractRemote implements IRemote {
public Map<String, Object> add(String runAsUser, String ticket,
Map<String, Object> setParams) throws HSAdminException {
String user = runAsUser;
Transaction transaction = new Transaction(user);
final String user = runAsUser;
final Transaction transaction = new Transaction(user);
try {
if (transaction.login(user, ticket)) {
ModuleInterface module = new GenericModuleImpl(transaction);
Constructor<? extends AbstractEntity> constructor =
final ModuleInterface module = new GenericModuleImpl(transaction);
final Constructor<? extends AbstractEntity> constructor =
getEntityClass().getConstructor();
AbstractEntity entity = constructor.newInstance();
final AbstractEntity entity = constructor.newInstance();
module.initialize(entity);
map2entity(transaction, setParams, entity);
transaction.beginTransaction();
AbstractEntity insertedEntity = module.add(entity);
final AbstractEntity insertedEntity = module.add(entity);
transaction.commitTransaction();
HashMap<String, Object> entry = new HashMap<String, Object>();
final HashMap<String, Object> entry = new HashMap<String, Object>();
entity2map(transaction, insertedEntity, entry);
return entry;
} else {
@ -96,18 +96,18 @@ public abstract class AbstractRemote implements IRemote {
public void delete(String runAsUser, String ticket,
Map<String, String> whereParams) throws HSAdminException {
String user = runAsUser;
Transaction transaction = new Transaction(user);
final String user = runAsUser;
final Transaction transaction = new Transaction(user);
try {
if (transaction.login(user, ticket)) {
ModuleInterface module = new GenericModuleImpl(transaction);
UnixUser unixUser = transaction.getLoginUser();
String queryCondition = buildQueryCondition(whereParams);
final ModuleInterface module = new GenericModuleImpl(transaction);
final UnixUser unixUser = transaction.getLoginUser();
final String queryCondition = buildQueryCondition(whereParams);
if (queryCondition == null || queryCondition.length() == 0) {
throw new HSAdminException(
"better safe than sorry: no where parameter found");
}
List<AbstractEntity> list = module.search(getEntityClass(),
final List<AbstractEntity> list = module.search(getEntityClass(),
queryCondition, null);
transaction.beginTransaction();
for (AbstractEntity e : list) {
@ -133,19 +133,19 @@ public abstract class AbstractRemote implements IRemote {
public List<Map<String, Object>> update(String runAsUser, String ticket,
Map<String, Object> setParams, Map<String, String> whereParams)
throws HSAdminException {
String user = runAsUser;
Transaction transaction = new Transaction(user);
final String user = runAsUser;
final Transaction transaction = new Transaction(user);
try {
if (transaction.login(user, ticket)) {
ModuleInterface module = new GenericModuleImpl(transaction);
UnixUser unixUser = transaction.getLoginUser();
ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
String queryCondition = buildQueryCondition(whereParams);
final ModuleInterface module = new GenericModuleImpl(transaction);
final UnixUser unixUser = transaction.getLoginUser();
final ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
final String queryCondition = buildQueryCondition(whereParams);
if (queryCondition == null || queryCondition.length() == 0) {
throw new HSAdminException(
"better safe than sorry: no where parameter found");
}
List<AbstractEntity> list = module.search(getEntityClass(),
final List<AbstractEntity> list = module.search(getEntityClass(),
queryCondition, getOrderBy());
transaction.beginTransaction();
for (AbstractEntity update : list) {
@ -153,7 +153,7 @@ public abstract class AbstractRemote implements IRemote {
transaction.detach(update);
map2entity(transaction, setParams, update);
update = module.update(update);
HashMap<String, Object> entry = new HashMap<String, Object>();
final HashMap<String, Object> entry = new HashMap<String, Object>();
entity2map(transaction, update, entry);
result.add(entry);
} else {
@ -188,7 +188,7 @@ public abstract class AbstractRemote implements IRemote {
protected void replaceKey(Map<String, String> whereParams, String shortKey, String regularKey) {
if (whereParams.containsKey(shortKey)) {
String value = whereParams.get(shortKey);
final String value = whereParams.get(shortKey);
whereParams.remove(shortKey);
whereParams.put(regularKey, value);
}
@ -200,18 +200,18 @@ public abstract class AbstractRemote implements IRemote {
private String buildQueryCondition(Map<String, String> whereParams) {
regularizeKeys(whereParams);
StringBuffer cond = new StringBuffer();
Iterator<String> keyIterator = whereParams.keySet().iterator();
final StringBuffer cond = new StringBuffer();
final Iterator<String> keyIterator = whereParams.keySet().iterator();
while (keyIterator.hasNext()) {
if (cond.length() > 0) {
cond.append(" AND ");
}
String field = keyIterator.next();
String value = whereParams.get(field).replaceAll("'", "\'");
final String field = keyIterator.next();
final String value = whereParams.get(field).replaceAll("'", "\'");
cond.append("obj.");
cond.append(field);
cond.append(" = ");
boolean numeric = "id".equals(field);
final boolean numeric = "id".equals(field);
if (!numeric) cond.append("'");
cond.append(value);
if (!numeric) cond.append("'");

View File

@ -1,200 +0,0 @@
package de.hsadmin.remote;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.model.Transaction;
import de.hsadmin.core.util.TextUtil;
import de.hsadmin.mods.cust.Contact;
import de.hsadmin.mods.cust.Customer;
public class CustomerRemote extends AbstractRemote {
@Override
protected Class<? extends AbstractEntity> getEntityClass() {
return Customer.class;
}
@Override
protected void entity2map(Transaction tx, AbstractEntity entity, Map<String, Object> resultMap) {
Customer cust = (Customer) entity;
resultMap.put("id", Long.toString(cust.getId()));
resultMap.put("membercode", cust.getName());
resultMap.put("memberno", Integer.toString(cust.getMemberNo()));
Date memberSince = cust.getMemberSince();
if (assertNotNull(memberSince)) {
resultMap.put("membersince", TextUtil.format(memberSince));
}
Date memberUntil = cust.getMemberUntil();
if (assertNotNull(memberUntil)) {
resultMap.put("memberuntil", TextUtil.format(memberUntil));
}
resultMap.put("memberrole", cust.getMemberRole());
Date authorContract = cust.getAuthorContract();
if (assertNotNull(authorContract)) {
resultMap.put("authorcontract", TextUtil.format(authorContract));
}
Date nonDiscContract = cust.getNonDiscContract();
if (assertNotNull(nonDiscContract)) {
resultMap.put("nondisccontract", TextUtil.format(nonDiscContract));
}
Date sharesUpdated = cust.getSharesUpdated();
if (assertNotNull(sharesUpdated)) {
resultMap.put("sharesupdated", TextUtil.format(sharesUpdated));
}
resultMap.put("sharessigned", Integer.toString(cust.getSharesSigned()));
resultMap.put("uidvat", cust.getUidVAT());
Set<Contact> contacts = cust.getContacts();
if (contacts != null && !contacts.isEmpty()) {
Contact c = contacts.iterator().next();
resultMap.put("contact_salut", c.getSalut());
resultMap.put("contact_title", c.getTitle());
resultMap.put("contact_firstname", c.getFirstName());
resultMap.put("contact_lastname", c.getLastName());
resultMap.put("contact_firma", c.getFirma());
resultMap.put("contact_co", c.getCo());
resultMap.put("contact_street", c.getStreet());
resultMap.put("contact_zipcode", c.getZipCode());
resultMap.put("contact_city", c.getCity());
resultMap.put("contact_country", c.getCountry());
resultMap.put("contact_phone_private", c.getPhonePrivate());
resultMap.put("contact_phone_office", c.getPhoneOffice());
resultMap.put("contact_phone_mobile", c.getPhoneMobile());
resultMap.put("contact_fax", c.getFax());
resultMap.put("contact_email", c.getEmail());
}
}
@Override
protected void map2entity(Transaction tx, Map<String, Object> setParams,
AbstractEntity entity) {
Customer cust = (Customer) entity;
String idStr = (String) setParams.get("id");
if (assertNotNull(idStr)) {
cust.setId(Long.parseLong(idStr));
}
String memberCode = (String) setParams.get("membercode");
if (assertNotNull(memberCode)) {
cust.setName(memberCode);
}
String password = (String) setParams.get("password");
if (assertNotNull(password)) {
cust.setPassword(password);
}
String memberNo = (String) setParams.get("memberno");
if (assertNotNull(memberNo)) {
cust.setMemberNo(Integer.parseInt(memberNo));
}
String memberSince = (String) setParams.get("membersince");
if (assertNotNull(memberSince)) {
cust.setMemberSince(TextUtil.parseDate(memberSince));
}
String memberUntil = (String) setParams.get("memberuntil");
if (assertNotNull(memberUntil)) {
cust.setMemberUntil(TextUtil.parseDate(memberUntil));
}
String memberRole = (String) setParams.get("memberrole");
if (assertNotNull(memberRole)) {
cust.setMemberRole(memberRole);
}
String authorContract = (String) setParams.get("authorcontract");
if (assertNotNull(authorContract)) {
cust.setAuthorContract(TextUtil.parseDate(authorContract));
}
String nonDiscContract = (String) setParams.get("nondisccontract");
if (assertNotNull(nonDiscContract)) {
cust.setNonDiscContract(TextUtil.parseDate(nonDiscContract));
}
String sharesUpdated = (String) setParams.get("sharesupdated");
if (assertNotNull(sharesUpdated)) {
cust.setSharesUpdated(TextUtil.parseDate(sharesUpdated));
}
String sharesSigned = (String) setParams.get("sharessigned");
if (assertNotNull(sharesSigned)) {
cust.setSharesSigned(Integer.parseInt(sharesSigned));
}
String uidVat = (String) setParams.get("uidvat");
if (assertNotNull(uidVat)) {
cust.setUidVAT(uidVat);
}
Set<Contact> contacts = cust.getContacts();
Contact c = null;
if (contacts == null || contacts.isEmpty()) {
c = new Contact(cust);
contacts.add(c);
} else {
c = contacts.iterator().next();
}
String salut = (String) setParams.get("contact_salut");
if (assertNotNull(salut)) {
c.setSalut(salut);
}
String title = (String) setParams.get("contact_title");
if (assertNotNull(title)) {
c.setTitle(title);
}
String firstName = (String) setParams.get("contact_firstname");
if (assertNotNull(firstName)) {
c.setFirstName(firstName);
}
String lastName = (String) setParams.get("contact_lastname");
if (assertNotNull(lastName)) {
c.setLastName(lastName);
}
String firma = (String) setParams.get("contact_firma");
if (assertNotNull(firma)) {
c.setFirma(firma);
}
String co = (String) setParams.get("contact_co");
if (assertNotNull(co)) {
c.setCo(co);
}
String street = (String) setParams.get("contact_street");
if (assertNotNull(street)) {
c.setStreet(street);
}
String zipCode = (String) setParams.get("contact_zipcode");
if (assertNotNull(zipCode)) {
c.setZipCode(zipCode);
}
String city = (String) setParams.get("contact_city");
if (assertNotNull(city)) {
c.setCity(city);
}
String country = (String) setParams.get("contact_country");
if (assertNotNull(country)) {
c.setCountry(country);
}
String phonePrivate = (String) setParams.get("contact_phone_private");
if (assertNotNull(phonePrivate)) {
c.setPhonePrivate(phonePrivate);
}
String phoneOffice = (String) setParams.get("contact_phone_office");
if (assertNotNull(phoneOffice)) {
c.setPhoneOffice(phoneOffice);
}
String phoneMobile = (String) setParams.get("contact_phone_mobile");
if (assertNotNull(phoneMobile)) {
c.setPhoneMobile(phoneMobile);
}
String fax = (String) setParams.get("contact_fax");
if (assertNotNull(fax)) {
c.setFax(fax);
}
String eMail = (String) setParams.get("contact_email");
if (assertNotNull(eMail)) {
c.setEmail(eMail);
}
}
@Override
protected void regularizeKeys(Map<String, String> whereParams) {
replaceKey(whereParams, "membercode", "name");
replaceKey(whereParams, "memberno", "memberNo");
replaceKey(whereParams, "membersince", "memberSince");
replaceKey(whereParams, "memberuntil", "memberUntil");
}
}

View File

@ -23,25 +23,25 @@ public class DomainRemote extends AbstractRemote {
@Override
protected void entity2map(Transaction tx, AbstractEntity entity, Map<String, Object> resultMap) {
Domain dom = (Domain) entity;
String id = Long.toString(dom.getId());
final Domain dom = (Domain) entity;
final String id = Long.toString(dom.getId());
resultMap.put("id", id);
String name = dom.getName();
final String name = dom.getName();
resultMap.put("name", name);
String user = dom.getUser().getName();
final String user = dom.getUser().getName();
resultMap.put("user", user);
String hive = dom.getHiveName();
final String hive = dom.getHiveName();
resultMap.put("hive", hive);
String pac = dom.getUser().getPac().getName();
final String pac = dom.getUser().getPac().getName();
resultMap.put("pac", pac);
Date sDate = dom.getSince();
final Date sDate = dom.getSince();
if (assertNotNull(sDate)) {
String since = TextUtil.format(sDate);
final String since = TextUtil.format(sDate);
resultMap.put("since", since);
}
List<String> domainOptionsList = new ArrayList<String>();
final List<String> domainOptionsList = new ArrayList<String>();
resultMap.put("domainoptions", domainOptionsList);
Set<DomainOption> domainOptions = dom.getDomainoptions();
final Set<DomainOption> domainOptions = dom.getDomainoptions();
if (domainOptions != null) {
for (DomainOption opt : domainOptions) {
domainOptionsList.add(opt.getName());
@ -51,23 +51,23 @@ public class DomainRemote extends AbstractRemote {
@Override
protected void map2entity(Transaction tx, Map<String, Object> setParams, AbstractEntity entity) {
Domain dom = (Domain) entity;
String name = (String) setParams.get("name");
String user = (String) setParams.get("user");
final Domain dom = (Domain) entity;
final String name = (String) setParams.get("name");
final String user = (String) setParams.get("user");
if (assertNotNull(name)) {
dom.setName(name);
}
if (assertNotNull(user)) {
UnixUser u = new UnixUser();
final UnixUser u = new UnixUser();
u.setName(user);
dom.setUser(u);
}
Object domOptsObj = setParams.get("domainoptions");
final Object domOptsObj = setParams.get("domainoptions");
if (domOptsObj != null && domOptsObj instanceof Object[]) {
Set<DomainOption> domainOptionsSet = new HashSet<DomainOption>();
Object[] domOptions = (Object[]) domOptsObj;
final Set<DomainOption> domainOptionsSet = new HashSet<DomainOption>();
final Object[] domOptions = (Object[]) domOptsObj;
for (int i=0; i<domOptions.length; i++) {
DomainOption domainOption = new DomainOption();
final DomainOption domainOption = new DomainOption();
domainOption.setName((String)domOptions[i]);
domainOptionsSet.add(domainOption);
}

View File

@ -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;