Improve output: distinguish between failed assertions (failures) and unexpected exceptions (errors), and print a filtered stack trace for any exception.

This commit is contained in:
jeb228 2010-01-29 22:13:57 +00:00
commit 4f2e303079
1839 changed files with 235630 additions and 0 deletions

View file

@ -0,0 +1,35 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
public class BeanDependency {
private Object bean;
private String nearKey;
private String farKey;
public Object getBean(){
return bean;
}
public void setBean(Object bean){
this.bean = bean;
}
public String getNearKey(){
return nearKey;
}
public void setNearKey (String nearKey){
this.nearKey = nearKey;
}
public String getFarKey(){
return farKey;
}
public void setFarKey(String farKey){
this.farKey = farKey;
}
}

View file

@ -0,0 +1,62 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.HashMap;
public class ButtonForm {
private String action = "";
private String label = "no label specified";
private String cssClass = null;
private HashMap<String,String> params = null;
public ButtonForm() {
action = ""; // submits to same page
cssClass = null;
label = "no label specified";
params = null;
}
public ButtonForm(String actionStr, String classStr, String labelStr, HashMap<String,String> paramMap) {
action = actionStr;
cssClass = classStr; // can be null
label = labelStr;
params = paramMap;
}
public String getAction(){
return action;
}
public void setAction(String s){
action = s;
}
public String getLabel(){
return label;
}
public void setLabel(String s){
label = s;
}
public String getCssClass(){
if (cssClass==null){
return "";
}
return "class=\""+cssClass+"\"";
}
public void setCssClass(String s){
cssClass=s;
}
public HashMap<String,String> getParams(){
return params;
}
public void setParams(HashMap<String,String> p){
params = p;
}
public void addParam(String key, String value){
if (params==null){
params = new HashMap<String,String>();
}
params.put(key, value);
}
}

View file

@ -0,0 +1,44 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
public class Checkbox {
private String name = null;
private String value = null;
private String body = null;
private boolean checked = false;
public String getName(){
return name;
}
private void setName(String name){
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean getChecked (){
return checked;
}
public void setChecked (boolean checked){
this.checked = checked;
}
}

View file

@ -0,0 +1,98 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
public class DynamicField {
private String name = null;
private String table = null;
private int maxCardinality = 1;
private int minCardinality = -1;
private int visible = -1;
private List<DynamicFieldRow> rowList = null;
private DynamicFieldRow rowTemplate = null;
private HashMap metadata = new HashMap();
private Boolean deleteable = true;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public int getMaxCardinality() {
return maxCardinality;
}
public void setMaxCardinality (int maxCardinality) {
this.maxCardinality = maxCardinality;
}
public int getMinCardinality () {
return minCardinality;
}
public void setMinCardinality(int minCardinality) {
this.minCardinality = minCardinality;
}
public int getVisible() {
return visible;
}
public void setVisible(int visible) {
this.visible = visible;
}
public boolean getDeleteable() {
return deleteable;
}
public void setDeleteable(boolean deleteable) {
this.deleteable = deleteable;
}
public HashMap getMetadata() {
return metadata;
}
public void setMetadata(HashMap metadata) {
this.metadata = metadata;
}
public List<DynamicFieldRow> getRowList() {
return rowList;
}
public void setRowList (List<DynamicFieldRow> rowList) {
this.rowList = rowList;
}
public DynamicFieldRow getRowTemplate() {
return rowTemplate;
}
public void setRowTemplate(DynamicFieldRow dfr) {
rowTemplate = dfr;
}
}

View file

@ -0,0 +1,37 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.Map;
public class DynamicFieldRow {
private int id = -1;
private String value = null;
private Map parameterMap = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Map getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map parameterMap) {
this.parameterMap = parameterMap;
}
}

View file

@ -0,0 +1,350 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.List;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vedit.forwarder.PageForwarder;
import edu.cornell.mannlib.vedit.beans.BeanDependency;
import edu.cornell.mannlib.vedit.beans.FormObject;
import java.lang.reflect.Method;
import java.io.Serializable;
public class EditProcessObject implements Serializable {
private String key = null;
private Class beanClass = null;
private Class implementationClass = null;
private boolean useRecycledBean = false;
private Object beanMask = null;
private List simpleMask = new LinkedList();
private HashMap validatorMap = new HashMap();
private HashMap errMsgMap = new HashMap();
private HashMap defaultValueMap = new HashMap();
private List preProcessorList = new LinkedList();
private List changeListenerList = new LinkedList();
private Object originalBean = null;
private Object newBean = null;
private String idFieldName = null;
private Class idFieldClass = null;
private FormObject formObject = null;
private Object dataAccessObject = null;
private HashMap additionalDaoMap = new HashMap();
private Method insertMethod = null;
private Method updateMethod = null;
private Method deleteMethod = null;
private PageForwarder postInsertPageForwarder = null;
private PageForwarder postUpdatePageForwarder = null;
private PageForwarder postDeletePageForwarder = null;
private HttpSession session = null;
private String referer = null;
private String action = null;
private Map requestParameterMap = null;
private HashMap badValueMap = new HashMap();
private HashMap<String,Object> attributeMap = new HashMap<String,Object>();
/***** experimental ******/
private Stack epoStack = new Stack();
private HashMap beanDependencies = new HashMap();
private Method getMethod = null;
//assumed to take an integer primary key argument, at least for now
public String getKey(){
return key;
}
public void setKey(String key){
this.key = key;
}
public Class getBeanClass(){
return beanClass;
}
public void setBeanClass(Class beanClass){
this.beanClass = beanClass;
}
public Class getImplementationClass(){
return implementationClass;
}
public void setImplementationClass(Class implementationClass){
this.implementationClass = implementationClass;
}
public Object getBeanMask() {
return beanMask;
}
public void setBeanMask(Object beanMask) {
this.beanMask = beanMask;
}
public List getSimpleMask(){
return simpleMask;
}
public void setSimpleMask(List simpleMask){
this.simpleMask = simpleMask;
}
public List getChangeListenerList() {
return changeListenerList;
}
public void setChangeListenerList(List changeListenerList) {
this.changeListenerList = changeListenerList;
}
public List getPreProcessorList() {
return preProcessorList;
}
public void setPreProcessorList(List preProcessorList) {
this.preProcessorList = preProcessorList;
}
public Object getOriginalBean(){
return originalBean;
}
public void setOriginalBean(Object originalBean){
this.originalBean = originalBean;
}
public Object getNewBean(){
return newBean;
}
public void setNewBean(Object newBean){
this.newBean = newBean;
}
public String getIdFieldName() {
return idFieldName;
}
public void setIdFieldName(String ifn) {
this.idFieldName = ifn;
}
public Class getIdFieldClass() {
return idFieldClass;
}
public void setIdFieldClass(Class cls) {
this.idFieldClass = cls;
}
public FormObject getFormObject() {
return formObject;
}
public void setFormObject(FormObject foo){
formObject=foo;
}
public HttpSession getSession(){
return session;
}
public boolean getUseRecycledBean(){
return useRecycledBean;
}
public void setUseRecycledBean(boolean useRecycledBean){
this.useRecycledBean = useRecycledBean;
}
public void setSession(HttpSession session){
this.session = session;
}
public String getReferer(){
return referer;
}
public void setReferer(String referer){
this.referer = referer;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public Map getRequestParameterMap() {
return requestParameterMap;
}
public void setRequestParameterMap (Map rpmap) {
requestParameterMap = rpmap;
}
public PageForwarder getPostInsertPageForwarder(){
return postInsertPageForwarder;
}
public void setPostInsertPageForwarder(PageForwarder pipf){
postInsertPageForwarder = pipf;
}
public PageForwarder getPostUpdatePageForwarder(){
return postUpdatePageForwarder;
}
public void setPostUpdatePageForwarder(PageForwarder pupf){
postUpdatePageForwarder = pupf;
}
public PageForwarder getPostDeletePageForwarder(){
return postDeletePageForwarder;
}
public void setPostDeletePageForwarder(PageForwarder pdpf){
postDeletePageForwarder = pdpf;
}
public Object getDataAccessObject() {
return dataAccessObject;
}
public void setDataAccessObject(Object dao) {
dataAccessObject = dao;
}
public HashMap getAdditionalDaoMap() {
return additionalDaoMap;
}
public void setAdditionalDaoMap(HashMap adm) {
additionalDaoMap = adm;
}
public Method getInsertMethod(){
return insertMethod;
}
public void setInsertMethod(Method insertMethod){
this.insertMethod = insertMethod;
}
public Method getUpdateMethod(){
return updateMethod;
}
public void setUpdateMethod(Method updateMethod){
this.updateMethod = updateMethod;
}
public Method getDeleteMethod(){
return deleteMethod;
}
public void setDeleteMethod(Method deleteMethod){
this.deleteMethod = deleteMethod;
}
public Method getGetMethod(){
return getMethod;
}
public void setGetMethod(Method getMethod){
this.getMethod = getMethod;
}
public HashMap getDefaultValueMap() {
return defaultValueMap;
}
public void setDefaultValueMap(HashMap dvh) {
this.defaultValueMap = dvh;
}
public HashMap getValidatorMap(){
return validatorMap;
}
public void setValidatorMap(HashMap validatorMap){
this.validatorMap = validatorMap;
}
public HashMap getErrMsgMap() {
return errMsgMap;
}
public void setErrMsgMap(HashMap emh){
errMsgMap = emh;
}
public HashMap getBadValueMap() {
return badValueMap;
}
public void setBadValueMap(HashMap bvh){
badValueMap = bvh;
}
public Map getAttributeMap() {
return this.attributeMap;
}
public Object getAttribute(String key) {
return this.attributeMap.get(key);
}
public void setAttribute(String key, Object value) {
this.attributeMap.put(key, value);
}
public Stack getEpoStack(){
return epoStack;
}
public HashMap /*to BeanDependency*/ getBeanDependencies(){
return beanDependencies;
}
public void setBeanDependencies(HashMap beanDependencies){
this.beanDependencies = beanDependencies;
}
public BeanDependency getBeanDependency(String name){
return (BeanDependency) beanDependencies.get(name);
}
public Object getDependentBean(String name){
return ((BeanDependency)beanDependencies.get(name)).getBean();
}
/******* probably will need to change this *******/
public void setEpoStack(Stack epoStack){
this.epoStack = epoStack;
}
}

View file

@ -0,0 +1,54 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
public class FieldHelp {
private String description = null;
private String descriptionUri = null;
private String examples = null;
private String examplesUri = null;
private String helpUri = null;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescriptionUri() {
return descriptionUri;
}
public void setDescriptionUri(String descriptionUri) {
this.descriptionUri = descriptionUri;
}
public String getExamples() {
return examples;
}
public void setExamples(String examples) {
this.examples = examples;
}
public String getExamplesUri() {
return examplesUri;
}
public void setExamplesUri(String examplesUri) {
this.examplesUri = examplesUri;
}
public String getHelpUri() {
return helpUri;
}
public void setHelpUri(String helpUri) {
this.helpUri = helpUri;
}
}

View file

@ -0,0 +1,62 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import edu.cornell.mannlib.vedit.beans.Option;
public class FormObject implements Serializable {
private HashMap values = new HashMap();
private HashMap optionLists = new HashMap();
private HashMap checkboxLists = new HashMap();
private HashMap errorMap = new HashMap();
private List dynamicFields = null;
public HashMap getValues(){
return values;
}
public void setValues(HashMap values){
this.values = values;
}
public String valueByName(String name){
return (String) values.get(name);
}
public HashMap getOptionLists() {
return optionLists;
}
public void setOptionLists(HashMap optionLists) {
this.optionLists = optionLists;
}
public List optionListByName(String key){
return (List) optionLists.get(key);
}
public HashMap getCheckboxLists(){
return checkboxLists;
}
public HashMap getErrorMap(){
return errorMap;
}
public void setErrorMap(HashMap errorMap){
this.errorMap = errorMap;
}
public List getDynamicFields() {
return dynamicFields;
}
public void setDynamicFields(List dynamicFields){
this.dynamicFields = dynamicFields;
}
}

View file

@ -0,0 +1,214 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/**
*
* @author jc55
*
*/
public class LoginFormBean {
public static final int ANYBODY=0;
public int getAnybody(){ return ANYBODY; }
public static final int NON_EDITOR = 1;
public int getNonEditor(){ return NON_EDITOR; }
public static final int EDITOR =4;
public int getEditor(){return EDITOR;}
public static final int CURATOR=5;
public int getCurator(){return CURATOR;}
public static final int DBA =50;
public int getDba(){return DBA;}
public boolean getBla(){ return true; }
private String userURI;
private String sessionId;
private String loginBrowser;
private String loginRemoteAddr;
private String loginName;
private String loginPassword;
private String loginStatus;
private int loginUserId;
private String loginRole;
private String duplicatePassword;
private String emailAddress;
private Hashtable errors;
public boolean validateLoginForm() {
boolean allOk=true;
if ( loginName.equals("")) {
errors.put( "loginName","Please enter your Vivo user name" );
loginName = "";
allOk = false;
}
if ( loginPassword.equals("")) {
errors.put( "loginPassword","Please enter your Vivo password" );
loginPassword="";
allOk=false;
}
return allOk;
}
public LoginFormBean() {
sessionId = "";
loginBrowser = "";
loginRemoteAddr = "";
loginName = "";
loginPassword = "";
loginStatus = "none";
loginUserId = 0;
loginRole = "1";
duplicatePassword = "";
emailAddress = "";
errors = new Hashtable();
}
public String toString(){
String name = "-not-logged-in-";
if( getLoginName() != null && !"".equals(getLoginName()) )
name = getLoginName();
return this.getClass().getName()
+" loginName: " + name
+" loginStatus: "+ getLoginStatus()
+" loginRole: "+ getLoginRole();
}
/**
Tests a HttpSession to see if logged in and authenticated.
@returns loginRole if seems to be authenticated, -1 otherwise
*/
public int testSessionLevel( HttpServletRequest request ){
//TODO: security code added by bdc34, should be checked by jc55
HttpSession currentSession = request.getSession();
int returnRole = -1;
if ( getLoginStatus().equals("authenticated") &&
currentSession.getId().equals( getSessionId() ) &&
request.getRemoteAddr().equals( getLoginRemoteAddr() ) ) {
try{
returnRole = Integer.parseInt( getLoginRole() );
}catch(Throwable thr){ }
}
return returnRole;
}
public static boolean loggedIn(HttpServletRequest request, int minLevel) {
if( request == null ) return false;
HttpSession sess = request.getSession(false);
if( sess == null ) return false;
Object obj = sess.getAttribute("loginHandler");
if( obj == null || ! (obj instanceof LoginFormBean))
return false;
LoginFormBean lfb = (LoginFormBean)obj;
return ( "authenticated".equals(lfb.loginStatus ) &&
Integer.parseInt(lfb.loginRole ) >= minLevel) ;
}
/********************** GET METHODS *********************/
public String getUserURI() {
return userURI;
}
public String getSessionId() {
return sessionId;
}
public String getLoginBrowser() {
return loginBrowser;
}
public String getLoginRemoteAddr() {
return loginRemoteAddr;
}
public String getLoginName() {
return loginName;
}
public String getLoginPassword() {
return loginPassword;
}
public String getLoginStatus() {
return loginStatus;
}
public int getLoginUserId() {
return loginUserId;
}
public String getLoginRole() {
return loginRole;
}
public String getDuplicatePassword() {
return duplicatePassword;
}
public String getEmailAddress() {
return emailAddress;
}
public String getErrorMsg( String s ) {
String errorMsg =(String) errors.get( s.trim() );
return ( errorMsg == null ) ? "" : errorMsg;
}
/********************** SET METHODS *********************/
public void setUserURI( String uri ) {
this.userURI = uri;
}
public void setSessionId( String id ) {
sessionId = id;
}
public void setLoginBrowser( String b ) {
loginBrowser = b;
}
public void setLoginRemoteAddr( String ra ) {
loginRemoteAddr = ra;
}
public void setLoginName( String ln ) {
loginName = ln;
}
public void setLoginPassword( String lp ) {
loginPassword = lp;
}
public void setLoginStatus( String ls ) {
loginStatus = ls;
}
public void setLoginUserId(int int_val) {
loginUserId=int_val;
}
public void setLoginRole( String lr ) {
loginRole = lr;
}
public void setDuplicatePassword( String dp ) {
duplicatePassword = dp;
}
public void setEmailAddress( String ea ) {
emailAddress = ea;
}
public void setErrorMsg( String key, String msg ) {
errors.put( key,msg );
}
}

View file

@ -0,0 +1,59 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.io.Serializable;
public class Option implements Serializable {
private String value = null;
private String body = null;
private boolean selected = false;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean getSelected (){
return selected;
}
public void setSelected (boolean selected){
this.selected = selected;
}
//default constructor
public Option() {
}
public Option (String value, String body, boolean selected) {
this.value = value;
this.body = body;
this.selected = selected;
}
// construct an Option with body and value
public Option(String value, String body) {
this(value, body, false);
}
// construct an Option with equal body and value
public Option (String name){
this(name, name, false);
}
}

View file

@ -0,0 +1,195 @@
package edu.cornell.mannlib.vedit.beans;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/**
* User Session information
* @author John Fereira
* @since 29.06.2004
*/
public class UserSession {
private int currentEntityId;
private int currentPortalId;
private int currentTabId;
private String lastSearchURL;
private boolean isPatronAuthenticated;
private boolean isAdminAuthenticated;
private String referer;
private String lastSearchTerm;
private String flag1Pref;
public void setFlag1Pref(String s) { flag1Pref=s; }
public String getFlag1Pref() { return flag1Pref; }
private String flag2Pref;
public void setFlag2Pref(String s) { flag2Pref=s; }
public String getFlag2Pref() { return flag2Pref; }
private String flag3Pref;
public void setFlag3Pref(String s) { flag3Pref=s; }
public String getFlag3Pref() { return flag3Pref; }
//search wrapper was part of the mysql full text search, no longer in use.
// private SearchWrapper searchWrapper;
// public void setSearchWrapper(SearchWrapper sw) { searchWrapper=sw; }
// public SearchWrapper getSearchWrapper() { return searchWrapper; }
// public void disposeOf(SearchWrapper sw) {
// if (sw!=null){
// sw.dispose();
// }
// this.searchWrapper=null;
// }
/** constructor */
public UserSession() {
this.isPatronAuthenticated = false;
this.isAdminAuthenticated = false;
}
/**
* set current entity id
* @param currentEntityId : unique id
*/
public void setCurrentEntityId(int currentEntityId) {
this.currentEntityId = currentEntityId;
}
/**
* get Current entity Id
* @return : the entity Id
*/
public int getCurrentEntityId() {
return currentEntityId;
}
/**
* set current portal id
* @param currentPortalId : unique id
*/
public void setCurrentPortalId(int currentPortalId) {
this.currentPortalId = currentPortalId;
}
/**
* get Current portal Id
* @return : the portal Id
*/
public int getCurrentPortalId() {
return currentPortalId;
}
/**
* set current tab id
* @param currentTabId : unique id
*/
public void setCurrentTabId(int currentTabId) {
this.currentTabId = currentTabId;
}
/**
* get current tab id
* @return : the tab Id
*/
public int getCurrentTabId() {
return currentTabId;
}
/**
* set last SearchURL in session
* @param lastSearchURL : a url string
*/
public void setLastSearchURL(String lastSearchURL) {
this.lastSearchURL = lastSearchURL;
}
/**
* get last Search URL
* @return : last search url string
*/
public String getLastSearchURL() {
return lastSearchURL;
}
/**
* Set boolen flag to indicated if patron has authenticated
* @param isPatronAuthenticated : true or false
*/
public void setIsPatronAuthenticated(boolean isPatronAuthenticated) {
this.isPatronAuthenticated = isPatronAuthenticated;
}
/**
* get boolean flag indicating whethor or not patron has authenticated
* @return : true or false
*/
public boolean getIsPatronAuthenticated() {
return isPatronAuthenticated;
}
/**
* set boolean flag indicating whether or not an Administrator has
* authenticated
* @param isAdminAuthenticated : true or false
*/
public void setIsAdminAuthenticated(boolean isAdminAuthenticated) {
this.isAdminAuthenticated = isAdminAuthenticated;
}
/**
* get boolean flag indicating whether or not an Administrator has
* authenticated
* @return : true or false
*/
public boolean getIsAdminAuthenticated() {
return isAdminAuthenticated;
}
/**
* set referer url in session
* @param referer : a referer url string
*/
public void setReferer(String referer) {
this.referer = referer;
}
/**
* get referer url in session
* @return : a referer url string
*/
public String getReferer() {
return referer;
}
/**
* set lastSearchTerm in session
* @param lastSearchTerm : a lastSearchTerm string
*/
public void setLastSearchTerm(String lastSearchTerm) {
this.lastSearchTerm = lastSearchTerm;
}
/**
* get lastSearchTerm in session
* @return : a lastSearchTerm string
*/
public String getLastSearchTerm() {
return lastSearchTerm;
}
/**
* @param isAdminAuthenticated The isAdminAuthenticated to set.
*/
public void setAdminAuthenticated(boolean isAdminAuthenticated) {
this.isAdminAuthenticated = isAdminAuthenticated;
}
/**
* @param isPatronAuthenticated The isPatronAuthenticated to set.
*/
public void setPatronAuthenticated(boolean isPatronAuthenticated) {
this.isPatronAuthenticated = isPatronAuthenticated;
}
}

View file

@ -0,0 +1,218 @@
package edu.cornell.mannlib.vedit.controller;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.beans.LoginFormBean;
import edu.cornell.mannlib.vedit.util.FormUtils;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class BaseEditController extends VitroHttpServlet {
public static final boolean FORCE_NEW = true; // when you know you're starting a new edit process
public static final String JSP_PREFIX = "/templates/edit/specific/";
protected static DateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
private static final Log log = LogFactory.getLog(BaseEditController.class.getName());
private static final String DEFAULT_LANDING_PAGE = Controllers.SITE_ADMIN;
protected static final String MULTIPLEXED_PARAMETER_NAME = "multiplexedParam";
private final String EPO_HASH_ATTR = "epoHash";
private final String EPO_KEYLIST_ATTR = "epoKeylist";
private final int MAX_EPOS = 5;
private final Calendar cal = Calendar.getInstance();
private final Random rand = new Random(cal.getTimeInMillis());
/* EPO is reused if the controller is passed an epoKey, e.g.
if a previous form submission failed validation, or the edit is a multistage process. */
protected EditProcessObject createEpo(HttpServletRequest request) {
return createEpo(request, false);
}
protected EditProcessObject createEpo(HttpServletRequest request, boolean forceNew) {
/* this is actually a bit of a misnomer, because we will reuse an epo
if an epoKey parameter is passed */
EditProcessObject epo = null;
HashMap epoHash = getEpoHash(request);
String existingEpoKey = request.getParameter("_epoKey");
if (!forceNew && existingEpoKey != null && epoHash.get(existingEpoKey) != null) {
epo = (EditProcessObject) epoHash.get(existingEpoKey);
epo.setKey(existingEpoKey);
epo.setUseRecycledBean(true);
} else {
LinkedList epoKeylist = getEpoKeylist(request);
if (epoHash.size() == MAX_EPOS) {
try {
epoHash.remove(epoKeylist.getFirst());
epoKeylist.removeFirst();
} catch (Exception e) {
// see JIRA issue VITRO-340, "Odd exception from backend editing"
// possible rare concurrency issue here
log.error("Error removing old EPO", e);
}
}
Random rand = new Random();
String epoKey = createEpoKey();
while (epoHash.get(epoKey) != null) {
epoKey+=Integer.toHexString(rand.nextInt());
}
epo = new EditProcessObject();
epoHash.put (epoKey,epo);
epoKeylist.add(epoKey);
epo.setKey(epoKey);
epo.setReferer( (forceNew) ? request.getRequestURL().append('?').append(request.getQueryString()).toString() : request.getHeader("Referer") );
epo.setSession(request.getSession());
}
return epo;
}
private LinkedList getEpoKeylist(HttpServletRequest request){
return (LinkedList) request.getSession().getAttribute(EPO_KEYLIST_ATTR);
}
private HashMap getEpoHash(HttpServletRequest request){
HashMap epoHash = (HashMap) request.getSession().getAttribute(EPO_HASH_ATTR);
if (epoHash == null) {
epoHash = new HashMap();
request.getSession().setAttribute(EPO_HASH_ATTR,epoHash);
//since we're making a new EPO hash, we should also make a new keylist.
LinkedList epoKeylist = new LinkedList();
request.getSession().setAttribute(EPO_KEYLIST_ATTR,epoKeylist);
}
return epoHash;
}
private String createEpoKey(){
return Long.toHexString(cal.getTimeInMillis());
}
protected boolean checkLoginStatus(HttpServletRequest request, HttpServletResponse response){
return checkLoginStatus(request, response, null);
}
protected boolean checkLoginStatus(HttpServletRequest request, HttpServletResponse response, String postLoginRedirectURI){
LoginFormBean loginBean = (LoginFormBean) request.getSession().getAttribute("loginHandler");
String loginPage = request.getContextPath() + Controllers.LOGIN;
if (loginBean == null){
try{
if (postLoginRedirectURI == null)
request.getSession().setAttribute("postLoginRequest",request.getRequestURI()+"?"+request.getQueryString());
else
request.getSession().setAttribute("postLoginRequest",postLoginRedirectURI+"?"+request.getQueryString());
response.sendRedirect(loginPage);
return false;
} catch (IOException ioe) {
log.error("checkLoginStatus() could not redirect to login page");
return false;
}
} else {
if (!loginBean.getLoginStatus().equals("authenticated")) {
try{
response.sendRedirect(loginPage);
return false;
} catch (IOException ioe) {
log.error("checkLoginStatus() could not redirect to login page");
return false;
}
}
}
return true;
}
protected void setRequestAttributes(HttpServletRequest request, EditProcessObject epo){
Portal portal = (Portal)request.getAttribute("portalBean");
request.setAttribute("epoKey",epo.getKey());
request.setAttribute("epo",epo);
request.setAttribute("globalErrorMsg",epo.getAttribute("globalErrorMsg"));
request.setAttribute("portalBean",portal);
request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+portal.getThemeDir()+"css/edit.css\"/>");
}
protected void populateBeanFromParams(Object bean, HttpServletRequest request) {
Map params = request.getParameterMap();
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()){
String key = "";
try {
key = (String) paramNames.nextElement();
} catch (ClassCastException cce) {
log.error("populateBeanFromParams() could not cast parameter name to String");
}
String value = "";
if (key.equals(MULTIPLEXED_PARAMETER_NAME)) {
String multiplexedStr = request.getParameterValues(key)[0];
Map paramMap = FormUtils.beanParamMapFromString(multiplexedStr);
Iterator paramIt = paramMap.keySet().iterator();
while (paramIt.hasNext()) {
String param = (String) paramIt.next();
String demultiplexedValue = (String) paramMap.get(param);
FormUtils.beanSet(bean, param, demultiplexedValue);
}
} else {
try {
value = (String) request.getParameterValues(key)[0];
} catch (ClassCastException cce) {
try {
value = ((Integer) params.get(key)).toString();
} catch (ClassCastException ccf) {
log.error("populateBeanFromParams() could not cast parameter name to String");
}
}
FormUtils.beanSet(bean, key, value);
}
}
}
protected String MODEL_ATTR_NAME = "jenaOntModel";
protected OntModel getOntModel( HttpServletRequest request, ServletContext ctx ) {
OntModel ontModel = null;
try {
ontModel = (OntModel) request.getSession().getAttribute(MODEL_ATTR_NAME);
} catch (Exception e) {}
if ( ontModel == null ) {
try {
ontModel = (OntModel) ctx.getAttribute(MODEL_ATTR_NAME);
} catch (Exception e) {
throw new RuntimeException("Could not find OntModel in context attribute '"+MODEL_ATTR_NAME+"'");
}
}
return ontModel;
}
public String getDefaultLandingPage(HttpServletRequest request) {
return(request.getContextPath() + DEFAULT_LANDING_PAGE);
}
}

View file

@ -0,0 +1,78 @@
package edu.cornell.mannlib.vedit.controller;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.io.IOException;
/**
* This controller exists only so we can request different edit form controllers without having to have entries in web.xml for each.
* @author bjl23
*
*/
public class EditFrontController extends VitroHttpServlet {
private static final Log log = LogFactory.getLog(EditFrontController.class.getName());
private static final String CONTROLLER_PKG = "edu.cornell.mannlib.vitro.webapp.controller.edit";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
String controllerName = request.getParameter("controller")+"RetryController";
if (controllerName==null || controllerName.length()==0) {
log.error("doPost() found no controller parameter");
}
Class controller = null;
Object controllerInstance = null;
try {
controller = Class.forName(CONTROLLER_PKG+"."+controllerName);
try {
controllerInstance = controller.getConstructor((Class[]) null).newInstance((Object[]) null);
((HttpServlet)controllerInstance).init(getServletConfig());
} catch (Exception e) {
log.error("doPost() could not instantiate specific controller "+controllerName);
}
} catch (ClassNotFoundException e){
log.error("doPost() could not find controller "+CONTROLLER_PKG+"."+controllerName);
}
Class[] args = new Class[2];
args[0] = HttpServletRequest.class;
args[1] = HttpServletResponse.class;
try {
Method meth = controller.getDeclaredMethod("doGet",args);
Object[] methArgs = new Object[2];
methArgs[0] = request;
methArgs[1] = response;
try {
meth.invoke(controllerInstance,methArgs);
} catch (IllegalAccessException e) {
log.error("doPost() encountered IllegalAccessException on invoking "+controllerName);
} catch (InvocationTargetException e) {
log.error("doPost() encountered InvocationTargetException on invoking "+controllerName);
log.debug(e.getTargetException().getMessage());
e.printStackTrace();
}
} catch (NoSuchMethodException e){
log.error("could not find doPost() method in "+controllerName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request,response);
}
}

View file

@ -0,0 +1,499 @@
package edu.cornell.mannlib.vedit.controller;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.forwarder.PageForwarder;
import edu.cornell.mannlib.vedit.listener.ChangeListener;
import edu.cornell.mannlib.vedit.listener.EditPreProcessor;
import edu.cornell.mannlib.vedit.util.FormUtils;
import edu.cornell.mannlib.vedit.util.OperationUtils;
import edu.cornell.mannlib.vedit.validator.ValidationObject;
import edu.cornell.mannlib.vedit.validator.Validator;
public class OperationController extends BaseEditController {
private static final Log log = LogFactory.getLog(OperationController.class.getName());
public void doPost (HttpServletRequest request, HttpServletResponse response) {
String defaultLandingPage = getDefaultLandingPage(request);
// get the Edit Process Object which will tell us wh
HashMap epoHash = null;
EditProcessObject epo = null;
try {
epoHash = (HashMap) request.getSession().getAttribute("epoHash");
epo = (EditProcessObject) epoHash.get(request.getParameter("_epoKey"));
} catch (NullPointerException e) {
//session or edit process expired
try {
response.sendRedirect(defaultLandingPage);
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
return;
}
if (epo == null) {
try {
response.sendRedirect(defaultLandingPage);
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
return;
}
// if we're canceling, we don't need to do anything
if (request.getParameter("_cancel") != null){
String referer = epo.getReferer();
if (referer == null) {
try {
response.sendRedirect(defaultLandingPage);
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
return;
}
else {
try {
response.sendRedirect(referer);
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
return;
}
}
// reset - if reset button is of type submit
if (request.getParameter("_reset") != null) {
try {
response.sendRedirect(request.getHeader("Referer"));
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
return;
}
try {
Object newObj = getNewObj(epo);
//populate this object from the req. params
boolean valid = populateObjectFromRequestParamsAndValidate(epo, newObj, request);
//run preprocessors
runPreprocessors(epo, newObj);
//applySimpleMask(epo, newObj);
//put the newObj back in the epo where other things can look at it
epo.setNewBean(newObj);
//if validation failed, go back to the form controller
if (!valid){
retry(request,response);
return;
}
String action = getAction(request);
boolean status = performEdit(epo, newObj, action);
if (status == FAILURE) {
retry(request,response);
}
/* put request parameters and attributes into epo where the listeners can see */
epo.setRequestParameterMap(request.getParameterMap());
notifyChangeListeners(epo, action);
/* send the user somewhere */
if (action.equals("insert")){
// Object[] args = new Object[1];
// args[0] = result;
// epo.setNewBean(epo.getGetMethod().invoke(facade,args));
PageForwarder pipf = epo.getPostInsertPageForwarder();
if (pipf != null){
pipf.doForward(request,response,epo);
return;
}
} else if (action.equals("update")){
PageForwarder pupf = epo.getPostUpdatePageForwarder();
if (pupf != null) {
pupf.doForward(request,response,epo);
return;
}
} else if (action.equals("delete")){
PageForwarder pdpf = epo.getPostDeletePageForwarder();
if (pdpf != null) {
pdpf.doForward(request,response,epo);
return;
}
}
//if no page forwarder was set, just go back to referring page:
String referer = epo.getReferer();
if (referer == null)
response.sendRedirect(defaultLandingPage);
else
response.sendRedirect(referer);
} catch (Exception e) {
log.error("Error performing edit", e);
String errMsg = (e.getMessage() != null)
? e.getMessage()
: "Error performing edit";
epo.setAttribute("globalErrorMsg", errMsg);
try {
retry(request, response);
} catch (IOException ioe) {
log.error(this.getClass().getName() + " IOError on redirect: ", ioe);
}
}
}
private void retry(HttpServletRequest request, HttpServletResponse response) throws IOException {
String referer = request.getHeader("Referer");
int epoKeyIndex = referer.indexOf("_epoKey");
if (epoKeyIndex<0)
response.sendRedirect(referer+"&_epoKey="+request.getParameter("_epoKey"));
else{
String url = referer.substring(0,epoKeyIndex) + "_epoKey="+request.getParameter("_epoKey");
response.sendRedirect(url);
}
return;
}
private void runPreprocessors(EditProcessObject epo, Object newObj) {
if (epo.getPreProcessorList() != null && epo.getPreProcessorList().size()>0) {
Iterator preIt = epo.getPreProcessorList().iterator();
while (preIt.hasNext()) {
try {
EditPreProcessor epp = (EditPreProcessor) preIt.next();
epp.process(newObj, epo);
} catch (ClassCastException e) {}
}
}
}
private void applySimpleMask(EditProcessObject epo, Object newObj) {
// apply the simple mask
//if (epo.getSimpleMask() != null) {
// Iterator smaskIt = epo.getSimpleMask().iterator();
// while (smaskIt.hasNext()){
// Object[] simpleMaskPair = (Object[]) smaskIt.next();
// FormUtils.beanSet(newObj,(String)simpleMaskPair[0],simpleMaskPair[1].toString());
// }
//}
}
private Object getNewObj(EditProcessObject epo) {
Object newObj = null;
if (epo.getOriginalBean() != null) { // we're updating or deleting an existing bean
if (epo.getImplementationClass() != null) {
newObj = OperationUtils.cloneBean(epo.getOriginalBean(), epo.getImplementationClass());
} else {
newObj = OperationUtils.cloneBean(epo.getOriginalBean());
}
} else {
Class cls = epo.getBeanClass();
try {
newObj = cls.newInstance();
} catch (IllegalAccessException iae) {
throw new RuntimeException("Illegal access - see error logs.");
} catch (InstantiationException ie) {
throw new RuntimeException("Unable to instantiate " + cls.getSimpleName());
}
}
epo.setNewBean(newObj); // is this dangerous?
return newObj;
}
private boolean populateObjectFromRequestParamsAndValidate(EditProcessObject epo, Object newObj, HttpServletRequest request) {
boolean valid = true;
String currParam="";
Enumeration penum = request.getParameterNames();
while (penum.hasMoreElements()){
currParam = (String) penum.nextElement();
if (!(currParam.indexOf("_")==0)){
String currValue = request.getParameterValues(currParam)[0];
// "altnew" values come in with the same input name but at position 1 of the array
if(currValue.length()==0 && request.getParameterValues(currParam).length>1) {
currValue = request.getParameterValues(currParam)[1];
}
//validate the entry
boolean fieldValid = true;
if ( request.getParameter("_delete") == null ) { // don't do validation if we're deleting
List validatorList = (List) epo.getValidatorMap().get(currParam);
if (validatorList != null) {
Iterator valIt = validatorList.iterator();
String errMsg = "";
while (valIt.hasNext()){
Validator val = (Validator)valIt.next();
ValidationObject vo = val.validate(currValue);
if (!vo.getValid()){
valid = false;
fieldValid = false;
errMsg += vo.getMessage() + " ";
epo.getBadValueMap().put(currParam,currValue);
} else {
try {
epo.getBadValueMap().remove(currParam);
epo.getErrMsgMap().remove(currParam);
} catch (Exception e) {}
}
}
if (errMsg.length()>0) {
epo.getErrMsgMap().put(currParam,errMsg);
log.info("doPost() putting error message "+errMsg+" for "+currParam);
}
}
}
if (fieldValid){
if (currValue.length()==0) {
HashMap defaultHash = epo.getDefaultValueMap();
try {
String defaultValue = (String)defaultHash.get(currParam);
if (defaultValue != null)
currValue=defaultValue;
} catch (Exception e) {}
}
try {
FormUtils.beanSet(newObj,currParam,currValue,epo);
epo.getErrMsgMap().remove(currParam);
epo.getBadValueMap().remove(currParam);
} catch (NumberFormatException e) {
if (currValue.length()>0) {
valid=false;
epo.getErrMsgMap().put(currParam,"Please enter an integer");
epo.getBadValueMap().put(currParam,currValue);
}
} catch (IllegalArgumentException f) {
valid=false;
log.error("doPost() reports IllegalArgumentException for "+currParam);
log.debug("doPost() error message: "+f.getMessage());
epo.getErrMsgMap().put(currParam, f.getMessage());
epo.getBadValueMap().put(currParam,currValue);
}
}
}
}
return valid;
}
private String getAction(HttpServletRequest request) {
if (request.getParameter("_update") != null ) {
return "update";
} else if (request.getParameter("_delete") != null ) {
return "delete";
} else {
return "insert";
}
}
private void notifyChangeListeners(EditProcessObject epo, String action) {
List changeListeners = epo.getChangeListenerList();
if (changeListeners != null){
Iterator changeIt = changeListeners.iterator();
while (changeIt.hasNext()) {
ChangeListener cl = (ChangeListener) changeIt.next();
if (action.equals("insert"))
cl.doInserted(epo.getNewBean(),epo);
else if (action.equals("update"))
cl.doUpdated(epo.getOriginalBean(),epo.getNewBean(),epo);
else if (action.equals("delete"))
cl.doDeleted(epo.getOriginalBean(),epo);
}
}
}
private boolean SUCCESS = false;
private boolean FAILURE = !SUCCESS;
private boolean performEdit(EditProcessObject epo, Object newObj, String action) {
/* do the actual edit operation */
String partialClassName;
if (epo.getBeanClass() != null) {
partialClassName = epo.getBeanClass().getSimpleName();
} else {
partialClassName = epo.getNewBean().getClass().getSimpleName();
}
Object dataAccessObject = null;
if (epo.getDataAccessObject() != null) {
dataAccessObject = epo.getDataAccessObject();
} else {
throw new RuntimeException(OperationController.class.getName()+" needs to be passed an EPO containing a data access object with which to perform the desired operation");
}
Class[] classList = new Class[1];
classList[0] = (epo.getBeanClass() != null) ? epo.getBeanClass() : newObj.getClass();
newObj.getClass().getGenericSuperclass();
Class[] superClassList = new Class[1];
superClassList[0] = newObj.getClass().getSuperclass();
Method meth=null;
Method deleteMeth=null;
Method insertMeth=null;
// probably want to change this so it will walk up the class tree indefinitely looking for a good method to use
if ("update".equals(action)){
if (epo.getUpdateMethod() != null) {
meth = epo.getUpdateMethod();
} else {
try {
meth = dataAccessObject.getClass().getMethod("update"+partialClassName,classList);
} catch (NoSuchMethodException e) {
try {
meth = dataAccessObject.getClass().getMethod("update"+partialClassName,superClassList);
} catch (NoSuchMethodException f) {
try { // if there isn't a single update method, let's see if we can delete the old data and then insert the new
deleteMeth = dataAccessObject.getClass().getMethod("delete"+partialClassName,classList);
try {
insertMeth = dataAccessObject.getClass().getMethod("insert"+partialClassName,classList);
} catch (NoSuchMethodException ee) {
insertMeth = dataAccessObject.getClass().getMethod("insertNew"+partialClassName,classList);
}
} catch (NoSuchMethodException g) {
log.error("doPost() could not find method(s) for updating "+partialClassName);
}
}
}
}
} else if ("delete".equals(action)) {
if (epo.getDeleteMethod() != null) {
meth = epo.getDeleteMethod();
} else {
try {
meth = dataAccessObject.getClass().getMethod("delete"+partialClassName,classList);
} catch (NoSuchMethodException e) {
try {
meth = dataAccessObject.getClass().getMethod("delete"+partialClassName,superClassList);
} catch (NoSuchMethodException f) {
log.error("doPost() could not find method delete"+partialClassName+"() on "+dataAccessObject.getClass().getName());
}
}
}
} else {
if (epo.getInsertMethod() != null) {
meth = epo.getInsertMethod();
} else {
try {
meth = dataAccessObject.getClass().getMethod("insert"+partialClassName,classList);
} catch (NoSuchMethodException e) {
try {
meth = dataAccessObject.getClass().getMethod("insertNew"+partialClassName,classList);
} catch (NoSuchMethodException f) {
try {
meth = dataAccessObject.getClass().getMethod("insertNew"+partialClassName,superClassList);
} catch (NoSuchMethodException g) {
try {
meth = dataAccessObject.getClass().getMethod("insertNew"+partialClassName,superClassList);
} catch (NoSuchMethodException h) {
log.error("doPost() could not find method for inserting "+partialClassName);
}
}
}
}
}
}
Object[] insArgList = new Object[1];
insArgList[0] = newObj;
Object result = null;
if ( (meth == null) && action.equals("update") ) {
//System.out.println("OperationController performing two-stage (deletion followed by insertion) update");
try {
Object[] delArgList = new Object[1];
delArgList[0] = epo.getOriginalBean();
deleteMeth.invoke(dataAccessObject,delArgList);
insertMeth.invoke(dataAccessObject,insArgList);
} catch (InvocationTargetException e) {
log.error(this.getClass().getName()+" encountered exception performing two-stage update");
Throwable innerE = e.getTargetException();
log.error(innerE);
if (innerE.getMessage()!=null) {
log.error(innerE.getMessage());
epo.setAttribute("globalErrorMsg",innerE.getMessage());
}
return FAILURE;
} catch (IllegalAccessException iae) {
log.error(iae);
epo.setAttribute("globalErrorMessage", "Illegal access - see error logs.");
return FAILURE;
}
} else {
try {
result = meth.invoke(dataAccessObject,insArgList);
} catch (InvocationTargetException e) {
log.error(this.getClass().getName()+" encountered exception performing edit action");
Throwable innerE = e.getTargetException();
//innerE.printStackTrace();
log.error(innerE);
if (innerE.getMessage()!=null) {
//System.out.println(innerE.getMessage());
log.error(innerE.getMessage());
epo.setAttribute("globalErrorMsg",innerE.getMessage());
}
return FAILURE;
} catch (IllegalAccessException iae) {
log.error(iae);
epo.setAttribute("globalErrorMessage", "Illegal access - see error logs.");
return FAILURE;
}
}
if (result != null) {
// need to put the result of the insert in the id of the newbean
try {
Class[] setIdArgs = new Class[1];
if (epo.getIdFieldClass() != null)
setIdArgs[0] = epo.getIdFieldClass();
else
setIdArgs[0] = int.class;
String idMutator = "set";
if (epo.getIdFieldName() != null) {
idMutator += epo.getIdFieldName();
} else {
idMutator += "Id";
}
Method setIdMeth = epo.getNewBean().getClass().getMethod(idMutator,setIdArgs);
try {
Object[] idArg = new Object[1];
idArg[0] = result;
setIdMeth.invoke((Object)epo.getNewBean(),idArg);
} catch (IllegalAccessException e) {
log.error("doPost() encountered IllegalAccessException setting id of new bean");
} catch (InvocationTargetException f) {
log.error(f.getTargetException().getMessage());
}
} catch (NoSuchMethodException e) {
//log.error("doPost() could not find setId() method for "+partialClassName);
} catch (Exception f) {
//log.error("doPost() could not set id of new bean.");
}
}
return SUCCESS;
}
}

View file

@ -0,0 +1,12 @@
package edu.cornell.mannlib.vedit.forwarder;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
public interface PageForwarder {
public void doForward(HttpServletRequest request, HttpServletResponse response, EditProcessObject epo);
}

View file

@ -0,0 +1,37 @@
package edu.cornell.mannlib.vedit.forwarder.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.io.IOException;
import java.net.URLEncoder;
import edu.cornell.mannlib.vedit.forwarder.PageForwarder;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class UrlForwarder implements PageForwarder {
private static final Log log = LogFactory.getLog(UrlForwarder.class.getName());
private String theUrl = null;
public UrlForwarder (String theUrl) {
this.theUrl = theUrl;
}
public void doForward(HttpServletRequest request, HttpServletResponse response, EditProcessObject epo) {
try {
response.sendRedirect(response.encodeRedirectURL(theUrl));
} catch (IOException ioe) {
log.error("doForward() could not send redirect.");
}
}
}

View file

@ -0,0 +1,15 @@
package edu.cornell.mannlib.vedit.listener;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
public interface ChangeListener {
public void doInserted(Object newObj, EditProcessObject epo);
public void doUpdated(Object oldObj, Object newObj, EditProcessObject epo);
public void doDeleted(Object oldObj, EditProcessObject epo);
}

View file

@ -0,0 +1,11 @@
package edu.cornell.mannlib.vedit.listener;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
public interface EditPreProcessor {
public void process(Object o, EditProcessObject epo);
}

View file

@ -0,0 +1,223 @@
package edu.cornell.mannlib.vedit.tags;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspWriter;
import javax.servlet.ServletException;
import edu.cornell.mannlib.vedit.beans.FormObject;
import edu.cornell.mannlib.vedit.beans.DynamicField;
import edu.cornell.mannlib.vedit.beans.DynamicFieldRow;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringEscapeUtils;
import edu.cornell.mannlib.vedit.tags.EditTag;
public class DynamicFieldsTag extends EditTag {
private char PATH_SEP = File.separatorChar;
public final String MARKUP_FILE_PATH = "templates"+PATH_SEP+"edit"+PATH_SEP+"specific"+PATH_SEP;
private String name = null;
private String type = null;
private String usePage = null;
private String preMarkup = null;
private String templateMarkup = null;
private String postMarkup = null;
public void setName( String name ) {
this.name = name;
}
public void setType( String type ) {
this.type = type;
}
public void setUsePage( String usePage ) {
this.usePage = usePage;
}
public void parseMarkup() throws JspException{
try {
int preStart = -1;
int templateStart = -1;
int postStart = -1;
InputStream fis = new FileInputStream (pageContext.getServletContext().getRealPath(new String())+PATH_SEP+MARKUP_FILE_PATH+usePage);
InputStream bis = new BufferedInputStream(fis);
BufferedReader in = new BufferedReader(new InputStreamReader(bis));
List<String> lines = new ArrayList<String>();
lines.add(""); // 0th line
int lineIndex = 0;
while (in.ready()) {
++lineIndex;
String currentLine = in.readLine();
if (currentLine != null && currentLine.indexOf("<!--") ==0 && currentLine.indexOf("@pre")>0 ) {
preStart = lineIndex;
} else if (currentLine != null && currentLine.indexOf("<!--") ==0 && currentLine.indexOf("@template")>0 ) {
templateStart = lineIndex;
} else if (currentLine != null && currentLine.indexOf("<!--") ==0 && currentLine.indexOf("@post")>0 ) {
postStart = lineIndex;
}
lines.add(currentLine);
}
in.close();
StringBuffer preMarkupB = new StringBuffer();
StringBuffer postMarkupB = new StringBuffer();
StringBuffer templateMarkupB = new StringBuffer();
if (templateStart>preStart && preStart>0) {
for (int i=preStart+1; i<templateStart; i++) {
preMarkupB.append(lines.get(i)).append("\n");
}
} else {
System.out.println("DynamicFieldsTag could not find @pre markup in "+MARKUP_FILE_PATH+usePage);
throw new JspException("DynamicFieldsTag could not parse @pre markup section");
}
preMarkup = preMarkupB.toString();
if (postStart>templateStart && templateStart>0) {
for (int i=templateStart+1; i<postStart; i++) {
templateMarkupB.append(lines.get(i)).append("\n");
}
} else {
System.out.println("DynamicFieldsTag could not find @template markup in "+MARKUP_FILE_PATH+usePage);
throw new JspException("DynamicFieldsTag could not parse @template markup section");
}
templateMarkup = templateMarkupB.toString();
if (postStart>0) {
for (int i=postStart+1; i<lines.size(); i++) {
postMarkupB.append(lines.get(i)).append("\n");
}
} else {
System.out.println("DynamicFieldsTag could not find @post markup in "+MARKUP_FILE_PATH+usePage);
throw new JspException("DynamicFieldsTag could not parse @post markup section");
}
postMarkup = postMarkupB.toString();
} catch (FileNotFoundException e) {
System.out.println("DynamicFieldsTag could not find markup file at "+pageContext.getServletContext().getRealPath(new String())+"\\"+MARKUP_FILE_PATH+usePage);
} catch (IOException ioe) {
System.out.println("DynamicFieldsTag encountered IOException reading "+pageContext.getServletContext().getRealPath(new String())+"\\"+MARKUP_FILE_PATH+usePage);
}
}
public String strReplace(String input, String pattern, String replacement) {
String[] piece = input.split(pattern);
StringBuffer output = new StringBuffer();
for (int i=0; i<piece.length; i++) {
output.append(piece[i]);
if (i<piece.length-1)
output.append(replacement);
}
return output.toString();
}
public int doEndTag() throws JspException {
try {
parseMarkup();
JspWriter out = pageContext.getOut();
HashMap values = null;
try {
FormObject foo = getFormObject();
List<DynamicField> dynfs = foo.getDynamicFields();
Iterator<DynamicField> dynIt = dynfs.iterator();
int i = 9899;
while (dynIt.hasNext()) {
DynamicField dynf = dynIt.next();
StringBuffer genTaName = new StringBuffer().append("_").append(dynf.getTable()).append("_");
genTaName.append("-1").append("_");
Iterator pparamIt = dynf.getRowTemplate().getParameterMap().keySet().iterator();
while(pparamIt.hasNext()) {
String key = (String) pparamIt.next();
String value = (String) dynf.getRowTemplate().getParameterMap().get(key);
byte[] valueInBase64 = Base64.encodeBase64(value.getBytes());
genTaName.append(key).append(":").append(new String(valueInBase64)).append(";");
}
String preWithVars = new String(preMarkup);
preWithVars = strReplace(preWithVars,type+"NN",Integer.toString(i));
preWithVars = strReplace(preWithVars,"\\$genTaName",genTaName.toString());
preWithVars = strReplace(preWithVars,"\\$fieldName",dynf.getName());
out.print(preWithVars);
Iterator<DynamicFieldRow> rowIt = dynf.getRowList().iterator();
while (rowIt.hasNext()) {
++i;
DynamicFieldRow row = rowIt.next();
if (row.getValue()==null)
row.setValue("");
if (row.getValue().length()>0) {
StringBuffer taName = new StringBuffer().append("_").append(dynf.getTable()).append("_");
taName.append(row.getId()).append("_");
Iterator paramIt = row.getParameterMap().keySet().iterator();
while(paramIt.hasNext()) {
String key = (String) paramIt.next();
String value = (String) row.getParameterMap().get(key);
byte[] valueInBase64 = Base64.encodeBase64(value.getBytes());
taName.append(key).append(":").append(new String(valueInBase64)).append(";");
}
if (row.getValue().length()>0) {
String templateWithVars = new String(templateMarkup);
templateWithVars = strReplace(templateWithVars,type+"NN",Integer.toString(i));
templateWithVars = strReplace(templateWithVars,"\\$taName",taName.toString());
templateWithVars = strReplace(templateWithVars,"\\$\\$",row.getValue());
out.print(templateWithVars);
}
}
}
out.print(postMarkup);
}
// output the row template for the javascript to clone
out.println("<!-- row template inserted by DynamicFieldsTag -->");
String hiddenTemplatePreMarkup = new String(preMarkup);
// bit of a hack to hide the template from the user:
hiddenTemplatePreMarkup = strReplace(hiddenTemplatePreMarkup,"display\\:none\\;","");
hiddenTemplatePreMarkup = strReplace(hiddenTemplatePreMarkup,"display\\:block\\;","");
hiddenTemplatePreMarkup = strReplace(hiddenTemplatePreMarkup,"display\\:inline\\;","");
hiddenTemplatePreMarkup = strReplace(hiddenTemplatePreMarkup,"style\\=\\\"","style=\"display:none;");
out.print(hiddenTemplatePreMarkup);
String hiddenTemplateTemplateMarkup = new String(templateMarkup);
hiddenTemplateTemplateMarkup = strReplace(hiddenTemplateTemplateMarkup, "\\$\\$", "");
out.print(hiddenTemplateTemplateMarkup);
out.print(postMarkup);
} catch (Exception e){
System.out.println("DynamicFieldsTag could not get the form object");
}
} catch(Exception ex) {
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
}

View file

@ -0,0 +1,58 @@
package edu.cornell.mannlib.vedit.tags;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.HashMap;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspWriter;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.beans.FormObject;
import org.apache.commons.lang.StringEscapeUtils;
public class EditTag extends TagSupport {
private String name = null;
public void setName( String name ) {
this.name = name;
}
public int doEndTag() throws JspException {
return SKIP_BODY;
}
public EditProcessObject getEpo() {
EditProcessObject epo = null;
String epoKey = null;
String epoKeyAttr = (String) pageContext.getRequest().getAttribute("epoKey");
if (epoKeyAttr != null) {
epoKey = epoKeyAttr;
}
else {
String epoKeyParam = (String) pageContext.getRequest().getParameter("epoKey");
if (epoKeyParam != null) {
epoKey = epoKeyParam;
}
}
HashMap epoHash = (HashMap) pageContext.getSession().getAttribute("epoHash");
try {
epo = (EditProcessObject) epoHash.get(epoKey);
} catch (NullPointerException npe) {
System.out.println("Null epoHash in edu.cornell.mannlib.vitro.edu.tags.utils.TagUtils.getEpo()");
}
return epo;
}
public FormObject getFormObject() {
FormObject foo=null;
try {
foo=getEpo().getFormObject();
} catch (NullPointerException npe) {
System.out.println("Null epo in edu.cornell.mannlib.vitro.edit.tags.utils.TagUtils.getFormObject()");
}
return foo;
}
}

View file

@ -0,0 +1,40 @@
package edu.cornell.mannlib.vedit.tags;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspWriter;
import edu.cornell.mannlib.vedit.beans.FormObject;
import edu.cornell.mannlib.vedit.tags.EditTag;
import org.apache.commons.lang.StringEscapeUtils;
/** This tag allows validation error messages to be displayed on a form JSP **/
public class ErrorTag extends EditTag {
private String name = null;
public void setName( String name ) {
this.name = name;
}
public int doEndTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
String errors = null;
try {
errors = (String) getFormObject().getErrorMap().get(name);
} catch (Exception e){
System.out.println("Could not get the form object from which to extract validation error message.");
}
if (errors != null){
out.print(StringEscapeUtils.escapeHtml((String) errors));
}
} catch(Exception ex) {
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
}

View file

@ -0,0 +1,70 @@
package edu.cornell.mannlib.vedit.tags;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.collections.OrderedMapIterator;
import java.util.List;
import java.util.Iterator;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import edu.cornell.mannlib.vedit.beans.Option;
import edu.cornell.mannlib.vedit.tags.EditTag;
import org.apache.commons.lang.StringEscapeUtils;
public class OptionTag extends EditTag {
private String name = null;
public void setName( String name ) {
this.name = name;
}
private void outputOptionsMarkup(List optList, JspWriter out) throws IOException {
Iterator it = optList.iterator();
while (it.hasNext()){
Option opt = (Option) it.next();
if (opt.getValue() == null)
opt.setValue("");
if (opt.getBody() == null)
opt.setBody("");
out.print("<option value=\""+StringEscapeUtils.escapeHtml(opt.getValue())+"\"");
if (opt.getSelected())
out.print(" selected=\"selected\"");
out.print(">");
out.print(StringEscapeUtils.escapeHtml(opt.getBody()));
out.print("</option>\n");
}
}
public int doEndTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
List optList = null;
ListOrderedMap optGroups = null;
try {
optList = (List) getFormObject().getOptionLists().get(name);
outputOptionsMarkup(optList,out);
} catch (ClassCastException e){
// maybe it's a ListOrderedMap of optgroups
optGroups = (ListOrderedMap) getFormObject().getOptionLists().get(name);
OrderedMapIterator ogKey = optGroups.orderedMapIterator();
while (ogKey.hasNext()) {
String optGroupName = (String) ogKey.next();
out.println("<optgroup label=\""+StringEscapeUtils.escapeHtml(optGroupName)+"\">");
outputOptionsMarkup((List)optGroups.get(optGroupName),out);
out.println("</optgroup>");
}
} catch (NullPointerException npe) {
System.out.println("OptionTag could not find option list for "+name);
}
} catch(Exception ex) {
ex.printStackTrace();
throw new JspException(ex.getMessage());
}
return SKIP_BODY; // EVAL_PAGE; did colnames only //EVAL_PAGE in connection pooled version;
}
}

View file

@ -0,0 +1,48 @@
package edu.cornell.mannlib.vedit.tags;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.HashMap;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspWriter;
import edu.cornell.mannlib.vedit.beans.FormObject;
import org.apache.commons.lang.StringEscapeUtils;
import edu.cornell.mannlib.vedit.tags.EditTag;
public class ValueTag extends EditTag {
private String name = null;
public void setName( String name ) {
this.name = name;
}
public int doEndTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
HashMap values = null;
try {
// FormObject foo = (FormObject) pageContext.getSession().getAttribute("FormObject");
// FormObject foo = TagUtils.getFormObject(pageContext);
FormObject foo = getFormObject();
values = foo.getValues();
} catch (Exception e){
System.out.println("Could not get the form object from which to build an option list");
}
if (values != null){
String value = (String) values.get(name);
if (value != null)
out.print(StringEscapeUtils.escapeHtml(value));
} else {
System.out.println("ValueTag unable to get HashMap of form values");
}
} catch(Exception ex) {
throw new JspException(ex.getMessage());
}
return SKIP_BODY;
}
}

View file

@ -0,0 +1,416 @@
package edu.cornell.mannlib.vedit.util;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.beans.FormObject;
import edu.cornell.mannlib.vedit.beans.Option;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class FormUtils {
protected static final Log log = LogFactory.getLog(FormUtils.class.getName());
/* this class needs to be reworked */
public static String htmlFormFromBean (Object bean, String action, FormObject foo) {
return htmlFormFromBean(bean,action,null,foo,new HashMap());
}
public static String htmlFormFromBean (Object bean, String action, FormObject foo, HashMap badValuesHash) {
return htmlFormFromBean(bean,action,null,foo,badValuesHash);
}
/**
* Creates a basic XHTML editing form for a bean class
*
* This is the simplest version, creating an input field for each and every setter method in the bean.
*
* @param bean the bean class for which an editing form should be built
* @return XHTML markup of an editing form for the specified class
* @author bjl23
*/
public static String htmlFormFromBean (Object bean, String action, EditProcessObject epo, FormObject foo, HashMap BadValuesHash) {
String formMarkup = "";
Class beanClass = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : bean.getClass();
Method[] meths = beanClass.getMethods();
for (int i=0; i<meths.length; i++) {
if (meths[i].getName().indexOf("set") == 0) {
// we have a setter method
Method currMeth = meths[i];
Class[] currMethParamTypes = currMeth.getParameterTypes();
Class currMethType = currMethParamTypes[0];
String currMethTypeStr = currMethType.toString();
if (currMethTypeStr.equals("int") || currMethTypeStr.indexOf("class java.lang.String")>-1 || currMethTypeStr.indexOf("class java.util.Date")>-1) {
//we only want people directly to type in ints, strings, and dates
//of course, most of the ints are probably foreign keys anyway...
String elementName = currMeth.getName().substring(3,currMeth.getName().length());
formMarkup += "<tr><td align=\"right\">";
formMarkup += "<p><strong>"+elementName+"</strong></p>";
formMarkup += "</td><td>";
formMarkup += "<input name=\""+elementName+"\" ";
//if int, make a smaller box
if (currMethTypeStr.equals("int")){
formMarkup += " size=\"11\" maxlength=\"11\" ";
}
else
formMarkup += "size=\"75%\" ";
//see if there's something in the bean using
//the related getter method
Class[] paramClass = new Class[1];
paramClass[0] = currMethType;
try {
Method getter = beanClass.getMethod("get"+elementName,(Class[]) null);
Object existingData = null;
try {
existingData = getter.invoke(bean, (Object[]) null);
} catch (Exception e) {
log.error ("Exception invoking getter method");
}
String value = "";
if (existingData != null){
if (existingData instanceof String){
value += existingData;
}
else if (!(existingData instanceof Integer && (Integer)existingData <= -10000)) {
value += existingData.toString();
}
}
String badValue = (String) BadValuesHash.get(elementName);
if (badValue != null)
value = badValue;
formMarkup += " value=\""+StringEscapeUtils.escapeHtml(value)+"\" ";
foo.getValues().put(elementName, value);
} catch (NoSuchMethodException e) {
// System.out.println("Could not find method get"+elementName+"()");
}
formMarkup += "/>\n";
formMarkup += "</td></tr>";
}
}
}
return formMarkup;
}
public static List /*of Option*/ makeOptionListFromBeans (List beanList, String valueField, String bodyField, String selectedValue, String selectedBody) {
return makeOptionListFromBeans (beanList, valueField, bodyField, selectedValue, selectedBody, true);
}
public static List /*of Option*/ makeOptionListFromBeans (List beanList, String valueField, String bodyField, String selectedValue, String selectedBody, boolean forceSelectedInclusion) {
List optList = new LinkedList();
if (beanList == null)
return optList;
Iterator beanIt = beanList.iterator();
boolean foundSelectedValueInBeans = false;
while (beanIt.hasNext()){
Object bean = beanIt.next();
String value="";
Method valueMeth = null;
Object valueObj = null;
try {
valueMeth = bean.getClass().getMethod("get"+valueField, (Class[]) null);
valueObj = valueMeth.invoke(bean, (Object[]) null);
} catch (Exception e) {
log.warn("Could not find method get"+valueField+" on "+bean.getClass());
}
if (valueObj != null){
value = valueObj.toString();
}
String body="";
Method bodyMeth = null;
Object bodyObj = null;
try {
bodyMeth = bean.getClass().getMethod("get"+bodyField, (Class[]) null);
bodyObj = bodyMeth.invoke(bean, (Object[]) null);
} catch (Exception e) {
log.warn(" could not find method get"+bodyField);
}
if (bodyObj != null){
body = bodyObj.toString();
}
Option opt = new Option();
opt.setValue(value);
opt.setBody(body);
if (selectedValue != null){
if (selectedValue.equals(value)) {
opt.setSelected(true);
foundSelectedValueInBeans = true;
}
} else {
if (selectedBody != null){
if (selectedBody.equals(body)) {
opt.setSelected(true);
foundSelectedValueInBeans = true;
}
}
}
optList.add(opt);
}
/* if the list of beans doesn't include the selected value/body, insert it anyway so we don't inadvertently change the value of the
field to the first thing that happens to be in the select list */
boolean skipThisStep = !forceSelectedInclusion;
// for now, if the value is a negative integer, we won't try to preserve it, as the bean was probably just instantiated
// should switch to a more robust way of handling inital bean values later
if (selectedValue == null) {
skipThisStep = true;
} else {
try {
int selectedValueInt = Integer.decode(selectedValue);
if (selectedValueInt < 0)
skipThisStep = true;
} catch (NumberFormatException e) {}
}
if (!foundSelectedValueInBeans && !skipThisStep) {
log.trace("Adding the selected option!");
Option sOpt = new Option();
sOpt.setValue(selectedValue);
if (selectedBody == null || selectedBody.length() == 0)
sOpt.setBody(selectedValue.toString());
else
sOpt.setBody(selectedBody);
sOpt.setSelected(true);
optList.add(sOpt);
}
return optList;
}
public static List<Option> makeVClassOptionList(WebappDaoFactory wadf, String selectedVClassURI) {
List<Option> vclassOptionList = new LinkedList<Option>();
for (VClass vclass : wadf.getVClassDao().getAllVclasses()) {
Option option = new Option();
option.setValue(vclass.getURI());
if ( (selectedVClassURI != null) && (vclass.getURI() != null) && (selectedVClassURI.equals(vclass.getURI())) ) {
option.setSelected(true);
}
String ontologyName = null;
if (vclass.getNamespace() != null) {
Ontology ont = wadf.getOntologyDao().getOntologyByURI(vclass.getNamespace());
if ( (ont != null) && (ont.getName() != null) ) {
ontologyName = ont.getName();
}
}
StringBuffer classNameBuffer = new StringBuffer();
if (vclass.getName() != null) {
classNameBuffer.append(vclass.getName());
}
if (ontologyName != null) {
classNameBuffer.append(" (").append(ontologyName).append(")");
}
option.setBody(classNameBuffer.toString());
vclassOptionList.add(option);
}
return vclassOptionList;
}
public static void beanSet(Object newObj, String field, String value) {
beanSet (newObj, field, value, null);
}
public static void beanSet(Object newObj, String field, String value, EditProcessObject epo) {
SimpleDateFormat standardDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Class cls = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : newObj.getClass();
Class[] paramList = new Class[1];
paramList[0] = String.class;
boolean isInt = false;
boolean isDate = false;
boolean isBoolean = false;
Method setterMethod = null;
try {
setterMethod = cls.getMethod("set"+field,paramList);
} catch (NoSuchMethodException e) {
//let's try int
paramList[0] = int.class;
try {
setterMethod = cls.getMethod("set"+field,paramList);
isInt = true;
} catch (NoSuchMethodException f) {
//boolean
paramList[0] = boolean.class;
try {
setterMethod = cls.getMethod("set"+field,paramList);
isBoolean = true;
//System.out.println("Found boolean field "+field);
} catch (NoSuchMethodException h) {
//let's try Date!
paramList[0] = Date.class;
try {
// this isn't so great ; should probably be in a validator
if(value != null && value.length() > 0 && value.indexOf(":") < 1) {
value += " 00:00:00";
}
setterMethod = cls.getMethod("set"+field,paramList);
isDate = true;
} catch (NoSuchMethodException g) {
//System.out.println("beanSet could not find a setter method for "+field+" in "+cls.getName());
}
}
}
}
Object[] arglist = new Object[1];
if (isInt)
arglist[0] = Integer.decode(value);
else if (isDate)
if (value != null && value.length()>0) {
try {
arglist[0] = standardDateFormat.parse(value);
} catch (ParseException p) {
try {
arglist[0] = minutesOnlyDateFormat.parse(value);
} catch (ParseException q) {
log.error(FormUtils.class.getName()+" could not parse"+value+" to a Date object.");
throw new IllegalArgumentException("Please enter a date/time in one of these formats: '2007-07-07', '2007-07-07 07:07', or '2007-07-07 07:07:07'");
}
}
} else {
arglist[0] = null;
}
else if (isBoolean) {
arglist[0] = (value.equalsIgnoreCase("true"));
//System.out.println("Setting "+field+" "+value+" "+arglist[0]);
} else {
arglist[0] = value;
}
try {
setterMethod.invoke(newObj,arglist);
} catch (Exception e) {
// System.out.println("Couldn't invoke method");
// System.out.println(e.getMessage());
// System.out.println(field+" "+arglist[0]);
}
}
/**
* Takes a bean and uses all of its setter methods to set null values
* @return
*/
public static Object nullBean(Object bean){
Class cls = bean.getClass();
Method[] meths = cls.getMethods();
for (int i=0; i<meths.length; ++i){
Method meth = meths[i];
if (meth.getName().indexOf("set")==0){
try{
meth.invoke(bean,(Object[]) null);
} catch (Exception e) {
log.error ("edu.cornell.mannlib.vitro.edit.FormUtils nullBean(Object) unable to use "+meth.getName()+" to set null.");
}
}
}
return bean;
}
/**
* Takes any nonnull values from an overlay bean and sets them on a base bean
* @param base
* @param overlay
* @return overlaid bean
*/
public static Object overlayBean (Object base, Object overlay) throws IllegalArgumentException {
Class baseCls = base.getClass();
Class overlayCls = overlay.getClass();
if (overlayCls != baseCls)
throw new IllegalArgumentException("overlayBean requires two objects of the same type");
Method[] meths = overlayCls.getMethods();
for (int i=0; i<meths.length; ++i){
Method meth = meths[i];
String methName = meth.getName();
if (methName.indexOf("get")==0){
try {
Object overlayObj = meth.invoke(overlay,(Object[]) null);
if (overlayObj != null) {
String setterName = "set"+methName.substring(3,methName.length());
Class setterArgClass = null;
if (overlayObj instanceof Integer)
setterArgClass = int.class;
else
setterArgClass = overlayObj.getClass();
Class[] setterArgClasses = new Class[1];
setterArgClasses[0] = setterArgClass;
try {
Method setterMeth = baseCls.getMethod(setterName,setterArgClasses);
Object[] setterObjs = new Object[1];
setterObjs[0] = overlayObj;
setterMeth.invoke(base,setterObjs);
} catch (NoSuchMethodException e) {
log.error("edu.cornell.mannlib.vitro.edit.FormUtils.overlayBean(Object,Object) could not find setter method "+setterName);
}
}
} catch (Exception e) {
log.error("edu.cornell.mannlib.vitro.edit.FormUtils overlayBean(Object,Object) could not invoke getter method "+methName);
}
}
}
return base;
}
/**
* Decodes a Base-64-encoded String of format key:value;key2:value2;key3:value, and puts the keys and values in a Map
* @param params
* @return
*/
public static Map beanParamMapFromString(String params) {
String[] param = params.split(";");
Map beanParamMap = new HashMap();
for (int i=0; i<param.length; i++) {
String[] p = param[i].split(":");
beanParamMap.put(p[0],new String(Base64.decodeBase64(p[1].getBytes())));
}
return beanParamMap;
}
}

View file

@ -0,0 +1,128 @@
package edu.cornell.mannlib.vedit.util;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy.ContextSetup;
public class OperationUtils{
private static final Log log = LogFactory.getLog(OperationUtils.class.getName());
public static void beanSetAndValidate(Object newObj, String field, String value, EditProcessObject epo){
Class cls = (epo.getBeanClass() != null) ? epo.getBeanClass() : newObj.getClass();
Class[] paramList = new Class[1];
paramList[0] = String.class;
boolean isInt = false;
boolean isBoolean = false;
Method setterMethod = null;
try {
setterMethod = cls.getMethod("set"+field,paramList);
} catch (NoSuchMethodException e) {
//let's try int
paramList[0] = int.class;
try {
setterMethod = cls.getMethod("set"+field,paramList);
isInt = true;
} catch (NoSuchMethodException f) {
//let's try boolean
paramList[0]=boolean.class;
try {
setterMethod = cls.getMethod("set"+field,paramList);
isBoolean = true;
log.debug("found boolean field "+field);
} catch (NoSuchMethodException g) {
log.error("beanSet could not find an appropriate String, int, or boolean setter method for "+field);
}
}
}
Object[] arglist = new Object[1];
if (isInt)
arglist[0] = Integer.decode(value);
else if (isBoolean)
arglist[0] = (value.equalsIgnoreCase("TRUE"));
else
arglist[0] = value;
try {
setterMethod.invoke(newObj,arglist);
} catch (Exception e) {
System.out.println("Couldn't invoke method");
System.out.println(e.getMessage());
System.out.println(field+" "+arglist[0]);
}
}
/**
* Takes a bean and clones it using reflection.
* Any fields without standard getter/setter methods will not be copied.
* @param bean
* @return
*/
public static Object cloneBean (Object bean) {
return cloneBean(bean, bean.getClass());
}
/**
* Takes a bean and clones it using reflection.
* Any fields without standard getter/setter methods will not be copied.
* @param bean
* @return
*/
public static Object cloneBean (Object bean, Class beanClass){
Object newBean = null;
try {
newBean = beanClass.newInstance();
Method[] beanMeths = beanClass.getMethods();
for (int i=0; i<beanMeths.length ; ++i){
String methName = beanMeths[i].getName();
if (methName.indexOf("get")==0){
String fieldName = methName.substring(3,methName.length());
Class returnType = beanMeths[i].getReturnType();
try {
Class[] args = new Class[1];
args[0] = returnType;
Method setterMethod = beanClass.getMethod("set"+fieldName,args);
try {
Object fieldVal = beanMeths[i].invoke(bean,(Object[])null);
try {
Object[] setArgs = new Object[1];
setArgs[0] = fieldVal;
setterMethod.invoke(newBean,setArgs);
} catch (IllegalAccessException iae) {
System.out.println("edu.cornell.mannlib.vitro.edit.utils.OperationUtils encountered IllegalAccessException invoking "+setterMethod.getName());
} catch (InvocationTargetException ite) {
System.out.println("edu.cornell.mannlib.vitro.edit.utils.OperationUtils encountered InvocationTargetException invoking "+setterMethod.getName());
System.out.println(ite.getTargetException().getClass().toString());
}
} catch (IllegalAccessException iae) {
System.out.println(OperationUtils.class.getName()+" encountered IllegalAccessException invoking "+beanMeths[i].getName());
} catch (InvocationTargetException ite) {
System.out.println(OperationUtils.class.getName()+" encountered InvocationTargetException invoking "+beanMeths[i].getName());
System.out.println(ite.getTargetException().getClass().toString());
} catch (IllegalArgumentException iae) {
// System.out.println(OperationUtils.class.getName()+" found that "+beanMeths[i].getName()+" requires one or more arguments. Skipping.");
}
} catch (NoSuchMethodException nsme){
// ignore this field because there is no setter method
}
}
}
} catch (InstantiationException ie){
System.out.println("edu.cornell.mannlib.vitro.edit.utils.OperationUtils.cloneBean("+bean.getClass().toString()+") could not instantiate new instance of bean.");
System.out.println(ie.getStackTrace());
} catch (IllegalAccessException iae){
System.out.println("edu.cornell.mannlib.vitro.edit.utils.OperationUtils.cloneBean("+bean.getClass().toString()+") encountered illegal access exception instantiating new bean.");
System.out.println(iae.getStackTrace());
}
return newBean;
}
}

View file

@ -0,0 +1,559 @@
package edu.cornell.mannlib.vedit.util;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/*
Porter stemmer in Java. The original paper is in
Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
no. 3, pp 130-137,
See also http://www.tartarus.org/~martin/PorterStemmer
History:
Release 1
Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below.
The words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1]
is then out outside the bounds of b.
Release 2
Similarly,
Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below.
'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and
b[j] is then outside the bounds of b.
Release 3
Considerably revised 4/9/00 in the light of many helpful suggestions
from Brian Goetz of Quiotix Corporation (brian@quiotix.com).
Release 4
*/
import java.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy.ContextSetup;
/**
* Stemmer, implementing the Porter Stemming Algorithm
*
* The Stemmer class transforms a word into its root form. The input
* word can be provided a character at time (by calling add()), or at once
* by calling one of the various stem(something) methods.
*/
class Stemmer
{ private char[] b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private static final int INC = 50;
/* unit of size whereby b is increased */
private static final Log log = LogFactory.getLog(Stemmer.class.getName());
public Stemmer()
{ b = new char[INC];
i = 0;
i_end = 0;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{ if (i == b.length)
{ char[] new_b = new char[i+INC];
for (int c = 0; c < i; c++) new_b[c] = b[c];
b = new_b;
}
b[i++] = ch;
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{ if (i+wLen >= b.length)
{ char[] new_b = new char[i+wLen+INC];
for (int c = 0; c < i; c++) new_b[c] = b[c];
b = new_b;
}
for (int c = 0; c < wLen; c++) b[i++] = w[c];
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString() { return new String(b,0,i_end); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b[j] != b[j-1]) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{ int l = s.length();
int o = k-l+1;
if (o < 0) return false;
for (int i = 0; i < l; i++) if (b[o+i] != s.charAt(i)) return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++) b[o+i] = s.charAt(i);
k = j+l;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{ if (b[k] == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b[k-1] != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
} }
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() { switch (b[k])
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
} }
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{ if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
{ case 'a': if (ends("al")) break; return;
case 'c': if (ends("ance")) break;
if (ends("ence")) break; return;
case 'e': if (ends("er")) break; return;
case 'i': if (ends("ic")) break; return;
case 'l': if (ends("able")) break;
if (ends("ible")) break; return;
case 'n': if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break; return;
case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break; return;
/* takes care of -ous */
case 's': if (ends("ism")) break; return;
case 't': if (ends("ate")) break;
if (ends("iti")) break; return;
case 'u': if (ends("ous")) break; return;
case 'v': if (ends("ive")) break; return;
case 'z': if (ends("ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{ k = i - 1;
if (k > 1) { step1(); step2(); step3(); step4(); step5(); step6(); }
i_end = k+1; i = 0;
}
public static String StemString( String inputStr, int maxLength )
{
String outputStr="";
int previousCh=0;
char[] w = new char[maxLength];
char[] inputArray = inputStr.toCharArray();
Stemmer s = new Stemmer();
int inputArrayIndex=0, stemmerInputBufferIndex=0, ch=0;
for ( inputArrayIndex=0; inputArrayIndex<inputArray.length; inputArrayIndex++ ) {
ch = inputArray[inputArrayIndex];
if ( Character.isLetter((char) ch)) {
stemmerInputBufferIndex = 0; // start collecting letters for a new word
while ( inputArrayIndex < inputArray.length ) { // keep reading until hit character other than a letter
ch = Character.toLowerCase((char) ch);
w[stemmerInputBufferIndex] = (char) ch;
if (stemmerInputBufferIndex < maxLength-1 ) {
stemmerInputBufferIndex++;
}
if ( inputArrayIndex < inputArray.length-1 ) {
previousCh = ch;
ch = inputArray[++inputArrayIndex];
if ( !Character.isLetter((char) ch) ) { // parse the word in preparation for starting a new one
for (int c = 0; c < stemmerInputBufferIndex; c++) { // copy to stemmer internal buffer
s.add(w[c]);
}
s.stem();
{
String u;
u = s.toString();
outputStr += u;
if ( ch == '-' ) { // replace - with space
outputStr += " ";
} else if ( ch == '.' ) {
if ( Character.isDigit( (char) previousCh )) {
outputStr += ".";
} else {
outputStr += " ";
//previousCh = 32; // set to whitespace; extra spaces should be filtered out on next pass
}
} else {
Character Ch = new Character((char) ch);
outputStr += Ch.toString();
}
stemmerInputBufferIndex=0; // to avoid repeats after )
}
break;
}
} else {
break;
}
}
} else if ( Character.isWhitespace((char) ch) ) {
if ( !Character.isWhitespace((char) previousCh ) ) {
if ( previousCh != '.' ) {
Character Ch = new Character((char) ch);
outputStr += Ch.toString();
}
}
} else if ( ch == '(' ) { // open paren; copy all characters until close paren
while ( ch != ')' ) {
if ( inputArrayIndex < inputArray.length ) {
ch = inputArray[inputArrayIndex++];
} else {
log.trace ("");
log.trace("1 short of EOS in paren at pos: " + inputArrayIndex + " of " + inputStr );
break;
}
Character Ch = new Character((char) ch);
//outputStr += Ch.toString();
//System.out.print( Ch.toString() );
}
//log.trace("");
/* not needed -- just duplicates close paren
if ( ch == ')') {
Character Ch = new Character((char) ch);
outputStr += Ch.toString();
log.trace( Ch.toString() );
}
*/
stemmerInputBufferIndex=0;
} else if ( ch == ')' ) { // when is last character of input string
Character Ch = new Character((char) ch);
outputStr += Ch.toString();
log.trace( Ch.toString() );
log.trace("found close paren at position: " + inputArrayIndex + " of input term " + inputStr );
} else if ( ch == '-' ) { // replace - with space
outputStr += " ";
} else if ( ch == '.' ) {
if ( Character.isDigit( (char) previousCh )) {
outputStr += ".";
} else {
outputStr += " ";
//previousCh = 32; // set to whitespace; extra spaces should be filtered out on next pass
}
} else {
Character Ch = new Character((char) ch);
outputStr += Ch.toString();
}
previousCh = ch;
if (ch < 0) break;
}
if ( stemmerInputBufferIndex > 0 ) {
for (int c = 0; c < stemmerInputBufferIndex; c++) {
s.add(w[c]);
}
s.stem();
String u;
u = s.toString();
outputStr += u;
}
return outputStr == null ? ( outputStr.equals("") ? null : outputStr.trim() ) : outputStr.trim();
}
/*
public static void main(String[] args)
{
char[] w = new char[501];
Stemmer s = new Stemmer();
for (int i = 0; i < args.length; i++)
try
{
FileInputStream in = new FileInputStream(args[i]);
try
{ while(true)
{ int ch = in.read();
if (Character.isLetter((char) ch))
{
int j = 0;
while(true)
{ ch = Character.toLowerCase((char) ch);
w[j] = (char) ch;
if (j < 500) j++;
ch = in.read();
if (!Character.isLetter((char) ch))
{
// to test add(char ch)
for (int c = 0; c < j; c++) s.add(w[c]);
// or, to test add(char[] w, int j)
// s.add(w, j);
s.stem();
{ String u;
// and now, to test toString() :
u = s.toString();
// to test getResultBuffer(), getResultLength() :
// u = new String(s.getResultBuffer(), 0, s.getResultLength());
System.out.print(u);
}
break;
}
}
}
if (ch < 0) break;
System.out.print((char)ch);
}
}
catch (IOException e)
{ log.trace("error reading " + args[i]);
break;
}
}
catch (FileNotFoundException e)
{ log.trace("file " + args[i] + " not found");
break;
}
}
*/
public static void main(String[] args)
{
char[] w = new char[501];
Stemmer s = new Stemmer();
for (int i = 0; i < args.length; i++) {
System.out.println( StemString( args[i], 100 ));
}
}
}

View file

@ -0,0 +1,36 @@
package edu.cornell.mannlib.vedit.validator;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
public class ValidationObject {
private boolean valid = false;
private String message;
private Object validatedObject = null;
public boolean getValid(){
return valid;
}
public void setValid(boolean valid){
this.valid = valid;
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
public Object getValidatedObject(){
return validatedObject;
}
public void setValidatedObject(Object validatedObject){
this.validatedObject = validatedObject;
}
}

View file

@ -0,0 +1,9 @@
package edu.cornell.mannlib.vedit.validator;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
public interface Validator {
public ValidationObject validate(Object obj) throws IllegalArgumentException;
}

View file

@ -0,0 +1,44 @@
package edu.cornell.mannlib.vedit.validator.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.validator.*;
import java.util.HashSet;
import java.util.Iterator;
public class EnumValuesValidator implements Validator {
private HashSet legalValues = new HashSet();
public ValidationObject validate(Object obj){
ValidationObject vo = new ValidationObject();
if (legalValues.contains((String)obj)){
vo.setValid(true);
} else {
vo.setValid(false);
if (legalValues.size()<7){
String msgString = "Please enter one of ";
Iterator valuesIt = legalValues.iterator();
while (valuesIt.hasNext()) {
String legalValue = (String) valuesIt.next();
msgString += "'"+legalValue+"'";
if (valuesIt.hasNext())
msgString += ", ";
else
msgString += ".";
}
vo.setMessage(msgString);
}
else {
vo.setMessage("Please enter a legal value.");
}
}
vo.setValidatedObject(obj);
return vo;
}
public EnumValuesValidator (String[] legalValues){
for (int i=0; i<legalValues.length; i++)
this.legalValues.add(legalValues[i]);
}
}

View file

@ -0,0 +1,54 @@
package edu.cornell.mannlib.vedit.validator.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.validator.Validator;
import edu.cornell.mannlib.vedit.validator.ValidationObject;
public class IntValidator implements Validator {
protected int minVal = -1;
protected int maxVal = -1;
public ValidationObject validate (Object obj) throws IllegalArgumentException {
ValidationObject vo = new ValidationObject();
int theInt = -1;
if (obj instanceof String) {
try {
theInt = Integer.parseInt((String) obj);
} catch (NumberFormatException e) {
vo.setValid(false);
vo.setMessage("Please enter an integer");
vo.setValidatedObject(obj);
return vo;
}
} else {
try {
theInt = ((Integer) obj).intValue();
} catch (Exception e) {
vo.setValid(false);
vo.setMessage("Please enter an integer");
vo.setValidatedObject(obj);
return vo;
}
}
if ( theInt < minVal || theInt > maxVal ) {
vo.setValid(false);
vo.setMessage("Enter a number between "+minVal+" and "+maxVal);
} else {
vo.setValid(true);
}
vo.setValidatedObject(obj);
return vo;
}
public IntValidator (int minVal, int maxVal){
this.minVal = minVal;
this.maxVal = maxVal;
}
}

View file

@ -0,0 +1,26 @@
package edu.cornell.mannlib.vedit.validator.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.validator.Validator;
import edu.cornell.mannlib.vedit.validator.ValidationObject;
public class RequiredFieldValidator implements Validator {
public ValidationObject validate (Object obj) throws IllegalArgumentException {
ValidationObject vo = new ValidationObject();
if (obj==null || (obj instanceof String && ((String)obj).length()==0)) {
vo.setValid(false);
vo.setMessage("Please enter a value");
} else {
vo.setValid(true);
}
vo.setValidatedObject(obj);
return vo;
}
}

View file

@ -0,0 +1,32 @@
package edu.cornell.mannlib.vedit.validator.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import edu.cornell.mannlib.vedit.validator.Validator;
import edu.cornell.mannlib.vedit.validator.ValidationObject;
import java.util.regex.*;
public class UrlValidator implements Validator {
public ValidationObject validate (Object obj) throws IllegalArgumentException {
ValidationObject vo = new ValidationObject();
String theString = null;
if (!(obj instanceof String)){
throw new IllegalArgumentException("Expected instance of String");
}
Pattern pat = Pattern.compile("[a-z]{3,5}*://.*\\.[a-z]{2,4}");
Matcher mat = pat.matcher(theString);
if (mat.matches()){
vo.setValid(true);
} else {
vo.setValid(false);
vo.setMessage("Please enter a valid URL");
}
vo.setValidatedObject(obj);
return vo;
}
}

View file

@ -0,0 +1,53 @@
package edu.cornell.mannlib.vedit.validator.impl;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.cornell.mannlib.vedit.validator.Validator;
import edu.cornell.mannlib.vedit.validator.ValidationObject;
public class XMLNameValidator implements Validator {
private final static String ERR_MSG = "Must start with a letter or '_' and use only letters, digits, '.', '-' or '_'. No spaces allowed.";
Pattern pat = null;
boolean permitEmpty = false;
public XMLNameValidator() {
pat = Pattern.compile("[A-Za-z_][A-Za-z0-9_\\-\\.]*");
}
public XMLNameValidator(boolean permitEmpty) {
this();
this.permitEmpty = permitEmpty;
}
public ValidationObject validate (Object obj) throws IllegalArgumentException {
ValidationObject vo = new ValidationObject();
String theString = null;
try {
theString = (String) obj;
} catch (ClassCastException e) {
throw new IllegalArgumentException("Expected instance of String");
}
if (permitEmpty && (theString == null || "".equals(theString))) {
vo.setValid(true);
} else {
Matcher mat = pat.matcher(theString);
if (mat.matches()){
vo.setValid(true);
} else {
vo.setValid(false);
vo.setMessage(ERR_MSG);
}
}
vo.setValidatedObject(obj);
return vo;
}
}