получить IP-адрес клиента для каждого запроса в муле

Я запустил wsdl с сервисами cxf в муле. Я передал IP-адрес клиента в качестве переменной классу java в конфигурации xml mule. Я реализовал вызываемый класс для получения IP-адреса и вставки ip в базу данных. Для тестирования я создал веб-сервис с wsdl мула. во время этой процедуры, когда я создал класс wsdl, клиентский IP-адрес вставлен в базу данных. К сожалению, когда я использовал веб-сервис и отправлял запросы, IP-адрес не вставлялся в базу данных. Моя цель: я хочу вставлять IP-адрес клиента в базу данных после каждого запроса.

Я использую Mule 3.3.0 CE. и мой код ниже:

<mule 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: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.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.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/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd ">

<global-property name="allowed" value="192.168.3.76,192.168.3.74,192.168.3.75" />

<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
        xmlns:ss="http://www.springframework.org/schema/security" 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="Weather" doc:name="Weather">
    <http:inbound-endpoint host="localhost" port="9091"
        path="/web-service/weather" exchange-pattern="request-response" doc:name="HTTP">
    <mule-ss:http-security-filter realm="mule-realm" />
    </http:inbound-endpoint>
    <expression-filter
        expression="#['${allowed}'.contains(parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS']))]"
        doc:name="Expression" />

    <set-variable variableName="remoteClientAddress"
        value="#[parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS'])]" />
    <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" />      

    <cxf:proxy-service 
        service="Weather"
        wsdlLocation="http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl"
        namespace="http://ws.cdyne.com/WeatherWS/"
        validationEnabled="true" doc:name="SOAP">
    </cxf:proxy-service>

    <copy-properties propertyName="SOAPAction" doc:name="Property" />

    <cxf:proxy-client doc:name="SOAP" />

    <outbound-endpoint 
        address="http://wsf.cdyne.com/WeatherWS/Weather.asmx"
        exchange-pattern="request-response" doc:name="Generic">
    </outbound-endpoint>

</flow>

и мой класс Java:

public class IpClient  implements Callable {

  @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", "report", "root", "123456");

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

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

ps.setString(1, remClient);

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

  ps.executeUpdate();

  c.close();

  return true;

  }

person S Tajeri    schedule 09.03.2013    source источник
comment
Q: Вызывается ли когда-нибудь ваша функция Java? В: Если нет, то почему? В: Какие инструменты отладки/логирования у вас есть? Какие шаги отладки вы пробовали?   -  person paulsm4    schedule 09.03.2013
comment
Да, @paulsm4, моя функция Java всегда вызывается. Я просто использую мул студию. и я снова использую soapui pro для тестирования. Можете ли вы объяснить больше?   -  person S Tajeri    schedule 09.03.2013
comment
Вы выполнили отладку, чтобы увидеть значение remClient внутри компонента Java?   -  person Seba    schedule 09.03.2013
comment
Предложение (не связанное с вашим вопросом): используйте set-session-variable вместо message-properties-transformer для установки переменной сеанса.   -  person David Dossot    schedule 10.03.2013
comment
Почему бы вам не использовать конечную точку исходящего трафика JDBC? Зачем пользовательский класс для такого простого запроса?   -  person David Dossot    schedule 10.03.2013
comment
Также я заметил, что вы возвращаете true из компонента: не испортит ли это значение ваш исходящий вызов? true становится новой полезной нагрузкой...   -  person David Dossot    schedule 10.03.2013
comment
@Seba, я вижу remClient внутри java-компонента.   -  person S Tajeri    schedule 10.03.2013
comment
@DavidDossot, раньше я использовал конечную точку исходящего трафика JDBC, но хотел добавить в свой проект некоторые функции, которые не мог определить в конфигурации xml. поэтому я использовал пользовательский класс.   -  person S Tajeri    schedule 10.03.2013
comment
@DavidDossot, я не хочу возвращать переменную в конфигурацию xml, я просто сохраняю значение моей переменной в базе данных.   -  person S Tajeri    schedule 10.03.2013


Ответы (1)


Ваша проблема, безусловно, связана с тем, что вы не отправляете запрос SOAP в службу Mule.

Проверьте, как URL-адрес конечной точки в SOAPui.

person David Dossot    schedule 14.03.2013
comment
мой URL-адрес в SoapUI — это ссылка вместо URL-адреса мула (localhost:9091/веб-служба/погода). - person S Tajeri; 15.03.2013