2013-05-08 2 views
0

Я хочу сохранить некоторую информацию в базу данных, когда отправляю запрос на услугу mule. этой проблемы: я написал ниже конфигурации в XML-файле:Почему бы не изменить состояние жизненного цикла mule runtime?

<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:http="http://www.mulesoft.org/schema/mule/http" 
xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" 
xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" 
xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security" 
xmlns:ss="http://www.springframework.org/schema/security" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" 
xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd 
    http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
    http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd 
    http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd 
    http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd 
    http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/3.3/mule-spring-security.xsd 
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd 
    http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd "> 



<spring:beans> 
    <spring:bean id="Initializer" name="Initializer" class="org.mule.example.scripting.IpClient" doc:name="Bean"/> 
</spring:beans> 
<notifications> 
    <notification event="COMPONENT-MESSAGE"/> 
    <notification-listener ref="Initializer"/> 
</notifications> 



<configuration doc:name="Configuration"> 
    <expression-language> 
     <global-functions> 
      def parseIp(fullIp) { 
      return 
      fullIp.substring(fullIp.indexOf('/') + 1, fullIp.indexOf(':')) 
      } 
    </global-functions> 
    </expression-language> 
</configuration> 


<http:connector name="httpConnector" doc:name="HTTP\HTTPS"> 
    <service-overrides sessionHandler="org.mule.session.NullSessionHandler" /> 
</http:connector> 

<mule-ss:security-manager> 
    <mule-ss:delegate-security-provider 
     name="memory-dao" delegate-ref="authenticationManager" /> 
</mule-ss:security-manager> 
<spring:beans> 
    <ss:authentication-manager alias="authenticationManager"> 
     <ss:authentication-provider> 
      <ss:user-service id="userService"> 
       <ss:user name="weather" password="weather" authorities="ROLE_ADMIN" /> 
      </ss:user-service> 
     </ss:authentication-provider> 
    </ss:authentication-manager> 
</spring:beans> 

<flow name="Serive_test" doc:name="Serive_test"> 
    <http:inbound-endpoint host="localhost" port="8089" 
     path="service/local-weather" exchange-pattern="request-response" 
     doc:name="HTTP"> 
     <mule-ss:http-security-filter realm="mule-realm" /> 
    </http:inbound-endpoint> 

    <async doc:name="Async"> 
     <set-variable variableName="remoteClientAddress" 
      value="#[parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS'])]" 
      doc:name="Variable" /> 

     <message-properties-transformer 
      doc:name="myproperty" scope="session"> 
      <add-message-property key="message.payload.remoteClientAddress" 
       value="#[parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS'])]" /> 

     </message-properties-transformer> 

     <component doc:name="classTest" class="org.mule.example.scripting.IpClient" /> 
    </async> 
    <cxf:proxy-service service="Weather" doc:name="Weather_webservice" 
     wsdlLocation="http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl" namespace="http://ws.cdyne.com/WeatherWS/" 
     payload="envelope"></cxf:proxy-service> 
    <copy-properties propertyName="SOAPAction" doc:name="Property"></copy-properties> 
    <cxf:proxy-client doc:name="Weather_webservice" 
     payload="envelope" /> 
    <outbound-endpoint address="http://wsf.cdyne.com/WeatherWS/Weather.asmx" 
     exchange-pattern="request-response" doc:name="HTTP"></outbound-endpoint> 

</flow> 

и IpClient класс:

public class IpClient implements Callable,ModelNotificationListener<ModelNotification> { 


@Override 
public void onNotification(ModelNotification notification) { 
    // TODO Auto-generated method stub 
    System.out.println("Notification order event: " + notification.getActionName()); 

    if(notification.getAction() == ModelNotification.MODEL_DISPOSED || notification.getAction() == ModelNotification.MODEL_STOPPED){ 

     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
     Date date = new Date(); 

     ConnectDB c = new ConnectDB("localhost:3306", "accounting", "root", ""); 

     String sql = " INSERT INTO weather (ip, date, CurrentState) VALUES (?,?,?) "; 

     PreparedStatement ps = null; 
     try { 
      ps = c.getConnnection().prepareStatement(sql); 
      ps.setString(1, "127.0.0.1"); 
      ps.setString(2, dateFormat.format(date).toString());     
      ps.setString(3, notification.getActionName());         
      ps.executeUpdate(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
      c.close(); 
     }   

    } 
} 


@Override 
public Object onCall(MuleEventContext eventContext) throws Exception { 


    MuleMessage msg = eventContext.getMessage();  

    String remClient = msg.getProperty("remoteClientAddress", PropertyScope.INVOCATION); 


    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    Date date = new Date(); 

    ConnectDB c = new ConnectDB("localhost:3306", "accounting", "root", ""); 

    String sql = " INSERT INTO weather (ip, date, CurrentState) VALUES (?,?,?) "; 

    PreparedStatement ps = c.getConnnection().prepareStatement(sql); 

    ps.setString(1, remClient); 

    ps.setString(2, dateFormat.format(date).toString()); 

    ps.setString(3, msg.getMuleContext().getLifecycleManager().getCurrentPhase()); 

    ps.executeUpdate(); 

    c.close(); 

    return msg.getPayload(); 

} 

}

эта программа просто работает правильно, если я начинаю работать оказание услуг. например, мой сервис запускался раньше, чем внезапно был разложен (например, мой wsdl (http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl не работает)). моя программа регистрации журнала сохранила все записи в состоянии начала и после того, как она разоблачила ее, работает аналогично. если я остановил свое обслуживание и запустил его снова, он работает правильно, и он сохраняет все записи в несогласованном режиме. Я не знаю, как изменить свою программу, чтобы она корректно сохранялась во время выполнения.

ответ

0

Bean не используется в качестве <component> в любом месте конфигурации, поэтому метод onCall не будет вызван.

Если вы задумали с:

<notification event="COMPONENT-MESSAGE"/> 

это иметь Initializer вызывается для каждого вызова компонента затем вы должны сделать это реализовать ComponentMessageNotificationListener (как вы сделали это осуществить ModelNotificationListener).

+0

Thanks @David. но у меня есть проблема. Зачем работать мой веб-сервис, когда wsdl службы 'wsdlLocation =" http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl "' не работает, моя служба cxf работает правильно. если я повторно запускаю свою службу, она не работает, и есть исключение, связанное с страницей (адрес wsdl), недоступно. Должна ли моя служба работать до повторного запуска? –

+0

Это действительно странно: если он работал один раз, он должен продолжать работать. Откройте новый вопрос и покажите ошибку, которую вы получите во второй раз. –

Смежные вопросы