lee-m
2005-07-18 10:47
> ofbiz是一个很庞大很复杂的东东。想学好不是容易的事,所?> 你要做好心理准备。别想几个星期就可以搞定。对于一个新手

> 此蹈湛伎赡芫突岜凰恼庑┡渲梦募阍巍O旅嫖壹虻サ母

> 你介绍我以前使用ofbiz的一些心得吧:

>

> 1、首先是配置数据原:

> 假设你的ofbiz在D盘下:

> D:\ofbiz\ofbiz\commonapp\etc\entityengine.xml

> 在这个文件中配置数据原,以下为mssql2000根据自己的数据库来修改配置文件

<!--
    For DAO/JDBC Helper: Tries:
      1. JNDI Datasource IF jdbc.jndi.name, context.provider, etc are specified
      2. Tyrex if available (uses jdbc.driver, jdbc.uri, jdbc.username, jdbc.password, isolation.level)
      3. Direct to manually laoded JDBC driver (uses jdbc.driver, jdbc.uri, jdbc.username, jdbc.password)

    Transaction Isolation Levels - For Tyrex (<helperName>.isolation.level) can be as follows:
     * None
     * ReadCommitted
     * ReadUncommitted
     * RepeatableRead
     * Serializable (default)
    -->
    <datasource name="localmssql"
            helper-class="org.ofbiz.core.entity.GenericHelperDAO"
            field-type-name="mssql"
            check-on-start="true"
            add-missing-on-start="true"
            join-style="theta-oracle">
        <sql-load-path path="commonapp/db" prepend-env="ofbiz.home"/>
        <sql-load-path path="ecommerce/etc" prepend-env="ofbiz.home"/>
        <inline-jdbc
                jdbc-driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"
                jdbc-uri="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=ofbiz;SelectMethod=Cursor"
                jdbc-username="sa"
                jdbc-password=""
                isolation-level="Serializable"/>
        <!-- <jndi-jdbc jndi-server-name="localjndi" jndi-name="java:/MySqlDataSource" isolation-level="Serializable"/> -->
    </datasource>    
 
<p>

同样在entityengine.xml这个文件中

<delegator name="default" entity-model-reader="main" entity-group-reader="main" entity-eca-reader="main" 
    		distributed-cache-clear-enabled="false">
        <group-map group-name="org.ofbiz.commonapp" datasource-name="localmssql"/>
    </delegator>
    <delegator name="other" entity-model-reader="main" entity-group-reader="main" entity-eca-reader="main">
        <group-map group-name="org.ofbiz.commonapp" datasource-name="localpostgres"/>
    </delegator>

    <entity-model-reader name="main">
        <resource loader="mainfile" location="entitymodel_jd.xml"/>
        <resource loader="mainfile" location="entitymodel.xml"/>        
        <resource loader="mainfile" location="entitymodel_content.xml"/>
        <resource loader="mainfile" location="entitymodel_accounting.xml"/>
        <resource loader="mainfile" location="entitymodel_humanres.xml"/>
        <resource loader="mainfile" location="entitymodel_shipment.xml"/>
        <resource loader="mainfile" location="entitymodel_workeffort.xml"/>
        <resource loader="mainfile" location="entitymodel_workflow.xml"/>
        <resource loader="mainfile" location="entitymodel_order.xml"/>
        <resource loader="mainfile" location="entitymodel_party.xml"/>
        <resource loader="mainfile" location="entitymodel_product.xml"/>
        <resource loader="mainfile" location="entitymodel_marketing.xml"/>
        <resource loader="mainfile" location="entitymodel_jdreport.xml"/>
    </entity-model-reader>

比如entitymodel_jdreport.xml是本人增加的一个数据库对应的文件此文件在D:\ofbiz\ofbiz\commonapp\entitydef目录下该文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE entitymodel PUBLIC "-//OFBiz//DTD Entity Model//EN" "http://www.ofbiz.org/dtds/entitymodel.dtd">
<!--
/**
 *  Title: Entity Generator Definitions for the General Data Model
 *  Description: None
 *  Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
 *
 *  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, FITNESS 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.
 *
 * @author     David E. Jones (jonesde@ofbiz.org)
 * @author     Andy Zeneski (jaz@ofbiz.org)
 * @version    $Revision: 1.8 $
 */
-->

<entitymodel>
  <!-- ========================================================= -->
  <!-- ======================== Defaults ======================= -->
  <!-- ========================================================= -->
    <title>Entity of an Open For Business Project Component</title>
    <description>None</description>
    <copyright>Copyright (c) 2002 The Open For Business Project - www.ofbiz.org</copyright>
    <author>None</author>
    <version>1.0</version>
    <!-- jdsoft  -->
<!--
    <entity entity-name="UserLogin"
            package-name="org.ofbiz.commonapp.security.login"
            title="User Login Entity">
      <field name="userLoginId" type="id-vlong-ne"></field>
      <field name="partyId" type="id"></field>
      <field name="currentPassword" type="short-varchar"></field>
      <field name="passwordHint" type="description"></field>
      <field name="enabled" type="indicator"></field>
      <field name="disabledDateTime" type="date-time"></field>
      <field name="successiveFailedLogins" type="numeric"></field>
      <prim-key field="userLoginId"/>      
    </entity>
-->
  <!-- ========================================================= -->
  <!-- org.ofbiz.commonapp.common.datasource -->
  <!-- ========================================================= -->
<!--
    <entity entity-name="DataSource"
            package-name="org.ofbiz.commonapp.common.datasource"
            title="Data Source Entity">
      <field name="dataSourceId" type="id-ne"></field>
      <field name="dataSourceTypeId" type="id"></field>
      <field name="description" type="description"></field>
      <prim-key field="dataSourceId"/>
      <relation type="one" fk-name="DATA_SRC_TYP" rel-entity-name="DataSourceType">
        <key-map field-name="dataSourceTypeId"/>
      </relation>
      <relation type="many" rel-entity-name="PartyDataSource">
        <key-map field-name="dataSourceId"/>
      </relation>
    </entity>
    <entity entity-name="DataSourceType"
            package-name="org.ofbiz.commonapp.common.datasource"
            title="Data Source Type Entity">
      <field name="dataSourceTypeId" type="id"></field>
      <field name="description" type="description"></field>
      <prim-key field="dataSourceTypeId"/>
      <relation type="many" rel-entity-name="DataSource">
        <key-map field-name="dataSourceTypeId"/>
      </relation>
    </entity>
-->    
  <!-- ========================================================= -->
  <!-- com.jdsoft.commonapp.com.jm -->
  <!-- ========================================================= -->
  
     <entity entity-name="WsjUser"
            package-name="jdsoft.com.WsjUser"
            title="SrZc User">
            <field name="userId" type="id-vlong-ne"></field>
            <field name="userName" type="description"></field>
            <field name="userAge" type="description"></field>
            <field name="userDepartment" type="description"></field>
            <field name="userStudy" type="description"></field>
            <field name="userType" type="description"></field>
            <field name="userLogintime" type="date-time"></field>
            <field name="userPassword" type="description"></field>
            <field name="userSex" type="description"></field>
            <prim-key field="userId"/>
      </entity>    
</entitymodel>
<p>

<field name="ctym1" type="dm"></field>

其中name为数据库字段,type为类型,该类型在D:\ofbiz\ofbiz\commonapp\entitydef\fieldtypemssql.xml

不同的数据库配置为件的名称也不同。上面为mssql的培植文件

内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fieldtypemodel PUBLIC "-//OFBiz//DTD Field Type Model//EN" "http://www.ofbiz.org/dtds/fieldtypemodel.dtd">

<!--
/**
 *  $Id: fieldtypemssql.xml,v 1.3 2004/11/11 05:51:59 shil Exp $
 *  Title: Entity Generator Definitions for the General Data Model
 *  Description: None
 *  Copyright (c) 2002 The Open For Business Project - www.ofbiz.org
 *
 *  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, FITNESS 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.
 *
 *@author     David E. Jones
 *@created    June 5, 2001
 *@version    1.0
 */
-->

<fieldtypemodel>
  <!-- ===================== field-type-def ==================== -->
   <!-- General Types --> 
    <field-type-def type="blob" sql-type="BINARY" java-type="java.lang.Object"></field-type-def>
    
    <field-type-def type="date-time" sql-type="DATETIME" java-type="java.sql.Timestamp"></field-type-def>
    <field-type-def type="date" sql-type="DATETIME" java-type="java.sql.Date"></field-type-def>
    <field-type-def type="time" sql-type="DATETIME" java-type="java.sql.Time"></field-type-def>
    
    <field-type-def type="currency-amount" sql-type="DECIMAL(18,2)" java-type="Double"><validate name="isSignedDouble" /></field-type-def>
    <field-type-def type="floating-point" sql-type="DECIMAL(24,2)" java-type="Double"><validate name="isSignedDouble" /></field-type-def>
    <field-type-def type="numeric" sql-type="DECIMAL(18,0)" java-type="Long"><validate name="isSignedLong" /></field-type-def>

    <field-type-def type="id" sql-type="VARCHAR(20)" java-type="String"></field-type-def>
    <field-type-def type="id-long" sql-type="VARCHAR(60)" java-type="String"></field-type-def>
    <field-type-def type="id-vlong" sql-type="VARCHAR(255)" java-type="String"></field-type-def>

    <field-type-def type="indicator" sql-type="CHAR(1)" java-type="String"></field-type-def>
    <field-type-def type="very-short" sql-type="VARCHAR(10)" java-type="String"></field-type-def>
    <field-type-def type="short-varchar" sql-type="VARCHAR(60)" java-type="String"></field-type-def>
    <field-type-def type="long-varchar" sql-type="VARCHAR(255)" java-type="String"></field-type-def>
    <field-type-def type="very-long" sql-type="VARCHAR(4000)" java-type="String"></field-type-def>
   
    <field-type-def type="comment" sql-type="VARCHAR(255)" java-type="String"></field-type-def>
    <field-type-def type="description" sql-type="VARCHAR(255)" java-type="String"></field-type-def>
    <field-type-def type="name" sql-type="VARCHAR(60)" java-type="String"></field-type-def>
    <field-type-def type="value" sql-type="VARCHAR(255)" java-type="String"></field-type-def>

   <!-- Specialized Types -->
    <field-type-def type="credit-card-number" sql-type="VARCHAR(40)" java-type="String"><validate name="isAnyCard" /></field-type-def>
    <field-type-def type="credit-card-date" sql-type="VARCHAR(20)" java-type="String"><validate name="isDateAfterToday" /></field-type-def>
    <field-type-def type="email" sql-type="VARCHAR(255)" java-type="String"><validate name="isEmail" /></field-type-def>
    <field-type-def type="url" sql-type="VARCHAR(255)" java-type="String"></field-type-def>
    <field-type-def type="id-ne" sql-type="VARCHAR(20)" java-type="String"><validate name="isNotEmpty" /></field-type-def>
    <field-type-def type="id-long-ne" sql-type="VARCHAR(60)" java-type="String"><validate name="isNotEmpty" /></field-type-def>
    <field-type-def type="id-vlong-ne" sql-type="VARCHAR(255)" java-type="String"><validate name="isNotEmpty" /></field-type-def>
    <field-type-def type="tel-number" sql-type="VARCHAR(60)" java-type="String"><validate name="isInternationalPhoneNumber" /></field-type-def>
    
    <field-type-def type="dm" sql-type="VARCHAR(20)" java-type="String"><validate name="isNotEmpty" /></field-type-def>
</fieldtypemodel>

首先在数据库里创建一个ofbiz的数据库,启动ofbiz,则ofbiz会根据以上的数据库配置文件生成对应的数据库。

好了到这里告一个段落,接下来我们在D:\ofbiz\ofbiz\commonapp\globalservices这个目录下面增加一个文件

文件名为:services_jdreport.xml,内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE services PUBLIC "-//OFBiz//DTD Services Config//EN" "http://www.ofbiz.org/dtds/services.dtd">

<services>
    <description>Common Application Components Order Services</description>
    <vendor>OFBiz</vendor>
    <version>1.0</version>
  <!-- ========================================================= -->
  <!-- ================卫生局报表=数据存储服务================== -->
  <!-- ========================================================= -->    
    <!--	    
    <service name="processOrder" engine="workflow" location="org.ofbiz.commonapp.order.order" invoke="ProcessOrder">
        <description>Service for testing the workflow engine</description>
        <attribute name="orderId" type="String" mode="IN" optional="false"/>         
        <attribute name="orderStatusId" type="String" mode="INOUT" optional="false"/>
    </service>
    --> 
<service name="insertOrUpdateUserRecord" engine="java" location="com.jdsoft.report.user.UserServies" invoke="storeUser">
        <description>Add Result for Database</description>
        <attribute name="userId" type="String" mode="INOUT"/>
        <attribute name="userName" type="String" mode="IN"/>
        <attribute name="userAge" type="String" mode="IN"/>
        <attribute name="userDepartment" type="String" mode="IN"/> 
        <attribute name="userSex" type="String" mode="IN"/> 
        <attribute name="userStudy" type="String" mode="IN"/> 
        <attribute name="userLogintime" type="String" mode="IN"/> 
        <attribute name="userType" type="String" mode="IN"/> 
        <attribute name="userPassword" type="String" mode="IN"/> 
        <attribute name="sign" type="String" mode="INOUT"/> 
    </service>	
     <service name="deleteUserDo" engine="java" location="com.jdsoft.report.user.UserServies" invoke="deleteUser">
        <description>Add Result for Database</description>
        <attribute name="userId" type="String" mode="INOUT"/>
    </service>
</services>

<p>

然后在D:\ofbiz\ofbiz\commonapp\etc目录下的serviceengine.xml 文件里注册该服务配置文件具体如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE service-config PUBLIC "-//OFBiz//DTD Service Engine Config//EN" "http://www.ofbiz.org/dtds/service-config.dtd">

<service-config>
    <!-- Name of the service to use for authorization -->
    <authorization service-name="userLogin"/>

    <!-- Thread pool configuration (max/min threads, uses to live and time to live) -->
    <thread-pool ttl="18000000"
                 wait-millis="750"
                 jobs="3"
                 min-threads="5"
                 max-threads="20"
                 poll-enabled="true"
                 poll-db-millis="20000"/>

    <!-- Service Engine Configuration -->
    <engine name="bsh" class="org.ofbiz.core.service.engine.BeanShellEngine"/>
    <engine name="group" class="org.ofbiz.core.service.group.ServiceGroupEngine"/>    
    <engine name="http" class="org.ofbiz.core.service.engine.HttpEngine"/>
    <engine name="interface" class="org.ofbiz.core.service.engine.InterfaceEngine"/>
    <engine name="jacl" class="org.ofbiz.core.service.engine.BSFEngine"/>
    <engine name="java" class="org.ofbiz.core.service.engine.StandardJavaEngine"/>
    <engine name="javascript" class="org.ofbiz.core.service.engine.BSFEngine"/>
    <engine name="jms" class="org.ofbiz.core.service.jms.JmsServiceEngine"/> 
    <engine name="jpython" class="org.ofbiz.core.service.engine.BSFEngine"/>
    <engine name="route" class="org.ofbiz.core.service.engine.RouteEngine"/>
    <engine name="simple" class="org.ofbiz.core.minilang.SimpleServiceEngine"/>
    <engine name="soap" class="org.ofbiz.core.service.engine.SOAPClientEngine"/>
    <engine name="workflow" class="org.ofbiz.core.workflow.WorkflowEngine"/>    
       
    <!-- Resource Loader Configuration -->
    <resource-loader name="mainfile" class="org.ofbiz.core.config.FileLoader"
            prepend-env="ofbiz.home" prefix="/commonapp/globalservices/"/>
    <resource-loader name="maincp" class="org.ofbiz.core.config.ClasspathLoader"/>
    <resource-loader name="mainurl" class="org.ofbiz.core.config.UrlLoader"/>

    <!-- Service definition files -->
    <global-services loader="mainfile" location="services_test.xml"/>
    <global-services loader="mainfile" location="services_accounting.xml"/>
    <global-services loader="mainfile" location="services_content.xml"/>
    <global-services loader="mainfile" location="services_common.xml"/>
    <global-services loader="mainfile" location="services_marketing.xml"/>
    <global-services loader="mainfile" location="services_order.xml"/>
    <global-services loader="mainfile" location="services_party.xml"/>
    <global-services loader="mainfile" location="services_product.xml"/>
    <global-services loader="mainfile" location="services_project.xml"/>
    <global-services loader="mainfile" location="services_security.xml"/>
    <global-services loader="mainfile" location="services_shipment.xml"/>
    <global-services loader="mainfile" location="services_workeffort.xml"/>
    <global-services loader="mainfile" location="services_workflow.xml"/>
    <global-services loader="mainfile" location="services_jdreport.xml"/>

    <!-- Service-Group definition files -->
    <service-groups loader="mainfile" location="groups_test.xml"/> 
    <service-groups loader="mainfile" location="groups_accounting.xml"/>   
    <service-groups loader="mainfile" location="groups_common.xml"/>   
    <service-groups loader="mainfile" location="groups_shipment.xml"/>
    
	<!-- ECA definition files -->
    <service-ecas loader="mainfile" location="secas_test.xml"/>
    <service-ecas loader="mainfile" location="secas_accounting.xml"/>  
    <service-ecas loader="mainfile" location="secas_order.xml"/>  
    <service-ecas loader="mainfile" location="secas_party.xml"/> 
    <service-ecas loader="mainfile" location="secas_product.xml"/>   
    <service-ecas loader="mainfile" location="secas_workeffort.xml"/>
    
    <!-- JMS Service Queue/Topic Configuration -->
    <!--
    <jms-service name="serviceMessenger" send-mode="all">
        <server jndi-server-name="default"
                jndi-name="jms/TopicConnectionFactory"
                topic-queue="jms/OFBTopic"
                type="topic"
                username="admin"
                password="admin"
                listen="true"/>
    </jms-service>
    -->

</service-config>
<p>

其中

 <global-services loader="mainfile" location="services_jdreport.xml"/>
<p>

为增加的“服务”配置文件到这里配置基本完成。接下来就可以编写原代码了,具体如下:

package com.jdsoft.report.user;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.ofbiz.core.entity.GenericDelegator;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.service.LocalDispatcher;
import org.ofbiz.core.service.ModelService;
import org.ofbiz.core.util.Debug;
import org.ofbiz.core.util.SiteDefs;
import org.ofbiz.core.util.UtilFormatOut;
import org.ofbiz.core.util.UtilHttp;
import org.ofbiz.core.util.UtilMisc;
import com.jdsoft.report.common.DoubleToStr;
import com.jdsoft.core.gaui.component.*;

 import java.util.*;
 import java.sql.Timestamp;
 import java.lang.*;
 import javax.servlet.http.*;
 import org.ofbiz.core.entity.*;
 import org.ofbiz.core.util.*;

 import org.ofbiz.commonapp.common.*;
 import org.ofbiz.commonapp.security.login.*;

public class UserEvents {

	public static String storeUserRecord(HttpServletRequest request, HttpServletResponse response){
		Debug.log("==事件开始== storeUserRecord Start Event==");
		Map result = new HashMap();
		Map resultData = new HashMap();
		String storeService="insertOrUpdateUserRecord";
		LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
		//取得map值
		result = getIncomePayout(request);
		System.out.println("===result data Return==="+result);
		if (result == null) {
			request.setAttribute(SiteDefs.ERROR_MESSAGE,"非法输入!");
			request.setAttribute("SAVE_DATA_SIGN", "error");
			return "error";
		}
		/*
		//权限检查
		boolean blnRight=true;
		if (!blnRight) {
			request.setAttribute(SiteDefs.ERROR_MESSAGE,"无权限!");
			request.setAttribute("SAVE_DATA_SIGN", "error");
			return "error";
		}
		*/
		//备份数据
		Iterator keys = result.keySet().iterator();
		for(int i=0;keys.hasNext() ;i++){
			Object key = keys.next();
			Object keyvalue = result.get(key);
			resultData.put(key,keyvalue);
		}
		//操作检查
		if (result.get("sign").equals("ADD")) {
			GenericDelegator  delegator = (GenericDelegator) request.getAttribute("delegator");
			List staffRecord =null;
			/*
			try{
				Debug.log("==编码=="+((Map)result.get("user")).get("sqDM")+","+result.get("serialNum")+" ==");
				staffRecord = delegator.findByAnd("JmJmgzryxx",UtilMisc.toMap("sqdm",((Map)result.get("user")).get("sqDM"),"gzrybm",result.get("serialNum")));
			}catch (Exception e) {
				Debug.logWarning(e.getMessage());

			        request.setAttribute(SiteDefs.ERROR_MESSAGE,e.getMessage());
			        request.setAttribute("RESULT_DATA",resultData );
			        request.setAttribute("SAVE_DATA_SIGN", "error");
				return "error";
			}
			
			if (staffRecord.size()!=0){
				Debug.log("==编码重复== ==");
				request.setAttribute(SiteDefs.ERROR_MESSAGE,"编码重复");
				request.setAttribute("RESULT_DATA",resultData );
				request.setAttribute("SAVE_DATA_SIGN", "error");
				return "error";
			}*/
		}
		//调存储服务
		Debug.log("==调存储服务=="+ storeService +"==");
		try{
			result=dispatcher.runSync(storeService,result);
			if (ModelService.RESPOND_SUCCESS.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
				//返回一些对象
				request.setAttribute("userId", result.get("userId"));
				request.setAttribute("SAVE_DATA_SIGN", "success");
				Debug.log("-->>storeEvent : success to store  by SERVICE ["+storeService+"]");
			} else {
				Debug.log("-->> storeEvent : fail to store  by SERVICE ["+storeService+"]  because of result is not RESPOND_SUCCESS");
				Debug.log("-->> storeEvent : "+result.get(ModelService.ERROR_MESSAGE));
				request.setAttribute(SiteDefs.ERROR_MESSAGE, result.get(ModelService.ERROR_MESSAGE));
				request.setAttribute("RESULT_DATA",resultData );
				request.setAttribute("SAVE_DATA_SIGN", "error");
				return "error";
			}
		} catch (Exception e) {
			request.setAttribute(SiteDefs.ERROR_MESSAGE, e.getMessage());
			Debug.log("-->> [storeEvent] : fail to store order by SERVICE ["+storeService+"]  because of exception");
			Debug.log(e);
			request.setAttribute("RESULT_DATA",resultData );
			request.setAttribute("SAVE_DATA_SIGN", "error");
			return "error";
		}
		Debug.log("==事件结束== End Event==");
		HttpSession session = request.getSession();
        Map user=(Map) session.getAttribute("user");
        String type= UtilFormatOut.makeString(user.get("roleDM"));
		if (resultData.get("sign").equals("ADD"))
		  {
			return "insertsuccess";
		  }
		else
			{
			if(type.equals("1"))
            return "upusersussess";
			else
		    return "updatesuccess";
			}
		
	}

	private static Map getIncomePayout(HttpServletRequest request){
		Map headMap=new HashMap();
		/*
		HttpSession session = request.getSession();
		Map user=(Map) session.getAttribute("user");
		//判断是否登陆
		Debug.log("==user=="+ user +"==");
		if (user==null || user.size()<1) return null;
		*/	
		
		String userId=UtilFormatOut.makeString( request.getParameter("userId"));
		String userName=UtilFormatOut.makeString( request.getParameter("userName"));
		String userAge=UtilFormatOut.makeString( request.getParameter("userAge"));
		String userDepartment=UtilFormatOut.makeString( request.getParameter("userDepartment"));
		String userSex=UtilFormatOut.makeString( request.getParameter("userSex"));
		String userStudy=UtilFormatOut.makeString( request.getParameter("userStudy"));
        String userType=UtilFormatOut.makeString( request.getParameter("userType"));
        String userPassword=UtilFormatOut.makeString( request.getParameter("userPassword"));
		//其他
		String userLogintime =UtilFormatOut.makeString( GACalendar.getText(request,"userLogintime"));
		String sign = UtilFormatOut.makeString( request.getParameter("sign"));
		if (sign==null || sign.equals("")) sign="ADD";
		else sign="UPDATE";	
        	 headMap.put("userId",userId);	
        	 headMap.put("userName",userName);	
        	 headMap.put("userAge",userAge);	
        	 headMap.put("userDepartment",userDepartment);
        	 headMap.put("userSex",userSex);	
        	 headMap.put("userStudy",userStudy);	
        	 headMap.put("userLogintime",userLogintime);
        	 //其他    	 
        	 headMap.put("userType",userType);	
        	 headMap.put("userPassword",userPassword);
                 headMap.put("sign",sign); 
	
		 return headMap;
		
	}

	public static String delUser(HttpServletRequest request, HttpServletResponse response){
		
		
		Debug.log("==事件开始==delIncomePayout Start Event==");
		Map result = new HashMap();
		LocalDispatcher dispatcher=(LocalDispatcher) request.getAttribute("dispatcher");
		/*
		//权限检查
		boolean blnRight=true;
		if (!blnRight) {
			request.setAttribute(SiteDefs.ERROR_MESSAGE,"无权限!");
			request.setAttribute("DEL_DATA_SIGN","error");
			return "error";
		}
		*/
		//取得map值
		String[] userIds=request.getParameterValues("userId");
		String userId="";
		GenericDelegator  delegator = (GenericDelegator) request.getAttribute("delegator");
		GenericValue staffRecord=null;
		List staffRecords =null;
		HttpSession session = request.getSession();
		Map user=(Map) session.getAttribute("user");		
		for (int i=0;i<userIds.length;i++) {
			userId=userIds[i];
			result.clear();
			//result.put("user",user);
			result.put("userId",userId);
			/*			
			//操作检查
			staffRecord =null;
			try{
				staffRecord = delegator.findByPrimaryKey("JmJmgzryxx",UtilMisc.toMap("dm",userId));
			}catch (Exception e) {
				Debug.logWarning(e.getMessage());
			        request.setAttribute(SiteDefs.ERROR_MESSAGE,e.getMessage());
			        request.setAttribute("DEL_DATA_SIGN:"+userId, "unexception error");
				return "error";
			}
			Debug.log("====staffRecord:=="+staffRecord);
			if (staffRecord==null){
				Debug.log("==不存在=="+userId+" ==");
				//request.setAttribute(SiteDefs.ERROR_MESSAGE,"==不存在=="+userId+" ==");
				//request.setAttribute("SAVE_DATA_SIGN", "error");
				continue;
			}
			staffRecords =null;
			try{
				staffRecords = delegator.findByAnd("JmEtjzjh",UtilMisc.toMap("jzr",userId));
			}catch (Exception e) {
				Debug.logWarning(e.getMessage());
			        request.setAttribute(SiteDefs.ERROR_MESSAGE,e.getMessage());
			        request.setAttribute("DEL_DATA_SIGN:"+userId, "unexception error");
				return "error";
			}
			Debug.log("====staffRecords:=="+staffRecords);
			if (staffRecords.size()!=0){
				Debug.log("===="+userId+" ==在儿童免疫计划表中已经使用==");
				request.setAttribute(SiteDefs.ERROR_MESSAGE,"==不能删除=="+userId+" ==");
				//request.setAttribute("SAVE_DATA_SIGN", "error");
				continue;
			}
			*/
			//调服务
			try{
				result=dispatcher.runSync("deleteUserDo",result);
				if (ModelService.RESPOND_SUCCESS.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
					userId = (String)result.get("userId");					
					request.setAttribute("userId", userId);
					Debug.log("->>Return userId:[" + userId + "]");
					Debug.log("-->>storeEvent : success to store  by SERVICE [deleteUser]");
				} else {
					Debug.log("-->> storeEvent : fail to store  by SERVICE [deleteUser] because of result is not RESPOND_SUCCESS");
					Debug.log("-->> storeEvent : "+result.get(ModelService.ERROR_MESSAGE));
					request.setAttribute(SiteDefs.ERROR_MESSAGE, "数据删除错误"+ result.get(ModelService.ERROR_MESSAGE));
					request.setAttribute("userId", userId);
					request.setAttribute("DEL_DATA_SIGN:"+userId,"error");					
				}
			} catch (Exception e) {
				request.setAttribute(SiteDefs.ERROR_MESSAGE,"数据删除服务错误"+ e.getMessage());
				Debug.log("-->> [storeEvent] : fail to store order by SERVICE [deleteUser] because of exception");
				Debug.log(e);
				request.setAttribute("userId", userId);
				request.setAttribute("DEL_DATA_SIGN:"+userId,"error");
				return "error";
			}
		}
		request.setAttribute("DEL_DATA_SIGN","success");
		Debug.log("==事件结束==deleteUser End Event==");
		
		return "success";
		
	}

}

package com.jdsoft.report.user;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.ofbiz.core.entity.GenericDelegator;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.service.DispatchContext;
import org.ofbiz.core.service.ModelService;
import org.ofbiz.core.util.Debug;
import org.ofbiz.core.util.UtilFormatOut;
import org.ofbiz.core.util.UtilMisc;
import com.jdsoft.report.common.FormatHelper;
import org.ofbiz.core.util.UtilDateTime;
/**
 * @author wangxl
 */
public class UserServies {
	public static Map storeUser(DispatchContext ctx,Map context){
		Debug.log("==存储服务开始==storeUser ==");
		Map result = new HashMap();
		List toBeStored =new ArrayList();
		GenericDelegator delegator = ctx.getDelegator();
		GenericValue headData =null;
		String sign=UtilFormatOut.makeString(context.get("sign"));
		String userId=UtilFormatOut.makeString(context.get("userId"));
		/*
		String serialNum=UtilFormatOut.makeString(context.get("serialNum"));
		String name=UtilFormatOut.makeString(context.get("name"));
		if (serialNum.equals("") || name.equals("")){
			Debug.log( "Lack of necessary data ");
	        	result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
	        	result.put(ModelService.ERROR_MESSAGE, "缺少必需的数据:编码或者姓名");
	        	return result;
	        }
		String roleCode="1";
		*/
        	Map headMap= new HashMap() ;                   
                //其他  
                if (!UtilFormatOut.makeString(context.get("userLogintime")).equals("")) headMap.put("userLogintime",FormatHelper.changStringToTimestamp((String)context.get("userLogintime")));
                if (!UtilFormatOut.makeString(context.get("userId")).equals("")) headMap.put("userId",(String)context.get("userId"));
                if (!UtilFormatOut.makeString(context.get("userName")).equals("")) headMap.put("userName",(String)context.get("userName"));
                if (!UtilFormatOut.makeString(context.get("userAge")).equals("")) headMap.put("userAge",(String)context.get("userAge"));
                if (!UtilFormatOut.makeString(context.get("userId")).equals("")) headMap.put("userId",(String)context.get("userId"));
                if (!UtilFormatOut.makeString(context.get("userDepartment")).equals("")) headMap.put("userDepartment",(String)context.get("userDepartment"));
                if (!UtilFormatOut.makeString(context.get("userSex")).equals("")) headMap.put("userSex",(String)context.get("userSex"));
                if (!UtilFormatOut.makeString(context.get("userStudy")).equals("")) headMap.put("userStudy",(String)context.get("userStudy"));
                if (!UtilFormatOut.makeString(context.get("userType")).equals("")) headMap.put("userType",(String)context.get("userType"));
                if (!UtilFormatOut.makeString(context.get("userPassword")).equals("")) headMap.put("userPassword",(String)context.get("userPassword"));
        	/*
        	//把时间由String类型转换为Date类型
		if (!UtilFormatOut.checkNull(creDate).equals("")) {
			creDate = UtilFormatOut.checkNull(creDate) +" 00:00:00.000";
			if (creDate.length()<15){creDate="";}
			Timestamp createdDateTime = Timestamp.valueOf(creDate);
			java.sql.Date datCreatedDate = new java.sql.Date(createdDateTime.getTime());
			mapArchive.put("createdDate",datCreatedDate);
		}
		else {
			mapArchive.put("createdDate","");
		}
                */
        	if (sign.equals("UPDATE")){
        		
        	try {
	        		headData= delegator.findByPrimaryKey("WsjUser",UtilMisc.toMap("userId", UtilFormatOut.makeString(context.get("userId"))));
	        	} catch (GenericEntityException e1) {
	        		e1.printStackTrace();
	        	}
	        if (headData==null) {
	        	Debug.log( "Update Error ");
	        	result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
	        	result.put(ModelService.ERROR_MESSAGE, "User误");
	        	return result;
	        	}
	        headData.setFields(headMap);
        	}else if (sign.equals("ADD")){
        		userId = delegator.getNextSeqId("WsjUser").toString();
        		headMap.put("userId", userId);
        		headData=delegator.makeValue("WsjUser",headMap);
        	}else {
        		result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        		result.put(ModelService.ERROR_MESSAGE, "标志错误");
        		return result;
        	}
        	toBeStored.add(headData);

        	try {
        		delegator.storeAll(toBeStored);
        		result.put("sign", sign);
        		result.put("userId",userId);
        		result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
        	} catch (GenericEntityException gee) {
        		Debug.logError("-->> [FeeAppServies:storeUserLines] : delegator.storeAll error");
        		Debug.logError(gee);
        		result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        		result.put(ModelService.ERROR_MESSAGE, "数据存储错误" + gee.getMessage());
        	}
        	Debug.log("==存储服务结束==storeIncomePayout ==");
        	return result;
	}

	public static Map deleteUser(DispatchContext ctx,Map context){
		
		Debug.log("==服务开始==deleteUser ==");
		Map result = new HashMap();
		GenericDelegator delegator = ctx.getDelegator();
		String userId=UtilFormatOut.makeString(context.get("userId"));
		if (userId.trim().equals("") || userId==null){
			result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
			result.put(ModelService.ERROR_MESSAGE, "删除对象为空" );
			return result;
		}
		try {

			GenericValue headData= delegator.findByPrimaryKey("WsjUser",
					UtilMisc.toMap("userId", userId));
			if (headData==null){
				result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
				result.put(ModelService.ERROR_MESSAGE, "不存在删除对象");
			}
			if (headData!=null) headData.remove();
			result.put("userId", userId);
			result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
		} catch (GenericEntityException gee) {
			Debug.logError(gee);
			result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
			result.put(ModelService.ERROR_MESSAGE, "数据删除错误" + gee.getMessage());
		}
		Debug.log("==服结束==deleteUser ==");
		return result;
		
	}
    
}
<p>

上面有两个类文件,一个为UserEvents.java,另一个为UserServies.java

用户发送的请求是通过UserEvents来调用UserServies。可以说是通过事件来调用服务。由于时间的关系,先简单说到这里,下次有时间接着说ofbiz的jpublic筐架(ofbiz的表示层)。如果有不清楚的地方可以通过邮件跟我联系lee_m_@126.com

猜你喜欢
2Go 上一页 1 2