diff --git a/serverApps/.classpath b/serverApps/.classpath new file mode 100644 index 0000000000..bea8b213d6 --- /dev/null +++ b/serverApps/.classpath @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/serverApps/.project b/serverApps/.project new file mode 100644 index 0000000000..b4b4bf18aa --- /dev/null +++ b/serverApps/.project @@ -0,0 +1,26 @@ + + + serverApps + + + base + dbPort + looks + tools + + + + org.eclipse.jdt.core.javabuilder + + + + + com.ibm.etools.validation.validationbuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/serverApps/.settings/com.genuitec.jboss.ide.eclipse.xdoclet.run.prefs b/serverApps/.settings/com.genuitec.jboss.ide.eclipse.xdoclet.run.prefs new file mode 100644 index 0000000000..198a961cc4 --- /dev/null +++ b/serverApps/.settings/com.genuitec.jboss.ide.eclipse.xdoclet.run.prefs @@ -0,0 +1,3 @@ +#Thu Sep 15 18:36:13 PDT 2005 +eclipse.preferences.version=1 +xdoclet.build.policy=automatic diff --git a/serverApps/.settings/org.eclipse.jdt.ui.prefs b/serverApps/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000000..15cfde9aec --- /dev/null +++ b/serverApps/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,3 @@ +#Thu Sep 21 14:16:48 PDT 2006 +eclipse.preferences.version=1 +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/serverApps/.settings/org.eclipse.ltk.core.refactoring.prefs b/serverApps/.settings/org.eclipse.ltk.core.refactoring.prefs new file mode 100644 index 0000000000..364ca3a238 --- /dev/null +++ b/serverApps/.settings/org.eclipse.ltk.core.refactoring.prefs @@ -0,0 +1,3 @@ +#Thu Sep 21 14:16:48 PDT 2006 +eclipse.preferences.version=1 +org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false diff --git a/serverApps/RUN_build.bat b/serverApps/RUN_build.bat new file mode 100644 index 0000000000..e34b235d24 --- /dev/null +++ b/serverApps/RUN_build.bat @@ -0,0 +1,18 @@ +@Title Build Adempiere Apps +@Rem $Header: /cvsroot/adempiere/serverApps/RUN_build.bat,v 1.7 2005/09/16 00:50:24 jjanke Exp $ + +@CALL ..\utils_dev\myDevEnv.bat +@IF NOT %ADEMPIERE_ENV%==Y GOTO NOBUILD + +@echo Cleanup ... +@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main clean + +@echo Building ... +@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main main + +@pause +@exit + +:NOBUILD +@Echo Check myDevEnv.bat (copy from myDevEnvTemplate.bat) +@Pause diff --git a/serverApps/RUN_build.sh b/serverApps/RUN_build.sh new file mode 100644 index 0000000000..5f80633c60 --- /dev/null +++ b/serverApps/RUN_build.sh @@ -0,0 +1,18 @@ +# Module compiling script +# Ported from Windows script Marek Mosiewicz + + +SAVED_DIR=`pwd` #save current dir +cd `dirname $0`/../utils_dev #change dir to place where script resides - doesn not work with sym links +UTILS_DEV=`pwd` #this is adempiere source +cd $SAVED_DIR #back to the saved directory + +. $UTILS_DEV/myDevEnv.sh #call environment +echo done +if [ ! $ADEMPIERE_ENV==Y ] ; then + echo "Can't set developemeent environemnt - check myDevEnv.sh" + exit 1 +fi + +echo running Ant +$JAVA_HOME/bin/java -Dant.home="." $ANT_PROPERTIES org.apache.tools.ant.Main diff --git a/serverApps/ServerApps.html b/serverApps/ServerApps.html new file mode 100644 index 0000000000..b70052b407 --- /dev/null +++ b/serverApps/ServerApps.html @@ -0,0 +1,33 @@ + + + +JBuilder Project ServerApps.jpx + + +

Project ServerApps Notes

+
+ + + + +
Title: + + +
Author: + + +
Company: + + +
Description: + + +

+

Things to do...

+
    + +
  1. First +
  2. Second +
+ + diff --git a/serverApps/build.xml b/serverApps/build.xml new file mode 100644 index 0000000000..8f431843a3 --- /dev/null +++ b/serverApps/build.xml @@ -0,0 +1,239 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/serverApps/documentation.bat b/serverApps/documentation.bat new file mode 100644 index 0000000000..fba97ad6db --- /dev/null +++ b/serverApps/documentation.bat @@ -0,0 +1,5 @@ +@Rem API Documentation for Server + +call ..\doc\documentation.bat "src\main\ejb;src\main\servlet" doc -private + +@pause diff --git a/serverApps/packages.txt b/serverApps/packages.txt new file mode 100644 index 0000000000..7a902d2e1f --- /dev/null +++ b/serverApps/packages.txt @@ -0,0 +1,4 @@ +org.compiere.session +org.compiere.jsp +org.compiere.wstore +org.compiere.www diff --git a/serverApps/src/ear/application.xml b/serverApps/src/ear/application.xml new file mode 100644 index 0000000000..7e2ef159ba --- /dev/null +++ b/serverApps/src/ear/application.xml @@ -0,0 +1,24 @@ + + + + adempiereApps + Adempiere HTML Application + + AdempiereSLib.jar + + + Adempiere.jar + + + adempiereApps.jar + + + + adempiereApps.war + /adempiere + + + diff --git a/serverApps/src/etc/WEB-INF/web.xml b/serverApps/src/etc/WEB-INF/web.xml new file mode 100644 index 0000000000..e9a9eb350c --- /dev/null +++ b/serverApps/src/etc/WEB-INF/web.xml @@ -0,0 +1,196 @@ + + + + Adempiere Application + Adempiere Web Application $Id: web.xml,v 1.1 2006/04/21 18:03:35 jjanke Exp $ + + ADEMPIERE_HOME + $USER_INSTALL_DIR$ + + + ADEMPIERE_LICENSE + OpenSource + + + ADEMPIERE_PRODUCT + 1 + + + Test + org.compiere.www.Test + + debug + 1 + + + + Test2 + org.compiere.www.Test2 + + + WAccount + Adempiere Account + org.compiere.www.WAccount + + + WCounter + org.compiere.wstore.WCounter + 15 + + + WFieldUpdate + Adempiere Field Update + Adempiere Field Update Command Window + org.compiere.www.WFieldUpdate + + + WLocation + Adempiere Location + org.compiere.www.WLocation + + + WLogin + Adempiere Login + org.compiere.www.WLogin + + + WLookup + Adempiere Lookup + org.compiere.www.WLookup + + + WMenu + Adempiere Menu + org.compiere.www.WMenu + + + WProcess + Adempiere Process + org.compiere.www.WProcess + + + WReport + Adempiere Report + org.compiere.www.WReport + + + WRequest + Requests + Adempiere Requets + org.compiere.wstore.WRequest + 10 + + + WStart + Adempiere Start + Adempiere Start - Creates the windows required + org.compiere.www.WStart + 10 + + + WStatus + Adempiere Status + Adempiere Status - First Servlet loaded + org.compiere.www.WStatus + + StatusInfo + Y + + 5 + + + WTask + Adempiere Task + org.compiere.www.WTask + + + WWindow + Adempiere Application Window + Adempiere Application Window + org.compiere.www.WWindow + + + WWorkflow + Adempiere Workflow + org.compiere.www.WWorkflow + + + Test + /Test + + + Test2 + /Test2 + + + WAccount + /WAccount + + + WCounter + /WCounter + + + WFieldUpdate + /WFieldUpdate + + + WLocation + /WLocation + + + WLogin + /WLogin + + + WLookup + /WLookup + + + WMenu + /WMenu + + + WProcess + /WProcess + + + WReport + /WReport + + + WRequest + /WRequest + + + WStart + /WStart + + + WStatus + /WStatus + + + WTask + /WTask + + + WWindow + /WWindow + + + WWorkflow + /WWorkflow + + + 15 + + + http://jakarta.apache.org/tomcat/debug-taglib + /store/debug-taglib.tld + + + http://jakarta.apache.org/tomcat/examples-taglib + /store/example-taglib.tld + + diff --git a/serverApps/src/jsf/WEB-INF/classes/log4j.xml b/serverApps/src/jsf/WEB-INF/classes/log4j.xml new file mode 100644 index 0000000000..dcdc1bde54 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/log4j.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/AdempiereInitServlet.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/AdempiereInitServlet.java new file mode 100644 index 0000000000..3ecf68e56d --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/AdempiereInitServlet.java @@ -0,0 +1,106 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import java.io.IOException; +import java.util.Properties; +import java.util.logging.Level; +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.UnavailableException; + +import org.compiere.Adempiere; +import org.compiere.util.CLogMgt; +import org.compiere.util.CLogger; +import org.compiere.util.Env; +import org.compiere.util.Ini; +import org.compiere.util.Login; + +/** + * for this project, this servlet needs to be replaced by a backing bean that can also log out + * initializes the adempiere "engine" -- basically logs into the server + * web.xml snippet: + * + adempiereInitServlet + org.compiere.jsf.AdempiereInitServlet + 1 + + * @author rfreden + * @todo wouldn't it be cool to have a Filter to implement lazy loading? + * @fixme the adempiere code here does a System.exit (terminating tomcat...) if it fails to connect to the db + */ +public class AdempiereInitServlet implements Servlet +{ + private static final CLogger log=CLogger.getCLogger(AdempiereInitServlet.class); + + private Properties adempiereProperties; + + private ServletConfig servletConfig=null; + + /** + * nop method, because this servlet doesn't actually serve anything + */ + public void service(ServletRequest servletRequest,ServletResponse servletResponse) + throws ServletException, IOException + {} + + public void init(ServletConfig s) throws ServletException + { + servletConfig=s; + // Adempiere start up and properties setup + //org.compiere.Adempiere.startupEnvironment(true); + if(!Adempiere.startupEnvironment(true)) + throw new UnavailableException("adempiere init failed"); + adempiereProperties = Env.getCtx(); + //CLogMgt.setLoggerLevel(Level.FINE, null); + CLogMgt.setLevel(Level.ALL); + + Ini.setProperty(Ini.P_UID, "SuperUser"); + Ini.setProperty(Ini.P_PWD, "System"); + Ini.setProperty(Ini.P_ROLE, "GardenWorld Admin"); + Ini.setProperty(Ini.P_CLIENT, "GardenWorld"); + Ini.setProperty(Ini.P_ORG, "*"); + Ini.setProperty(Ini.P_LANGUAGE, "English"); + //Ini.setProperty(Ini.P_LANGUAGE, "Danish_dk_DK"); + Ini.setProperty(Ini.P_WAREHOUSE, ""); + Login login = new Login(adempiereProperties); + + if (!login.batchLogin(null)) + throw new UnavailableException("Adempiere login failed"); + + log.info("adempiere login complete"); + } + + public String getServletInfo() + { + return "Adempiere Initialization Servlet, author Rigel Freden, copyright Possibility Forge, Inc. 2006"; + } + + public ServletConfig getServletConfig() + { + return servletConfig; + } + + /** + * @todo implement this method + */ + public void destroy() + {} +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerLookup.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerLookup.java new file mode 100644 index 0000000000..5a5f84d952 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerLookup.java @@ -0,0 +1,222 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import java.util.HashMap; + +import javax.faces.context.FacesContext; +import javax.faces.event.ActionEvent; + +import org.compiere.model.GridTab; +import org.compiere.model.GridWindow; +import org.compiere.util.CLogger; + +/** + * this class does the actual work for variables that start with actionListener_lookup + * basically every method here should have a void return type and take an ActionEvent as argument + * TODO: implement all methods for the dropdown and button menus, list them here + * gridToggle + * + * @author rfreden + * + */ +public class DynamicActionListenerLookup +{ + // this class makes use of the hidden variable "tabNo" + // which contains tab0Grid or somesuch, identifying the panel that's currently on top + // where the digit in the middle is the tabNo for adempiere + + // in case it will matter, it will also have a windowNo, a unique window identifier for adempiere + private static final CLogger log=CLogger.getCLogger(DynamicActionListenerLookup.class); + + private FacesContext facesContext; + + private Long tabNo; + + private TabStateManager tabStateManager; + + public DynamicActionListenerLookup(FacesContext ctx) + { + facesContext=ctx; + tabStateManager=new TabStateManager(facesContext); + } + + // FIXME: implement all these method stubs + public void undo(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void help(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void createNew(ActionEvent ae) + { + throw new UnsupportedOperationException(); + + } + + public void delete(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + /** + * tab control actionListener method; use actionListener="actionListener_lookup.focus" + * to raise the tab described by currentTabNo + * @param ae + */ + public void focus(ActionEvent ae) + { + log.info("focusing on tabNo "+tabNo); + tabStateManager.getUIState().setTabNo(tabNo.intValue()); + } + + public void save(ActionEvent ae) + { + // save tab on window + // check if this is called during the + GridTab gridTab=getCurrentGridTab(); + gridTab.getTableModel().open(0); + log.info("saving tab "+gridTab.getTabNo()); + if(!gridTab.dataSave(true)) + log.info("failed to save tab"); + } + + public void refresh(ActionEvent ae) + { + log.info("called"); + // FIXME: this open method is hackish at best + getCurrentGridTab().getTableModel().open(0); + getCurrentGridTab().dataRefresh(); + } + + public void lookup(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void attachment(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } +/* + public void gridToggle(ActionEvent ae) + { + log.info("entered"); + tabStateManager.gridToggle(); + } +*/ + public void history(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void menu(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void parent(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void detail(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void first(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void previous(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void next(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void last(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void report(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void archived(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void print(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void zoom(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void active(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void check(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void product(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void exit(ActionEvent ae) + { + throw new UnsupportedOperationException(); + } + + public void setTabNo(Long l) + { + log.info("setting tabNo to "+l); + tabNo=l; + } + + // these three parse the tabNo string + // FIXME: check them + private GridTab getCurrentGridTab() + { + Integer key=new Integer(tabStateManager.getUIState().getWindowNo()); + // get window from hashmap "grids" + GridWindow gridWindow=((HashMap)facesContext.getExternalContext() + .getSessionMap().get("grids")).get(key); + return gridWindow.getTab(tabStateManager.getUIState().getTabNo().intValue()); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerPropertyResolver.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerPropertyResolver.java new file mode 100644 index 0000000000..8546b22aea --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerPropertyResolver.java @@ -0,0 +1,116 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import javax.faces.el.PropertyNotFoundException; +import javax.faces.el.PropertyResolver; +import org.compiere.util.CLogger; + +/** + * this class continues the el lookup initiated by DynamicActionListenerVariableResolver, + * resolving the value to the proper name + * hmmm, i think this whole class is unnecessary + */ +public class DynamicActionListenerPropertyResolver extends PropertyResolver +{ + private final static CLogger log=CLogger.getCLogger(DynamicActionListenerPropertyResolver.class); + + private PropertyResolver originalResolver; + + public DynamicActionListenerPropertyResolver(PropertyResolver propertyResolver) + { + //log.info("entered"); + originalResolver = propertyResolver; + } + + public Object getValue(Object base,Object property) throws PropertyNotFoundException + { + if (base instanceof DynamicActionListenerLookup) + { + if(property instanceof Long) + ((DynamicActionListenerLookup)base).setTabNo((Long)property); + return base; + //throw new PropertyNotFoundException(); + } + return originalResolver.getValue(base,property); + } + + public Object getValue(Object base,int index) throws PropertyNotFoundException + { + if(base instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException(); + return originalResolver.getValue(base,index); + } + + /** + * TODO: test this method + */ + public void setValue(Object base,Object property,Object value) throws PropertyNotFoundException + { + //log.info("entered"); + if(base instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException("attempted to call set on a read-only field"); + else + { + originalResolver.setValue(base,property,value); + } + } + + public void setValue(Object obj,int i,Object obj1) throws PropertyNotFoundException + { + //log.info("entered"); + if(obj instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException(); + else + originalResolver.setValue(obj,i,obj1); + } + + public boolean isReadOnly(Object base,Object property) throws PropertyNotFoundException + { + //log.info("entered"); + if(base instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException(); + return originalResolver.isReadOnly(base,property); + } + + public boolean isReadOnly(Object obj,int i) throws PropertyNotFoundException + { + //log.info("entered"); + if(obj instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException(); + return originalResolver.isReadOnly(obj,i); + } + + // this should probably throw for our object + public Class getType(Object obj,Object obj1) throws PropertyNotFoundException + { + //log.info("entered"); + //if (!(obj instanceof DynamicFieldLookup)) + // hope this works.. + return originalResolver.getType(obj,obj1); + //else + // return com.ibm.faces.databind.SelectItemsWrapper.class; + } + + public Class getType(Object obj,int i) throws PropertyNotFoundException + { + //log.info("entered"); + if(obj instanceof DynamicActionListenerLookup) + throw new PropertyNotFoundException(); + return originalResolver.getType(obj,i); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerVariableResolver.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerVariableResolver.java new file mode 100644 index 0000000000..ff5de30382 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicActionListenerVariableResolver.java @@ -0,0 +1,49 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import javax.faces.context.FacesContext; +import javax.faces.el.VariableResolver; +import org.compiere.util.CLogger; + +/** + * this class exists only to signal that this is a custom lookup + */ +public class DynamicActionListenerVariableResolver extends VariableResolver +{ + private static final String LOOKUP_VAR="actionListener_lookup"; + private static final CLogger log=CLogger.getCLogger(DynamicActionListenerVariableResolver.class); + + private VariableResolver originalResolver; + + public DynamicActionListenerVariableResolver(VariableResolver variableResolver) + { + originalResolver=variableResolver; + } + + public Object resolveVariable(FacesContext facescontext, String s) + { + //log.info("resolving var "+s); + if(s.equals(LOOKUP_VAR)) + { + //log.info("matched a dynamic lookup for "+LOOKUP_VAR); + return new DynamicActionListenerLookup(facescontext); + } + //log.info("failed to match"); + return originalResolver.resolveVariable(facescontext,s); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldLookup.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldLookup.java new file mode 100644 index 0000000000..d2e2080607 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldLookup.java @@ -0,0 +1,333 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Level; + +import javax.faces.context.FacesContext; +import javax.faces.el.PropertyNotFoundException; +import javax.faces.model.SelectItem; + +import org.compiere.model.GridField; +import org.compiere.model.GridTab; +import org.compiere.model.GridWindow; +import org.compiere.util.CLogger; +import org.compiere.util.DB; +import org.compiere.util.Env; +import org.compiere.util.NamePair; + +/** + * this class provides enough of an interface to adempiere to get values for a + * field's label, tooltip text, and value from the adempiere model + */ +public class DynamicFieldLookup +{ + private final static CLogger log=CLogger.getCLogger(DynamicFieldLookup.class); + + private FacesContext facesContext; + + private Long tabNumber; + + private String columnName; + + private GridTab gridTab; + + private TabStateManager tabStateManager; + + // this exists so we can always call .value in el + static public class FieldProxy + { + private GridField gridField; + + public FieldProxy(GridField gF) + { + gridField=gF; + } + + public Object getValue() + { + return convertToValue(); + } + + public String getLabel() + { + //log.info("returning label "+gridField.getHeader()); + if(gridField.getDisplayType()==28) + { + if (gridField.getColumnName().equals("PaymentRule")) + { + return readReference(195); + //this.setForeground(Color.blue); + //setIcon(Env.getImageIcon("Payment16.gif")); // 29*14 + } + else if (gridField.getColumnName().equals("DocAction")) + { + return readReference(135); + //this.setForeground(Color.blue); + //setIcon(Env.getImageIcon("Process16.gif")); // 16*16 + } + else if (gridField.getColumnName().equals("CreateFrom")) + { + //setIcon(Env.getImageIcon("Copy16.gif")); // 16*16 + } + else if (gridField.getColumnName().equals("Record_ID")) + { + //setIcon(Env.getImageIcon("Zoom16.gif")); // 16*16 + // FIXME: this probably does something that needs to be emulated in our jsf layer + //this.setText(Msg.getMsg(Env.getCtx(), "ZoomDocument")); + } + else if (gridField.getColumnName().equals("Posted")) + { + return readReference(234); + //this.setForeground(Color.magenta); + //setIcon(Env.getImageIcon("InfoAccount16.gif")); // 16*16 + } + } + return gridField.getHeader(); + } + + public String getTooltip() + { + return gridField.getDescription(); + } + + // arg may need to be an Object to handle all cases + public void setValue(Object o) + { + String s=o.toString(); + // some values may not be writable, should catch it in DynamicFieldPropertyResolver.isReadOnly + if(s.equals("true")) + s="Y"; + else if(s.equals("false")) + s="N"; + + // TODO: this really probably belongs somewhere else + + String ret=gridField.setValueValidate(s,true); + if(ret!=null) + throw new PropertyNotFoundException(ret); + //log.info("got back from setValueValidate (null is success) "+ret); + } + + // this is for conversion in jsf + public Class getType() + { + // TODO: there probably need to be other types here (Date in the future, for one) + if(gridField.getDisplayType()==20) + return java.lang.Boolean.class; + return java.lang.String.class; + } + + private Object convertToValue() + { + int displayType=gridField.getDisplayType(); + //log.info("got display type "+displayType); + // TODO: this only has like... 3 or 4 unique cases, refactor for + // reuse + // check display type to genereate jsf code for each specific + // component + switch (displayType) + { + case 10: + case 11: + case 12: + case 13: + case 14: + case 22: + case 29: + case 33: + case 34: + case 35: + case 36: + case 37: + // text box + // check if same line. make sure that it isn't the first field. + // It is possible that the first field can have same line checked and that would cause + // formatting issues. + log.info("getValue1 "+gridField.getValue()); + log.info("getValue2 "+gridField.getValue()); + return gridField.getValue(); + case 15: + // may want to convert this to a java.util.Date, same for case 16 + // date. have to chop timestamp off of gridField value + String dateString=""; + if(gridField.getValue()!=null) + { + String[] dateArray=gridField.getValue().toString().split(" "); + dateString=dateArray[0]; + return dateString; + } + case 16: + // probably unused so far + // date + time + // check if same line. make sure that it isn't the first field. + // It is possible that the first field can have same line checked and that + // would cause formatting issues. + return gridField.getValue(); + case 17: + case 18: + case 19: + // check if same line. make sure that it isn't the first field. + // It is possible that the first field can have same line checked and that would cause + // formatting issues. + ArrayList tmp=gridField.getLookup().getData(true, true, true, true); + ArrayList valueNamePairList=tmp; + ArrayList selectItems=new ArrayList(); + for(int i=0; i(); + String SQL; + if (Env.isBaseLanguage(Env.getCtx(), "AD_Ref_List")) + SQL = "SELECT Name FROM AD_Ref_List WHERE AD_Reference_ID=?"; + else + SQL = "SELECT t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t " + + "WHERE l.AD_Ref_List_ID=t.AD_Ref_List_ID" + + " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "'" + + " AND l.AD_Reference_ID=?"; + + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + pstmt.setInt(1, AD_Reference_ID); + ResultSet rs = pstmt.executeQuery(); + rs.next(); + String name = rs.getString(1); + rs.close(); + pstmt.close(); + return name; + } + catch (SQLException e) + { + log.log(Level.SEVERE, SQL, e); + } + return "ERROR"; + } // readReference + } // end FieldProxy + + public DynamicFieldLookup(FacesContext ctx) + { + facesContext=ctx; + tabStateManager=new TabStateManager(facesContext); + } + + public FieldProxy getProxy() + { + return new FieldProxy(gridTab.getField(columnName)); + } + + /** + * sets the GridTab for this field + * @param l + */ + public void setTabNumber(Long l) + { + //log.info("setting tab number"); + tabNumber=l; + // window # is available as a hidden field named windowNo + // GridWindows are stored in a session Map called grid + HashMap grids=(HashMap)facesContext.getExternalContext().getSessionMap().get("grids"); + //log.info("grids is "+grids+" getting windowNo "+tabStateManager.getUIState().getWindowNo()); + GridWindow gridWindow=grids.get(new Integer(tabStateManager.getUIState().getWindowNo())); + //log.info("gridWindow is "+gridWindow); + gridTab=gridWindow.getTab((int)tabNumber.longValue()); + //log.info("gridTab open status "+gridTab.isOpen()); + } + + /** + * + */ + public void setColumnName(String s) + { + // error checking for testing in development, all of this but the final assignment can be commented out in release + boolean b=false; + GridField[] gridFields=gridTab.getFields(); + for(int i=0;i > getProxies() + { + GridField[] gridFields=gridTab.getFields(); + ArrayList fieldProxies=new ArrayList(); + log.info("got "+gridFields.length+" fields"); + for (int i=0;i > tmp=new ArrayList >(); + tmp.add(fieldProxies); + return tmp; + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldPropertyResolver.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldPropertyResolver.java new file mode 100644 index 0000000000..c37fb37708 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldPropertyResolver.java @@ -0,0 +1,172 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import javax.faces.el.PropertyNotFoundException; +import javax.faces.el.PropertyResolver; +import org.compiere.util.CLogger; + +/** + * this class continues the el lookup initiated by DynamicFieldVariableResolver, + * resolving the value to the proper name + * + * TODO: this should deduce the tab number from the hidden field id = "tabNo" + */ +public class DynamicFieldPropertyResolver extends PropertyResolver +{ + // yes these should probably be an enum + public static final String DYNAMIC_VALUE_TOKEN="value"; + public static final String DYNAMIC_LABEL_TOKEN="label"; + public static final String DYNAMIC_TOOLTIP_TOKEN="tooltip"; + public static final String DYNAMIC_COLLECTION_TOKEN="fields"; + // less related to the others, these are more application state than 1:1 with adempiere model + //public static final String DYNAMIC_TAB_TOKEN="tabNo"; + //public static final String DYNAMIC_GRID_TOKEN="gridView"; + + private final static CLogger log=CLogger.getCLogger(DynamicFieldPropertyResolver.class); + + private PropertyResolver originalResolver; + + public DynamicFieldPropertyResolver(PropertyResolver propertyResolver) + { + originalResolver = propertyResolver; + } + + public Object getValue(Object o1,Object o2) throws PropertyNotFoundException + { + //log.info("entered getValue(Object,Object), base is type "+o1.getClass().getName()+" property is type "+o2.getClass().getName()+" value "+o2.toString()); + if (o1 instanceof DynamicFieldLookup) + { + //log.info("matches dynamic lookup"); + DynamicFieldLookup dynamicFieldLookup=(DynamicFieldLookup)o1; + if(o2 instanceof Long) + { + //log.info("looking up tab index "+(Long)o2); + dynamicFieldLookup.setTabNumber((Long)o2); + return dynamicFieldLookup; + } + else + { + //log.info("looking up named property "+(String)o2); + String s=(String)o2; + if(s.equals(DYNAMIC_VALUE_TOKEN)) + { + Object o=dynamicFieldLookup.getProxy().getValue(); + return o; + } + else if(s.equals(DYNAMIC_LABEL_TOKEN)) + return dynamicFieldLookup.getProxy().getLabel(); + else if(s.equals(DYNAMIC_TOOLTIP_TOKEN)) + return dynamicFieldLookup.getProxy().getTooltip(); + else if(s.equals(DYNAMIC_COLLECTION_TOKEN)) + return dynamicFieldLookup.getProxies(); + //else if(s.equals(DYNAMIC_TAB_TOKEN)) + // return dynamicFieldLookup.getTabNo(); + //else if(s.equals(DYNAMIC_GRID_TOKEN)) + // return dynamicFieldLookup.getGridView(); + else + { + dynamicFieldLookup.setColumnName(s); + return dynamicFieldLookup; + } + } + } + return originalResolver.getValue(o1,o2); + } + + public Object getValue(Object obj,int i) throws PropertyNotFoundException + { + if(obj instanceof DynamicFieldLookup) + throw new PropertyNotFoundException(); + return originalResolver.getValue(obj,i); + } + + /** + * TODO: test this method + */ + public void setValue(Object base,Object property,Object value) throws PropertyNotFoundException + { + if(base instanceof DynamicFieldLookup) + { + //log.info("setValue called for column "+((DynamicFieldLookup)base).getColumnName()+" value type "+value.getClass().getName()+" value "+value.toString()); + DynamicFieldLookup dfl=(DynamicFieldLookup)base; + String s=(String)property; + if(s.equals(DYNAMIC_VALUE_TOKEN)) // FIXME: this will probably break + { + dfl.getProxy().setValue(value.toString()); + } + else // tabNo fits this case + log.info("attempted to call set on read-only field: "+((DynamicFieldLookup)base).getColumnName()+" with terminating token "+s); + } + else + { + originalResolver.setValue(base,property,value); + } + } + + public void setValue(Object obj,int i,Object obj1) throws PropertyNotFoundException + { + if(obj instanceof DynamicFieldLookup) + { + //log.info("setValue with int arg called"); + throw new PropertyNotFoundException(); + } + else + originalResolver.setValue(obj,i,obj1); + } + + // FIXME: this likely needs to be a non constant return for custom lookup (false for value lookup?) + public boolean isReadOnly(Object base,Object property) throws PropertyNotFoundException + { + //log.info("invoked isReadOnly"); + if(base instanceof DynamicFieldLookup) + { + // FIXME: lookups obviously have more properties than just a name + // so we should associate them logically, java enums? or give them to different resolver classes perhaps + log.info("base id DynamicFieldLookup, property is "+property.toString()); + if(property instanceof String && ( ((String)property).equals("value") || ((String)property).equals("gridView") || ((String)property).equals("tabNo") )) + return false; + else + return true; + } + return originalResolver.isReadOnly(base,property); + } + + public boolean isReadOnly(Object obj,int i) throws PropertyNotFoundException + { + //log.info(""); + if(obj instanceof DynamicFieldLookup) + return true; + return originalResolver.isReadOnly(obj,i); + } + + public Class getType(Object base,Object property) throws PropertyNotFoundException + { + //log.info("getType called, base is of type "+base.getClass().getName()+" value "+base.toString()+" property is of type "+property.getClass().getName()+" value "+property.toString()+" and column name is "+((DynamicFieldLookup)base).getColumnName()); + // FIXME: this needs to return the type (to convert to from String) of the column + //return originalResolver.getType(base,property); + //return java.lang.String.class; + return ((DynamicFieldLookup)base).getProxy().getType(); + } + + public Class getType(Object obj,int i) throws PropertyNotFoundException + { + if(obj instanceof DynamicFieldLookup) + throw new PropertyNotFoundException(); + return originalResolver.getType(obj,i); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldVariableResolver.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldVariableResolver.java new file mode 100644 index 0000000000..9e162daa07 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/DynamicFieldVariableResolver.java @@ -0,0 +1,51 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import javax.faces.context.FacesContext; +import javax.faces.el.VariableResolver; + +import org.compiere.util.CLogger; + +/** + * this class exists only to signal that this is a custom lookup + */ +public class DynamicFieldVariableResolver extends VariableResolver +{ + private static final CLogger log=CLogger.getCLogger(DynamicFieldVariableResolver.class); + + private static final String LOOKUP_VAR="tab_lookup"; + + private VariableResolver originalResolver; + + public DynamicFieldVariableResolver(VariableResolver variableResolver) + { + originalResolver=variableResolver; + } + + public Object resolveVariable(FacesContext facescontext, String s) + { + //log.info("resolving var "+s); + if(s.equals(LOOKUP_VAR)) + { + //log.info("matching tab_lookup"); + return new DynamicFieldLookup(facescontext); + } + //log.info("failed to match"); + return originalResolver.resolveVariable(facescontext,s); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/JSFFilter.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/JSFFilter.java new file mode 100644 index 0000000000..a3c4b82356 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/JSFFilter.java @@ -0,0 +1,809 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Properties; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.compiere.model.GridField; +import org.compiere.model.GridTab; +import org.compiere.model.GridWindow; +import org.compiere.util.CLogger; +import org.compiere.util.Env; + +/** + * JSF Filter + * @author zbeatty + * + */ + +public class JSFFilter + implements Filter + { + + private FilterConfig filterConfig = null; + /** Logging */ + private static CLogger log = CLogger.getCLogger(JSFFilter.class); + + /** GridWindow timestamp */ + private long gridWindowTimestamp; + + /** Environment Variable */ + private Properties ctx; + + /** ID's and Window Nums */ + private int windowId; + private int windowNo; + + /** Tab count */ + private int tabCount; + + /** GridWindow, GridTab, GridFields */ + private GridWindow gridWindow = null; + private ArrayList tabList; + + /** + * Init + * @param config configuration + * @throws ServletException + */ + public void init(FilterConfig filterConfig) throws ServletException + { + this.filterConfig = filterConfig; + ctx = Env.getCtx(); + } + + /** + * Destroy + */ + public void destroy() + { + this.filterConfig = null; + } + + /** + * The filter checks to see if the requested file already exists. If it doesn't exist, then it + * generates a new file for the page requested. If it does exist, it compares the timestamp + * on the file to the timestamp on the GridWindow object to make sure it is not out of date. If + * it is out of date, it generates a new file for the page requested. If it is not out of date, + * displays the existing, up to date file. + * @param ServletRequest request + * @param ServletResponse response + * @param FilterChain chain + * @throws IOException + * @throws ServletException + */ + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException + { + // cast request into HttpServletRequest + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + HttpSession session = null; + + // get session from request. Using boolean true should create a new session if session doesn't exist + try + { + session = httpServletRequest.getSession(true); + } + catch (Exception e) + { + log.warning("There was a problem getting the session from the HttpServletRequest"); + } + + // get windowNo and windowId out of the request + try + { + windowNo = (Integer.parseInt(httpServletRequest.getParameter("windowNo"))); + windowId = (Integer.parseInt(httpServletRequest.getParameter("windowId"))); + } + catch (NumberFormatException nfe) + { + log.info("There was an error getting the request parameters: " + nfe); + } + + HashMap grids = new HashMap(); // holds HashMap(WindowNo, GridWindow) + StringBuilder generatedJSF = new StringBuilder(); + // get context and path to store file + String realContextPath = session.getServletContext().getRealPath("/"); // holds servlet context path + + try + { + // get "grids" out of the session to see if window exists + // note: attribute "grids" is expected to be in the session before the filter is hit. + if (session.getAttribute("grids") != null) + { + grids = (HashMap)session.getAttribute("grids"); + } + + // see if requested windowNo is in session + if (grids.isEmpty() || (! grids.containsKey(windowId))) + { + gridWindow = GridWindow.get(ctx, windowNo, windowId); + } + else + { + gridWindow = grids.get(windowNo); + } + + String jsfFile = realContextPath + "window/" + formatNameWithFirstLowerCase(gridWindow.getName()) + ".jsp"; + File file = new File(jsfFile); + + // check if file exists and up to date + if (file.exists()) + { + gridWindowTimestamp = getGridWindowTimeStamp(); + + if (gridWindowTimestamp > file.lastModified()) + { + generateJSFPage(generatedJSF, realContextPath); + saveFile(file, generatedJSF.toString()); + } + + } + else + { + generateJSFPage(generatedJSF, realContextPath); + saveFile(file, generatedJSF.toString()); + } + } + catch (NullPointerException npe) + { + log.info("Null pointer occured getting \"grids\" out of session: " + npe); + } + // load session attribute + grids.put(windowNo, gridWindow); + session.setAttribute("grids", grids); + // next filter + chain.doFilter(request, response); + } + + // creates the window, tabs, and fields for the requested window + private void generateJSFPage(StringBuilder jsfString, String realContextPath) + { + // There is a backing bean called menuBean that we will use for the menus of all windows + // TODO change titles to title="#{tab_lookup[tabNo].fieldColumnName.tooltip}" + jsfString.append(createAdempiereHeader()); + jsfString.append(createHeader()); + jsfString.append("\n\n\n" + gridWindow.getName() + + "\n\n" + + "\n\n\n" + + "\n\n\n" + // jsf Messages + + "" + + "\n" + + "\n\n\n
\n" + + "\n" + + // toolbar (Maybe extract to method) + + "\n" + + + "  \n\n" + + "\n" + + + "\n" + + + "\n" + + + "\n" + + + "\n  \n\n" + + "\n" + + + "\n" + + + "\n" + + + " \n" + + "\n" + + + "\n  \n\n" + + "\n" + + + "\n" + + + "\n" + + + "\n" + + + "\n  \n\n" + + "\n" + + + "\n" + + + "\n" + + + "\n" + + + "\n  \n\n" + + "\n" + + + "\n" + + + "\n" + + + "\n  \n\n" + + "\n" + + + "\n" + + + "\n" + + + "\n" + + + "  \n" + + "\n" + + + "\n" + + "
\n" + + // hidden field to store window number + + "\n" + + "\n" + + + "\n\n" + + "\n\n\n
\n\n"); + + // generate tabs + jsfString.append(generateTabInfo()); + // end generate tabs + jsfString.append("
\n
\n" + + "\n"); + // generate jsp pages for tabs. Each tab has a detail page and a table page + createDetailPage(realContextPath); + createTablePage(realContextPath); + int orderSubCount = 1; // used to increment orderSub count + for (int i = 0; i < tabCount; i++) { + GridTab gridTab = gridWindow.getTab(i); + String tabName = formatNameWithFirstLowerCase(gridTab.getName()); + jsfString.append("\n\n\n\n\n" + + "\n\n\n\n\n"); + } + jsfString.append("\n
\n" + + "
\n\n\n
"); + } + + // Generate GridTabs for JSF page + private StringBuilder generateTabInfo() + { + StringBuilder tabString = new StringBuilder(); + tabCount = gridWindow.getTabCount(); + for (int i = 0; i < tabCount; i++) + { + GridTab gridTab = gridWindow.getTab(i); + if (i == 0) + { + tabString.append("\n\n\n\n\n" + + "\n"); + } + else if(gridTab.getTabLevel() == 1) + { + tabString.append("baseIndentOneTabStyle unselectedTabStyle\" rendered=\"#{!(uiStateBean.tabNo eq " + gridTab.getTabNo() + ")}\"" + + " actionListener=\"#{actionListener_lookup[" + gridTab.getTabNo() + "].focus}\" onmouseover=\"this.className='baseIndentOneTabStyle " + + "unselectedMouseOverTabStyle';\" onmouseout=\"this.className='baseIndentOneTabStyle unselectedTabStyle';\" />\n" + + "\n"); + } + + else if(gridTab.getTabLevel() == 2) + { + tabString.append("baseIndentTwoTabStyle unselectedTabStyle\" rendered=\"#{!(uiStateBean.tabNo eq " + gridTab.getTabNo() + ")}\"" + + " actionListener=\"#{actionListener_lookup[" + gridTab.getTabNo() + "].focus}\" onmouseover=\"this.className='baseIndentTwoTabStyle " + + "unselectedMouseOverTabStyle';\" onmouseout=\"this.className='baseIndentTwoTabStyle unselectedTabStyle';\" />\n" + + "\n"); + } + tabString.append("\n\n"); + } + return tabString; + } + // Generate Detail jsp page + private void createDetailPage(String realContextPath) + { + File detailFile = null; + + for (int i = 0; i < tabCount; i ++) + { + StringBuilder detailJSP = new StringBuilder(); + detailJSP.append(createAdempiereHeader()); + detailJSP.append(createHeader()); + detailJSP.append("\n"); + + GridTab gridTab = gridWindow.getTab(i); + String fileName = formatNameWithFirstLowerCase(gridTab.getName()) + "Detail"; + String jsfFile = realContextPath + "window/" + fileName + ".jsp"; + detailFile = new File(jsfFile); + gridTab.dataRefreshAll(); + + boolean isSolo = false; // true if not same line as previous + for (int j = 0; j < gridTab.getFieldCount(); j++) + { + GridField gridField = gridTab.getField(j); + // check if displayed + if (gridField.isDisplayed()) + { + int displayType = gridField.getDisplayType(); + // check display type to genereate jsf code for each specific component + switch(displayType) + { + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: // this is a Date format. Comes as Date + Time and needs to be chopped in Backing Bean + case 16: // this is a Date + Time format. + case 21: // complete address comma seperated ex: street, city, state, zip + case 22: + case 29: + case 33: + case 34: + case 35: + case 36: + case 37: + // text box + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 17: + case 18: + case 19: + // lookup + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + ArrayList al = gridField.getLookup().getData(true, true, true, true); + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n\n"); + + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 20: + // Check box + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 23: + case 24: + case 25: + case 27: + case 28: + // custom component + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 30: + // search + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 31: + // locator + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + case 32: + // image + // check if same line. make sure that it isn't the first field. It is possible that the + // first field can have same line checked and that would cause formatting issues. + if(gridField.isSameLine() && j != 0) + { + isSolo = false; + } + else + { + if (isSolo) + { + detailJSP.append("\n"); + } + detailJSP.append("\n"); + isSolo = true; + } + detailJSP.append("\n\n"); + // check if same line. if yes and not first field, close table row + if (gridField.isSameLine() && j != 0) + { + detailJSP.append("\n"); + } + break; + default: + log.severe("Display Type not handled for " + gridField.getColumnName() + " with display type: " + gridField.getDisplayType()); + break; + } + } + } + detailJSP.append("
" + + "\n" + + "\n
\n" + + "\n\n\n
\n" + + "\n" + + "\n" + + "
" + + "\n" + + " \n
" + + "\n" + + "\n
" + + "\n" + + "\n
" + + "\n" + + "\n
"); + saveFile(detailFile, detailJSP.toString()); + } + } + // Generate Table jsp page + private void createTablePage(String realContextPath) + { + File tableFile = null; + for (int i = 0; i < tabCount; i ++) + { + StringBuilder tableJSP = new StringBuilder(); + tableJSP.append(createAdempiereHeader()); + tableJSP.append(createHeader()); + + GridTab gridTab = gridWindow.getTab(i); + String fileName = formatNameWithFirstLowerCase(gridTab.getName()) + "Table"; + String jsfFile = realContextPath + "window/" + fileName + ".jsp"; + tableFile = new File(jsfFile); + gridTab.dataRefreshAll(); + // counter for subscripts + int subscriptCount = 0; + + tableJSP.append("\n"); + for (int j = 0; j < gridTab.getFieldCount(); j++) + { + GridField gridField = gridTab.getField(j); + + tableJSP.append("\n\n"); + + // check if displayed + if (gridField.isDisplayed()) + { + int displayType = gridField.getDisplayType(); + // check display type to genereate jsf code for each specific component + switch(displayType) + { + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: // this is a Date format. Comes as Date + Time and needs to be chopped in Backing Bean + case 16: // this is a Date + Time format. + case 21: // complete address comma seperated ex: street, city, state, zip + case 22: + case 29: + case 33: + case 34: + case 35: + case 36: + case 37: + // text box + tableJSP.append("\n"); + break; + case 17: + case 18: + case 19: + // lookup + tableJSP.append("\n\n\n"); + break; + case 20: + // check box + tableJSP.append("\n"); + break; + case 23: + case 24: + case 25: + case 27: + case 28: + // custom component + tableJSP.append("\n"); + break; + case 30: + // search + tableJSP.append("\n"); + subscriptCount++; + break; + case 31: + // locator + tableJSP.append("\n"); + subscriptCount++; + break; + case 32: + // image + tableJSP.append("\n"); + subscriptCount++; + break; + default: + log.severe("Display Type not handled for " + gridField.getColumnName() + " with display type: " + gridField.getDisplayType()); + subscriptCount++; + break; + } + } + tableJSP.append("\n"); + } + tableJSP.append(""); + saveFile(tableFile, tableJSP.toString()); + } + + } + // Save GridWindow jsf test file + private void saveFile(File file, String generatedJSF) + { + try + { + FileWriter out = new FileWriter(file); + out.write(generatedJSF); + out.flush(); + out.close(); + } + catch (IOException ioe) + { + log.severe("Error " + ioe.toString() + " occurred in saveGridWindow"); + } + } + // format name of file or tab + private String formatNameWithFirstLowerCase(String name) + { + String[] tempNameArray = name.split(" "); + for (int i = 0; i < tempNameArray.length; i++) + { + if (i == 0) + { + name = tempNameArray[i].toLowerCase(); + } + else + { + name += tempNameArray[i]; + } + } + return name; + } + // adempiere header + private StringBuilder createAdempiereHeader(){ + StringBuilder adempiereHeader = new StringBuilder(); + adempiereHeader.append("<%--/*************************************************************\n" + + " **********\n" + + " *******\n" + + " * Product: Adempiere ERP & CRM Smart Business Solution\n" + + " * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.\n" + + " * This program is free software; you can redistribute it and/or modify it\n" + + " * under the terms version 2 of the GNU General Public License as published\n" + + " * by the Free Software Foundation. This program is distributed in the hope\n" + + " * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied\n" + + " * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" + + " * See the GNU General Public License for more details.\n" + + " * You should have received a copy of the GNU General Public License along\n" + + " * with this program; if not, write to the Free Software Foundation, Inc.,\n" + + " * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.\n" + + " * You may reach us at: ComPiere, Inc. - http://www.adempiere.org/license.html\n" + + " * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org\n" + + " **************************************************************\n" + + " **********\n" + + " *****/--%>\n"); + return adempiereHeader; + } + // page header + private StringBuilder createHeader() + { + StringBuilder headerString = new StringBuilder(); + headerString.append("<%@page contentType=\"text/html\"%>\n<%@page pageEncoding=\"UTF-8\"%>\n" + + "<%@ taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\"%>\n" + + "<%@ taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\"%>\n" + + "<%@ taglib uri=\"http://myfaces.apache.org/tomahawk\" prefix=\"t\"%>\n"); + return headerString; + } + // Get GridWindow TimeStamp + private long getGridWindowTimeStamp() + { + Timestamp timeStamp = gridWindow.getModelUpdated(true); + if(timeStamp.equals(null)) + { + log.severe("Could not get GridWindow TimeStamp"); + } + return timeStamp.getTime(); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/Log4JInitServlet.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/Log4JInitServlet.java new file mode 100644 index 0000000000..6c7a7029e0 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/Log4JInitServlet.java @@ -0,0 +1,51 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import javax.servlet.ServletException; +import javax.servlet.UnavailableException; +import javax.servlet.http.HttpServlet; + +import org.apache.log4j.xml.DOMConfigurator; + +/** + * manually initializes the log4j system independent of adempiere's main logging; + * enables jsf components and other existing code to use log4j for their output. + * this should not be considered anything near a permanent solution, unless there is + * no better way to integrate the two logging systems + * init param, "log4j-init-file"; make sure to put an xml descriptor file somewhere this can see it + * @author rfreden + */ +public class Log4JInitServlet extends HttpServlet +{ + private static final long serialVersionUID = 2294612125299399465L; + + /** + * loads the log4j.xml logging descriptor + * @todo load the init file as a resource, also handle alternate configuration (properties file) + */ + public void init() throws ServletException + { + super.init(); + String path=getServletContext().getRealPath("/"); + String fn=getInitParameter("log4j-init-file"); + if(fn!=null) + DOMConfigurator.configure(path+fn); + else + throw new UnavailableException("could not find log4j xml descriptor, make sure it exists and is specified in web.xml"); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/MenuBean.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/MenuBean.java new file mode 100644 index 0000000000..f3deeee087 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/MenuBean.java @@ -0,0 +1,134 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.jsf; + +import java.util.ArrayList; +import java.util.List; +import org.apache.myfaces.custom.navmenu.NavigationMenuItem; + +import org.apache.log4j.Logger; + +/** + * provides a model of the main menu bar + * + * @author rfreden + */ +public class MenuBean +{ + private static final Logger log=Logger.getLogger(MenuBean.class); + + private List menu; + + // label, icon, action + // all three null for menu break + // first element is the submenu title + private static final String[][] fileMenu= { { "File", null, null }, + { "Print Screen", "/images/PrintScreen16.gif", null }, + { "Screen Shot", "/images/ScreenShot16.gif", null }, + { "Report", "/images/Report16.gif", null }, { "Print", "/images/Print16.gif", null }, + { null, null, null }, { "End", "/images/End16.gif", null }, + { "Exit", "/images/Exit16.gif", null } }; + + private static final String[][] editMenu= { { "Edit", null, null }, + { "New Record", "/images/New16.gif", null }, { "Save", "/images/Save16.gif", null }, + { null, null, null }, { "Copy Record", "/images/Copy16.gif", null }, + { "Delete Record", "/images/Delete16.gif", null }, + { "Undo Changes", "/images/Undo16.gif", null }, + { "Requery", "/images/Refresh16.gif", null }, { null, null, null }, + { "Look Up Record", "/images/Find16.gif", null } }; + + private static final String[][] viewMenu= { { "View", null, null }, + { "Product Info", "/images/Product16.gif", null }, + { "Business Partner Info", "/images/BPartner16.gif", null }, + { "Account Info", "/images/InfoAccount16.gif", null }, + { "Schedule Info", "/images/InfoSchedule16.gif", null }, { null, null, null }, + { "Order Info", "/images/Info16.gif", null }, + { "Invoice Info", "/images/Info16.gif", null }, + { "Shipment Info", "/images/Info16.gif", null }, + { "Payment Info", "/images/Info16.gif", null }, + { "Cash Journal Info", "/images/Info16.gif", null }, + { "Resource Info", "/images/Info16.gif", null }, + { "Asset Info", "/images/Info16.gif", null }, { null, null, null }, + { "Attachment", "/images/Attachment16.gif", null }, + { "History Records", "/images/History16.gif", null }, { null, null, null }, + { "Grid Toggle", "/images/Multi16.gif", null } }; + + private static final String[][] goMenu= { { "Go", null, null }, + { "First Record", "/images/First16.gif", null }, + { "Previous Record", "/images/Previous16.gif", null }, + { "Next Record", "/images/Next16.gif", null }, + { "Last Record", "/images/Last16.gif", null }, { null, null, null }, + { "Parent Record", "/images/Parent16.gif", null }, + { "Detail Record", "/images/Detail16.gif", null }, { null, null, null }, + { "Zoom Across (Where Used)", "/images/ZoomAcross16.gif", null }, + { "Check Requests", "/images/Request16.gif", null }, + { "Archived Documents/Reports", "/images/Archive16.gif", null }, + { "Menu", "/images/Home16.gif", null } }; + + private static final String[][] toolsMenu= { { "Tools", null, null }, + { "Calculator", "/images/Calculator16.gif", null }, + { "Calendar", "/images/Calendar16.gif", null }, + { "Editor", "/images/Editor16.gif", null }, { "Script", "/images/Script16.gif", null }, + { "Active Workflows", "/images/WorkFlow16.gif", null }, { null, null, null }, + { "Preference", "/images/Preference16.gif", null } }; + + private static final String[][] helpMenu= { { "Help", null, null }, + { "Help", "/images/Help16.gif", null }, { "Online", "/images/Online16.gif", null }, + { "Email Support", "/images/EMailSupport16.gif", null }, + { "About", "/images/About16.gif", null } }; + + /** Creates a new instance of MenuBean */ + public MenuBean() + { + menu=new ArrayList(); + menu.add(getNavigationItemListFromArray(fileMenu)); + menu.add(getNavigationItemListFromArray(editMenu)); + menu.add(getNavigationItemListFromArray(viewMenu)); + menu.add(getNavigationItemListFromArray(goMenu)); + menu.add(getNavigationItemListFromArray(toolsMenu)); + menu.add(getNavigationItemListFromArray(helpMenu)); + } + + public List getMenu() + { + return menu; + } + + private NavigationMenuItem getNavigationItemListFromArray(String[][] sa) + { + NavigationMenuItem root=new NavigationMenuItem(sa[0][0], sa[0][2], sa[0][1], false); + List tmp=new ArrayList(); + for (int i=1; i, for windowNo and tab state string + * but... this class should be the only interface to that (currently there is an el expression that looks like #{sessionScope.tabNo[windowNo]} ) + * this object is _only valid for the windowNo it is instantiated from_ + * the class furthermore should be the interface to windowNo, which is a request parameter + * @author rfreden + * + */ +public class TabStateManager +{ + private static final CLogger log=CLogger.getCLogger(TabStateManager.class); + + // the map should be a non clobberable singleton + private static Map tabNo; + + private FacesContext facesContext; + + public TabStateManager(FacesContext fc) + { + facesContext=fc; + if(tabNo==null) + { + // if it doesn't exist in the session, then instantiate it and put it there + if((tabNo=(Map)facesContext.getExternalContext().getSessionMap().get("tabNo"))==null) + { + tabNo=new HashMap(); + facesContext.getExternalContext().getSessionMap().put("tabNo",tabNo); + } + } + } + + public UIStateBean getUIState() + { + return (UIStateBean)facesContext.getApplication().getVariableResolver().resolveVariable(facesContext,"uiStateBean"); + } +} diff --git a/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/UIStateBean.java b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/UIStateBean.java new file mode 100644 index 0000000000..413a2b1f0b --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/classes/org/compiere/jsf/UIStateBean.java @@ -0,0 +1,84 @@ +package org.compiere.jsf; + +import java.io.Serializable; + +import javax.faces.context.FacesContext; +import javax.faces.event.ActionEvent; + +import org.compiere.util.CLogger; + +/** + * holds state for a window; currently it tracks only the windowNo attribute, provided on initial load + * an instance of this class should be available for any window page, as it is persisted throughout the view existence via t:saveState + * @author rfreden + * + */ +public class UIStateBean implements Serializable +{ + private static final long serialVersionUID=2930846164351L; + + private static final CLogger log=CLogger.getCLogger(UIStateBean.class); + + // TODO: this should be an Integer + private String windowNo; + + private boolean gridView; + + private int tabNo; + + public UIStateBean() + { + // int and boolean default initializers put this initial state at tab0Detail + String[] s=(String[])FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap().get("windowNo"); + if(s!=null) + { + windowNo=s[0]; + log.info("got windowNo "+windowNo); + } + } + + public void setWindowNo(String w) + { + log.info("setting windowNo "+w); + windowNo=w; + } + + public String getWindowNo() + { + //log.info("getting windowNo "+windowNo); + return windowNo; + } + + public Boolean getGridView() + { + return gridView; + } + + public void setGridView(Boolean b) + { + gridView=b; + } + + public Integer getTabNo() + { + return tabNo; + } + + public void setTabNo(Integer i) + { + tabNo=i; + } + + public String getTabState() + { + String s="tab"+String.valueOf(tabNo)+(gridView?"Table":"Detail"); + log.info("returning "+s); + return s; + } + + public void toggleGridView(ActionEvent ae) + { + log.info("called"); + gridView=!gridView; + } +} diff --git a/serverApps/src/jsf/WEB-INF/faces-config.xml b/serverApps/src/jsf/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..abd0d0283b --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/faces-config.xml @@ -0,0 +1,35 @@ + + + + + + + + + en_US + + org.compiere.jsf.DynamicFieldVariableResolver + org.compiere.jsf.DynamicActionListenerVariableResolver + org.compiere.jsf.DynamicFieldPropertyResolver + org.compiere.jsf.DynamicActionListenerPropertyResolver + + + + menuBean + org.compiere.jsf.MenuBean + request + + + + uiStateBean + org.compiere.jsf.UIStateBean + request + + + + treeBacker + org.compiere.jsf.backing.TreeBacker + request + + + diff --git a/serverApps/src/jsf/WEB-INF/web.xml b/serverApps/src/jsf/WEB-INF/web.xml new file mode 100644 index 0000000000..48a08599f5 --- /dev/null +++ b/serverApps/src/jsf/WEB-INF/web.xml @@ -0,0 +1,66 @@ + + + + + + + log4jInitServlet + org.compiere.jsf.Log4JInitServlet + + log4j-init-file + WEB-INF/classes/log4j.xml + + 1 + + + + + adempiereInitServlet + + org.compiere.jsf.AdempiereInitServlet + + 1 + + + + jsfFilter + org.compiere.jsf.JSFFilter + + + jsfFilter + /window/* + + + + extensionsFilter + + + org.apache.myfaces.webapp.filter.ExtensionsFilter + + + + + extensionsFilter + *.jsf + + + + extensionsFilter + /faces/myFacesExtensionResource/* + + + + facesServlet + javax.faces.webapp.FacesServlet + 1 + + + facesServlet + /faces/* + + + facesServlet + *.jsf + + + diff --git a/serverApps/src/jsf/css/ThemeCompiere/theme.css b/serverApps/src/jsf/css/ThemeCompiere/theme.css new file mode 100644 index 0000000000..9384b01eda --- /dev/null +++ b/serverApps/src/jsf/css/ThemeCompiere/theme.css @@ -0,0 +1,294 @@ +/* ThemeAdempiereMenu Style Sheet */ + +.ThemeAdempiereMenu,.ThemeAdempiereSubMenuTable +{ + font-family: verdana, arial, sans-serif; + font-size: 13px; + + padding: 0; + + white-space: nowrap; + cursor: default; +} + +.ThemeAdempiereSubMenu +{ + position: absolute; + visibility: hidden; + + /* + Netscape/Mozilla renders borders by increasing + their z-index. The following line is necessary + to cover any borders underneath + */ + z-index: 100; + border: 0; + padding: 0; + + overflow: visible; + border: 1px solid #8C867B; + + filter:progid:DXImageTransform.Microsoft.Shadow(color=#BDC3BD, Direction=135, Strength=4); +} + +.ThemeAdempiereSubMenuTable +{ + overflow: visible; +} + +.ThemeAdempiereMainItem,.ThemeAdempiereMainItemHover,.ThemeAdempiereMainItemActive, +.ThemeAdempiereMenuItem,.ThemeAdempiereMenuItemHover,.ThemeAdempiereMenuItemActive +{ + border: 0; + cursor: default; + white-space: nowrap; +} + +.ThemeAdempiereMainItem +{ + + /*background-color: BLUE;*/ +} + +.ThemeAdempiereMainItemHover,.ThemeAdempiereMainItemActive +{ + background-color: #C6D3EF; +} + +.ThemeAdempiereMenuItem +{ + background-color: WHITE; +} + +.ThemeAdempiereMenuItemHover,.ThemeAdempiereMenuItemActive +{ + background-color: #C6D3EF; +} + + +/* horizontal main menu */ + +.ThemeAdempiereMainItem +{ + padding: 1px; + border: 0; +} + +td.ThemeAdempiereMainItemHover,td.ThemeAdempiereMainItemActive +{ + padding: 0px; + border: 1px solid #3169C6; +} + +.ThemeAdempiereMainFolderLeft,.ThemeAdempiereMainItemLeft, +.ThemeAdempiereMainFolderText,.ThemeAdempiereMainItemText, +.ThemeAdempiereMainFolderRight,.ThemeAdempiereMainItemRight +{ + background-color: inherit; +} + +/* vertical main menu sub components */ + +td.ThemeAdempiereMainFolderLeft,td.ThemeAdempiereMainItemLeft +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 0px; + padding-right: 2px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + border-left: 1px solid #3169C6; + + background-color: inherit; +} + +td.ThemeAdempiereMainFolderText,td.ThemeAdempiereMainItemText +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 5px; + padding-right: 5px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + + background-color: inherit; + white-space: nowrap; +} + +td.ThemeAdempiereMainFolderRight,td.ThemeAdempiereMainItemRight +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 0px; + padding-right: 0px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + border-right: 1px solid #3169C6; + + background-color: inherit; +} + +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainFolderLeft, +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainItemLeft +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 1px; + padding-right: 2px; + + white-space: nowrap; + + border: 0; + background-color: inherit; +} + +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainFolderText, +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainItemText +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 5px; + padding-right: 5px; + + border: 0; + background-color: inherit; +} + +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainItemRight, +tr.ThemeAdempiereMainItem td.ThemeAdempiereMainFolderRight +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 0px; + padding-right: 1px; + + border: 0; + background-color: inherit; +} + +/* sub menu sub components */ + +.ThemeAdempiereMenuFolderLeft,.ThemeAdempiereMenuItemLeft +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 1px; + padding-right: 3px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + border-left: 1px solid #3169C6; + + background-color: inherit; + white-space: nowrap; +} + +.ThemeAdempiereMenuFolderText,.ThemeAdempiereMenuItemText +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 5px; + padding-right: 5px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + + background-color: inherit; + white-space: nowrap; +} + +.ThemeAdempiereMenuFolderRight,.ThemeAdempiereMenuItemRight +{ + padding-top: 2px; + padding-bottom: 2px; + padding-left: 0px; + padding-right: 0px; + + border-top: 1px solid #3169C6; + border-bottom: 1px solid #3169C6; + border-right: 1px solid #3169C6; + + background-color: inherit; + white-space: nowrap; +} + +.ThemeAdempiereMenuItem .ThemeAdempiereMenuFolderLeft, +.ThemeAdempiereMenuItem .ThemeAdempiereMenuItemLeft +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 2px; + padding-right: 3px; + + white-space: nowrap; + + border: 0; + /* FIXME: pick a neutral color here or sync with the background */ + background-color: #cfcfcf; +} + +.ThemeAdempiereMenuItem .ThemeAdempiereMenuFolderText, +.ThemeAdempiereMenuItem .ThemeAdempiereMenuItemText +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 5px; + padding-right: 5px; + + border: 0; + background-color: inherit; +} + +.ThemeAdempiereMenuItem .ThemeAdempiereMenuFolderRight, +.ThemeAdempiereMenuItem .ThemeAdempiereMenuItemRight +{ + padding-top: 3px; + padding-bottom: 3px; + padding-left: 0px; + padding-right: 1px; + + border: 0; + background-color: inherit; +} + +/* menu splits */ + +.ThemeAdempiereMenuSplit +{ + margin: 2px; + height: 1px; + overflow: hidden; + background-color: inherit; + border-top: 1px solid #C6C3BD; +} + +/* image shadow animation */ + +/* + seq1: image for normal + seq2: image for hover and active + + To use, in the icon field, input the following: + +*/ + +.ThemeAdempiereMenuItem img.seq1 +{ + display: inline; +} + +.ThemeAdempiereMenuItemHover seq2, +.ThemeAdempiereMenuItemActive seq2 +{ + display: inline; +} + +.ThemeAdempiereMenuItem .seq2, +.ThemeAdempiereMenuItemHover .seq1, +.ThemeAdempiereMenuItemActive .seq1 +{ + display: none; +} diff --git a/serverApps/src/jsf/css/adempiere.css b/serverApps/src/jsf/css/adempiere.css new file mode 100644 index 0000000000..54bd335086 --- /dev/null +++ b/serverApps/src/jsf/css/adempiere.css @@ -0,0 +1,730 @@ +/***********************************************/ +/* HTML tag styles */ +/********************************************** */ + +body{ + font-family: Arial, sans-serif; + color: #000000; + line-height: normal; + margin: 0px; + padding: 0px; + background-image: url(../images/page_bkgd3.jpg); + background-color: #FFFFFF; + background-repeat: repeat-x; +} +a{ + color: #006699; + text-decoration: none; +} +a:link{ + color: #006699; + text-decoration: none; + font-weight: normal; +} +a:visited{ + color: #006699; + font-weight: normal; + text-decoration: none; +} +a:hover{ + color: #006699; + text-decoration: underline; +} +h1, h2, h3, h4, h5, h6, h7 { + font-family: Arial,sans-serif; + margin: 0px; + padding: 0px; +} +ul{ + list-style-type: square; + list-style-position: inside; + margin-right: 10px; +} +ul ul{ + list-style-type: disc; +} +ul ul ul{ + list-style-type: none; +} +label{ + color: #333333; + font-family: Arial,sans-serif; + font-size: 80%; +} +ol{ + list-style-position: inside; + margin-right: 10px; +} +img{ +text-decoration: none; +} +/***********************************************/ +/* Layout Divs */ +/***********************************************/ + +/************** #container div styles ************* */ +#indexProductbar{ + padding: 0px; + background-color: #FFFFFF; + width: 160px; + float: left; +} +#content{ + float:right; + width: 596px; + margin: 0px 0px 0px 0px; + color:#333333; + padding: 0px 0px 0px 0px; +} +#indexContent{ + width: 419px; + margin: 0px 0px 0px 0px; + color:#333333; + padding: 0px 0px 0px 0px; + background-color: #FFFFFF; + float: left; +} +#fullcontent{ + width: 760px; + margin: 0px 0px 0px 0px; + color:#333333; + padding: 0px 0px 0px 0px; +} +#leftPod{ + float: left; + margin: 0px; + padding: 0px; + background-repeat: no-repeat; + height: 320px; + width: 160px; + background-image: url(/images/adempiere_guy.jpg); +} +#leftPod2{ + width: 127px; + margin: 0px; + padding: 7px 0px 0px 2px; + background-image: url(../images/title_bkgd.jpg); + height: 23px; + float: left; + border-left: solid #CCCCCC 1px; + border-right: solid #CCCCCC 1px; + border-top: solid #CCCCCC 1px; +} +#leftPod3{ + width: 129px; + padding: 0px 0px 0px 0px; + text-align: center; + float: left; + border-right: solid #CCCCCC 1px; + border-left: solid #CCCCCC 1px; +} +#leftPod4{ + float: none; + margin: 0px; + padding: 0px; + width: 129px; + background-color: #FFFFFF; +} +#rightPod{ + float:right; + width: 100%; + border-left: 1px solid #cccccc; + border-bottom: 1px solid #cccccc; +} +#rightPod2{ + float:none; + width: 160px; + background-image: url(../images/title_bkgd.jpg); + height: 23px; + text-align: left; + padding: 7px 0px 0px 0px; + background-repeat: no-repeat; +} +#rightPod3{ + float:none; + width: 158px; + text-align: center; + margin: 0px 0px 0px 0px; + background-color: #FFFFFF; +} +#rightPod5{ + float:none; + width: 158px; + text-align: center; + margin: 0px 0px 0px 0px; + background-color: #FFFFFF; + height: 280px; + padding-top: 25px; +} +/************** #topNav styles ************* */ +#topNav{ + position: relative; + top: 4px; + height: 22px; + padding: 0px; + margin: -95px 0px 0px 400px; + left: 5px; + width: 350px; + text-align: right; + font-size: 60%; + vertical-align: middle; +} +#topLink{ + position: relative; + top: 4px; + height: 22px; + padding: 0px; + margin: 0px; + left: 190px; + width: 500px; +} +a.toplink, a.toplink:visited{ + color: #003366; + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: none; + border-right-width: 1px; + border-right-style: solid; + border-right-color: #999999; +} +a.toplink:hover{ + color: #003366; + font-weight: bold; + text-decoration: underline; +} +a.alttoplink, a.alttoplink:visited{ + color: #003366; + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: none; +} +a.alttoplink:hover{ + color: #003366; + font-weight: bold; + text-decoration: underline; +} + +/************* #globalNav styles ************* */ + +#globalNav{ + color: #003366; + white-space: nowrap; + background-image: url(../images/navbar_adempiere.jpg); + background-repeat: no-repeat; + font-family: Arial, Helvetica, sans-serif; + height: 28px; + width: 100%; +} +#globalNav img{ + display: block; +} +#globalNav a { + font-size: 90%; + padding: 0 4px 0 0; +} +#globalLink{ + position: relative; + top: 4px; + height: 22px; + padding: 0px; + margin: 0px; + left: 190px; + width: 400px; +} +a.glink, a.glink:visited{ + font-size: small; + color: #99FFFF; + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: none; + border-right-width: 0px; + border-right-style: solid; + border-right-color: #999999; +} +a.glink:hover{ + color: #FFFFFF; + text-decoration: none; +} +a.altlink, a.altlink:visited{ + font-size: small; + color: #99FFFF; + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: none; +} +a.altlink:hover{ + color: #FFFFFF; + text-decoration: none; +} + +/************** #tabNav styles ************* */ + +#tabNav{ + position: relative; + padding: -10px 0px 5px 20px; + margin: 0px; + left: 25px; + width: 520px; +} +a.tabNav, a.tabNav:visited{ + color: #ffffff; + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: underline; +} +a.tabNav:hover{ + color: #ffffff; + font-weight: bold; + text-decoration: underline; +} +/************** Header styles ************* */ +#masthead{ + width: 100%; + border-bottom: 1px solid #cccccc; +} +#header{ + font-family: Arial, Helvetica, sans-serif; + height: 94px; + width: 100%; + margin: 0; + background-color: #0099CC; + background-image: url(../images/adempiere_5a.jpg); + background-repeat: no-repeat; + + font-weight: bolder; + } +#logoHeader{ + font-family: Arial, Helvetica, sans-serif; + height: 94px; + width: 100%; + z-index: 10; +} +#navBar{ + padding: 0px; + background-color: #eeeeee; + width: 159px; +} +#fullheightcontainer{ + margin-left:auto; + margin-right:auto; + position:inherit; + width:760px; + height:100%; + background-color: #FFFFFF; +} +#wrapper{ + min-height:100%; + height:100%; + background:#FFFFFF; +} +#wrapp\65 r{ + height:auto; +} +* html #wrapper{ + height:100%; + width: 760px; + background-color: #FFFFFF; +} +#outer{ + z-index:1; + position:relative; + margin-left:160px; + width:440px; + background:#FFFFFF; + height:100%; +} +/***********************************************/ +/* Components */ +/***********************************************/ + +/*************** title styles ************* */ +#index1{ + text-align: center; + background-color: #FFFFFF; + color: #003366; + font-weight: bolder; + font-size: 1.2em; + height: auto; + padding-top: 10px; +} +#index2{ + text-align: right; + background-color: #FFFFFF; + color: #0099cc; + font-weight: bold; + font-size: .9em; + padding-right: 10px; + height: auto; + margin-top: 0px; +} +#index3{ + text-align: left; + color: #003366; + font-weight: bold; + font-size: 1.0em; +} +#pageName{ + margin: 25px 0px 0px 5px; + padding: 0px 0px 0px 20px; + color: #003366; + font-size: 150%; +} +#pageNameimg{ + margin: 5px 0px 20px 25px; + padding: 0px 0px 0px 0px; +} +#sectionTitle{ + font-weight: bold; + color: #003366; + margin: 0px 0px 0px 0px; + padding: 10px 0px 10px 10px; +} +#sectionTitle2{ + font-size: 90%; + font-weight: bold; + color: #003366; + margin: 0px 0px 0px 0px; + padding: 5px 0px 10px 0px; +} +#storyTitle1{ + font-size: 115%; + font-weight: bold; + color: #003366; + margin: 20px 10px 10px 25px; + padding: 0px; +} +#storyTitle2{ + font-size: 105%; + font-weight: bold; + color: #333333; + margin: 0px 0px 10px 30px; + padding: 0px; +} +#storyTabletitle1{ + font-size: 105%; + font-weight: bold; + color: #333333; + margin: 0px 0px 5px 15px; + padding: 0px; +} +#storyTabletitle2{ + font-size: 115%; + font-weight: bold; + color: #003366; + margin: 0px 0px 10px 0px; + padding: 0px; +} +#dynamicTitle{ + font-size: 100%; + font-weight: bolder; + color: #333333; + margin: 0px 0px 0px 0px; + padding: 0px 0px 0px 3px; +} +#siteMap1{ + font-size: 120%; + font-weight: bold; + color: #006699; + margin: 20px 15px 10px 25px; + padding: 0px; +} +#siteMap2{ + font-size: 90%; + font-weight: bold; + color: #006699; + margin: 0px 0px 5px 40px; + padding: 0px; + font-style: normal; +} +#aboutNav{ + position: relative; + top: 4px; + height: 22px; + padding: 4px 0px 0px 0px; + margin: 2px 0px 8px 0px; + width: 410px; + text-align: center; + font-size: 90%; + vertical-align: middle; +} +a.aboutNav, a.aboutNav:visited{ + font-weight: bold; + margin: 0px; + padding: 2px 5px 4px 5px; + text-decoration: underline; +} +a.aboutNav:hover{ + font-weight: bold; + text-decoration: underline; +} +/************* #breadCrumb styles *************/ + +#breadCrumb{ + font-size: 70%; + margin: 5px 0px 0px 20px; +} + + +/************** .centerPod styles ***************/ + +.centerPod{ + padding: 0px 0px 0px 0px; + font-size: 0.91em; + background-color: #FFFFFF; + margin: 0px 0px 0px 0px; +} +.centerPod2{ + background-image: url(../images/title_bkgd.jpg); + height: 31px; +} +.centerPod3{ +} +/************** .story styles *****************/ + +.story{ + font-size: 80%; + width: 100%; +} +.story p{ + padding: 0px 0px 10px 0px; + margin: 0px 20px 0px 35px; +} +#storyImg{ + margin: 10px 10px 10px 30px; + text-align: center; +} +.story a{ + text-decoration:underline +} +.story a:visited{ + text-decoration:underline +} +.story a:hover{ + text-decoration: underline; +} +#storySidebar{ + float:right; + width: 158px; + text-align: left; + margin: 0px 1px 10px 10px; + background-color: #FFFFFF; + border: 1px solid #cccccc; +} +/************** .webStore styles *****************/ +#webStorecontent{ + float:right; + width: 750px; + margin: 0px 0px 0px 0px; + color:#333333; + padding: 0px 10px 0px 0px; +} +.webStore{ + font-size: 80%; + width: 100%; +} +.webStore p{ + padding: 0px 0px 10px 0px; + margin: 0px 20px 0px 35px; +} +/************* #siteInfo styles ***************/ + +#siteInfo{ + clear: both; + font-size: 75%; + color: #999999; + padding: 5px 5px 5px 5px; + text-align: center; + border-top: 1px solid #cccccc; +} + +/************* #search styles ***************/ + +#search{ + padding: 5px 0px 5px 10px; + font-size: 90%; + margin-top: -24px; + margin-left: 596px; +} +#search form{ + margin: 0px; + padding: 0px; +} +#search label{ + display: block; + margin: 0px; + padding: 0px; +} +#searchStore{ + padding: 5px 0px 5px 10px; + font-size: 90%; + margin-top: -24px; + margin-left: 30px; +} +/*********** #navBar link styles ***********/ + +#navBar ul a:link, #navBar ul a:visited{ +display: block; +} +#navBar ul { +list-style: none; margin: 0; padding: 0; +} +#navBar li {border-bottom: 1px solid #EEE;} +html>body #navBar li {border-bottom: none;} + +/*********** leftNav styles ***********/ + +#sectionLinks{ + position: relative; + margin: 0px; + padding: 0px; + font-size: 88%; + border-right: 1px solid #cccccc; + border-bottom: 1px solid #cccccc; +} +#sectionLinks h3{ + padding: 10px 0px 2px 10px; +} +#sectionLinks a:link{ + padding: 2px 0px 2px 10px; + border-top: 1px solid #cccccc; + width: auto; + voice-family: "\"}\""; + voice-family:inherit; + width: auto; +} +#sectionLinks a:visited{ + border-top: 1px solid #cccccc; + padding: 2px 0px 2px 10px; +} +#sectionLinks a:hover{ + border-top: 1px solid #cccccc; + background-color: #dddddd; + padding: 2px 0px 2px 10px; +} +#lnavFade{ + width: 160px; + border: 0px; + height: 100px; + background-color: #FFFFFF; + background-image: url(../images/lnav_fade.jpg); +} +/*********** #login styles ***********/ +#login{ + position: relative; + margin: 0px; + padding: 10px 0px 10px 10px; + background-color: #FFFFFF; + border-right: 1px solid #cccccc; +} +#loginNew{ + font-family: Arial, sans-serif; + color: #FF0000; + font-size: 80%; + text-align: left; + background-color: #FFFFFF; + padding: 10px 0px 10px 10px; + border-right: 1px solid #cccccc; +} + +/*********** #subscribe styles ***********/ +#subscribe{ + text-align: left; + background-color: #eeeeee; + padding: 10px 0px 10px 10px; + border-right: 1px solid #cccccc; + border-top: 1px solid #cccccc; +} +#subscribeLink{ + font-family: Arial, sans-serif; + color: #FF0000; + font-size: 90%; + padding-right: 5px; +} +#subscribeLink ul a:link, #navBar ul a:visited, #navBar ul a:link{ + display: block; + color: #006699; +} +#subscribeLink ul { +list-style: none; margin: 0; padding: 0; +} +#subscribeLink li {border-bottom: 1px solid #EEE;} +html>body #subscribeLink li {border-bottom: none;} +/*********** .relatedLinks styles ***********/ + +.relatedLinks{ + position: relative; + margin: 0px; + padding: 0px 0px 10px 10px; + font-size: 80%; + color: #006699; +} +.relatedLinks h3{ + padding: 10px 0px 2px 0px; +} +.relatedLinks a:link, +.relatedLinks a:visited{ + display: block; + color: #000033; +} +.relatedLinks a:hover { + display: block; + color: #000033; + text-decoration: underline; +} +.sitemapLinks1{ + position: relative; + margin: 0px; + padding: 3px 0px 5px 65px; + font-size: 80%; +} +.sitemapLinks2{ + position: relative; + margin: 0px; + padding: 0px 0px 5px 65px; + font-size: 80%; +} +.sitemapLinks3{ + position: relative; + margin: 0px; + padding: 0px 0px 10px 65px; + font-size: 80%; +} +/************** #headlines styles ************* */ + +#headlines{ + margin: 0px; + padding: 0px 0px 0px 0px; + width: 160px; + float: right; + background-color: #FFFFFF; +} +#headlines2{ + margin: 0px; + padding: 0px 0px 0px 0px; + width: 160px; + float: right; + background-color: #FFFFFF; + border-left: solid #CCCCCC 1px; + border-right: solid #CCCCCC 1px; + border-top: solid #CCCCCC 1px; +} +#headlines3{ + margin: 0px; + padding: 0px 0px 0px 0px; + width: 162px; + float: right; + background-color: #FFFFFF; +} +#headlines p{ + padding: 5px 0px 5px 0px; +} +/************** #table styles ************* */ +#tableText{ + color: #333333; + font-size: 0.7em; +} diff --git a/serverApps/src/jsf/css/iconToolbar.css b/serverApps/src/jsf/css/iconToolbar.css new file mode 100644 index 0000000000..897b5d7fe2 --- /dev/null +++ b/serverApps/src/jsf/css/iconToolbar.css @@ -0,0 +1,20 @@ +.mainDocumentStyle { + background-color: #cfcfcf; +} + +/* used in toolbar buttons */ +.iconButtonStyle { + background-color: #cfcfcf; + border: 3px groove #e0e0e0; + margin: 0px; +} + +.rightLabel { + text-align: right; + white-space: nowrap; +} + +.leftLabel { + text-align: left; + white-space: nowrap; +} diff --git a/serverApps/src/jsf/css/misc.css b/serverApps/src/jsf/css/misc.css new file mode 100644 index 0000000000..c5811bba8d --- /dev/null +++ b/serverApps/src/jsf/css/misc.css @@ -0,0 +1,22 @@ +/* pink background for required but empty fields */ +.requiredTextField { + background-color: #ffd6dd; +} + +/* the blue background for filled required fields */ +.filledTextField { + background-color: #9191ff; +} + +/* orange like the title says */ +.orangeTextField { + background-color: #ffc55c; +} + +.fixedWidthInputText { + width: 15em; +} + +.fillCellTableView { + width: 100%; +} diff --git a/serverApps/src/jsf/css/tab.css b/serverApps/src/jsf/css/tab.css new file mode 100644 index 0000000000..0c9f8cd2b9 --- /dev/null +++ b/serverApps/src/jsf/css/tab.css @@ -0,0 +1,50 @@ +/* +if you could do multiple inheritance in css this would be perfect for it + not every aspect of this setup is as styled as it should be; + the buttons aren't properly squished together +*/ + +.baseParentTabStyle { + background-color: inherit; + width: 115px; +} + +/* indented first level style tab button */ +.baseIndentOneTabStyle { + background-color: inherit; + width: 100px; +} + +.baseIndentTwoTabStyle { + background-color: inherit; + width: 85px; +} + +.selectedTabStyle { + border-left: 2px inset; + border-top: 2px inset; + border-bottom: 2px inset; + border-right: none; +} + +.unselectedTabStyle { + border: 2px outset; +} + +/* inherits from selectedTabStyle */ +.selectedMouseOverTabStyle { + color: WHITE; + border-left: 2px inset BLACK; + border-top: 2px inset BLACK; + border-bottom: 2px inset BLACK; + border-right: none; +} + +.unselectedMouseOverTabStyle { + color: WHITE; + border: 2px outset BLACK; +} + +.childTab { + padding-left: 15px; +} diff --git a/serverApps/src/jsf/css/wideTable.css b/serverApps/src/jsf/css/wideTable.css new file mode 100644 index 0000000000..c287581932 --- /dev/null +++ b/serverApps/src/jsf/css/wideTable.css @@ -0,0 +1,21 @@ +.wideTableStyle { + table-layout: fixed; + border-style: solid; + border-width: 1px; +} + +.wideTableHeaderStyle { + white-space: nowrap; + border-right: solid; + border-left: solid; + border-width: 1px; +} +wideTableRowStyle { + border-style: solid; + border-width: 1px; +} + +.wideTableCellStyle { + border-style: solid; + border-width: 1px; +} diff --git a/serverApps/src/jsf/javaScript/aa.js b/serverApps/src/jsf/javaScript/aa.js new file mode 100644 index 0000000000..93901abdeb --- /dev/null +++ b/serverApps/src/jsf/javaScript/aa.js @@ -0,0 +1,764 @@ +/* +Copyright 2005 Vitaliy Shevchuk (shevit@users.sourceforge.net) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +AjaxAnywhere.defaultInstanceName = "default"; + +// constructor; +function AjaxAnywhere() { + + this.id = AjaxAnywhere.defaultInstanceName; + this.formName = null; + this.notSupported = false; + this.delayBeforeContentUpdate = true; + this.delayInMillis = 100; + + if (window.XMLHttpRequest) { + this.req = new XMLHttpRequest(); + } else if (window.ActiveXObject) { + try { + this.req = new ActiveXObject("Msxml2.XMLHTTP"); + } catch(e) { + try { + this.req = new ActiveXObject("Microsoft.XMLHTTP"); + } catch(e1) { + this.notSupported = true; + /* XMLHTTPRequest not supported */ + } + } + } + + if (this.req == null || typeof this.req == "undefined") + this.notSupported = true; +} + +/** +* Stores substitutes SubmitButton names in to redo sustitution if a button was eventually inside a refresh zone. +*/ +AjaxAnywhere.prototype.substitutedSubmitButtons = new Array(); +AjaxAnywhere.prototype.substitutedSubmitButtonsInfo = new Object(); + +/** +* Returns a Form object that corresponds to formName property of this AjaxAnywhere class instance. +*/ +AjaxAnywhere.prototype.findForm = function () { + var form; + if (this.formName != null) + form = document.forms[this.formName]; + else if (document.forms.length > 0) + form = document.forms[0]; + + if (typeof form != "object") + alert("AjaxAnywhere error: Form with name [" + this.formName + "] not found"); + return form; +} + + +/** +* Binds this instance to window object using "AjaxAnywhere."+this.id as a key. +*/ +AjaxAnywhere.prototype.bindById = function () { + var key = "AjaxAnywhere." + this.id; + window[key] = this; +} + +/** +* Finds an instance by id. +*/ +AjaxAnywhere.findInstance = function(id) { + var key = "AjaxAnywhere." + id; + return window[key]; +} + +/** +* This function is used to submit all form fields by AJAX request to the server. +* If the form is submited with <input type=submit|image>, submitButton should be a reference to the DHTML object. Otherwise - undefined. +*/ +AjaxAnywhere.prototype.submitAJAX = function(additionalPostData, submitButton) { + + if (this.notSupported) + return this.onSubmitAjaxNotSupported(additionalPostData, submitButton); + + if (additionalPostData == null || typeof additionalPostData == "undefined") + additionalPostData = ""; + + this.bindById(); + + var form = this.findForm(); + + var actionAttrNode = form.attributes["action"].nodeValue; + var url = actionAttrNode == null?null:actionAttrNode.nodeValue; + if ((url == null) || (url == "")) + url = location.href; + + var pos = url.indexOf("#"); + if (pos!=-1) + url = url.substring(0,pos); + if ((url == null) || (url == "")) + url = location.href; + pos = url.indexOf("#"); + if (pos!=-1) + url = url.substring(0,pos); + + var zones = this.getZonesToReload(url, submitButton); + + if (zones == null) { + // submit in tradiditional way : + this.submitOld(form,submitButton) + return; + } + + this.dropPreviousRequest(); + + this.req.open("POST", url, true); + this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + this.req.setRequestHeader("Accept", "text/xml"); + + var postData = this.preparePostData(submitButton); + + if (zones != "") + postData = '&aazones=' + encodeURIComponent(zones) + "&" + postData + "&" + additionalPostData; + else + postData += "&" + additionalPostData; + + this.sendPreparedRequest(postData); + +} +/** +* sends a GET request to the server. +*/ +AjaxAnywhere.prototype.getAJAX = function(url, zonesToRefresh) { + if (this.notSupported) + return this.onGetAjaxNotSupported(url); + + this.bindById(); + + if (zonesToRefresh == null || typeof zonesToRefresh == "undefined") + zonesToRefresh = ""; + var urlDependentZones = this.getZonesToReload(url); + if (urlDependentZones == null) { + location.href = url; + return; + } + + if (urlDependentZones.length != 0) + zonesToRefresh += "," + urlDependentZones; + + this.dropPreviousRequest(); + + url += (url.indexOf("?") != -1) ? "&" : "?"; + + url += "aaxmlrequest=true&aa_rand=" + Math.random(); + // avoid caching + + if (zonesToRefresh != null && zonesToRefresh != "") + url += '&aazones=' + encodeURIComponent(zonesToRefresh); + + this.req.open("GET", url, true); + this.req.setRequestHeader("Accept", "text/xml"); + + this.sendPreparedRequest(""); +} + +/** +* @private +*/ +AjaxAnywhere.prototype.sendPreparedRequest = function (postData) { + var callbackKey = this.id + "_callbackFunction"; + if (typeof window[callbackKey] == "undefined") + window[callbackKey] = new Function("AjaxAnywhere.findInstance(\"" + this.id + "\").callback(); "); + this.req.onreadystatechange = window[callbackKey]; + + this.showLoadingMessage(); + + this.req.send(postData); +} +/** +* Used internally by AjaxAnywhere. Aborts previous request if not completed. +*/ +AjaxAnywhere.prototype.dropPreviousRequest = function() { + if (this.req.readyState != 0 && this.req.readyState != 4) { + // abort previous request if not completed + this.req.abort(); + this.handlePrevousRequestAborted(); + } +} + +/** +* Internally used to prepare Post data. +* If the form is submited with <input type=submit|image>, submitButton is a reference to the DHTML object. Otherwise - undefined. +*/ +AjaxAnywhere.prototype.preparePostData = function(submitButton) { + var form = this.findForm(); + var result = "&aaxmlrequest=true"; + for (var i = 0; i < form.elements.length; i++) { + var el = form.elements[i]; + if (el.tagName.toLowerCase() == "select") { + for (var j = 0; j < el.options.length; j++) { + var op = el.options[j]; + if (op.selected) + result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(op.value); + } + } else if (el.tagName.toLowerCase() == "textarea") { + result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value); + } else if (el.tagName.toLowerCase() == "input") { + if (el.type.toLowerCase() == "checkbox" || el.type.toLowerCase() == "radio") { + if (el.checked) + result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value); + } else if (el.type.toLowerCase() == "submit") { + if (el == submitButton) // is "el" the submit button that fired the form submit? + result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value); + } else if (el.type.toLowerCase() != "button") { + result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value); + } + } + } + if (typeof submitButton != 'undefined' && submitButton != null && submitButton.type.toLowerCase() == "image") { + if (submitButton.name == null || submitButton.name == "" || typeof submitButton.name == "undefined") + result += "&x=1&y=1"; // .x and .y coordinates calculation is not supported. + else + result += "&" + encodeURIComponent(submitButton.name) + ".x=1&" + + encodeURIComponent(submitButton.name) + ".y=1"; + } + return result; +} + +/** +* Pauses the thread of execution for the specified number of milliseconds +* @private +*/ +function delay(millis) { + date = new Date(); + var curDate = null; + do { + curDate = new Date(); + } + while (curDate - date < millis); +} + +/** +* A callback. internally used +*/ +AjaxAnywhere.prototype.callback = function() { + + if (this.req.readyState == 4) { + + this.onBeforeResponseProcessing(); + this.hideLoadingMessage(); + + if (this.req.status == 200) { + + if (this.req.getResponseHeader('content-type').toLowerCase().substring(0, 8) != 'text/xml') + alert("AjaxAnywhere error : content-type in not text/xml : [" + this.req.getResponseHeader('content-type') + "]"); + + var docs = this.req.responseXML.getElementsByTagName("document"); + var redirects = this.req.responseXML.getElementsByTagName("redirect"); + var zones = this.req.responseXML.getElementsByTagName("zone"); + var exceptions = this.req.responseXML.getElementsByTagName("exception"); + var scripts = this.req.responseXML.getElementsByTagName("script"); + var images = this.req.responseXML.getElementsByTagName("image"); + + if (redirects.length != 0) { + var newURL = redirects[0].firstChild.data; + location.href = newURL; + } + if (docs.length != 0) { + var newContent = docs[0].firstChild.data; + + //cleanup ressources + delete this.req; + + document.close(); + document.write(newContent); + document.close(); + } + + if (images.length != 0) { + var preLoad = new Array(images.length); + for (var i = 0; i < images.length; i++) { + var img = images[i].firstChild; + if (img != null) { + preLoad[i] = new Image(); + preLoad[i].src = img.data; + } + } + if (this.delayBeforeContentUpdate) { + delay(this.delayInMillis); + } + } + + if (zones.length != 0) { + for (var i = 0; i < zones.length; i++) { + var zoneNode = zones[i]; + + var name = zoneNode.getAttribute("name"); + var id = zoneNode.getAttribute("id"); + + var fc = zoneNode.firstChild; + + var html = (fc == null)?"":fc.data; + + var zoneHolder = name!=null? + document.getElementById("aazone." + name): + document.getElementById(id); + + if (zoneHolder != null && typeof(zoneHolder) != "undefined") { + zoneHolder.innerHTML = html; + } + + } + } + if (exceptions.length != 0) { + var e = exceptions[0]; + var type = e.getAttribute("type"); + var stackTrace = e.firstChild.data; + this.handleException(type, stackTrace); + } + + if (scripts.length != 0) { + for (var $$$$i = 0; $$$$i < scripts.length; $$$$i++) { + // use $$$$i variable to avoid collision with "i" inside user script + var script = scripts[$$$$i].firstChild; + if (script != null) { + script = script.data; + if (script.indexOf("document.write") != -1) { + this.handleException("document.write", "This script contains document.write(), which is not compatible with AjaxAnywhere : \n\n" + script); + } else { + eval(script); + } + } + } + + var globals = this.getGlobalScriptsDeclarationsList(script); + if (globals != null) + for (var i in globals) { + var objName = globals[i]; + try { + window[objName] = eval(objName); + } catch(e) { + } + } + } + + } else { + if (this.req.status != 0) + this.handleHttpErrorCode(this.req.status); + } + this.restoreSubstitutedSubmitButtons(); + this.onAfterResponseProcessing(); + + } + + +} + +/** +* Default sample loading message show function. Overrride it if you like. +*/ +AjaxAnywhere.prototype.showLoadingMessage = function() { + + var div = document.getElementById("AA_" + this.id + "_loading_div"); + if (div == null) { + div = document.createElement("DIV"); + + document.body.appendChild(div); + div.id = "AA_" + this.id + "_loading_div"; + + div.innerHTML = " Loading..."; + div.style.position = "absolute"; + div.style.border = "1 solid black"; + div.style.color = "white"; + div.style.backgroundColor = "blue"; + div.style.width = "100px"; + div.style.heigth = "50px"; + div.style.fontFamily = "Arial, Helvetica, sans-serif"; + div.style.fontWeight = "bold"; + div.style.fontSize = "11px"; + } + div.style.top = document.body.scrollTop + "px"; + div.style.left = (document.body.offsetWidth - 100 - (document.all?20:0)) + "px"; + + div.style.display = ""; +} + +/** +* Default sample loading message hide function. Overrride it if you like. +*/ +AjaxAnywhere.prototype.hideLoadingMessage = function() { + var div = document.getElementById("AA_" + this.id + "_loading_div"); + if (div != null) + div.style.display = "none"; + +} + +/** +* This function is used to facilitatte AjaxAnywhere integration with existing projects/frameworks. +* It substitutes default Form.sumbit(). +* The new implementation calls AjaxAnywhere.isFormSubmitByAjax() function to find out if the form +* should be submitted in traditional way or by AjaxAnywhere. +*/ +AjaxAnywhere.prototype.substituteFormSubmitFunction = function() { + if (this.notSupported) + return; + + this.bindById(); + + var form = this.findForm(); + + form.submit_old = form.submit; + var code = "var ajax = AjaxAnywhere.findInstance(\"" + this.id + "\"); " + + "if (typeof ajax !='object' || ! ajax.isFormSubmitByAjax() ) " + + "ajax.findForm().submit_old();" + + " else " + + "ajax.submitAJAX();" + form.submit = new Function(code); + +} +/** +* Substitutes the default behavior of <input type=submit|image> to submit the form via AjaxAnywhere. +* +* @param {boolean} indicates if existing onClick handlers should be preserved. +* If keepExistingOnClickHandler==true, +* Existing handler will be called first if it returns false, or if event.returnValue==false, AjaxAnywhere will not +* continue form submission. +* If keepExistingOnClickHandler==false or undefines, existing onClick event handlers will be replaced. +* +* @param {Array} list of submitButtons and submitImages names. If the parameter is omitted or undefined, +* all elements will be processed +*/ +AjaxAnywhere.prototype.substituteSubmitButtonsBehavior = function (keepExistingOnClickHandler, elements) { + if (this.notSupported) + return; + + var form = this.findForm(); + if (elements == null || typeof elements == "undefined") { // process all elements + elements = new Array(); + for (var i = 0; i < form.elements.length; i++) { + elements.push(form.elements[i]); + } + + var inputs = document.getElementsByTagName("input"); + for (var i = 0; i < inputs.length; i++) { + var input = inputs[i]; + if (input.type != null && typeof input.type != "undefined" && + input.type.toLowerCase() == "image" && input.form == form) { + elements.push(input); + } + } + + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el.tagName.toLowerCase() == "input" && (el.type.toLowerCase() == "submit" + || el.type.toLowerCase() == "image")) { + this.substituteSubmitBehavior(el, keepExistingOnClickHandler); + + } + } + } else { //process only specified elements + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el == null) + continue; + + if (typeof el != "object") + el = form.elements[el]; + + if (typeof el != "undefined") { + if (el.tagName.toLowerCase() == "input" && (el.type.toLowerCase() == "submit" + || el.type.toLowerCase() == "image")) + this.substituteSubmitBehavior(el, keepExistingOnClickHandler); + } + } + } + +} +/** +* Performs a single element behavior substitution +* +* @private +*/ +AjaxAnywhere.prototype.substituteSubmitBehavior = function (el, keepExistingOnClickHandler) { + + var inList = false; + for (var i = 0; i < this.substitutedSubmitButtons.length; i++) { + var btnName = this.substitutedSubmitButtons[i]; + if (btnName == el.name) { + inList = true; + break; + } + } + if (!inList) + this.substitutedSubmitButtons.push(el.name); + + this.substitutedSubmitButtonsInfo[el.name] = keepExistingOnClickHandler; + + if (keepExistingOnClickHandler && (typeof el.onclick != "undefined") && ( el.onclick != null) && ( el.onclick != "")) { + el.AA_old_onclick = el.onclick; + } + + el.onclick = handleSubmitButtonClick; + el.ajaxAnywhereId = this.id; +} + +/** +* +* @private +*/ +AjaxAnywhere.prototype.restoreSubstitutedSubmitButtons = function() { + if (this.substitutedSubmitButtons.length == 0) + return; + + var form = this.findForm(); + + for (var i = 0; i < this.substitutedSubmitButtons.length; i++) { + var name = this.substitutedSubmitButtons[i]; + var el = form.elements[name]; + if (el != null && typeof el != "undefined") { + if (el.onclick != handleSubmitButtonClick) { + var keepExistingOnClickHandler = this.substitutedSubmitButtonsInfo[el.name]; + this.substituteSubmitBehavior(el, keepExistingOnClickHandler); + } + } else { + //input type=image + if (name != null && typeof name != "undefined" && name.length != 0) { + var elements = document.getElementsByName(name); + if (elements != null) + for (var j = 0; j < elements.length; j++) { + el = elements[j]; + if (el != null && typeof el != "undefined" + && el.tagName.toLowerCase() == "input" + && typeof el.type != "undefined" && el.type.toLowerCase() == "image") { + if (el.onclick != handleSubmitButtonClick) { + var keepExistingOnClickHandler = this.substitutedSubmitButtonsInfo[el.name]; + this.substituteSubmitBehavior(el, keepExistingOnClickHandler); + } + } + } + } + } + } +} + +/** +* @private +*/ +function handleSubmitButtonClick(_event) { + + if (typeof this.AA_old_onclick != "undefined") { + if (false == this.AA_old_onclick(_event)) + return false; + if (typeof window.event != "undefined") + if (window.event.returnValue == false) + return false; + } + var onsubmit = this.form.onsubmit; + if (typeof onsubmit == "function") { + if (false == onsubmit(_event)) + return false; + if (typeof window.event != "undefined") + if (window.event.returnValue == false) + return false; + } + AjaxAnywhere.findInstance(this.ajaxAnywhereId).submitAJAX('', this); + + return false; +} +/** +* Override this function if you use AjaxAnywhere.substituteFormSubmitFunction() to +* dynamically inform AjaxAnywhere of the method you want to use for the form submission. +*/ +AjaxAnywhere.prototype.isFormSubmitByAjax = function () { + return true; +} + +/** +* Some browsers (notably IE) do not load images from thier cache when content is updated using +* innerHTML. As a result, each image is re-requested from the server even though the image exists +* in the cache. To work around this issue, AjaxAnywhere preloads images present in the new content +* and intrduces a brief dely (default of 100 milleseconds) before calling innerHTML. +* See http://support.microsoft.com/default.aspx?scid=kb;en-us;319546 for further details. +* This function can be used to change this behaviour. +* @param (boolean) isDelay +*/ +AjaxAnywhere.prototype.setDelayBeforeLoad = function (isDelay) { + this.delayBeforeContentUpdate = isDelay; +} + +/** +* Returns the current delay behavior. +*/ +AjaxAnywhere.prototype.isDelayBeforeLoad = function () { + return this.delayBeforeContentUpdate; +} + +/** +* Sets the delay period in milliseconds. The default delay is 100 milliseconds. +* @param (int) delayMillis +*/ +AjaxAnywhere.prototype.setDelayTime = function (delayMillis) { + this.delayInMillis = delayMillis; +} + +/** +* Returns the delay period in milliseconds. +*/ +AjaxAnywhere.prototype.getDelayTime = function () { + return this.delayInMillis; +} + +/** +* If an exception is throws on the server-side during AJAX request, it will be processed +* by this function. The default implementation is alert(stackTrace); +* Override it if you need. +*/ +AjaxAnywhere.prototype.handleException = function(type, details) { + alert(details); +} +/** +* If an HTTP Error code returned during AJAX request, it will be processed +* by this function. The default implementation is alert(code); +* Override it if you need. +*/ +AjaxAnywhere.prototype.handleHttpErrorCode = function(code) { + var details = confirm("AjaxAnywhere default error handler. XMLHttpRequest HTTP Error code:" + code + " \n\n Would you like to view the response content in a new window?"); + if (details) { + var win = window.open("", this.id + "_debug_window"); + if (win != null) { + win.document.write("" + this.req.responseText); + win.document.close(); + win.focus(); + } else { + alert("Please, disable your pop-up blocker for this site first."); + } + } +} + +/** +* Override it if you need. +*/ +AjaxAnywhere.prototype.handlePrevousRequestAborted = function() { + alert("AjaxAnywhere default error handler. INFO: previous AJAX request dropped") +} + + +/** +* If the HTML received in responce to AJAX request contains JavaScript that defines new +* functions/variables, they must be propagated to the proper context. Override this method +* to return the Array of function/variable names. +*/ +AjaxAnywhere.prototype.getGlobalScriptsDeclarationsList = function(script) { + return null; +} + +/** +* This function should be overridden by AjaxAnywhere user to implement client-side +* determination of zones to reload. +* +* If the form is submited with &lt;input type=submit|image&gt;, submitButton is a reference to the DHTML object. Otherwise - undefined. +* +* @Returns a comma separated list of zones to reload, or "document.all" to reload +* the whole page. Returns null if the request must be sent in traditional way +* +*/ +AjaxAnywhere.prototype.getZonesToReload = function(url, submitButton) { + return this.getZonesToReaload(); + // backward compatibility only +} +/** +* depreceted : wrond spelling : Reaload will be removed in later versions +*/ +AjaxAnywhere.prototype.getZonesToReaload = function(url, submitButton) { + return ""; +} + +/** +* Override this method to implement a custom action +*/ +AjaxAnywhere.prototype.onRequestSent = function () { +}; +/** +* Override this method to implement a custom action +*/ +AjaxAnywhere.prototype.onBeforeResponseProcessing = function () { +}; +/** +* Override this method to implement a custom action +*/ +AjaxAnywhere.prototype.onAfterResponseProcessing = function () { +}; + +/** +* Provides a default implementation from graceful degradation for getAJAX() +* calls location.href=url if XMLHttpRequest is unavailable, reloading the entire page . +*/ +AjaxAnywhere.prototype.onGetAjaxNotSupported = function (url) { + location.href = url; + return false; +}; + +/** +* Provides a default implementation from graceful degradation for submitAJAX() +* calls form.submit() if XMLHttpRequest is unavailable, reloading the entire page +*/ +AjaxAnywhere.prototype.onSubmitAjaxNotSupported = function (additionalPostData, submitButton) { + var form = this.findForm(); + + var actionAttrNode = form.attributes["action"].nodeValue; + var url = actionAttrNode == null?null:actionAttrNode.nodeValue; + var url_backup = url; + if (typeof additionalPostData != 'undefined' && additionalPostData != null) { + url += (url.indexOf("?") != -1) ? "&" : "?"; + url += additionalPostData; + form.attributes["action"].nodeValue= url; + // only POST method allows sending additional + // date by altering form action URL. + form.setAttribute("method", "post"); + } + + this.submitOld(form,submitButton); + + form.attributes["action"].nodeValue= url_backup; + return false; +}; +/** +* submit the form in tradiditional way : +* @private +*/ + +AjaxAnywhere.prototype.submitOld = function (form,submitButton){ + var submitHolder = null; + if (submitButton!=null && typeof submitButton!="undefined"){ + submitHolder = document.createElement("input"); + submitHolder.setAttribute("type","hidden"); + submitHolder.setAttribute("name",submitButton.name); + submitHolder.setAttribute("value",submitButton.value); + form.appendChild(submitHolder); + + } + + if (typeof form.submit_old == "undefined") + form.submit(); + else + form.submit_old(); + + if (submitButton!=null ){ + form.removeChild(submitHolder); + } +} + +// default instance. +ajaxAnywhere = new AjaxAnywhere(); +ajaxAnywhere.bindById(); \ No newline at end of file diff --git a/serverApps/src/jsf/js/JSCookMenu.js b/serverApps/src/jsf/js/JSCookMenu.js new file mode 100644 index 0000000000..2f7903d966 --- /dev/null +++ b/serverApps/src/jsf/js/JSCookMenu.js @@ -0,0 +1,923 @@ +/* + JSCookMenu v1.31. (c) Copyright 2002-2005 by Heng Yuan + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + ITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ + +// Globals +var _cmIDCount = 0; +var _cmIDName = 'cmSubMenuID'; // for creating submenu id + +var _cmTimeOut = null; // how long the menu would stay +var _cmCurrentItem = null; // the current menu item being selected; + +var _cmNoAction = new Object (); // indicate that the item cannot be hovered. +var _cmNoClick = new Object (); // similar to _cmNoAction but does not respond to mouseup/mousedown events +var _cmSplit = new Object (); // indicate that the item is a menu split + +var _cmItemList = new Array (); // a simple list of items + +// default node properties +var _cmNodeProperties = +{ + // main menu display attributes + // + // Note. When the menu bar is horizontal, + // mainFolderLeft and mainFolderRight are + // put in <span></span>. When the menu + // bar is vertical, they would be put in + // a separate TD cell. + + // HTML code to the left of the folder item + mainFolderLeft: '', + // HTML code to the right of the folder item + mainFolderRight: '', + // HTML code to the left of the regular item + mainItemLeft: '', + // HTML code to the right of the regular item + mainItemRight: '', + + // sub menu display attributes + + // HTML code to the left of the folder item + folderLeft: '', + // HTML code to the right of the folder item + folderRight: '', + // HTML code to the left of the regular item + itemLeft: '', + // HTML code to the right of the regular item + itemRight: '', + // cell spacing for main menu + mainSpacing: 0, + // cell spacing for sub menus + subSpacing: 0, + // auto disappear time for submenus in milli-seconds + delay: 500 +}; + +////////////////////////////////////////////////////////////////////// +// +// Drawing Functions and Utility Functions +// +////////////////////////////////////////////////////////////////////// + +// +// produce a new unique id +// +function cmNewID () +{ + return _cmIDName + (++_cmIDCount); +} + +// +// return the property string for the menu item +// +function cmActionItem (item, prefix, isMain, idSub, orient, nodeProperties) +{ + // var index = _cmItemList.push (item) - 1; + _cmItemList[_cmItemList.length] = item; + var index = _cmItemList.length - 1; + idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); + orient = '\'' + orient + '\''; + prefix = '\'' + prefix + '\''; + return ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + orient + ',' + index + ')" onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')" onmousedown="cmItemMouseDown (this,' + index + ')" onmouseup="cmItemMouseUp (this,' + index + ')"'; +} + +// +// this one is used by _cmNoClick to only take care of onmouseover and onmouseout +// events which are associated with menu but not actions associated with menu clicking/closing +// +function cmNoClickItem (item, prefix, isMain, idSub, orient, nodeProperties) +{ + // var index = _cmItemList.push (item) - 1; + _cmItemList[_cmItemList.length] = item; + var index = _cmItemList.length - 1; + idSub = (!idSub) ? 'null' : ('\'' + idSub + '\''); + orient = '\'' + orient + '\''; + prefix = '\'' + prefix + '\''; + return ' onmouseover="cmItemMouseOver (this,' + prefix + ',' + isMain + ',' + idSub + ',' + orient + ',' + index + ')" onmouseout="cmItemMouseOut (this,' + nodeProperties.delay + ')"'; +} + +function cmNoActionItem (item, prefix) +{ + return item[1]; +} + +function cmSplitItem (prefix, isMain, vertical) +{ + var classStr = 'cm' + prefix; + if (isMain) + { + classStr += 'Main'; + if (vertical) + classStr += 'HSplit'; + else + classStr += 'VSplit'; + } + else + classStr += 'HSplit'; + var item = eval (classStr); + return cmNoActionItem (item, prefix); +} + +// +// draw the sub menu recursively +// +function cmDrawSubMenu (subMenu, prefix, id, orient, nodeProperties) +{ + var str = '<div class="' + prefix + 'SubMenu" id="' + id + '"><table summary="sub menu" cellspacing="' + nodeProperties.subSpacing + '" class="' + prefix + 'SubMenuTable">'; + var strSub = ''; + + var item; + var idSub; + var hasChild; + + var i; + + var classStr; + + for (i = 5; i < subMenu.length; ++i) + { + item = subMenu[i]; + if (!item) + continue; + + hasChild = (item.length > 5); + idSub = hasChild ? cmNewID () : null; + + str += '<tr class="' + prefix + 'MenuItem"'; + if (item[0] != _cmNoClick) + str += cmActionItem (item, prefix, 0, idSub, orient, nodeProperties); + else + str += cmNoClickItem (item, prefix, 0, idSub, orient, nodeProperties); + str += '>' + + if (item == _cmSplit) + { + str += cmSplitItem (prefix, 0, true); + str += '</tr>'; + continue; + } + + if (item[0] == _cmNoAction || item[0] == _cmNoClick) + { + str += cmNoActionItem (item, prefix); + str += '</tr>'; + continue; + } + + classStr = prefix + 'Menu'; + classStr += hasChild ? 'Folder' : 'Item'; + + str += '<td class="' + classStr + 'Left">'; + + if (item[0] != null) + str += item[0]; + else + str += hasChild ? nodeProperties.folderLeft : nodeProperties.itemLeft; + + str += '<td class="' + classStr + 'Text">' + item[1]; + + str += '<td class="' + classStr + 'Right">'; + + if (hasChild) + { + str += nodeProperties.folderRight; + strSub += cmDrawSubMenu (item, prefix, idSub, orient, nodeProperties); + } + else + str += nodeProperties.itemRight; + str += '</td></tr>'; + } + + str += '</table></div>' + strSub; + return str; +} + +// +// The function that builds the menu inside the specified element id. +// +// @param id id of the element +// orient orientation of the menu in [hv][ab][lr] format +// menu the menu object to be drawn +// nodeProperties properties for each menu node +// +function cmDraw (id, menu, orient, nodeProperties, prefix) +{ + var obj = cmGetObject (id); + + if (!nodeProperties) + nodeProperties = _cmNodeProperties; + if (!prefix) + prefix = ''; + + var str = '<table summary="main menu" class="' + prefix + 'Menu" cellspacing="' + nodeProperties.mainSpacing + '">'; + var strSub = ''; + + if (!orient) + orient = 'hbr'; + + var orientStr = String (orient); + var orientSub; + var vertical; + + // draw the main menu items + if (orientStr.charAt (0) == 'h') + { + // horizontal menu + orientSub = 'v' + orientStr.substr (1, 2); + str += '<tr>'; + vertical = false; + } + else + { + // vertical menu + orientSub = 'v' + orientStr.substr (1, 2); + vertical = true; + } + + var i; + var item; + var idSub; + var hasChild; + + var classStr; + + for (i = 0; i < menu.length; ++i) + { + item = menu[i]; + + if (!item) + continue; + + str += vertical ? '<tr' : '<td'; + str += ' class="' + prefix + 'MainItem"'; + + hasChild = (item.length > 5); + idSub = hasChild ? cmNewID () : null; + + str += cmActionItem (item, prefix, 1, idSub, orient, nodeProperties) + '>'; + + if (item == _cmSplit) + { + str += cmSplitItem (prefix, 1, vertical); + str += vertical? '</tr>' : '</td>'; + continue; + } + + if (item[0] == _cmNoAction || item[0] == _cmNoClick) + { + str += cmNoActionItem (item, prefix); + str += vertical? '</tr>' : '</td>'; + continue; + } + + classStr = prefix + 'Main' + (hasChild ? 'Folder' : 'Item'); + + str += vertical ? '<td' : '<span'; + str += ' class="' + classStr + 'Left">'; + + str += (item[0] == null) ? (hasChild ? nodeProperties.mainFolderLeft : nodeProperties.mainItemLeft) + : item[0]; + str += vertical ? '</td>' : '</span>'; + + str += vertical ? '<td' : '<span'; + str += ' class="' + classStr + 'Text">'; + str += item[1]; + + str += vertical ? '</td>' : '</span>'; + + str += vertical ? '<td' : '<span'; + str += ' class="' + classStr + 'Right">'; + + str += hasChild ? nodeProperties.mainFolderRight : nodeProperties.mainItemRight; + + str += vertical ? '</td>' : '</span>'; + + str += vertical ? '</tr>' : '</td>'; + + if (hasChild) + strSub += cmDrawSubMenu (item, prefix, idSub, orientSub, nodeProperties); + } + if (!vertical) + str += '</tr>'; + str += '</table>' + strSub; + obj.innerHTML = str; + //document.write ("<xmp>" + str + ""); +} + +////////////////////////////////////////////////////////////////////// +// +// Mouse Event Handling Functions +// +////////////////////////////////////////////////////////////////////// + +// +// action should be taken for mouse moving in to the menu item +// +function cmItemMouseOver (obj, prefix, isMain, idSub, orient, index) +{ + clearTimeout (_cmTimeOut); + + if (!obj.cmPrefix) + { + obj.cmPrefix = prefix; + obj.cmIsMain = isMain; + } + + var thisMenu = cmGetThisMenu (obj, prefix); + + // insert obj into cmItems if cmItems doesn't have obj + if (!thisMenu.cmItems) + thisMenu.cmItems = new Array (); + var i; + for (i = 0; i < thisMenu.cmItems.length; ++i) + { + if (thisMenu.cmItems[i] == obj) + break; + } + if (i == thisMenu.cmItems.length) + { + //thisMenu.cmItems.push (obj); + thisMenu.cmItems[i] = obj; + } + + // hide the previous submenu that is not this branch + if (_cmCurrentItem) + { + // occationally, we get this case when user + // move the mouse slowly to the border + if (_cmCurrentItem == thisMenu) + return; + + var thatPrefix = _cmCurrentItem.cmPrefix; + var thatMenu = cmGetThisMenu (_cmCurrentItem, thatPrefix); + if (thatMenu != thisMenu.cmParentMenu) + { + if (_cmCurrentItem.cmIsMain) + _cmCurrentItem.className = thatPrefix + 'MainItem'; + else + _cmCurrentItem.className = thatPrefix + 'MenuItem'; + if (thatMenu.id != idSub) + cmHideMenu (thatMenu, thisMenu, thatPrefix); + } + } + + // okay, set the current menu to this obj + _cmCurrentItem = obj; + + // just in case, reset all items in this menu to MenuItem + cmResetMenu (thisMenu, prefix); + + var item = _cmItemList[index]; + var isDefaultItem = cmIsDefaultItem (item); + + if (isDefaultItem) + { + if (isMain) + obj.className = prefix + 'MainItemHover'; + else + obj.className = prefix + 'MenuItemHover'; + } + + if (idSub) + { + var subMenu = cmGetObject (idSub); + cmShowSubMenu (obj, prefix, subMenu, orient); + } + + var descript = ''; + if (item.length > 4) + descript = (item[4] != null) ? item[4] : (item[2] ? item[2] : descript); + else if (item.length > 2) + descript = (item[2] ? item[2] : descript); + + window.defaultStatus = descript; +} + +// +// action should be taken for mouse moving out of the menu item +// +function cmItemMouseOut (obj, delayTime) +{ + if (!delayTime) + delayTime = _cmNodeProperties.delay; + _cmTimeOut = window.setTimeout ('cmHideMenuTime ()', delayTime); + window.defaultStatus = ''; +} + +// +// action should be taken for mouse button down at a menu item +// +function cmItemMouseDown (obj, index) +{ + if (cmIsDefaultItem (_cmItemList[index])) + { + if (obj.cmIsMain) + obj.className = obj.cmPrefix + 'MainItemActive'; + else + obj.className = obj.cmPrefix + 'MenuItemActive'; + } +} + +// +// action should be taken for mouse button up at a menu item +// +function cmItemMouseUp (obj, index) +{ + var item = _cmItemList[index]; + + var link = null, target = '_self'; + + if (item.length > 2) + link = item[2]; + if (item.length > 3 && item[3]) + target = item[3]; + + if (link != null) + { + window.open (link, target); + } + + var prefix = obj.cmPrefix; + var thisMenu = cmGetThisMenu (obj, prefix); + + var hasChild = (item.length > 5); + if (!hasChild) + { + if (cmIsDefaultItem (item)) + { + if (obj.cmIsMain) + obj.className = prefix + 'MainItem'; + else + obj.className = prefix + 'MenuItem'; + } + cmHideMenu (thisMenu, null, prefix); + } + else + { + if (cmIsDefaultItem (item)) + { + if (obj.cmIsMain) + obj.className = prefix + 'MainItemHover'; + else + obj.className = prefix + 'MenuItemHover'; + } + } +} + +////////////////////////////////////////////////////////////////////// +// +// Mouse Event Support Utility Functions +// +////////////////////////////////////////////////////////////////////// + +// +// move submenu to the appropriate location +// +// @param obj the menu item that opens up the subMenu +// subMenu the sub menu to be shown +// orient the orientation of the subMenu +// +function cmMoveSubMenu (obj, subMenu, orient) +{ + var mode = String (orient); + var p = subMenu.offsetParent; + var subMenuWidth = cmGetWidth (subMenu); + var horiz = cmGetHorizontalAlign (obj, mode, p, subMenuWidth); + if (mode.charAt (0) == 'h') + { + if (mode.charAt (1) == 'b') + subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj)) + 'px'; + else + subMenu.style.top = (cmGetYAt (obj, p) - cmGetHeight (subMenu)) + 'px'; + if (horiz == 'r') + subMenu.style.left = (cmGetXAt (obj, p)) + 'px'; + else + subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj) - subMenuWidth) + 'px'; + } + else + { + if (horiz == 'r') + subMenu.style.left = (cmGetXAt (obj, p) + cmGetWidth (obj)) + 'px'; + else + subMenu.style.left = (cmGetXAt (obj, p) - subMenuWidth) + 'px'; + if (mode.charAt (1) == 'b') + subMenu.style.top = (cmGetYAt (obj, p)) + 'px'; + else + subMenu.style.top = (cmGetYAt (obj, p) + cmGetHeight (obj) - cmGetHeight (subMenu)) + 'px'; + } +} + +// +// automatically re-adjust the menu position based on available screen size. +// +function cmGetHorizontalAlign (obj, mode, p, subMenuWidth) +{ + var horiz = mode.charAt (2); + if (!(document.body)) + return horiz; + var body = document.body; + var browserLeft; + var browserRight; + if (window.innerWidth) + { + // DOM window attributes + browserLeft = window.pageXOffset; + browserRight = window.innerWidth + browserLeft; + } + else if (body.clientWidth) + { + // IE attributes + browserLeft = body.clientLeft; + browserRight = body.clientWidth + browserLeft; + } + else + return horiz; + if (mode.charAt (0) == 'h') + { + if (horiz == 'r' && (cmGetXAt (obj) + subMenuWidth) > browserRight) + horiz = 'l'; + if (horiz == 'l' && (cmGetXAt (obj) + cmGetWidth (obj) - subMenuWidth) < browserLeft) + horiz = 'r'; + return horiz; + } + else + { + if (horiz == 'r' && (cmGetXAt (obj, p) + cmGetWidth (obj) + subMenuWidth) > browserRight) + horiz = 'l'; + if (horiz == 'l' && (cmGetXAt (obj, p) - subMenuWidth) < browserLeft) + horiz = 'r'; + return horiz; + } +} + +// +// show the subMenu w/ specified orientation +// also move it to the correct coordinates +// +// @param obj the menu item that opens up the subMenu +// subMenu the sub menu to be shown +// orient the orientation of the subMenu +// +function cmShowSubMenu (obj, prefix, subMenu, orient) +{ + if (!subMenu.cmParentMenu) + { + // establish the tree w/ back edge + var thisMenu = cmGetThisMenu (obj, prefix); + subMenu.cmParentMenu = thisMenu; + if (!thisMenu.cmSubMenu) + thisMenu.cmSubMenu = new Array (); + //thisMenu.cmSubMenu.push (subMenu); + thisMenu.cmSubMenu[thisMenu.cmSubMenu.length] = subMenu; + } + + // position the sub menu + cmMoveSubMenu (obj, subMenu, orient); + subMenu.style.visibility = 'visible'; + + // + // On IE, controls such as SELECT, OBJECT, IFRAME (before 5.5) + // are window based controls. So, if the sub menu and these + // controls overlap, sub menu would be hidden behind them. Thus + // one needs to turn the visibility of these controls off when the + // sub menu is showing, and turn their visibility back on + // when the sub menu is hiding. + // + if (document.all) // it is IE + { + /* part of Felix Zaslavskiy's fix on hiding controls + not really sure if this part is necessary, but shouldn't + hurt. */ + if (!subMenu.cmOverlap) + subMenu.cmOverlap = new Array (); +/*@cc_on @*/ +/*@if (@_jscript_version >= 5.5) +@else @*/ + cmHideControl ("IFRAME", subMenu); +/*@end @*/ + cmHideControl ("SELECT", subMenu); + cmHideControl ("OBJECT", subMenu); + } +} + +// +// reset all the menu items to class MenuItem in thisMenu +// +function cmResetMenu (thisMenu, prefix) +{ + if (thisMenu.cmItems) + { + var i; + var str; + var items = thisMenu.cmItems; + for (i = 0; i < items.length; ++i) + { + if (items[i].cmIsMain) + str = prefix + 'MainItem'; + else + str = prefix + 'MenuItem'; + if (items[i].className != str) + items[i].className = str; + } + } +} + +// +// called by the timer to hide the menu +// +function cmHideMenuTime () +{ + if (_cmCurrentItem) + { + var prefix = _cmCurrentItem.cmPrefix; + cmHideMenu (cmGetThisMenu (_cmCurrentItem, prefix), null, prefix); + } +} + +// +// hide thisMenu, children of thisMenu, as well as the ancestor +// of thisMenu until currentMenu is encountered. currentMenu +// will not be hidden +// +function cmHideMenu (thisMenu, currentMenu, prefix) +{ + var str = prefix + 'SubMenu'; + + // hide the down stream menus + if (thisMenu.cmSubMenu) + { + var i; + for (i = 0; i < thisMenu.cmSubMenu.length; ++i) + { + cmHideSubMenu (thisMenu.cmSubMenu[i], prefix); + } + } + + // hide the upstream menus + while (thisMenu && thisMenu != currentMenu) + { + cmResetMenu (thisMenu, prefix); + if (thisMenu.className == str) + { + thisMenu.style.visibility = 'hidden'; + cmShowControl (thisMenu); + } + else + break; + thisMenu = cmGetThisMenu (thisMenu.cmParentMenu, prefix); + } +} + +// +// hide thisMenu as well as its sub menus if thisMenu is not +// already hidden +// +function cmHideSubMenu (thisMenu, prefix) +{ + if (thisMenu.style.visibility == 'hidden') + return; + if (thisMenu.cmSubMenu) + { + var i; + for (i = 0; i < thisMenu.cmSubMenu.length; ++i) + { + cmHideSubMenu (thisMenu.cmSubMenu[i], prefix); + } + } + cmResetMenu (thisMenu, prefix); + thisMenu.style.visibility = 'hidden'; + cmShowControl (thisMenu); +} + +// +// hide a control such as IFRAME +// +function cmHideControl (tagName, subMenu) +{ + var x = cmGetX (subMenu); + var y = cmGetY (subMenu); + var w = subMenu.offsetWidth; + var h = subMenu.offsetHeight; + + var i; + for (i = 0; i < document.all.tags(tagName).length; ++i) + { + var obj = document.all.tags(tagName)[i]; + if (!obj || !obj.offsetParent) + continue; + + // check if the object and the subMenu overlap + + var ox = cmGetX (obj); + var oy = cmGetY (obj); + var ow = obj.offsetWidth; + var oh = obj.offsetHeight; + + if (ox > (x + w) || (ox + ow) < x) + continue; + if (oy > (y + h) || (oy + oh) < y) + continue; + + // if object is already made hidden by a different + // submenu then we dont want to put it on overlap list of + // of a submenu a second time. + // - bug fixed by Felix Zaslavskiy + if(obj.style.visibility == "hidden") + continue; + + //subMenu.cmOverlap.push (obj); + subMenu.cmOverlap[subMenu.cmOverlap.length] = obj; + obj.style.visibility = "hidden"; + } +} + +// +// show the control hidden by the subMenu +// +function cmShowControl (subMenu) +{ + if (subMenu.cmOverlap) + { + var i; + for (i = 0; i < subMenu.cmOverlap.length; ++i) + subMenu.cmOverlap[i].style.visibility = ""; + } + subMenu.cmOverlap = null; +} + +// +// returns the main menu or the submenu table where this obj (menu item) +// is in +// +function cmGetThisMenu (obj, prefix) +{ + var str1 = prefix + 'SubMenu'; + var str2 = prefix + 'Menu'; + while (obj) + { + if (obj.className == str1 || obj.className == str2) + return obj; + obj = obj.parentNode; + } + return null; +} + +// +// return true if this item is handled using default handlers +// +function cmIsDefaultItem (item) +{ + if (item == _cmSplit || item[0] == _cmNoAction || item[0] == _cmNoClick) + return false; + return true; +} + +// +// returns the object baring the id +// +function cmGetObject (id) +{ + if (document.all) + return document.all[id]; + return document.getElementById (id); +} + +// +// functions that obtain the width of an HTML element. +// +function cmGetWidth (obj) +{ + var width = obj.offsetWidth; + if (width > 0 || !cmIsTRNode (obj)) + return width; + if (!obj.firstChild) + return 0; + // use TABLE's length can cause an extra pixel gap + //return obj.parentNode.parentNode.offsetWidth; + + // use the left and right child instead + return obj.lastChild.offsetLeft - obj.firstChild.offsetLeft + cmGetWidth (obj.lastChild); +} + +// +// functions that obtain the height of an HTML element. +// +function cmGetHeight (obj) +{ + var height = obj.offsetHeight; + if (height > 0 || !cmIsTRNode (obj)) + return height; + if (!obj.firstChild) + return 0; + // use the first child's height + return obj.firstChild.offsetHeight; +} + +// +// functions that obtain the coordinates of an HTML element +// +function cmGetX (obj) +{ + var x = 0; + + do + { + x += obj.offsetLeft; + obj = obj.offsetParent; + } + while (obj); + return x; +} + +function cmGetXAt (obj, elm) +{ + var x = 0; + + while (obj && obj != elm) + { + x += obj.offsetLeft; + obj = obj.offsetParent; + } + if (obj == elm) + return x; + return x - cmGetX (elm); +} + +function cmGetY (obj) +{ + var y = 0; + do + { + y += obj.offsetTop; + obj = obj.offsetParent; + } + while (obj); + return y; +} + +function cmIsTRNode (obj) +{ + var tagName = obj.tagName; + return tagName == "TR" || tagName == "tr" || tagName == "Tr" || tagName == "tR"; +} + +// +// get the Y position of the object. In case of TR element though, +// we attempt to adjust the value. +// +function cmGetYAt (obj, elm) +{ + var y = 0; + + if (!obj.offsetHeight && cmIsTRNode (obj)) + { + var firstTR = obj.parentNode.firstChild; + obj = obj.firstChild; + y -= firstTR.firstChild.offsetTop; + } + + while (obj && obj != elm) + { + y += obj.offsetTop; + obj = obj.offsetParent; + } + + if (obj == elm) + return y; + return y - cmGetY (elm); +} + +// +// debug function, ignore :) +// +function cmGetProperties (obj) +{ + if (obj == undefined) + return 'undefined'; + if (obj == null) + return 'null'; + + var msg = obj + ':\n'; + var i; + for (i in obj) + msg += i + ' = ' + obj[i] + '; '; + return msg; +} \ No newline at end of file diff --git a/serverApps/src/jsf/js/MyFacesHack.js b/serverApps/src/jsf/js/MyFacesHack.js new file mode 100644 index 0000000000..9dbdae7386 --- /dev/null +++ b/serverApps/src/jsf/js/MyFacesHack.js @@ -0,0 +1,59 @@ +// +// Overrides the original JSCookMenu function to work with MyFaces +// +function cmItemMouseUp (obj, index) +{ + var item = _cmItemList[index]; + + var link = null, target = '_self'; + + if (item.length > 2) + link = item[2]; + if (item.length > 3 && item[3]) + target = item[3]; + + if (link != null) + { + // changes by Richard J. Barbalace + if (link.match(/^\w*:A\]\w*:\/\//) != null ) { + // Link is a URL + link = link.replace(/^\w*:A\]/, ""); // Remove JSF ID + window.open (link, target); + } else if (link.match(/^\w*:A\]\w*:/) != null ) { + // Link is a script method + link = link.replace(/^\w*:A\]\w*:/, ""); // Remove JSF ID + eval(link); + } else { + // Link is a JSF action + var dummyForm = document.forms[target]; + dummyForm.elements['jscook_action'].value = link; + dummyForm.submit(); + } + } + + var prefix = obj.cmPrefix; + var thisMenu = cmGetThisMenu (obj, prefix); + + var hasChild = (item.length > 5); + if (!hasChild) + { + if (cmIsDefaultItem (item)) + { + if (obj.cmIsMain) + obj.className = prefix + 'MainItem'; + else + obj.className = prefix + 'MenuItem'; + } + cmHideMenu (thisMenu, null, prefix); + } + else + { + if (cmIsDefaultItem (item)) + { + if (obj.cmIsMain) + obj.className = prefix + 'MainItemHover'; + else + obj.className = prefix + 'MenuItemHover'; + } + } +} diff --git a/serverApps/src/jsf/js/ThemeCompiere/theme.js b/serverApps/src/jsf/js/ThemeCompiere/theme.js new file mode 100644 index 0000000000..b125c2fe1a --- /dev/null +++ b/serverApps/src/jsf/js/ThemeCompiere/theme.js @@ -0,0 +1,48 @@ +// directory of where all the images are +var cmThemeAdempiereBase = '/adempiere-webapp/images/ThemeAdempiere'; + +/* +if(myThemeAdempiereBase) + cmThemeAdempiereBase = myThemeAdempiereBase; +*/ +var cmThemeAdempiere = +{ + // main menu display attributes + // + // Note. When the menu bar is horizontal, + // mainFolderLeft and mainFolderRight are + // put in . When the menu + // bar is vertical, they would be put in + // a separate TD cell. + + // HTML code to the left of the folder item + mainFolderLeft: ' ', + // HTML code to the right of the folder item + mainFolderRight: ' ', + // HTML code to the left of the regular item + mainItemLeft: ' ', + // HTML code to the right of the regular item + mainItemRight: ' ', + + // sub menu display attributes + + // 0, HTML code to the left of the folder item + folderLeft: '', + // 1, HTML code to the right of the folder item + folderRight: '', + // 2, HTML code to the left of the regular item + itemLeft: '', + // 3, HTML code to the right of the regular item + itemRight: '', + // 4, cell spacing for main menu + mainSpacing: 0, + // 5, cell spacing for sub menus + subSpacing: 0, + // 6, auto dispear time for submenus in milli-seconds + delay: 500 +}; + +// for horizontal menu split +var cmThemeAdempiereHSplit = [_cmNoAction, '
']; +var cmThemeAdempiereMainHSplit = [_cmNoAction, '
']; +var cmThemeAdempiereMainVSplit = [_cmNoAction, '|']; diff --git a/serverApps/src/main/servlet/org/compiere/wstore/AdvertisementServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/AdvertisementServlet.java new file mode 100644 index 0000000000..7811852230 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/AdvertisementServlet.java @@ -0,0 +1,161 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Web Request. + * + * @author Jorg Janke + * @version $Id: AdvertisementServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class AdvertisementServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(AdvertisementServlet.class); + /** Name */ + static public final String NAME = "AdvertisementServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("AdvertisementServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Avertisement Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + /*************************************************************************/ + + public static final String P_ADVERTISEMENT_ID = "W_Advertisement_ID"; + + /** + * Process the HTTP Get request + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr() + " - forward to request.jsp"); + response.sendRedirect("advertisements.jsp"); + } // doGet + + + /************************************************************************** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + + // Get Session attributes + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // + Properties ctx = JSPEnv.getCtx(request); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu == null) + { + log.warning("No web user"); + response.sendRedirect("loginServlet?ForwardTo=advertisement.jsp"); // entry + return; + } + int W_Advertisement_ID = WebUtil.getParameterAsInt(request, P_ADVERTISEMENT_ID); + MAdvertisement ad = new MAdvertisement (ctx, W_Advertisement_ID, null); + if (ad.get_ID() == 0) + { + WebUtil.createForwardPage(response, "Web Advertisement Not Found", "advertisements.jsp", 0); + return; + } + StringBuffer info = new StringBuffer(); + // + String Name = WebUtil.getParameter (request, "Name"); + if (Name != null && Name.length() > 0 && !Name.equals(ad.getName())) + { + ad.setName(Name); + info.append("Name - "); + } + String Description = WebUtil.getParameter (request, "Description"); + if (Description != null && Description.length() > 0 && !Description.equals(ad.getDescription())) + { + ad.setDescription(Description); + info.append("Description - "); + } + String ImageURL = null; + String AdText = WebUtil.getParameter (request, "AdText"); + if (AdText != null && AdText.length() > 0 && !AdText.equals(ad.getAdText())) + { + ad.setAdText(AdText); + info.append("AdText - "); + } + String ClickTargetURL = WebUtil.getParameter (request, "ClickTargetURL"); + if (ClickTargetURL != null && ClickTargetURL.length() > 0 && !ClickTargetURL.equals(ad.getClickTargetURL())) + { + ad.setClickTargetURL(ClickTargetURL); + info.append("ClickTargetURL - "); + } + if (info.length() > 0) + { + if (ad.save()) + WebUtil.createForwardPage(response, "Web Advertisement Updated: " + info.toString(), "advertisements.jsp", 0); + else + WebUtil.createForwardPage(response, "Web Advertisement Update Error", "advertisements.jsp", 0); + } + else + WebUtil.createForwardPage(response, "Web Advertisement not changed", "advertisements.jsp", 0); + } // doPost + +} // AdvertisementSerlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/AssetServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/AssetServlet.java new file mode 100644 index 0000000000..077b2f635c --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/AssetServlet.java @@ -0,0 +1,312 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import java.util.logging.*; +import java.util.zip.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Asset (Delivery) Servlet. + * + * @author Jorg Janke + * @version $Id: AssetServlet.java,v 1.3 2006/09/16 08:32:33 comdivision Exp $ + */ +public class AssetServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(AssetServlet.class); + /** Name */ + static public final String NAME = "assetServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("AssetServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Assets Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + + /** + * Process the HTTP Get request. + * (logout, deleteCookie) + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(false); + // + String url = "/assets.jsp"; + if (session == null + || session.getAttribute(WebInfo.NAME) == null + || session.getAttribute(WebUser.NAME) == null) + url = "/login.jsp"; + else + { + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + WebInfo info = (WebInfo)session.getAttribute(WebInfo.NAME); + if (info != null) + info.setMessage(""); + + // Parameter = Asset_ID - if invoice is valid and belongs to wu then create PDF & stream it + String msg = streamAsset(request, response); + if (info != null) + info.setMessage(Msg.parseTranslation(ctx, msg)); + if (msg == null // OK + || msg.length() == 0 + || msg.startsWith("**")) + // if not returned - results in exception: Cannot forward after response has been committed + return; + } + + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + doGet(request,response); + } // doPost + + /** + * Stream asset + * @param request request + * @param response response + * @return "" or error message + */ + protected String streamAsset (HttpServletRequest request, HttpServletResponse response) + { + // Get Asset ID + int A_Asset_ID = WebUtil.getParameterAsInt (request, "Asset_ID"); + if (A_Asset_ID == 0) + { + log.fine("No ID)"); + return "No Asset ID"; + } + byte[] assetInfo = String.valueOf(A_Asset_ID).getBytes(); + + // Get Asset + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + WebEnv.dump(request); + MAsset asset = new MAsset(ctx, A_Asset_ID, null); + if (asset.getA_Asset_ID() != A_Asset_ID) + { + log.fine("Asset not found - ID=" + A_Asset_ID); + return "Asset not found"; + } + // Get WebUser & Compare with invoice + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu.getC_BPartner_ID() != asset.getC_BPartner_ID()) + { + log.warning ("A_Asset_ID=" + A_Asset_ID + + " - BP_Invoice=" + asset.getC_BPartner_ID() + + " <> BP_User=" + wu.getC_BPartner_ID()); + return "Your asset not found"; + } + if (!asset.isDownloadable() || wu.isCreditStopHold() || !wu.isEMailVerified()) + return "Asset not downloadable"; + + // Name & URL + String pd = WebUtil.getParameter(request, "PD"); + String dl_name = null; + String dl_url = null; + InputStream in = null; + int M_ProductDownload_ID = 0; + if (pd != null && pd.length() > 0) + { + MProductDownload[] pdls = asset.getProductDownloads(); + if (pdls != null) + { + for (int i = 0; i < pdls.length; i++) + { + if (pdls[i].getDownloadURL().indexOf(pd) != -1) + { + M_ProductDownload_ID = pdls[i].getM_ProductDownload_ID(); + dl_name = pd; + dl_url = pdls[i].getDownloadURL(); + in = pdls[i].getDownloadStream(ctx.getProperty(WebSessionCtx.CTX_DOCUMENT_DIR)); + break; + } + } + } + } + log.fine(dl_name + " - " + dl_url); + if (dl_name == null || dl_url == null || in == null) + return "@NotFound@ @A_Asset_ID@: " + pd; + + /** + Download SupportContract.pdf for Jorg Janke - jjanke@adempiere.org + Version = 120 - Lot = . - SerNo = . + Guarantee Date = 5/30/05 + Thank you for using Adempiere Customer Asset Management + **/ + String lot = asset.getLot(); + if (lot == null || lot.length() == 0) + lot = "."; + String ser = asset.getSerNo(); + if (ser == null || ser.length() == 0) + ser = "."; + Object[] args = new Object[] { + dl_name, + wu.getName() + " - " + wu.getEmail(), + asset.getVersionNo(), + lot, + ser, + asset.getGuaranteeDate()}; + String readme = Msg.getMsg(ctx, "AssetDeliveryTemplate", args); + + + // Send File + MAssetDelivery ad = asset.confirmDelivery(request, wu.getAD_User_ID()); + if (M_ProductDownload_ID != 0) + ad.setM_ProductDownload_ID(M_ProductDownload_ID); + ad.setDescription(dl_name); + // + float speed = 0; + try + { + response.setContentType("application/zip"); + response.setHeader("Content-Location", "asset.zip"); + // response.setContentLength(length); + + int bufferSize = 2048; // 2k Buffer + response.setBufferSize(bufferSize); + // + log.fine(in + ", available=" + in.available()); + long time = System.currentTimeMillis(); + + // Zip Output Stream + ServletOutputStream out = response.getOutputStream (); + ZipOutputStream zip = new ZipOutputStream(out); // Servlet out + zip.setMethod(ZipOutputStream.DEFLATED); + zip.setLevel(Deflater.BEST_COMPRESSION); + zip.setComment(readme); + + // Readme File + ZipEntry entry = new ZipEntry("readme.txt"); + entry.setExtra(assetInfo); + zip.putNextEntry(entry); + zip.write(readme.getBytes(), 0, readme.length()); + zip.closeEntry(); + + // Payload + entry = new ZipEntry(dl_name); + entry.setExtra(assetInfo); + zip.putNextEntry(entry); + byte[] buffer = new byte[bufferSize]; + int count = 0; + int totalSize = 0; + do + { + count = in.read(buffer, 0, bufferSize); // read delivery + if (count > 0) + { + totalSize += count; + zip.write (buffer, 0, count); // write zip + } + } while (count != -1); + zip.closeEntry(); + + // Fini + zip.finish(); + zip.close(); + in.close(); + time = System.currentTimeMillis() - time; + speed = ((float)totalSize/1024) / ((float)time/1000); + String msg = (totalSize/1024) + "kB - " + time + " ms - " + speed + " kB/sec"; + log.fine(msg); + + // Delivery Record + ad.setDeliveryConfirmation(msg); + ad.save(); + asset.save(); + } + catch (IOException ex) + { + String msg = ex.getMessage (); + if (msg == null || msg.length () == 0) + msg = ex.toString (); + log.warning(msg); + // Delivery Record + try + { + if (msg.length () > 120) + msg = msg.substring (0, 119); + ad.setDeliveryConfirmation (msg); + ad.save (); + // asset.save(); not delivered + } + catch (Exception ex1) + { + log.log(Level.SEVERE, "2 - " + ex); + } + // nned to differentiate error message as response committed + return "** Streaming error; Please Retry"; + } + // + return null; + } // streamAsset + +} // AssetServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/BasketServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/BasketServlet.java new file mode 100644 index 0000000000..afe0d295a0 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/BasketServlet.java @@ -0,0 +1,303 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.math.*; +import java.util.*; +import java.util.logging.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.util.*; + +/** + * Shopping Basket. + * you could add a new line via parameter + * ?M_Product_ID=11&Name=aaaaa&Quantity=1&Price=11.11 + * if price list found, the price will be potentially overwritten + * + * @author Jorg Janke + * @version $Id: BasketServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class BasketServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(BasketServlet.class); + /** Name */ + static public final String NAME = "basketServlet"; + /** SalesRep Parameter */ + static public final String P_SalesRep_ID = "SalesRep_ID"; + /** Product Parameter */ + static public final String P_Product_ID = "M_Product_ID"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("BasketServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Basket"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + + /************************************************************************** + * Process the HTTP Get request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr() + + " - " + request.getRequestURL()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + + // Create WebBasket + WebBasket wb = (WebBasket)session.getAttribute(WebBasket.NAME); + if (wb == null) + wb = new WebBasket(); + session.setAttribute(WebBasket.NAME, wb); + // SalesRep + int SalesRep_ID = WebUtil.getParameterAsInt (request, P_SalesRep_ID); + if (SalesRep_ID != 0) + { + wb.setSalesRep_ID(SalesRep_ID); + log.fine("SalesRep_ID=" + SalesRep_ID); + } + + // Get Price List + PriceList pl = (PriceList)session.getAttribute(PriceList.NAME); + if (pl == null) + { + log.fine("No Price List in session"); + pl = (PriceList)request.getAttribute(PriceList.NAME); + } + log.fine("PL=" + pl); + + // Do we delete? Delete_x + deleteLine (request, wb); + // Do we add? Add_x + addLine (request, pl, wb); + + log.info(wb.toString()); + // Go back to basket + String url = "/basket.jsp"; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Add Line + * @param request request + * @param pl price list + * @param wb web basket + */ + private void addLine (HttpServletRequest request, PriceList pl, WebBasket wb) + { + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + + // Get Parameter + int M_PriceList_ID = WebUtil.getParameterAsInt (request, "M_PriceList_ID"); + int M_PriceList_Version_ID = WebUtil.getParameterAsInt (request, "M_PriceList_Version_ID"); + wb.setM_PriceList_ID (M_PriceList_ID); + wb.setM_PriceList_Version_ID (M_PriceList_Version_ID); + // + int M_Product_ID = WebUtil.getParameterAsInt (request, P_Product_ID); + String Name = WebUtil.getParameter (request, "Name"); + String sQuantity = WebUtil.getParameter (request, "Quantity"); + String sPrice = WebUtil.getParameter (request, "Price"); + + // Search for Product ID Add_134 = Add + Enumeration en = request.getParameterNames (); + while (M_Product_ID == 0 && en.hasMoreElements ()) + { + String parameter = (String)en.nextElement (); + if (parameter.startsWith ("Add_")) + { + if (WebUtil.exists (request, parameter)) // to be sure + { + try + { + M_Product_ID = Integer.parseInt (parameter.substring (4)); + log.fine("Found Parameter=" + parameter + " -> " + M_Product_ID); + if (!WebUtil.exists(sQuantity)) + sQuantity = WebUtil.getParameter (request, "Qty_" + M_Product_ID); + if (!WebUtil.exists(sPrice)) + sPrice = WebUtil.getParameter (request, "Price_" + M_Product_ID); + if (!WebUtil.exists(Name)) + Name = WebUtil.getParameter (request, "Name_" + M_Product_ID); + log.fine("Found Parameters " + Name + ",Qty=" + sQuantity + ",Price=" + sPrice); + } + catch (Exception ex) + { + log.warning ("ParseError for " + parameter + " - " + ex.toString ()); + } + } + } + } + if (M_Product_ID == 0) + return; + + // **** Set Qty + BigDecimal Qty = null; + try + { + if (sQuantity != null && sQuantity.length () > 0) + Qty = new BigDecimal (sQuantity); + } + catch (Exception ex1) + { + log.warning ("(qty) - " + ex1.toString()); + } + if (Qty == null) + Qty = Env.ONE; + + // **** Set Price + BigDecimal Price = null; + // Find info in current price list + if (M_Product_ID != 0 && pl != null) + { + PriceListProduct plp = pl.getPriceListProduct(M_Product_ID); + if (plp != null) + { + Price = plp.getPrice (); + Name = plp.getName (); + log.fine("Found in PL = " + Name + " - " + Price); + } + } + /** if not found inPL and exists as parameter + try + { + if (Price == null && sPrice != null && sPrice.length () > 0) + Price = new BigDecimal (sPrice); + } + catch (Exception ex1) + { + log.warn ("addLine (price) - " + ex1.toString()); + } + /**/ + // Price not in session price list and not as parameter + if (Price == null && (pl == null || pl.isNotAllPrices())) + { + // Create complete Price List + int AD_Client_ID = Env.getContextAsInt(ctx, "AD_Client_ID"); + pl = PriceList.get (ctx, AD_Client_ID, M_PriceList_ID, null, null, true); + session.setAttribute(PriceList.NAME, pl); // set on session level + PriceListProduct plp = pl.getPriceListProduct(M_Product_ID); + if (plp != null) + { + Price = plp.getPrice (); + Name = plp.getName (); + log.fine("Found in complete PL = " + Name + " - " + Price); + } + } + + + if (Price != null) + { + WebBasketLine wbl = wb.add (M_Product_ID, Name, Qty, Price); + log.fine(wbl.toString()); + } + else // Price not found + log.warning ("Product Price not found - M_Product_ID=" + M_Product_ID + + ", Name=" + Name); + + } // addLine + + /** + * Delete Line. + * Delete_x + * @param request request + * @param wb web basket + */ + private void deleteLine (HttpServletRequest request, WebBasket wb) + { + try + { + String enc = request.getCharacterEncoding(); + if (enc == null) + request.setCharacterEncoding(WebEnv.ENCODING); + } + catch (Exception e) + { + log.log(Level.SEVERE, "Set CharacterEncoding=" + WebEnv.ENCODING, e); + } + Enumeration en = request.getParameterNames(); + while (en.hasMoreElements()) + { + String parameter = (String)en.nextElement(); + if (parameter.startsWith("Delete_")) + { + try + { + int line = Integer.parseInt (parameter.substring (7)); + log.fine("Delete parameter=" + parameter + " -> " + line); + wb.delete(line); + } + catch (NumberFormatException ex) + { + log.warning("ParseError for " + parameter + " - " + ex.toString()); + } + } + } + } // deleteLine + + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + // log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doGet(request, response); + } +} // Basket diff --git a/serverApps/src/main/servlet/org/compiere/wstore/CheckOutLinkTag.java b/serverApps/src/main/servlet/org/compiere/wstore/CheckOutLinkTag.java new file mode 100644 index 0000000000..f228d4facb --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/CheckOutLinkTag.java @@ -0,0 +1,130 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; +import org.apache.ecs.xhtml.*; +import org.compiere.util.*; + +/** + * CheckOut Links. + * Creates Basket / Checkout Link + *
+ *  
+ *	
+ * + * @author Jorg Janke + * @version $Id: CheckOutLinkTag.java,v 1.3 2006/07/30 00:53:21 jjanke Exp $ + */ +public class CheckOutLinkTag extends TagSupport +{ + /** Logger */ + private CLogger log = CLogger.getCLogger (getClass()); + /** One Line */ + private boolean m_oneLine = false; + + /** + * Set to one line + * @param var Y or something else + */ + public void setOneLine (String var) + { + m_oneLine = "Y".equals(var); + } // setOneLine + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + HttpSession session = pageContext.getSession(); + HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); + WebBasket wb = (WebBasket)session.getAttribute(WebBasket.NAME); + + // log.fine("WebBasket=" + wb); + if (wb != null && wb.getLineCount() > 0) + { + log.fine("WebBasket exists"); + // + JspWriter out = pageContext.getOut(); + HtmlCode html = new HtmlCode(); + // + if (!m_oneLine) + html.addElement(new hr("90%", "left")); + // + img img = new img ("basket.gif"); + img.setBorder(0); + a a = new a("basket.jsp"); + a.setClass("menuMain"); + if (m_oneLine) + { + a.addElement (img); + a.addElement ("Basket"); + html.addElement(a); + html.addElement(" - "); + } + else + { + a.addElement ("Basket"); + a.addElement (img); + html.addElement(a); + // List Content + p p = new p(); + p.setClass("Cbasket"); + ArrayList lines = wb.getLines(); + for (int i = 0; i < lines.size(); i++) + { + p.addElement("
"); + Object line = lines.get(i); + p.addElement(line.toString()); + } + p.addElement("

"); + html.addElement(p); + // html.addElement(new br()); + } + // + img = new img ("checkout.gif"); + img.setBorder(0); + String url = CheckOutServlet.NAME; + if (!request.isSecure()) + url = "https://" + request.getServerName() + request.getContextPath() + "/" + CheckOutServlet.NAME; + a = new a(url); + a.setClass("menuMain"); + a.addElement("Create Order"); + a.addElement(img); + html.addElement(a); + // + html.output(out); + } // web basket + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + +} // CheckOutLinkTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/CheckOutServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/CheckOutServlet.java new file mode 100644 index 0000000000..6c61d65332 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/CheckOutServlet.java @@ -0,0 +1,134 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.util.*; + + +/** + * Check Out. + * + * @author Jorg Janke + * @version $Id: CheckOutServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class CheckOutServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + /** Name */ + static public final String NAME = "checkOutServlet"; + /** Attribute */ + static public final String ATTR_CHECKOUT = "CheckOut"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("CheckOutServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web CheckOut Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine("destroy"); + } // destroy + + + /** + * Process the HTTP Get request. + * (logout, deleteCookie) + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + + // Web User/Basket + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + WebBasket wb = (WebBasket)session.getAttribute(WebBasket.NAME); + + String url = "/login.jsp"; + // Nothing in basket + if (wb == null || wb.getLineCount() == 0) + url = "/basket.jsp"; + else + { + session.setAttribute(ATTR_CHECKOUT, "Y"); // indicate checkout + if (wu != null && wu.isLoggedIn ()) + url = "/addressInfo.jsp"; + } + + // if (request.isSecure()) + // { + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + // } + // else + // Switch to secure + // { + // url = "https://" + request.getServerName() + request.getContextPath() + "/" + url; + // log.info ("doGet - Secure Forward to " + url); + // WUtil.createForwardPage(response, "Secure Access", url); + // } + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + HttpSession session = request.getSession(false); + } // doPost + +} // CheckOutServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/Click.java b/serverApps/src/main/servlet/org/compiere/wstore/Click.java new file mode 100644 index 0000000000..fdbfa8d374 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/Click.java @@ -0,0 +1,188 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Click Counter. + * Counts the click and forwards. + * + http://www.adempiere.com/wstore/click?target=www.yahoo.com + http://www.adempiere.com/wstore/click/www.yahoo.com + http://www.adempiere.com/wstore/click?www.yahoo.com + * + * + * @author Jorg Janke + * @version $Id: Click.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class Click extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + /** Name */ + static public final String NAME = "click"; + + /** Target Parameter */ + static public final String PARA_TARGET = "target"; + /** Fallback Target */ + static public final String DEFAULT_TARGET = "http://www.adempiere.org/"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("Click.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Click Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine("destroy"); + } // destroy + + + /************************************************************************** + * Process the HTTP Get request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + long time = System.currentTimeMillis(); + request.getSession(true); // force create session for ctx + // + String url = getTargetURL(request); + response.sendRedirect(url); + response.flushBuffer(); + log.fine("redirect - " + url); + + // Save Click + saveClick(request, url); + // + log.fine(url + " - " + (System.currentTimeMillis()-time) + "ms"); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + doGet (request, response); + } // doPost + + /** + * Get Target URL. + * 1 - target parameter + * 3 - parameter + * 2 - path + * @param request request + * @return URL + */ + private String getTargetURL (HttpServletRequest request) + { + // Get Named Parameter - /click?target=www... + String url = WebUtil.getParameter(request, PARA_TARGET); + // Check parameters - /click?www... + if (url == null || url.length() == 0) + { + Enumeration e = request.getParameterNames (); + if (e.hasMoreElements ()) + url = (String)e.nextElement (); + } + // Check Path - /click/www... + if (url == null || url.length() == 0) + { + url = request.getPathInfo (); + if (url != null) + url = url.substring(1); // cut off initial / + } + // Still nothing + if (url == null || url.length() == 0) + url = DEFAULT_TARGET; + // add http protocol + if (url.indexOf("://") == -1) + url = "http://" + url; + return url; + } // getTargetURL + + /** + * Save Click + */ + private boolean saveClick (HttpServletRequest request, String url) + { + Properties ctx = JSPEnv.getCtx(request); + // + MClick mc = new MClick (ctx, url, null); + mc.setRemote_Addr(request.getRemoteAddr()); + mc.setRemote_Host(request.getRemoteHost()); + String ref = request.getHeader("referer"); + if (ref == null || ref.length() == 0) + ref = request.getRequestURL().toString(); + mc.setReferrer(ref); + // + mc.setAcceptLanguage(request.getHeader("accept-language")); + mc.setUserAgent(request.getHeader("user-agent")); + // + HttpSession session = request.getSession(false); + if (session != null) + { + WebUser wu = (WebUser)session.getAttribute (WebUser.NAME); + if (wu != null) + { + mc.setEMail (wu.getEmail()); + mc.setAD_User_ID (wu.getAD_User_ID()); + } + } + return mc.save(); + } // saveClick + +} // Click diff --git a/serverApps/src/main/servlet/org/compiere/wstore/Counter.java b/serverApps/src/main/servlet/org/compiere/wstore/Counter.java new file mode 100644 index 0000000000..f196203355 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/Counter.java @@ -0,0 +1,131 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import javax.servlet.*; +import javax.servlet.http.*; +import java.io.*; +import java.util.*; + +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Web Page Counter + * + http://www.adempiere.com/wstore/counter + * + * + * @author Jorg Janke + * @version $Id: Counter.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class Counter extends HttpServlet implements Runnable +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(Counter.class); + + /** Name */ + static public final String NAME = "counter"; + + /** Requests */ + private List m_requests = Collections.synchronizedList(new ArrayList()); + + /** + * Initialize global variables + * + * @param config servlet config + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("Counter.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Counter"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info(""); + } // destroy + + + /************************************************************************** + * Process the HTTP Get request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + m_requests.add(request); + new Thread(this).start(); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + doGet (request, response); + } // doPost + + /************************************************************************** + * Async Process + */ + public void run() + { + long time = System.currentTimeMillis(); + // get Request + HttpServletRequest request = null; + if (m_requests.size() > 0) + request = (HttpServletRequest)m_requests.remove(0); + if (request == null) + { + log.log(Level.SEVERE, "Nothing in queue"); + return; + } + + Properties ctx = JSPEnv.getCtx(request); + String ref = request.getHeader("referer"); + if (ref == null || ref.length() == 0) + ref = request.getRequestURL().toString(); + log.info("Referer=" + request.getHeader("referer") + " - URL=" + request.getRequestURL()); + } // run + +} // Counter diff --git a/serverApps/src/main/servlet/org/compiere/wstore/EMailServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/EMailServlet.java new file mode 100644 index 0000000000..0aadd3fb1a --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/EMailServlet.java @@ -0,0 +1,118 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * EMail Servlet + * @author Jorg Janke + * @version $Id: EMailServlet.java,v 1.4 2006/09/24 12:11:16 comdivision Exp $ + */ +public class EMailServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(EMailServlet.class); + + /** Name */ + static public final String NAME = "emailServlet"; + + /** + * Initialize global variables + * + * @param config servlet config + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("EMailServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere EMail"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info(""); + } // destroy + + + /************************************************************************** + * Process the HTTP Get request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doPost (request, response); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + + String url = WebUtil.getParameter(request, "ForwardTo"); + if (url == null || url.length() == 0) + url = "emailVerify.jsp"; + + WebLogin thisLogin = new WebLogin(request, response, ctx); + thisLogin.init (); + if (!thisLogin.action ()) { + response.sendRedirect("loginServlet?ForwardTo=" + url); + return; + } + + url = "/" + url; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doPost +} // EMailServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/ExpenseServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/ExpenseServlet.java new file mode 100644 index 0000000000..6c3c851c07 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/ExpenseServlet.java @@ -0,0 +1,132 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.util.*; + +/** + * Web Expense Report. + * + * @author Jorg Janke + * @version $Id: ExpenseServlet.java,v 1.3 2006/07/30 00:53:21 jjanke Exp $ + */ +public class ExpenseServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(ExpenseServlet.class); + /** Name */ + static public final String NAME = "ExpenseServlet"; + /** Submit type */ + public static String P_SubmitType_Name = "Submit"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("ExpenseServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Expense Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + /*************************************************************************/ + + public static final String P_Expense_ID = "W_Expense_ID"; + + /** + * Process the HTTP Get request + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr() + " - forward to request.jsp"); + response.sendRedirect("expenses.jsp"); + } // doGet + + + /*************************************************************************/ + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + + // Get Session attributes + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // + Properties ctx = JSPEnv.getCtx(request); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu == null) + { + log.warning("No web user"); + response.sendRedirect("loginServlet?ForwardTo=expense.jsp"); // entry + return; + } + int W_Expense_ID = WebUtil.getParameterAsInt(request, P_Expense_ID); + String method = WebUtil.getParameter(request, P_SubmitType_Name); + if(method.startsWith("Save")) + { + // save BUT DON'T submit for approval + }else if(method.startsWith("Submit")){ + // save AND submit for approval + }else{ + // invalid + } + WebUtil.createForwardPage(response, "Web Expense Under Construction", "expenses.jsp", 0); + } // doPost + +} // ExpenseSerlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/InfoLinkTag.java b/serverApps/src/main/servlet/org/compiere/wstore/InfoLinkTag.java new file mode 100644 index 0000000000..2e99311d22 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/InfoLinkTag.java @@ -0,0 +1,313 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +import org.apache.ecs.xhtml.*; +import org.compiere.util.*; +import org.compiere.model.*; + +/** + * Info Links (Menu). + * Creates Invoice/Payment/Asset/AddressInfo/PaymentInfo Link + *
+ *  
+ *	
+ * + * @author Jorg Janke + * @version $Id: InfoLinkTag.java,v 1.6 2006/09/21 20:45:30 jjanke Exp $ + */ +public class InfoLinkTag extends TagSupport +{ + /** SV */ + private static final long serialVersionUID = 7608741032814139346L; + /** Logger */ + private static CLogger log = CLogger.getCLogger (InfoLinkTag.class); + /** One Line */ + private boolean m_oneLine = false; + + /** + * Set to one line + * @param var Y or something else + */ + public void setOneLine (String var) + { + m_oneLine = "Y".equals(var); + } // setOneLine + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); + Properties ctx = JSPEnv.getCtx(request); // creates wsc/wu + WebSessionCtx wsc = WebSessionCtx.get(request); + // + HttpSession session = pageContext.getSession(); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu != null && wu.isLoggedIn()) + { + if (ctx != null) + { + WebInfo info = (WebInfo)session.getAttribute(WebInfo.NAME); + if (info == null || wu.getAD_User_ID() != info.getAD_User_ID()) + { + info = new WebInfo (ctx, wu); + session.setAttribute (WebInfo.NAME, info); + } + } + // + // log.fine("WebUser exists - " + wu); + // + JspWriter out = pageContext.getOut(); + HtmlCode html = new HtmlCode(); + // + if (wu.isCustomer() || wu.isVendor()) + menuBPartner (html, wsc.wstore); + if (wu.isSalesRep()) + menuSalesRep (html, wsc.wstore); + if (wu.isEmployee() || wu.isSalesRep()) + menuUser (html, wu.isEmployee(), wsc.wstore); + menuAll (html, wsc.wstore); + // + html.output(out); + } + else + { + if (CLogMgt.isLevelFiner()) + log.fine("No WebUser"); + if (session.getAttribute(WebInfo.NAME) == null) + session.setAttribute (WebInfo.NAME, WebInfo.getGeneral()); + } + return (SKIP_BODY); + } // doStartTag + + /** + * Add Business Partner Links. + * My Assets + * My Invoices + * My Payments + * My Orders + * My Shipments + * My RfQ + * @param html code + * @param wstore web store + */ + private void menuBPartner (HtmlCode html, MStore wstore) + { + boolean first = true; + if (wstore.isMenuAssets()) + { + nl (html, first); // --- Assets + first = false; + a a = new a ("assets.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Assets"); + html.addElement (a); + } + // + if (wstore.isMenuInvoices()) + { + nl (html, first); // --- Invoices + first = false; + a a = new a ("invoices.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Invoices"); + html.addElement (a); + } + // + if (wstore.isMenuPayments()) + { + nl (html, first); // --- Payments + first = false; + a a = new a ("payments.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Payments"); + html.addElement (a); + } + // + if (wstore.isMenuOrders()) + { + nl (html, first); // --- Orders + first = false; + a a = new a ("orders.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Orders"); + html.addElement (a); + } + // + if (wstore.isMenuShipments()) + { + nl (html, first); // --- Shipments + first = false; + a a = new a ("shipments.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Shipments"); + html.addElement (a); + } + // + if (wstore.isMenuRfQs()) + { + nl (html, first); // --- RfQs + first = false; + a a = new a ("rfqs.jsp"); + a.setClass ("menuSub"); + a.addElement ("My RfQ's"); + html.addElement (a); + } + } // menuCustomer + + /** + * Add Links for all. + * My Requests + * Interest Area + * Registration + * @param html code + * @param wstore web store + */ + private void menuAll (HtmlCode html, MStore wstore) + { + boolean first = false; + if (wstore.isMenuRequests()) + { + nl (html, first); // Requests + a a = new a ("requests.jsp"); + a.setClass ("menuSub"); + a.addElement ("My Requests"); + html.addElement (a); + } + // + if (wstore.isMenuInterests()) + { + nl (html, first); // --- Interest Area + a a = new a ("info.jsp"); + a.setClass ("menuSub"); + a.addElement ("Interest Area"); + html.addElement (a); + } + + if (wstore.isMenuRegistrations()) + { + nl (html, false); // --- Registration + a a = new a ("registrations.jsp"); + a.setClass ("menuSub"); + a.addElement ("Registration"); + html.addElement (a); + } + } // menuAll + + /** + * Add Links for Sales Reps. + * Open Requests + * Advertisements + * Commissions + * C.Invoices + * @param html code + * @param wstore web store + */ + private void menuSalesRep (HtmlCode html, MStore wstore) + { + nl (html, true); // ------------ + // --- Assigned Requests + a a = new a ("requests_sr.jsp"); + a.setClass ("menuSub"); + a.addElement ("Open Requests"); + html.addElement (a); + // + nl (html, false); + // --- Advertisements + a = new a ("advertisements.jsp"); + a.setClass ("menuSub"); + a.addElement ("Advertisements"); + html.addElement (a); + // + nl (html, false); + // --- Commissions + a = new a ("commissionRuns.jsp"); + a.setClass ("menuSub"); + a.addElement ("Commissions"); + html.addElement (a); + // --- C.Invoices + a = new a ("commissionedInvoices.jsp"); + a.setClass ("menuDetail"); + a.addElement ("C.Invoices"); + html.addElement (a); + // + nl (html, false); + } // menuSalesRep + + /** + * Add Links for Users. + * Notes + * Expenses + * @param html code + * @param isEmployee employee + * @param wstore web store + */ + private void menuUser (HtmlCode html, boolean isEmployee, MStore wstore) + { + nl (html, true); // ------------ + // --- Notices + if (isEmployee) + { + a a = new a ("notes.jsp"); + a.setClass ("menuMain"); + a.addElement ("Notices"); + html.addElement (a); + // + nl (html, false); + } + // --- Expense + a a = new a ("expenses.jsp"); + a.setClass ("menuSub"); + a.addElement ("Expenses"); + html.addElement (a); + } // menuUser + + /** + * Add New Line / Break + * @param html code + * @param hr insert HR rather BR + */ + private void nl (HtmlCode html, boolean hr) + { + if (m_oneLine) + html.addElement(" - "); + else if (hr) + html.addElement(new hr("90%", "left")); + else + html.addElement(new br()); + } // nl + + /** + * End Tag + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + +} // InfoLinkTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/InfoServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/InfoServlet.java new file mode 100644 index 0000000000..447697923d --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/InfoServlet.java @@ -0,0 +1,175 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import javax.servlet.*; +import javax.servlet.http.*; +import java.io.*; +import java.util.*; + +import org.compiere.model.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Web Store Subscription Info. + * http://dev2/wstore/infoServlet?mode=subscribe&area=1000002&contact=1000000 + * + * @author Jorg Janke + * @version $Id: InfoServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class InfoServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + /** + * Initialize global variables + * @param config servlet configuration + * @throws ServletException + */ + public void init(ServletConfig config) throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("InfoServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Interest Area Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info("destroy"); + } // destroy + + /*************************************************************************/ + + /** + * Process the initial HTTP Get request. + * Reads the Parameter Amt and optional C_Invoice_ID + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // WEnv.dump(session); + // WEnv.dump(request); + + boolean success = processParameter(request); + + String url = "/info.jsp"; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Process the HTTP Post request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doGet (request, response); + } // doPost + + + /************************************************************************** + * Process Parameter and check them + * @param request request + * @return true if processed + */ + private boolean processParameter (HttpServletRequest request) + { + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + Properties ctx = JSPEnv.getCtx(request); + + // mode = subscribe + String mode = WebUtil.getParameter (request, "mode"); + if (mode == null) + return false; + boolean subscribe = !mode.startsWith("un"); + // area = 101 + int R_InterestArea_ID = WebUtil.getParameterAsInt(request, "area"); + MInterestArea ia = MInterestArea.get(ctx, R_InterestArea_ID); + // contact = -1 + int AD_User_ID = WebUtil.getParameterAsInt(request, "contact"); + // + log.fine("Subscribe=" + subscribe + + ",R_InterestArea_ID=" + R_InterestArea_ID + + ",AD_User_ID=" + AD_User_ID); + if (R_InterestArea_ID == 0 || AD_User_ID == 0) + return false; + // + MContactInterest ci = MContactInterest.get (ctx, R_InterestArea_ID, AD_User_ID, false, null); + ci.subscribe(subscribe); + boolean ok = ci.save(); + if (ok) + log.fine("success"); + else + log.log(Level.SEVERE, "subscribe failed"); + + // Lookup user if direct link + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu == null) + { + wu = WebUser.get(ctx, AD_User_ID); + session.setAttribute(WebUser.NAME, wu); + } + sendEMail (request, wu, ia.getName(), subscribe); + + return ok; + } // processParameter + + /** + * Send Subscription EMail. + * @param request request + * @param wu web user + */ + private void sendEMail (HttpServletRequest request, WebUser wu, + String listName, boolean subscribe) + { + String msg = JSPEnv.sendEMail(request, wu, + subscribe ? MMailMsg.MAILMSGTYPE_Subscribe : MMailMsg.MAILMSGTYPE_UnSubscribe, + new Object[]{listName, wu.getName(), listName}); + } // sendEMail + + +} // InfoServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/InvoiceServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/InvoiceServlet.java new file mode 100644 index 0000000000..8386872b70 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/InvoiceServlet.java @@ -0,0 +1,251 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + + +/** + * Check Out. + * + * @author Jorg Janke + * @version $Id: InvoiceServlet.java,v 1.3 2006/09/16 08:32:34 comdivision Exp $ + */ +public class InvoiceServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(InvoiceServlet.class); + /** Name */ + static public final String NAME = "invoiceServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("InvoiceServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Invoice Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine("destroy"); + } // destroy + + + /** + * Process the HTTP Get request. + * (logout, deleteCookie) + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + + String url = "/invoices.jsp"; + // + HttpSession session = request.getSession(false); + if (session == null + || session.getAttribute(WebInfo.NAME) == null) + url = "/login.jsp"; + else + { + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + WebInfo info = (WebInfo)session.getAttribute(WebInfo.NAME); + if (info != null) + info.setMessage(""); + + // Parameter = Invoice_ID - if invoice is valid and belongs to wu then create PDF & stream it + String msg = streamInvoice (request, response); + if (msg == null || msg.length() == 0) + return; + if (info != null) + info.setMessage(msg); + } + + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doGet (request, response); + } // doPost + + + /** + * Stream invoice + * @param request request + * @param response response + * @return "" or error message + */ + private String streamInvoice (HttpServletRequest request, HttpServletResponse response) + { + int MIN_SIZE = 2000; // if not created size is 1015 + + // Get Invoice ID + int C_Invoice_ID = WebUtil.getParameterAsInt (request, "Invoice_ID"); + if (C_Invoice_ID == 0) + { + log.fine("No ID)"); + return "No Invoice ID"; + } + + // Get Invoice + Properties ctx = JSPEnv.getCtx(request); + MInvoice invoice = new MInvoice (ctx, C_Invoice_ID, null); + if (invoice.getC_Invoice_ID() != C_Invoice_ID) + { + log.fine("Invoice not found - ID=" + C_Invoice_ID); + return "Invoice not found"; + } + // Get WebUser & Compare with invoice + HttpSession session = request.getSession(true); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu.getC_BPartner_ID() != invoice.getC_BPartner_ID()) + { + log.warning ("Invoice from BPartner - C_Invoice_ID=" + + C_Invoice_ID + " - BP_Invoice=" + invoice.getC_BPartner_ID() + + " = BP_Web=" + wu.getC_BPartner_ID()); + return "Your invoice not found"; + } + + // Check Directory + String dirName = ctx.getProperty("documentDir", "."); + try + { + File dir = new File (dirName); + if (!dir.exists ()) + dir.mkdir (); + } + catch (Exception ex) + { + log.log(Level.SEVERE, "Could not create directory " + dirName, ex); + return "Streaming error - directory"; + } + // Check if Invoice already created + String fileName = invoice.getPDFFileName (dirName); + File file = new File(fileName); + if (file.exists() && file.isFile() && file.length() > MIN_SIZE) + log.info("Existing: " + file + + " - " + new Timestamp(file.lastModified())); + else + { + log.info("New: " + fileName); + file = invoice.createPDF (file); + if (file != null) + { + invoice.setDatePrinted (new Timestamp(System.currentTimeMillis())); + invoice.save(); + } + } + // Issue Error + if (file == null || !file.exists() || file.length() < MIN_SIZE) + { + log.warning("File does not exist - " + file); + return "Streaming error - file"; + } + + // Send PDF + try + { + int bufferSize = 2048; // 2k Buffer + int fileLength = (int)file.length(); + // + response.setContentType("application/pdf"); + response.setBufferSize(bufferSize); + response.setContentLength(fileLength); + // + log.fine(file.getAbsolutePath() + ", length=" + fileLength); + long time = System.currentTimeMillis(); // timer start + // + FileInputStream in = new FileInputStream (file); + ServletOutputStream out = response.getOutputStream (); + byte[] buffer = new byte[bufferSize]; + double totalSize = 0; + int count = 0; + do + { + count = in.read(buffer, 0, bufferSize); + if (count > 0) + { + totalSize += count; + out.write (buffer, 0, count); + } + } while (count != -1); + out.flush(); + out.close(); + // + in.close(); + time = System.currentTimeMillis() - time; + double speed = (totalSize/1024) / ((double)time/1000); + log.fine("Length=" + + totalSize + " - " + + time + " ms - " + + speed + " kB/sec"); + } + catch (IOException ex) + { + log.log(Level.SEVERE, ex.toString()); + return "Streaming error"; + } + + return null; + } // streamInvoice + +} // InvoiceServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/IssueReportServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/IssueReportServlet.java new file mode 100644 index 0000000000..fd7ef6d1a4 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/IssueReportServlet.java @@ -0,0 +1,159 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Issue Reporting + * + * @author Jorg Janke + * @version $Id: IssueReportServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class IssueReportServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(IssueReportServlet.class); + + /** + * Initialize global variables + * @param config servlet configuration + * @throws ServletException + */ + public void init(ServletConfig config) throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("IssueReportServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Issue Reporting"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info(""); + } // destroy + + + /************************************************************************** + * Process the initial HTTP Get request. + * Reads the Parameter Amt and optional C_Invoice_ID + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + // WEnv.dump(session); + // WEnv.dump(request); + + int AD_Issue_ID = WebUtil.getParameterAsInt(request, "RECORDID"); + String DBAddress = WebUtil.getParameter(request, "DBADDRESS"); + String Comments = WebUtil.getParameter(request, "COMMENTS"); + String IssueString = WebUtil.getParameter(request, "ISSUE"); + // + StringBuffer responseText = new StringBuffer("Adempiere Support - ") + .append(new Date().toString()) + .append("\n"); + MIssue issue = null; + if (AD_Issue_ID != 0) + { + issue = new MIssue(ctx, AD_Issue_ID, null); + if (issue.get_ID() != AD_Issue_ID) + responseText.append("Issue Unknown - Request Ignored"); + else if (!issue.getDBAddress().equals(DBAddress)) + responseText.append("Not Issue Owner - Request Ignored"); + else + { + issue.addComments(Comments); + responseText.append(issue.createAnswer()); + } + } + else if (IssueString == null || IssueString.length() == 0) + { + responseText.append("Unknown Request"); + } + else + { + issue = MIssue.create(ctx, IssueString); + if (issue == null || !issue.save()) + responseText.append("Could not save Issue"); + else + responseText.append(issue.process()); + } + + // + StringBuffer answer = new StringBuffer(); + if (issue != null && issue.get_ID() != 0) + { + answer.append("RECORDID=").append(issue.get_ID()) + .append(MIssue.DELIMITER); + // answer.append("DOCUMENTNO=").append(".") + // .append(MIssue.DELIMITER); + } + answer.append("RESPONSE=").append(responseText); + // + response.setHeader("Cache-Control", "no-cache"); + response.setContentType("text/html; charset=UTF-8"); + PrintWriter out = response.getWriter(); // with character encoding support + out.write(URLEncoder.encode(answer.toString(), "UTF-8")); + out.flush(); + if (out.checkError()) + log.log(Level.SEVERE, "error writing"); + out.close(); + } // doGet + + /** + * Process the HTTP Post request. + * The actual payment processing + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doGet(request, response); + } // doPost + +} // IssueReportServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/JSPEnv.java b/serverApps/src/main/servlet/org/compiere/wstore/JSPEnv.java new file mode 100644 index 0000000000..96080154b8 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/JSPEnv.java @@ -0,0 +1,131 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; + +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * JSP Environment Utilities + * + * @author Jorg Janke + * @version $Id: JSPEnv.java,v 1.5 2006/09/21 20:45:30 jjanke Exp $ + */ +public class JSPEnv +{ + /** + * Get Context from Session + * @param request request + * @return properties + */ + public static Properties getCtx (HttpServletRequest request) + { + WebSessionCtx wsc = WebSessionCtx.get(request); + HttpSession session = request.getSession(true); + + // Add/set current user + WebUser wu = WebUser.get(request); + if (wu != null) + { + int AD_User_ID = wu.getAD_User_ID(); + Env.setContext(wsc.ctx, "#AD_User_ID", AD_User_ID); // security + } + + // Finish + session.setMaxInactiveInterval(1800); // 30 Min HARDCODED + String info = (String)wsc.ctx.get(WebSessionCtx.HDR_INFO); + if (info != null) + session.setAttribute(WebSessionCtx.HDR_INFO, info); + return wsc.ctx; + } // getCtx + + /*************************************************************************/ + + private final static String COOKIE_NAME = "AdempiereWebUser"; + + /** + * Get Web User from Cookie + * @param request request with cookie + * @return web user or null + */ + public static String getCookieWebUser (HttpServletRequest request) + { + Cookie[] cookies = request.getCookies(); + if (cookies == null) + return null; + for (int i = 0; i < cookies.length; i++) + { + if (COOKIE_NAME.equals(cookies[i].getName())) + return cookies[i].getValue(); + } + return null; + } // getCookieWebUser + + /** + * Add Cookie with web user + * @param request request (for context path) + * @param response response to add cookie + * @param webUser email address + */ + public static void addCookieWebUser (HttpServletRequest request, HttpServletResponse response, String webUser) + { + Cookie cookie = new Cookie(COOKIE_NAME, webUser); + cookie.setComment("Adempiere Web User"); + cookie.setPath(request.getContextPath()); + cookie.setMaxAge(2592000); // 30 days in seconds 60*60*24*30 + response.addCookie(cookie); + } // setCookieWebUser + + /** + * Remove Cookie with web user by setting user to _ + * @param request request (for context path) + * @param response response to add cookie + */ + public static void deleteCookieWebUser (HttpServletRequest request, HttpServletResponse response) + { + // Moved over to WebUtil as needed more general also for WebCM + org.compiere.util.WebUtil.deleteCookieWebUser (request, response, COOKIE_NAME); + } // deleteCookieWebUser + + /** + * Get Remote From info + * @param request request + * @return remore info + */ + public static String getFrom (HttpServletRequest request) + { + return WebUtil.getFrom (request); + } // getFrom + + /************************************************************************** + * Send EMail + * @param request request + * @param to web user + * @param msgType see MMailMsg.MAILMSGTYPE_* + * @param parameter object array with parameters + * @return mail EMail.SENT_OK or error message + */ + public static String sendEMail (HttpServletRequest request, WebUser to, + String msgType, Object[] parameter) + { + return WebUtil.sendEMail(request, to, msgType, parameter); + } // sendEMail + +} // JSPEnv diff --git a/serverApps/src/main/servlet/org/compiere/wstore/LocationServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/LocationServlet.java new file mode 100644 index 0000000000..1d1584f73d --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/LocationServlet.java @@ -0,0 +1,175 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import org.compiere.util.CLogger; +import org.compiere.util.WebEnv; +import org.compiere.util.WebSessionCtx; +import org.compiere.util.Util; +import org.compiere.model.MLocation; +import org.compiere.model.MCountry; +import org.compiere.model.MRegion; +import org.apache.taglibs.standard.tag.el.core.ExpressionUtil; +import org.apache.ecs.xhtml.option; +import org.apache.log4j.lf5.LogLevel; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.RequestDispatcher; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Properties; +import java.util.logging.Level; + +import sun.rmi.runtime.Log; + +/** + * Location Servlet + * + * @author Jorg Janke + * @version $Id: LocationServlet.java,v 1.5 2006/07/30 00:53:21 jjanke Exp $ + */ +public class LocationServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + /** + * Initialize global variables + * @param config servlet configuration + * @throws javax.servlet.ServletException + */ + public void init(ServletConfig config) throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("LocationServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Location Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info("destroy"); + } // destroy + + /** + * Process the initial HTTP Get request. + * Reads the Parameter Amt and optional C_Invoice_ID + * + * @param request request + * @param response response + * @throws ServletException + * @throws java.io.IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doPost(request, response); + } // doGet + + /** + * Process the HTTP Post request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + HttpSession session = request.getSession(true); + Properties ctx = JSPEnv.getCtx(request); + MLocation loc = new MLocation (ctx, 0, null); + response.setHeader("Cache-Control", "no-cache"); + response.setContentType("text/xml; charset=UTF-8"); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + + + String cmd = request.getParameter("cmd"); + if(cmd == null) + { + out.println("Unknown Request: NULL"); + }else{ + String selected = request.getParameter("selected"); + int selectedID = 0; + try{ + selectedID = Integer.parseInt(selected); + }catch(Exception e){ + selectedID = 0; + } + + if(cmd.equalsIgnoreCase("countries"))// should probably put these in enum + { + out.println(""); + MCountry[] countries = MCountry.getCountries(loc.getCtx()); + for(MCountry country : countries) + { + int id = country.getC_Country_ID(); + out.print(""+country.getName()+""); + } + out.println(""); + }else if(cmd.equalsIgnoreCase("regions")){ + String country = request.getParameter("country"); + try{ + int countryId = Integer.parseInt(country); + + out.println(""); + MRegion[] regions = MRegion.getRegions(loc.getCtx(), countryId); + if((regions.length > 0) && (selectedID == 0)) + selectedID = regions[0].getC_Region_ID(); + + for(MRegion region : regions) + { + int id = region.getC_Region_ID(); + out.print(""+region.getName()+""); + } + out.println(""); + }catch(Exception e){ + out.println("Unknown Country: " + country + ""); + } + }else{ + out.println("Unknown Request: "+cmd+""); + } + } + + out.flush(); + out.close(); + } // doPost +} diff --git a/serverApps/src/main/servlet/org/compiere/wstore/LocationTag.java b/serverApps/src/main/servlet/org/compiere/wstore/LocationTag.java new file mode 100644 index 0000000000..63e841c051 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/LocationTag.java @@ -0,0 +1,321 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; + +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +import org.apache.ecs.*; +import org.apache.ecs.xhtml.*; +import org.apache.taglibs.standard.tag.el.core.*; +import org.compiere.model.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Location City - Postal - Region - Country (Address). + *
+ *	
+ *	
+ * + * @author Jorg Janke + * @version $Id: LocationTag.java,v 1.3 2006/07/30 00:53:21 jjanke Exp $ + */ +public class LocationTag extends TagSupport +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + private String m_countryID_el; + private String m_regionID_el; + private String m_regionName_el; + private String m_city_el; + private String m_postal_el; + + private MCountry m_country; + + // CSS Classes + private static final String C_MANDATORY = "mandatory"; + private static final String C_ERROR = "error"; + + /** + * Set Country + * @param info_el country info + */ + public void setCountryID (String info_el) + { + m_countryID_el = info_el; + } // setCountry + + /** + * Set Region + * @param info_el region info + */ + public void setRegionID (String info_el) + { + m_regionID_el = info_el; + } // setRegion + + /** + * Set Region + * @param info_el region info + */ + public void setRegionName (String info_el) + { + m_regionName_el = info_el; + } // setRegion + + /** + * Set City + * @param info_el city info + */ + public void setCity (String info_el) + { + m_city_el = info_el; + } // setCity + + /** + * Set Postal + * @param info_el postal info + */ + public void setPostal (String info_el) + { + m_postal_el = info_el; + } // setPostal + + private int getCountryID(MLocation loc) + { + int C_Country_ID = 0; + try + { + String info = (String)ExpressionUtil.evalNotNull ("location", "countryID", + m_countryID_el, String.class, this, pageContext); + if (info != null && info.length () != 0) + C_Country_ID = Integer.parseInt (info); + } + catch (Exception e) + { + log.severe ("Country - " + e); + } + + if (C_Country_ID == 0) + C_Country_ID = loc.getC_Country_ID(); // default + + return C_Country_ID; + } + private int getRegionID(MLocation loc) + { + int C_Region_ID = 0; + try + { + String info = (String)ExpressionUtil.evalNotNull ("location", "regionID", + m_regionID_el, String.class, this, pageContext); + if (info != null && info.length () != 0) + C_Region_ID = Integer.parseInt (info); + } + catch (Exception e) + { + log.log(Level.SEVERE, "RegionID - " + e); + } + if (C_Region_ID == 0) + C_Region_ID = loc.getC_Region_ID(); // default + + return C_Region_ID; + } + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + MLocation loc = new MLocation (ctx, 0, null); + HtmlCode html = new HtmlCode(); + + int C_Country_ID = getCountryID(loc); + int C_Region_ID = getRegionID(loc); + option[] countries = getCountries(loc, C_Country_ID); +// if (m_country != null) m_country.DisplaySequence; + + String name = null; + label lbl = null; + input field = null; + select sel = null; + + // City *********************************************************** + name = "City"; + String city = (String)ExpressionUtil.evalNotNull ("location", "city", + m_city_el, String.class, this, pageContext); + + lbl = new label(); + lbl.setFor(name); + lbl.setID("LBL_"+name); + lbl.addElement(Msg.translate(ctx, name)); + html.addElement(lbl); + + field = new input (input.TYPE_TEXT, name, city); + field.setSize(40).setMaxlength(60).setID("ID_" + name); + field.setClass(C_MANDATORY); + html.addElement(field); + + html.addElement(new br()); + + // Postal *********************************************************** + name = "Postal"; + String postal = (String)ExpressionUtil.evalNotNull ("location", "postal", + m_postal_el, String.class, this, pageContext); + + lbl = new label(); + lbl.setFor(name); + lbl.setID("LBL_"+name); + lbl.addElement(Msg.translate(ctx, name)); + html.addElement(lbl); + + field = new input (input.TYPE_TEXT, name, postal); + field.setSize(10).setMaxlength(10).setID("ID_" + name); + field.setClass(C_MANDATORY); + html.addElement(field); + + html.addElement(new br()); + + + // Region ******************************************************* + name = "C_Region_ID"; + + lbl = new label(); + lbl.setFor(name); + lbl.setID("LBL_"+name); + + String regionName = (String)ExpressionUtil.evalNotNull ("location", "regionName", + m_regionName_el, String.class, this, pageContext); + field = new input (input.TYPE_TEXT, "RegionName", regionName); + field.setSize(40).setMaxlength(60).setID("ID_RegionName"); + if (m_country != null && m_country.isHasRegion()) + { + sel = new select (name, getRegions (loc, C_Country_ID, C_Region_ID)); + sel.setID("ID_" + name); + lbl.addElement(m_country.getRegionName()); + html.addElement(lbl); + html.addElement(sel); + html.addElement(new span(" - ")); + html.addElement(field); + } + else{ + lbl.addElement(Msg.translate(ctx, name)); + html.addElement(lbl); + html.addElement(field); + } + + html.addElement(new br()); + + // Country ******************************************************* + name = "C_Country_ID"; + + lbl = new label(); + lbl.setFor(name); + lbl.setID("LBL_"+name); + lbl.addElement(Msg.translate(ctx, name)); + html.addElement(lbl); + + sel = new select (name, countries); + sel.setID("ID_" + name); + sel.setClass(C_MANDATORY); + sel.setOnChange("changeCountry('ID_"+name+"');"); + html.addElement(sel); + + html.addElement(new br()); + + + + log.fine("C_Country_ID=" + C_Country_ID + ", C_Region_ID=" + C_Region_ID + + ", RegionName=" + regionName + ", City=" + city + ", Postal=" + postal); + + JspWriter out = pageContext.getOut(); + html.output(out); + // + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag - NOP + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + + /** + * Get Country Options. + * Add Regions for selected country + * Set Default + * @param loc MLocation + * @param C_Country_ID default country + * @return array of country options + */ + private option[] getCountries (MLocation loc, int C_Country_ID) + { + MCountry[] countries = MCountry.getCountries(loc.getCtx()); + option[] options = new option[countries.length]; + m_country = null; + // + for (int i = 0; i < countries.length; i++) + { + options[i] = new option (String.valueOf(countries[i].getC_Country_ID())); + options[i].addElement(Util.maskHTML(countries[i].getName())); + if (countries[i].getC_Country_ID() == C_Country_ID) + { + m_country = countries[i]; + options[i].setSelected (true); + } + } + // + return options; + } // getCountries + + /** + * Get Region Options for Country + * @param loc location + * @param C_Country_ID country + * @param C_Region_ID default region + * @return region array + */ + private option[] getRegions (MLocation loc, int C_Country_ID, int C_Region_ID) + { + MRegion[] regions = MRegion.getRegions(loc.getCtx(), C_Country_ID); + option[] options = new option[regions.length+1]; + // + options[0] = new option ("0"); + options[0].addElement(" "); + // + for (int i = 0; i < regions.length; i++) + { + options[i+1] = new option (String.valueOf(regions[i].getC_Region_ID())); + options[i+1].addElement(regions[i].getName()); + if (regions[i].getC_Region_ID() == C_Region_ID) + options[i+1].setSelected(true); + } + return options; + } // getRegions + + +} // LocationTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/LoginLinkTag.java b/serverApps/src/main/servlet/org/compiere/wstore/LoginLinkTag.java new file mode 100644 index 0000000000..9e1691048f --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/LoginLinkTag.java @@ -0,0 +1,216 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; +import org.apache.ecs.xhtml.*; +import org.compiere.util.*; + +/** + * Login Link. + * Creates Login/Logout Link + *
+ *  
+ *  Variable used - "webUser"
+ *	
+ * + * @author Jorg Janke + * @version $Id: LoginLinkTag.java,v 1.3 2006/07/30 00:53:21 jjanke Exp $ + */ +public class LoginLinkTag extends TagSupport +{ + /** Logger */ + protected static CLogger log = CLogger.getCLogger (LoginLinkTag.class); + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + // + WebUser wu = getWebUser(ctx); + if (wu == null) + pageContext.getSession().removeAttribute(WebUser.NAME); + else + pageContext.getSession().setAttribute (WebUser.NAME, wu); + // + String serverContext = ctx.getProperty(WebSessionCtx.CTX_SERVER_CONTEXT); + // log.fine("doStartTag - ServerContext=" + serverContext); + HtmlCode html = null; + if (wu != null && wu.isValid()) + html = getWelcomeLink (serverContext, wu); + else + html = getLoginLink (serverContext); + // + JspWriter out = pageContext.getOut(); + /** + // Delete Cookie Call + if (cookieUser != null && !cookieUser.equals(" ")) + { + log.fine("- Cookie=" + cookieUser); + html.addElement(" "); + a a = new a("loginServlet?mode=deleteCookie"); + a.setClass("menuDetail"); + a.addElement("(Delete Cookie)"); + html.addElement(a); + } + **/ + html.output(out); + // + // + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + + + /** + * Get WebUser. + * @param ctx context + * @return Web User or null + */ + private WebUser getWebUser (Properties ctx) + { + String address = pageContext.getRequest().getRemoteAddr(); + // Get stored User + WebUser wu = (WebUser)pageContext.getSession().getAttribute (WebUser.NAME); + if (wu != null) + { + log.finest("(" + address + ") - SessionContext: " + wu); + } + else + { + wu = (WebUser)pageContext.getAttribute(WebUser.NAME); + if (wu != null) + log.finest ("(" + address + ") - Context: " + wu); + } + if (wu != null) + return wu; + + // Check Coockie + String cookieUser = JSPEnv.getCookieWebUser ((HttpServletRequest)pageContext.getRequest()); + if (cookieUser == null || cookieUser.trim().length() == 0) + log.finer ("(" + address + ") - no cookie"); + else + { + // Try to Load + wu = WebUser.get (ctx, cookieUser); + log.finer ("(" + address + ") - Cookie: " + wu); + } + if (wu != null) + return wu; + // + return null; + } // getWebUser + + + /************************************************************************** + * Get Login Link + * @param serverContext server context + * @return link + */ + private HtmlCode getLoginLink(String serverContext) + { + HtmlCode retValue = new HtmlCode(); + // Login button + input button = new input(input.TYPE_BUTTON, "Login", "Login"); + button.setOnClick("window.top.location.replace('https://" + serverContext + "/loginServlet');"); + retValue.addElement(button); + + /** Link + a a = new a("https://" + serverContext + "/login.jsp"); + a.setClass("menuMain"); + a.addElement("Login"); + retValue.addElement(a); + **/ + + retValue.addElement(" "); + return retValue; + } // getLoginLink + + /** + * Get Welcome Link + * @param serverContext server Context + * @param wu web user + * @return link + */ + private HtmlCode getWelcomeLink(String serverContext, WebUser wu) + { + HtmlCode retValue = new HtmlCode(); + // + a a = new a("https://" + serverContext + "/login.jsp"); + a.setClass("menuMain"); + String msg = "Welcome " + wu.getName(); + a.addElement(msg); + retValue.addElement(a); + // + retValue.addElement("   "); + if (wu.isLoggedIn()) + { + // Verify + if (!wu.isEMailVerified()) + { + input button = new input(input.TYPE_BUTTON, "Verify", "Verify EMail"); + button.setOnClick("window.top.location.replace('emailVerify.jsp');"); + retValue.addElement(button); + retValue.addElement(" "); + } + + // Update + input button = new input(input.TYPE_BUTTON, "Update", "Update User Info"); + button.setOnClick("window.top.location.replace('update.jsp');"); + retValue.addElement(button); + retValue.addElement(" "); + + // Logout + button = new input(input.TYPE_BUTTON, "Logout", "Logout"); + button.setOnClick("window.top.location.replace('loginServlet?mode=logout');"); + retValue.addElement(button); + + /** Link + a = new a ("loginServlet?mode=logout"); + a.setClass ("menuMain"); + a.addElement ("Logout"); + retValue.addElement (a); + **/ + } + else + { + input button = new input (input.TYPE_BUTTON, "Login", "Login"); + button.setOnClick ("window.top.location.replace('https://" + serverContext + "/login.jsp');"); + retValue.addElement (button); + } + retValue.addElement (" "); + // + return retValue; + } // getWelcomeLink + +} // LoginLinkTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/LoginServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/LoginServlet.java new file mode 100644 index 0000000000..f2a6fa8a39 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/LoginServlet.java @@ -0,0 +1,193 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; + +import javax.servlet.*; +import javax.servlet.http.*; + +import org.compiere.model.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Web User Login. + *
+ * 	User posts Login
+ * 	- OK = forward
+ *  - Did not find user
+ * 	- Invalid Password
+ *	
+ * @author Jorg Janke + * @version $Id: LoginServlet.java,v 1.6 2006/10/08 18:17:43 comdivision Exp $ + */ +public class LoginServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + /** Name */ + static public final String NAME = "loginServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("LoginServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Login Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine("destroy"); + } // destroy + + /** + * Process the HTTP Get request. + * (logout, deleteCookie) + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + HttpSession session = request.getSession(true); // create new + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // + // WEnv.dump(request); + Properties ctx = JSPEnv.getCtx(request); // create if required + + org.compiere.util.WebLogin thisLogin = new org.compiere.util.WebLogin(request, response, ctx); + thisLogin.init (); + thisLogin.action (); + String url = thisLogin.getLogin_RelURL (); + + if (!url.startsWith("/")) + url = "/" + url; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + return; + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // WEnv.dump(session); + // WEnv.dump(request); + + + org.compiere.util.WebLogin thisLogin = new org.compiere.util.WebLogin(request, response, ctx); + thisLogin.init (); + + // Forward URL + String url = thisLogin.getForward (); + String salesRep = thisLogin.getSalesRep_ID (); // get SalesRep from request + if (salesRep != null) + session.setAttribute(thisLogin.getP_SalesRep_ID (), salesRep); + boolean checkOut = "Y".equals(session.getAttribute(CheckOutServlet.ATTR_CHECKOUT)); + // Set in login.jsp & addressInfo.jsp + boolean addressConfirm = "Y".equals(WebUtil.getParameter (request, "AddressConfirm")); + if (checkOut) + { + if (addressConfirm) + url = "/orderServlet"; + else + url = "/addressInfo.jsp"; + } + else + addressConfirm = false; + if (url == null || url.length() == 0) + { + url = (String)session.getAttribute(thisLogin.getP_ForwardTo ()); // get from session + if (url == null || url.length() == 0) + url = "/index.jsp"; + } + else + { + if (!url.startsWith("/")) + url = "/" + url; + session.setAttribute(thisLogin.getP_ForwardTo (), url); // save for log in issues + } + + // SalesRep Parameter + salesRep = (String)session.getAttribute(thisLogin.getP_SalesRep_ID ()); // get SalesRep from session + if (salesRep != null) + url += "?SalesRep_ID=" + salesRep; + // + String mode = WebUtil.getParameter (request, "Mode"); + log.fine("- targeting url=" + url + " - mode=" + mode); + + // Web User + WebUser wu = WebUser.get(request); + + // Handover Loginprodcess to general WebLogin Handler + // Frst set the URL from our current situation + thisLogin.setForward (url); + // Also handover adressConfirm + thisLogin.setAddressConfirm (addressConfirm); + // Start the process + thisLogin.action (); + // getback the URL + url = thisLogin.getForward (); + + wu = thisLogin.getWebUser (); + session.setAttribute (WebUser.NAME, wu); + + if (!url.startsWith("/")) + url = "/" + url; + log.info("doPost - Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); + dispatcher.forward(request, response); + } // doPost +} // LoginServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/MessageTag.java b/serverApps/src/main/servlet/org/compiere/wstore/MessageTag.java new file mode 100644 index 0000000000..24775d771e --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/MessageTag.java @@ -0,0 +1,85 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; +import org.compiere.util.*; + +/** + * Message/Translation Tag. + * + * + * @author Jorg Janke + * @version $Id: MessageTag.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class MessageTag extends TagSupport +{ + /** Logger */ + private CLogger log = CLogger.getCLogger (getClass()); + /** Text */ + private String m_txt; + + /** + * Set text + * @param txt text to be translated + */ + public void setTxt (String txt) + { + m_txt = txt; + } // setVar + + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + if (m_txt != null && m_txt.length() > 0) + { + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + String msg = Msg.translate(ctx, m_txt); + log.fine(m_txt + "->" + msg); + // + try + { + JspWriter out = pageContext.getOut(); + out.print (msg); + } + catch (Exception e) + { + throw new JspException(e); + } + } + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + +} // MessageTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/NoteServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/NoteServlet.java new file mode 100644 index 0000000000..5789d0a7f1 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/NoteServlet.java @@ -0,0 +1,216 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Web Notice. + * + * @author Jorg Janke + * @version $Id: NoteServlet.java,v 1.3 2006/09/16 08:32:34 comdivision Exp $ + */ +public class NoteServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + /** Name */ + static public final String NAME = "NoteServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("NoteServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Note Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine("destroy"); + } // destroy + + /*************************************************************************/ + + public static final String P_Note_ID = "AD_Note_ID"; + public static final String P_ATTACHMENT_INDEX = "AttachmentIndex"; + + /** + * Process the HTTP Get request. + * Attachment Download request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + String url = "/notes.jsp"; + // + HttpSession session = request.getSession(false); + if (session == null + || session.getAttribute(WebInfo.NAME) == null) + url = "/login.jsp"; + else + { + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + WebInfo info = (WebInfo)session.getAttribute(WebInfo.NAME); + if (info != null) + info.setMessage(""); + + // Parameter = Note_ID - if is valid and belongs to wu then create PDF & stream it + String msg = streamAttachment (request, response); + if (msg == null || msg.length() == 0) + return; + if (info != null) + info.setMessage(msg); + } + + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Stream Attachment + * @param request request + * @param response response + * @return "" or error message + */ + private String streamAttachment (HttpServletRequest request, HttpServletResponse response) + { + // Get Note ID + int AD_Note_ID = WebUtil.getParameterAsInt(request, P_Note_ID); + if (AD_Note_ID == 0) + { + log.fine("No AD_Note_ID)"); + return "No Notice ID"; + } + int attachmentIndex = WebUtil.getParameterAsInt(request, P_ATTACHMENT_INDEX); + if (attachmentIndex == 0) + { + log.fine("No index)"); + return "No Request Attachment index"; + } + log.info("AD_Notice_ID=" + AD_Note_ID + " / " + attachmentIndex); + + // Get Note + Properties ctx = JSPEnv.getCtx(request); + MNote doc = new MNote (ctx, AD_Note_ID, null); + if (doc.getAD_Note_ID() != AD_Note_ID) + { + log.fine("Note not found - ID=" + AD_Note_ID); + return "Notice not found"; + } + + MAttachment attachment = doc.getAttachment(false); + if (attachment == null) + { + log.fine("No Attachment for AD_Note_ID=" + AD_Note_ID); + return "Notice Attachment not found"; + } + + // Get WebUser & Compare with invoice + HttpSession session = request.getSession(true); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu.getAD_User_ID() != doc.getAD_User_ID()) + { + log.warning ("AD_Note_ID=" + + AD_Note_ID + " - User_ID=" + doc.getAD_User_ID() + + " = Web_User=" + wu.getAD_User_ID()); + return "Your Notice not found"; + } + // Stream it + return WebUtil.streamAttachment (response, attachment, attachmentIndex); + } // streamAttachment + + + /************************************************************************** + * Process the HTTP Post request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + String url = "/notes.jsp"; + + // Get Session attributes + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // + Properties ctx = JSPEnv.getCtx(request); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu == null) + { + log.warning("No web user"); + response.sendRedirect("loginServlet?ForwardTo=notes.jsp"); // entry + return; + } + WebEnv.dump(request); + + int AD_Note_ID = WebUtil.getParameterAsInt(request, P_Note_ID); + String processed = WebUtil.getParameter (request, "Processed"); + boolean prc = processed != null && processed.length() > 0; + if (prc) + { + MNote note = new MNote (ctx, AD_Note_ID, null); + if (note.get_ID() == AD_Note_ID) + { + note.setProcessed(true); + note.save(); + log.fine("doPost - " + note); + } + } + + // Redisplay + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doPost + +} // NoteServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/OrderServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/OrderServlet.java new file mode 100644 index 0000000000..614b461d94 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/OrderServlet.java @@ -0,0 +1,328 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + + +/** + * Web Order. + * + * @author Jorg Janke + * @version $Id: OrderServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class OrderServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(OrderServlet.class); +// private static Logger s_log = Logger.getCLogger(OrderServlet.class); + + /** Name */ + static public final String NAME = "orderServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("OrderServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Order Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + + /************************************************************************** + * Process the HTTP Get request. + * (logout, deleteCookie) + * Sends Web Request Page + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doPost (request, response); + } // doGet + + /** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + + // Web User/Basket + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + WebBasket wb = (WebBasket)session.getAttribute(WebBasket.NAME); + MOrder order = null; + + boolean done = false; + String url = "/paymentInfo.jsp"; + // Not logged in + if (wu == null || !wu.isLoggedIn()) + { + session.setAttribute("CheckOut", "Y"); // indicate checkout + url = "/login.jsp"; + done = true; + } + else + order = getOrder(request, ctx); + + // We have an Order + if (!done && order != null) + { + if (processOrder(request, order)) + url = "/orders.jsp"; + else + { + WebOrder wo = new WebOrder (order); + MPayment p = createPayment (session, ctx, wu, wo); + if (p != null) + { + session.setAttribute (PaymentServlet.ATTR_PAYMENT, p); + session.setAttribute(WebOrder.NAME, wo); + } + else + url = "/orders.jsp"; + } + done = true; + } + + // Nothing in basket + if (!done && (wb == null || wb.getLineCount() == 0)) + { + url = "/basket.jsp"; + done = true; + } + // Create Order & Payment Info + if (!done) + { + WebOrder wo = new WebOrder(wu, wb, ctx); + // We have an order - do delete basket & checkout indicator + if (wo.isInProgress() || wo.isCompleted()) + { + session.removeAttribute(CheckOutServlet.ATTR_CHECKOUT); + session.removeAttribute(WebBasket.NAME); + sendEMail(request, ctx, wo, wu); + } + // If the Order is negative, don't create a payment + if (wo.getGrandTotal().compareTo(Env.ZERO) > 0) + { + session.setAttribute(WebOrder.NAME, wo); + MPayment p = createPayment (session, ctx, wu, wo); + if (p == null) + { + WebUtil.createForwardPage(response, "Payment could not be created", "orders.jsp", 5); + return; + } + else + session.setAttribute (PaymentServlet.ATTR_PAYMENT, p); + } + else + { + url = "/orders.jsp"; + } + } + + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doPost + + + /************************************************************************** + * Create Payment, but don't save it + * @param session session + * @param ctx context + * @param wu web user + * @param wo Order + * @return Payment + */ + private MPayment createPayment(HttpSession session, Properties ctx, + WebUser wu, WebOrder wo) + { + // See PaymentServlet.doGet + MPayment p = new MPayment(ctx, 0, null); + p.setAD_Org_ID(wo.getAD_Org_ID()); + p.setIsSelfService(true); + p.setAmount (wo.getC_Currency_ID(), wo.getGrandTotal ()); // for CC selection + p.setIsOnline (true); + // Sales CC Trx + p.setC_DocType_ID(true); + p.setTrxType(MPayment.TRXTYPE_Sales); + p.setTenderType(MPayment.TENDERTYPE_CreditCard); + // Order Info + p.setC_Order_ID(wo.getC_Order_ID()); + // BP Info + p.setBP_BankAccount(wu.getBankAccount()); + // + return p; + } // createPayment + + /** + * Get Order + * @param request request + * @param ctx context + * @return true if processed + */ + private MOrder getOrder (HttpServletRequest request, Properties ctx) + { + // Order + String para = WebUtil.getParameter (request, "C_Order_ID"); + if (para == null || para.length() == 0) + return null; + int C_Order_ID = 0; + try + { + C_Order_ID = Integer.parseInt (para); + } + catch (NumberFormatException ex) + { + } + if (C_Order_ID == 0) + return null; + + log.fine("C_Order_ID=" + C_Order_ID); + return new MOrder (ctx, C_Order_ID, null); + } // getOrder + + + /** + * Process Order + * @param request request + * @param order order + * @return true if processed/ok + */ + private boolean processOrder (HttpServletRequest request, MOrder order) + { + // Doc Action + String DocAction = WebUtil.getParameter (request, "DocAction"); + if (DocAction == null || DocAction.length() == 0) + return false; + + MDocType dt = MDocType.get(order.getCtx(), order.getC_DocType_ID()); + if (!order.isSOTrx() + || order.getGrandTotal().compareTo(Env.ZERO) <= 0 + || !MDocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType())) + { + log.warning("Not a valid Sales Order " + order); + return true; + } + + // We have a Order No & DocAction + log.fine("DocAction=" + DocAction); + if (!MOrder.DOCACTION_Void.equals(DocAction)) + { + // Do not complete Prepayment + if (MOrder.STATUS_WaitingPayment.equals(order.getDocStatus())) + return false; + if (MDocType.DOCSUBTYPESO_PrepayOrder.equals(dt.getDocSubTypeSO())) + return false; + if (!MOrder.DOCACTION_Complete.equals(DocAction)) + { + log.warning("Invalid DocAction=" + DocAction); + return true; + } + } + order.setDocAction (DocAction, true); // force creation + boolean ok = order.processIt (DocAction); + order.save(); + return ok; + } // processOrder + + + /** + * Send Order EMail. + * @param request request + * @param ctx context + * @param wo web order + * @param wu web user + */ + private void sendEMail (HttpServletRequest request, Properties ctx, WebOrder wo, WebUser wu) + { + StringBuffer message = new StringBuffer("\n"); + // + MOrder mo = wo.getOrder(); + if (mo != null) + { + MOrderLine[] ol = mo.getLines(true, null); + for (int i = 0; i < ol.length; i++) + { + message.append("\n").append(ol[i].getQtyOrdered()).append(" * ") + .append(ol[i].getName()); + if (ol[i].getDescription() != null) + message.append(" - ").append(ol[i].getDescription()); + message.append(" (").append(ol[i].getPriceActual()) + .append(") = ").append(ol[i].getLineNetAmt()); + } // line + } // order + message.append("\n\n") + .append(Msg.getElement(ctx, "C_Order_ID")) + .append(": ") + .append(wo.getDocumentNo()) + .append(" - ").append(Msg.getElement(ctx, "GrandTotal")) + .append(": ").append(wo.getGrandTotal()); + + + JSPEnv.sendEMail(request, wu, MMailMsg.MAILMSGTYPE_OrderAcknowledgement, + new Object[]{ + wo.getDocumentNo(), + wu.getName(), + message.toString()}); + } // sendEMail + + +} // OrderServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/PaymentServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/PaymentServlet.java new file mode 100644 index 0000000000..8a12430ef2 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/PaymentServlet.java @@ -0,0 +1,414 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.math.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.process.*; +import org.compiere.util.*; + +/** + * Web Store Payment Entry & Confirmation + * + * @author Jorg Janke + * @version $Id: PaymentServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class PaymentServlet extends HttpServlet +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(PaymentServlet.class); + + public static final String ATTR_PAYMENT = "payment"; + + /** + * Initialize global variables + * @param config servlet configuration + * @throws ServletException + */ + public void init(ServletConfig config) throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("PaymentServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Payment Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info(""); + } // destroy + + + /************************************************************************** + * Process the initial HTTP Get request. + * Reads the Parameter Amt and optional C_Invoice_ID + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Get from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // WEnv.dump(session); + // WEnv.dump(request); + + // Non existing user or Existing Web Payment + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + MPayment p = (MPayment)session.getAttribute (ATTR_PAYMENT); + if (wu == null) + { + log.info ("No User"); + String url = "/index.jsp"; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } + + // Remove any open Order + session.removeAttribute(WebOrder.NAME); + // Payment Amount + String amtParam = WebUtil.getParameter (request, "Amt"); + if (amtParam == null || amtParam.length() == 0) + { + log.info ("No Payment Amount (" + amtParam + ")"); + doPost (request, response); + return; + } + char[] chars = amtParam.toCharArray(); + StringBuffer sb = new StringBuffer(); + boolean decimal = false; + for (int i = chars.length-1; i >=0; i--) + { + char c = chars[i]; + if (c == ',' || c == '.') + { + if (!decimal) + { + sb.insert (0, '.'); + decimal = true; + } + } + else if (Character.isDigit(c)) + sb.insert(0,c); + } + BigDecimal amt = null; + try + { + if (sb.length() > 0) + { + amt = new BigDecimal (sb.toString ()); + amt = amt.abs (); // make it positive + } + } + catch (Exception ex) + { + log.warning("Parsing Amount=" + amtParam + " (" + sb + ") - " + ex.toString()); + } + // Need to be positive amount + if (amt == null || amt.compareTo(Env.ZERO) < 0) + { + log.info("No valid Payment Amount (" + amtParam + ") - " + amt); + doPost (request, response); + return; + } + + String invoiceParam = WebUtil.getParameter (request, "C_Invoice_ID"); + int C_Invoice_ID = 0; + try + { + if (invoiceParam != null) + C_Invoice_ID = Integer.parseInt (invoiceParam); + } + catch (NumberFormatException ex) + { + log.warning("Parsing C_Invoice_ID=" + invoiceParam + " - " + ex.toString()); + } + log.info("Amt=" + amt + ", C_Invoice_ID=" + C_Invoice_ID); + + // Create New Payment for Amt & optional Invoice + // see OrderServlet.createPayment + p = new MPayment(ctx, 0, null); + // p.setAD_Org_ID(..); + p.setIsSelfService(true); + p.setAmount(0, amt); // for CC selection ges default from Acct Currency + p.setIsOnline(true); + + // Sales CC Trx + p.setC_DocType_ID(true); + p.setTrxType(MPayment.TRXTYPE_Sales); + p.setTenderType(MPayment.TENDERTYPE_CreditCard); + // Payment Info + p.setC_Invoice_ID(C_Invoice_ID); + // BP Info + p.setBP_BankAccount(wu.getBankAccount()); + // + // p.save(); + session.setAttribute (ATTR_PAYMENT, p); + + String url = "/paymentInfo.jsp"; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doGet + + /** + * Process the HTTP Post request. + * The actual payment processing + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("Post from " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + // WEnv.dump(session); + // WEnv.dump(request); + + // Web User/Payment + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + MPayment p = (MPayment)session.getAttribute (ATTR_PAYMENT); + WebOrder wo = (WebOrder)session.getAttribute (WebOrder.NAME); + + String url = null; + if (wu == null || p == null) + url = "/index.jsp"; + else if (processPayment(request, ctx, p, wu, wo)) + url = "/confirm.jsp"; + else + url = "/paymentInfo.jsp"; + + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doPost + + + /************************************************************************** + * Process Payment. + * @param request request + * @param ctx context + * @param payment payment + * @param wu web user + * @param wo web order (optional) + * @return true if processed + */ + private boolean processPayment(HttpServletRequest request, Properties ctx, + MPayment payment, WebUser wu, WebOrder wo) + { + boolean ok = processParameter(request, ctx, payment, wu); + if (ok) + { + // if negative amount - make it positive + if (payment.getPayAmt().compareTo(Env.ZERO) < 0) + payment.setPayAmt(payment.getPayAmt().abs()); + ok = payment.processOnline(); + if (ok) + { + // Process Web Order and Set Invoice ID + if (wo != null) + { + if (!wo.isCompleted()) + wo.process(payment); + if (!wo.isCompleted()) + log.warning("Order not processed " + wo); + } + else + log.warning("No Order"); + // + payment.processIt(DocAction.ACTION_Complete); + payment.save(); + sendThanksEMail (request, ctx, payment, wu, wo); + } + else + { + log.fine(payment.getErrorMessage()); + String errMsg = payment.getErrorMessage(); + payment.save (); + payment.setErrorMessage(errMsg); + request.getSession().setAttribute(WebSessionCtx.HDR_MESSAGE, errMsg); + // + sendDeclineEMail(request, payment, wu, wo); + } + } + return ok; + } // processPayment + + /** + * Process Parameter and check them + * @param request request + * @param ctx context + * @param p payment + * @param wu web user + * @return true if processed + */ + private boolean processParameter (HttpServletRequest request, Properties ctx, MPayment p, WebUser wu) + { + StringBuffer sb = new StringBuffer(); + p.setTenderType(MPayment.TENDERTYPE_CreditCard); + p.setTrxType(MPayment.TRXTYPE_Sales); + p.setA_EMail(wu.getEmail()); + // CC & Number + String ccType = WebUtil.getParameter (request, "CreditCard"); + p.setCreditCardType(ccType); + String ccNumber = WebUtil.getParameter (request, "CreditCardNumber"); + p.setCreditCardNumber (ccNumber); + String AD_Message = MPaymentValidate.validateCreditCardNumber(ccNumber, ccType); + if (AD_Message.length() > 0) + sb.append(Msg.getMsg(ctx, AD_Message)).append(" - "); + + // Optional Verification Code + String ccVV = WebUtil.getParameter (request, "CreditCardVV"); + p.setCreditCardVV(ccVV); + if (ccVV != null && ccVV.length() > 0) + { + AD_Message = MPaymentValidate.validateCreditCardVV (ccVV, ccType); + if (AD_Message.length () > 0) + sb.append (Msg.getMsg (ctx, AD_Message)).append (" - "); + } + // Exp + int mm = WebUtil.getParameterAsInt(request, "CreditCardExpMM"); + p.setCreditCardExpMM (mm); + int yy = WebUtil.getParameterAsInt(request, "CreditCardExpYY"); + p.setCreditCardExpYY (yy); + AD_Message = MPaymentValidate.validateCreditCardExp(mm, yy); + if (AD_Message.length() > 0) + sb.append(Msg.getMsg(ctx, AD_Message)).append(" - "); + + // Account Info + String aName = WebUtil.getParameter (request, "A_Name"); + if (aName == null || aName.length() == 0) + sb.append("Name - "); + else + p.setA_Name(aName); + String aStreet = WebUtil.getParameter (request, "A_Street"); + p.setA_Street(aStreet); + String aCity = WebUtil.getParameter (request, "A_City"); + if (aCity == null || aCity.length() == 0) + sb.append("City - "); + else + p.setA_City(aCity); + String aState = WebUtil.getParameter (request, "A_State"); + p.setA_State(aState); + String aZip = WebUtil.getParameter (request, "A_Zip"); + if (aZip == null || aZip.length() == 0) + sb.append("Zip - "); + else + p.setA_Zip(aZip); + String aCountry = WebUtil.getParameter (request, "A_Country"); + p.setA_Country(aCountry); + + // Error Message + boolean ok = sb.length() == 0; + p.setErrorMessage(sb.toString()); // always set + + // Save BP Bank Account + if (ok) + { + String SP = "SavePayment"; + String SavePayment = WebUtil.getParameter (request, SP); + if (SP.equals(SavePayment)) + p.saveToBP_BankAccount(wu.getBankAccount()); + } + // + return ok; + } // processParameter + + + /** + * Send Payment EMail. + * @param request request + * @param p payment + * @param wu web user + * @param wo optional web order + */ + private void sendThanksEMail (HttpServletRequest request, Properties ctx, + MPayment p, WebUser wu, WebOrder wo) + { + StringBuffer message = new StringBuffer() + .append(p.getPayAmt()) + .append(" (").append(Msg.getElement(ctx, "R_PnRef")) + .append("=").append(p.getR_PnRef()).append(") "); + if (wo != null) + message.append("\n").append(Msg.getElement(ctx, "C_Order_ID")) + .append(": ").append(wo.getDocumentNo()); + + JSPEnv.sendEMail(request, wu, MMailMsg.MAILMSGTYPE_PaymentAcknowledgement, + new Object[]{ + p.getDocumentNo() + " (" + p.getPayAmt() + ")", + wu.getName(), + message.toString()}); + // SalesRep EMail + if (wo != null && wo.getSalesRep_ID() != 0) + { + MClient client = MClient.get(ctx); + client.sendEMail(wo.getSalesRep_ID(), + "(CC) Payment: " + p.getDocumentNo() + " (" + p.getPayAmt() + ")", + "Order: " + wo.getDocumentNo() + + "\nUser: " + wu.getName() + " - " + wu.getEmail(), + null); + } + } // sendEMail + + /** + * Send Payment EMail. + * @param request request + * @param p payment + * @param wu web user + */ + private void sendDeclineEMail (HttpServletRequest request, + MPayment p, WebUser wu, WebOrder wo) + { + StringBuffer message = new StringBuffer(p.getErrorMessage()) + .append(" - ").append(p.getCurrencyISO()).append(" ").append(p.getPayAmt()) + .append(" (Reference=").append(p.getR_PnRef()).append(") "); + if (wo != null) + message.append("\nfor Order: ").append(wo.getDocumentNo()); + + JSPEnv.sendEMail(request, wu, MMailMsg.MAILMSGTYPE_PaymentError, + new Object[]{ + p.getDocumentNo() + " (" + p.getCurrencyISO() + " " + p.getPayAmt() + ")", + wu.getName(), + message.toString()}); + } // sendDeclineEMail + +} // PaymentServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/PriceList.java b/serverApps/src/main/servlet/org/compiere/wstore/PriceList.java new file mode 100644 index 0000000000..188f74cfb8 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/PriceList.java @@ -0,0 +1,466 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.sql.*; +import java.util.*; +import org.compiere.model.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Price List. + * ArrayList of PriceListProduct + * Implementation assumes a relatively small price list (< 200) + * This is the case, if the product is selected in the WebStore, + * but not if it is added via a direct link. In that case, it will + * load all products(!) + * + * @author Jorg Janke + * @version $Id: PriceList.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class PriceList +{ + /** + * Get Price List + * @param AD_Client_ID client + * @param M_PriceList_ID price list + * @param searchString query search string + * @param productCategory query product category string + * @param allRecords all if no query + * @return Price list + */ + public static PriceList get (Properties ctx, int AD_Client_ID, int M_PriceList_ID, + String searchString, String productCategory, boolean allRecords) + { + // Search Parameter + String search = searchString; + if (search != null && (search.length() == 0 || search.equals("%"))) + search = null; + if (search != null) + { + if (!search.endsWith("%")) + search += "%"; + if (!search.startsWith("%")) + search = "%" + search; + search = search.toUpperCase(); + } + int M_Product_Category_ID = 0; + try + { + if (productCategory != null && productCategory.length() > 0) + M_Product_Category_ID = Integer.parseInt(productCategory); + } + catch (Exception e) + {} + if (M_Product_Category_ID < 0) + M_Product_Category_ID = 0; + + // Search Price List Cache + String key = String.valueOf(AD_Client_ID) + "_" + M_PriceList_ID; + PriceList retValue = null; + if (search == null && M_Product_Category_ID == 0 && allRecords) + retValue = (PriceList)s_cache.get(key); + + // create New + if (retValue == null) + { + retValue = new PriceList (ctx, AD_Client_ID, M_PriceList_ID, + search, M_Product_Category_ID, allRecords); + if (search == null && M_Product_Category_ID == 0 && allRecords) + s_cache.put(key, retValue); + } + return retValue; + } // get + + /** Price List Cache */ + private static CCache s_cache + = new CCache("PriceList", 5, 60); // 1h Cache + /** Maximum Lines to be displayed */ + public static int MAX_LINES = 50; + + + /************************************************************************* + * PriceList constructor. + * @param ctx context + * @param AD_Client_ID client + * @param M_PriceList_ID optional price list + * @param searchString query search string + * @param M_Product_Category_ID query product category + * @param allRecords all if no query + */ + private PriceList (Properties ctx, int AD_Client_ID, int M_PriceList_ID, + String searchString, int M_Product_Category_ID, boolean allRecords) + { + log.finer("AD_Client_ID=" + AD_Client_ID + ", M_PriceList_ID=" + M_PriceList_ID + + ", Search=" + searchString + ",M_Product_Category_ID=" + M_Product_Category_ID + + ", All=" + allRecords); + m_ctx = ctx; + + // Get Price List + if (getM_PriceList_ID (AD_Client_ID, M_PriceList_ID) == 0) + if (getM_PriceList_ID(AD_Client_ID, 0) == 0) + return; + + // Get Price List Version + getM_PriceList_Version_ID(m_PriceList_ID, new Timestamp(System.currentTimeMillis())); + loadProducts (searchString, M_Product_Category_ID, allRecords); + } // PriceList + + /** Attribute Name - also in JSPs */ + public static final String NAME = "priceList"; + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + private String m_name = "Not found"; + private String m_description; + private String m_currency; + private String m_curSymbol; + private String m_AD_Language; + private boolean m_taxIncluded; + private int m_PriceList_ID = 0; + private int m_PriceList_Version_ID = 0; + private String m_searchInfo = ""; + private boolean m_notAllPrices = false; + + /** Price Lines */ + private ArrayList m_prices = new ArrayList(); + /** Context */ + private Properties m_ctx; + + /** + * Find Price List + * @param AD_Client_ID client + * @param M_PriceList_ID optional price list + * @return M_PriceList_ID + */ + private int getM_PriceList_ID (int AD_Client_ID, int M_PriceList_ID) + { + String sql = "SELECT M_PriceList_ID, pl.Name, pl.Description, pl.IsTaxIncluded," // 1..4 + + " c.ISO_Code, c.CurSymbol, cc.AD_Language " // 5..7 + + "FROM M_PriceList pl" + + " INNER JOIN C_Currency c ON (pl.C_Currency_ID=c.C_Currency_ID)" + // begin globalqss 29/09/2005 -- problem with postgres port + // + " LEFT OUTER JOIN C_Country cc ON (c.C_Currency_ID=cc.C_Currency_ID AND ROWNUM=1) " + + " LEFT OUTER JOIN C_Country cc ON (c.C_Currency_ID=cc.C_Currency_ID) " + // end globalqss 29/09/2005 + + "WHERE pl.IsActive='Y'" + + " AND pl.AD_Client_ID=?"; // #1 + if (M_PriceList_ID != 0) + sql += " AND pl.M_PriceList_ID=?"; // #2 + else + sql += " ORDER BY pl.IsDefault DESC"; + m_PriceList_ID = 0; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Client_ID); + if (M_PriceList_ID != 0) + pstmt.setInt(2, M_PriceList_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + m_PriceList_ID = rs.getInt(1); + m_name = rs.getString(2); + m_description = rs.getString(3); + m_taxIncluded = "Y".equals(rs.getString(4)); + m_currency = rs.getString(5); + m_curSymbol = rs.getString(6); + m_AD_Language = rs.getString(7); + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, "getM_PriceList_ID", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return m_PriceList_ID; + } // getM_PriceList_ID + + /** + * Get PL Version + * @param M_PriceList_ID price list + * @param day valid day + * @return M_PriceList_Version_ID + */ + private int getM_PriceList_Version_ID (int M_PriceList_ID, Timestamp day) + { + String sql = "SELECT plv.M_PriceList_Version_ID, plv.Name, plv.Description, plv.ValidFrom " // 1..4 + + "FROM M_PriceList_Version plv " + + "WHERE plv.M_PriceList_ID=?" // #1 + + " AND plv.ValidFrom <=? " // #2 + + "ORDER BY plv.ValidFrom DESC"; + PreparedStatement pstmt = null; + m_PriceList_Version_ID = 0; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, M_PriceList_ID); + pstmt.setTimestamp(2, day); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + m_PriceList_Version_ID = rs.getInt(1); + m_name = rs.getString(2); + m_description = rs.getString(3); + // m_validFrom = rs.getTimestamp(4); + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, "getM_PriceList_Version_ID", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + + return m_PriceList_Version_ID; + } // getM_PriceList_Version_ID + + /** + * Load From Product Price + * @param searchString query search string + * @param M_Product_Category_ID query product category + * @param allRecords all only true if called from BasketServlet + */ + private void loadProducts (String searchString, int M_Product_Category_ID, boolean allRecords) + { + // Set Search String + log.finer("loadProducts - M_PriceList_Version_ID=" + m_PriceList_Version_ID + + ", Search=" + searchString + ", M_Product_Category_ID=" + M_Product_Category_ID); + m_searchInfo = ""; + if (searchString != null) + m_searchInfo = searchString; + if (M_Product_Category_ID != 0) + { + if (m_searchInfo.length() != 0) + m_searchInfo += " - "; + m_searchInfo += MProductCategory.get(m_ctx, M_Product_Category_ID).getName(); + } + + m_prices.clear(); + m_notAllPrices = false; + // + String sql = "SELECT p.M_Product_ID, p.Value, p.Name, p.Description, " // 1..4 + + "p.Help, p.DocumentNote, p.ImageURL, p.DescriptionURL, " // 5..8 + + "pp.PriceStd, uom.Name, uom.UOMSymbol " // 9..11 + + "FROM M_ProductPrice pp " + + " INNER JOIN M_Product p ON (pp.M_Product_ID=p.M_Product_ID AND p.IsActive='Y' AND p.IsSold='Y')" + + " INNER JOIN C_UOM uom ON (p.C_UOM_ID=uom.C_UOM_ID) " + + "WHERE pp.M_PriceList_Version_ID=?" // #1 + + " AND pp.PriceStd > 0 " + + " AND p.IsSelfService='Y'"; + if (searchString != null) + sql += " AND UPPER(p.Value||p.Name||p.Description) LIKE ? "; // #2 + if (M_Product_Category_ID != 0) + sql += " AND p.M_Product_Category_ID=? "; // #3 + if (!allRecords && searchString == null && M_Product_Category_ID == 0) + { + sql += " AND p.IsWebStoreFeatured='Y' "; + m_notAllPrices = true; + } + sql += "ORDER BY p.M_Product_Category_ID, p.Value"; + // log.fine("loadProducts - " + sql); + + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + int index = 1; + pstmt.setInt(index++, m_PriceList_Version_ID); + if (searchString != null) + pstmt.setString(index++, searchString); + if (M_Product_Category_ID != 0) + pstmt.setInt(index++, M_Product_Category_ID); + ResultSet rs = pstmt.executeQuery(); + int no = 0; + while (rs.next()) + { + m_prices.add (new PriceListProduct( + rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), + rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), + rs.getBigDecimal(9), rs.getString(10), rs.getString(11) )); + // if not all records limit list + if (!allRecords && ++no > MAX_LINES) + { + m_notAllPrices = true; + break; + } + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, "load", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + log.fine("load #" + m_prices.size() + ", Search=" + m_searchInfo); + } // load + + + /************************************************************************** + * String Representation + * @return info + */ + public String toString() + { + StringBuffer sb = new StringBuffer("PriceList["); + sb.append(m_prices.size()) + .append("]"); + return sb.toString(); + } // toString + + /** + * Get Count + * @return size + */ + public int getPriceCount() + { + return m_prices.size(); + } // getPriceCount + + /** + * No Prices + * @return true if no prices + */ + public boolean isNoLines() + { + return getPriceCount() == 0; + } // getPriceCount + + /** + * Not all Prices displayed + * @return true if no prices + */ + public boolean isNotAllPrices() + { + return m_notAllPrices; + } // isNotAllPrices + + + /** + * Get Prices + * @return Price Array List + */ + public ArrayList getPrices() + { + return m_prices; + } // getPrices + + /** + * Get Price List for Product. + * Implementation assumes a relatively small price list (< 200) + * @param M_Product_ID product + * @return price list info or null + */ + public PriceListProduct getPriceListProduct (int M_Product_ID) + { + for (int i = 0; i < m_prices.size (); i++) + { + PriceListProduct plp = (PriceListProduct)m_prices.get (i); + if (plp.getId () == M_Product_ID) + return plp; + } + return null; + } // getPriceListProduct + + /** + * Get Search Info + * @return search info + */ + public String getSearchInfo() + { + return m_searchInfo; + } // getSearchInfo + + /*************************************************************************/ + + /** + * Get Name + * @return Price List Name + */ + public String getName() + { + return m_name; + } + public String getDescription() + { + return m_description; + } + public String getCurrency() + { + return m_currency; + } + public String getCurSymbol() + { + return m_curSymbol; + } + public String getAD_Language() + { + return m_AD_Language; + } + public boolean isTaxIncluded() + { + return m_taxIncluded; + } + public int getPriceList_ID() + { + return m_PriceList_ID; + } + public int getPriceList_Version_ID() + { + return m_PriceList_Version_ID; + } + +} // PriceList diff --git a/serverApps/src/main/servlet/org/compiere/wstore/PriceListProduct.java b/serverApps/src/main/servlet/org/compiere/wstore/PriceListProduct.java new file mode 100644 index 0000000000..dab9dbb66a --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/PriceListProduct.java @@ -0,0 +1,154 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.math.*; +import org.compiere.util.*; + +/** + * Price List Product + * + * @author Jorg Janke + * @version $Id: PriceListProduct.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class PriceListProduct +{ + /** + * Price List Product. + * @param M_Product_ID product + * @param value value + * @param name name + * @param description descriprion + * @param help help + * @param documentNote document note + * @param imageURL image + * @param descriptionURL description + * @param price price + * @param uomName uom + * @param uomSymbol uom + */ + public PriceListProduct (int M_Product_ID, String value, String name, String description, + String help, String documentNote, String imageURL, String descriptionURL, + BigDecimal price, String uomName, String uomSymbol) + { + // + m_Product_ID = M_Product_ID; + m_value = value; + m_name = name; + m_description = description; + // Help, DocumentNote, ImageURL, DescriptionURL, + m_help = help; + m_documentNote = documentNote; + m_imageURL = imageURL; + m_descriptionURL = descriptionURL; + // PriceStd, UOMName, UOMSymbol + m_price = price; + m_uomName = uomName; + m_uomSymbol = uomSymbol; + } // PriceListProduct + + /** Attribute Name */ + public static final String NAME = "PriceListProduct"; + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + private int m_Product_ID; + private String m_value; + private String m_name; + private String m_description; + + private String m_help; + private String m_documentNote; + private String m_imageURL; + private String m_descriptionURL; + + private BigDecimal m_price; + private String m_uomName; + private String m_uomSymbol; + + + /** + * String Representation + * @return info + */ + public String toString() + { + StringBuffer sb = new StringBuffer("PriceListProduct["); + sb.append(m_Product_ID).append("-").append(m_name) + .append("-").append(m_price) + .append("]"); + return sb.toString(); + } // toString + + /*************************************************************************/ + + /** + * Get Product IO + * @return M_Product_ID + */ + public int getId() + { + return m_Product_ID; + } + public String getValue() + { + return m_value; + } + /** + * Get Name + * @return name + */ + public String getName() + { + return m_name; + } + public String getDescription() + { + return m_description; + } + public String getHelp() + { + return m_help; + } + + public String getDocumentNote() + { + return m_documentNote; + } + public String getImageURL() + { + return m_imageURL; + } + public String getDescriptionURL() + { + return m_descriptionURL; + } + + public BigDecimal getPrice() + { + return m_price; + } + public String getUomName() + { + return m_uomName; + } + public String getUomSymbol() + { + return m_uomSymbol; + } + +} // PriceListProduct diff --git a/serverApps/src/main/servlet/org/compiere/wstore/PriceListTag.java b/serverApps/src/main/servlet/org/compiere/wstore/PriceListTag.java new file mode 100644 index 0000000000..aab83c1604 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/PriceListTag.java @@ -0,0 +1,126 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.jstl.core.*; +import javax.servlet.jsp.tagext.*; +import org.compiere.util.*; + +/** + * PriceList Tag. + * Loads Price List + *
+ *  
+ *  Variable used = "priceList"
+ *	
+ * + * @author Jorg Janke + * @version $Id: PriceListTag.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class PriceListTag extends TagSupport +{ + /** Price List ID */ + private int m_priceList_ID = 0; + + /** Web User */ + private PriceList m_priceList; + /** Logger */ + private CLogger log = CLogger.getCLogger (getClass()); + + /** + * Set Price List + * @param var price list + */ + public void setPriceList_ID (String var) + { + try + { + m_priceList_ID = Integer.parseInt (var); + } + catch (NumberFormatException ex) + { + log.warning("setPriceList_ID - " + ex.toString()); + } + } // setM_PriceList_ID + + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + // Create Price List + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + int AD_Client_ID = Env.getContextAsInt(ctx, "AD_Client_ID"); + int M_PriceList_ID = m_priceList_ID; + if (M_PriceList_ID == 0) + M_PriceList_ID = Env.getContextAsInt(ctx, "M_PriceList_ID"); + + // Check Business Partner + WebUser wu = (WebUser)pageContext.getSession().getAttribute(WebUser.NAME); + if (wu != null) + { + int PriceList_ID = wu.getM_PriceList_ID(); + if (PriceList_ID != 0) + { + log.fine("- using BP PriceList_ID=" + PriceList_ID); + M_PriceList_ID = PriceList_ID; + } + } + + // Get Parameters + String searchString = ctx.getProperty(ProductServlet.P_SEARCHSTRING); + String productCategory = ctx.getProperty(ProductServlet.P_M_PRODUCT_CATEGORY_ID); + + + // get price list + m_priceList = PriceList.get (ctx, AD_Client_ID, M_PriceList_ID, + searchString, productCategory, false); + if (M_PriceList_ID == 0) + Env.setContext(ctx, "#M_PriceList_ID", m_priceList.getPriceList_ID()); + + // Set Price List + HttpSession session = pageContext.getSession(); + session.setAttribute (PriceList.NAME, m_priceList); + log.fine("PL=" + m_priceList); + + // Set Locale from Price List + String AD_Language = m_priceList.getAD_Language(); + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = "en_US"; + Config.set(session, Config.FMT_LOCALE, AD_Language); + Config.set(session, Config.FMT_FALLBACK_LOCALE, "en_US"); + // + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + +} // PriceListTag diff --git a/serverApps/src/main/servlet/org/compiere/wstore/ProductCategoryListTag.java b/serverApps/src/main/servlet/org/compiere/wstore/ProductCategoryListTag.java new file mode 100644 index 0000000000..e4348b2bd1 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/ProductCategoryListTag.java @@ -0,0 +1,121 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.util.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; +import org.apache.ecs.xhtml.*; +import org.compiere.util.*; + +/** + * Product Category List + * + * + * + * + * @author Jorg Janke + * @version $Id: ProductCategoryListTag.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class ProductCategoryListTag extends TagSupport +{ + /** Logging */ + private static CLogger log = CLogger.getCLogger(ProductCategoryListTag.class); + + + /** + * Start Tag + * @return SKIP_BODY + * @throws JspException + */ + public int doStartTag() throws JspException + { + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + + int AD_Client_ID = Env.getAD_Client_ID(ctx); + String name = "M_Product_Category_ID"; + + option[] options = getCategories (AD_Client_ID); + select sel = new select (name, options); + sel.setID("ID_" + name); + + log.fine("AD_Client_ID=" + AD_Client_ID + ", #=" + options.length); + + // Assemble + HtmlCode html = new HtmlCode(); + html.addElement(sel); + + JspWriter out = pageContext.getOut(); + html.output(out); + // + return (SKIP_BODY); + } // doStartTag + + /** + * End Tag - NOP + * @return EVAL_PAGE + * @throws JspException + */ + public int doEndTag() throws JspException + { + return EVAL_PAGE; + } // doEndTag + + /** + * Get Product Category Options. + * @param AD_Client_ID client + * @return array of category options + */ + private option[] getCategories (int AD_Client_ID) + { + option[] options = (option[])s_categories.get(new Integer(AD_Client_ID)); + if (options != null) + return options; + + String sql = "SELECT M_Product_Category_ID, Name " + + "FROM M_Product_Category " + + "WHERE AD_Client_ID=" + AD_Client_ID + + " AND IsActive='Y' AND IsSelfService='Y' " + + "ORDER BY Name"; + KeyNamePair[] pairs = DB.getKeyNamePairs(sql, true); + options = new option[pairs.length]; + // + for (int i = 0; i < pairs.length; i++) + { + if (i == 0) + { + options[i] = new option ("-1"); + options[i].addElement(" "); + } + else + { + options[i] = new option (pairs[i].getID()); + options[i].addElement(Util.maskHTML(pairs[i].getName())); + } + } + // + s_categories.put(new Integer(AD_Client_ID), options); + return options; + } // getCountries + + /** Client Category Cache */ + static CCache s_categories + = new CCache("ProductCategory", 10, 60); + +} // ProductCategoryListTag + diff --git a/serverApps/src/main/servlet/org/compiere/wstore/ProductServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/ProductServlet.java new file mode 100644 index 0000000000..b12ab7a242 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/ProductServlet.java @@ -0,0 +1,129 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.util.*; + +/** + * Web Product Serach + * + * @author Jorg Janke + * @version $Id: ProductServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class ProductServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + + /** + * Initialize global variables + * @param config servlet configuration + * @throws ServletException + */ + public void init(ServletConfig config) throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("ProductServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Product Serach Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.info("destroy"); + } // destroy + + public static String P_SEARCHSTRING = "SearchString"; + public static String P_M_PRODUCT_CATEGORY_ID = "M_Product_Category_ID"; + + + /*************************************************************************/ + + /** + * Process the HTTP Post request. + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + + Properties ctx = JSPEnv.getCtx(request); + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // WEnv.dump(session); + // WEnv.dump(request); + + // Web User + // WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + + // Save in ctx for PriceListTag + + // Search Parameter + String searchString = WebUtil.getParameter (request, P_SEARCHSTRING); + if (searchString != null) + ctx.put(P_SEARCHSTRING, searchString); + // Product Category + String category = WebUtil.getParameter (request, P_M_PRODUCT_CATEGORY_ID); + if (category != null) + ctx.put(P_M_PRODUCT_CATEGORY_ID, category); + + // Forward + String url = "/index.jsp"; + log.info ("Forward to " + url); + RequestDispatcher dispatcher = getServletContext().getRequestDispatcher (url); + dispatcher.forward (request, response); + } // doPost + + + + /** + * Process the initial HTTP Get request. + * Reads the Parameter Amt and optional C_Invoice_ID + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + doPost (request, response); + } // doGet + +} // ProductServlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/RegistrationServlet.java b/serverApps/src/main/servlet/org/compiere/wstore/RegistrationServlet.java new file mode 100644 index 0000000000..811ce79c2b --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/RegistrationServlet.java @@ -0,0 +1,282 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.io.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.servlet.*; +import javax.servlet.http.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Registration Servlet. + * + * @author Jorg Janke + * @version $Id: RegistrationServlet.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class RegistrationServlet extends HttpServlet +{ + /** Logging */ + private CLogger log = CLogger.getCLogger(getClass()); + /** Name */ + static public final String NAME = "RegistrationServlet"; + + /** + * Initialize global variables + * + * @param config Configuration + * @throws ServletException + */ + public void init(ServletConfig config) + throws ServletException + { + super.init(config); + if (!WebEnv.initWeb(config)) + throw new ServletException("RegistrationServlet.init"); + } // init + + /** + * Get Servlet information + * @return Info + */ + public String getServletInfo() + { + return "Adempiere Web Registration Servlet"; + } // getServletInfo + + /** + * Clean up resources + */ + public void destroy() + { + log.fine(""); + } // destroy + + /*************************************************************************/ + + public static final String P_REGISTRATION_ID = "A_Registration_ID"; + + /** Thanks Msg */ + private String THANKS = "Thank you for your registration!"; + /** Problem Msg */ + private String PROBLEM = "Thank you for your registration - We experienced a problem - please let us know!"; + + /************************************************************************** + * Process the HTTP Get request. + * If not System registration - forward to registration.jsp + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + if (!processSystemRegistration(request, response)) + { + log.info("Forward to registration.jsp"); + response.sendRedirect("registration.jsp"); + } + } // doGet + + /** + * Process System Registration + * @param request request + * @param response response + * @return true if System Registration + */ + private boolean processSystemRegistration (HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + // System Info + String name = WebUtil.getParameter (request, "Name"); + String userName = WebUtil.getParameter (request, "UserName"); + String password = WebUtil.getParameter (request, "Password"); + // Not a System registration + if ((name == null || name.length() == 0)&& (userName == null || userName.length() == 0) && (password == null || password.length() == 0)) + return false; + log.info ("Name=" + name + ", User=" + userName); + // Registration Info + String description = WebUtil.getParameter (request, "Description"); + boolean inProduction = WebUtil.getParameterAsBoolean(request, "IsInProduction", "Y"); + Timestamp startDate = WebUtil.getParameterAsDate (request, "StartProductionDate"); + if (startDate == null) + startDate = new Timestamp(System.currentTimeMillis()); + boolean allowPublish = WebUtil.getParameterAsBoolean (request, "IsAllowPublish", "Y"); + boolean registered = WebUtil.getParameterAsBoolean (request, "IsRegistered", "Y"); + int Record_ID = WebUtil.getParameterAsInt(request, "Record_ID"); + + // Find User + Properties ctx = JSPEnv.getCtx(request); + MUser user = null; + int AD_User_ID = DB.getSQLValue(null, + "SELECT AD_User_ID FROM AD_User WHERE EMail=?", userName); + if (AD_User_ID > 0) + user = MUser.get(ctx, AD_User_ID); + else + log.warning("User Not found=" + userName); + + // Registration + MRegistration reg = null; + if (Record_ID > 0) + { + reg = new MRegistration (ctx, Record_ID, null); + if (reg.get_ID() != Record_ID) + { + log.warning("Registration Not found=" + Record_ID); + reg = null; + } + else if (user != null) + { + if (reg.getC_BPartner_ID() != user.getC_BPartner_ID()) + { + log.warning("Registration for different BP - AD_User_ID=" + + AD_User_ID + "(" + user.getEMail() + + "), BP RegistrationBP=" + reg.getC_BPartner_ID() + + "<>UserBP=" + user.getC_BPartner_ID()); + reg = null; + } + if (!password.equals(user.getPassword())) + { + log.warning("Password does not match - AD_User_ID=" + + AD_User_ID + "(" + user.getEMail() + ")"); + // ?? + } + } + } + if (reg == null) + { + log.fine("New Registration"); + reg = new MRegistration (ctx, name, allowPublish, inProduction, startDate, null); + Record_ID = 0; + } + // Common Update + reg.setDescription(description); + reg.setRemote_Addr(request.getRemoteAddr()); + reg.setRemote_Host(request.getRemoteHost()); + // User + if (user != null) + { + reg.setAD_User_ID(user.getAD_User_ID()); + reg.setC_BPartner_ID(user.getC_BPartner_ID()); + } + if (reg.save()) + { + if (Record_ID == 0) + reg.loadAttributeValues(request); // new + else + reg.updateAttributeValues(request); // existing + sendAnswer (response, THANKS + " Record_ID=" + reg.getA_Registration_ID()); + } + else + { + log.log(Level.SEVERE, "Registration not saved"); + sendAnswer (response, PROBLEM + " Record_ID=0"); + } + return true; + } // processSystemRegistration + + /** + * Send Answer + * @param response response + * @param answer answer + * @throws IOException + */ + private void sendAnswer (HttpServletResponse response, String answer) + throws IOException + { + response.setHeader("Cache-Control", "no-cache"); + response.setContentType("text/html; charset=UTF-8"); + PrintWriter out = response.getWriter(); // with character encoding support + out.print(answer); + out.flush(); + } // sendAnswer + + /************************************************************************** + * Process the HTTP Post request + * + * @param request request + * @param response response + * @throws ServletException + * @throws IOException + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException + { + log.info("From " + request.getRemoteHost() + " - " + request.getRemoteAddr()); + + // Get Session attributes + HttpSession session = request.getSession(true); + session.removeAttribute(WebSessionCtx.HDR_MESSAGE); + // + Properties ctx = JSPEnv.getCtx(request); + WebUser wu = (WebUser)session.getAttribute(WebUser.NAME); + if (wu == null) + { + log.warning("No web user"); + response.sendRedirect("loginServlet?ForwardTo=registration.jsp"); // entry + return; + } + int A_Registration_ID = WebUtil.getParameterAsInt(request, P_REGISTRATION_ID); + MRegistration reg = null; + if (A_Registration_ID > 0) + reg = new MRegistration (ctx, A_Registration_ID, null); + if (reg == null) + { + reg = new MRegistration (ctx, 0, null); + A_Registration_ID = 0; + } + // + String name = WebUtil.getParameter (request, "Name"); + if (name == null || name.length() == 0) + { + WebUtil.createForwardPage(response, "Name is Mandatory", "registrations.jsp", 4); + return; + } + reg.setName(name); + String description = WebUtil.getParameter (request, "Description"); + if (description != null && description.length() > 0) + reg.setDescription(description); + boolean isInProduction = WebUtil.getParameterAsBoolean (request, "IsInProduction"); + reg.setIsInProduction(isInProduction); + Timestamp assetServiceDate = WebUtil.getParameterAsDate (request, "AssetServiceDate"); + if (assetServiceDate == null) + assetServiceDate = new Timestamp(System.currentTimeMillis()); + reg.setAssetServiceDate(assetServiceDate); + boolean isAllowPublish = WebUtil.getParameterAsBoolean (request, "IsAllowPublish"); + reg.setIsAllowPublish(isAllowPublish); + if (reg.save()) + { + if (A_Registration_ID == 0) + reg.loadAttributeValues(request); // new + else + reg.updateAttributeValues(request); // existing + WebUtil.createForwardPage(response, THANKS, "registrations.jsp", 3); + } + else + { + log.log(Level.SEVERE, "Registration not saved"); + WebUtil.createForwardPage(response, PROBLEM, "registrations.jsp", 3); + } + } // doPost + +} // RegistrationSerlet diff --git a/serverApps/src/main/servlet/org/compiere/wstore/RequestOrderRefTag.java b/serverApps/src/main/servlet/org/compiere/wstore/RequestOrderRefTag.java new file mode 100644 index 0000000000..f1190a75e7 --- /dev/null +++ b/serverApps/src/main/servlet/org/compiere/wstore/RequestOrderRefTag.java @@ -0,0 +1,154 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.wstore; + +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.servlet.http.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; +import org.apache.ecs.xhtml.*; +import org.apache.taglibs.standard.tag.el.core.*; +import org.compiere.util.*; + +/** + * Request Order Reference Tag + *
+ *	
+ *	
+ * + * @author Jorg Janke + * @version $Id: RequestOrderRefTag.java,v 1.2 2006/07/30 00:53:21 jjanke Exp $ + */ +public class RequestOrderRefTag extends TagSupport +{ + /** Logger */ + private static CLogger log = CLogger.getCLogger (RequestOrderRefTag.class); + + /** Business Partner Parameter */ + private String m_bpartnerID_el = null; + + /** + * Set B.Partner parameter + * @param bpartnerID_el region info + */ + public void setBpartnerID (String bpartnerID_el) + { + m_bpartnerID_el = bpartnerID_el; + } // setBPartner + + /** + * Start Tag + * @return SKIP_BODY + */ + public int doStartTag() + { + // Parameter + int C_BPartner_ID = 0; + try + { + String info = (String)ExpressionUtil.evalNotNull ("requestOrder", "bpartnerID", + m_bpartnerID_el, String.class, this, pageContext); + if (info != null && info.length () != 0) + C_BPartner_ID = Integer.parseInt (info); + } + catch (Exception e) + { + log.severe ("BPartner - " + e); + } + + JspWriter out = pageContext.getOut(); + select select = getRefOrders(C_BPartner_ID); + select.output(out); + // + return (SKIP_BODY); + } // doStartTag + + /** + * Create Select List + * @param C_BPartner_ID b partner + * @return select list + */ + private select getRefOrders(int C_BPartner_ID) + { + select select = new select(RequestServlet.P_REF_ORDER_ID, getOrders(C_BPartner_ID)); + select.setID("ID_" + RequestServlet.P_REF_ORDER_ID); + return select; + } // getRequestType + + /** + * Get the Request Type options + * @param C_BPartner_ID b partner + * @return array of options + */ + private option[] getOrders(int C_BPartner_ID) + { + Properties ctx = JSPEnv.getCtx((HttpServletRequest)pageContext.getRequest()); + ArrayList