Example usage for javax.jms ObjectMessage getStringProperty

List of usage examples for javax.jms ObjectMessage getStringProperty

Introduction

In this page you can find the example usage for javax.jms ObjectMessage getStringProperty.

Prototype


String getStringProperty(String name) throws JMSException;

Source Link

Document

Returns the value of the String property with the specified name.

Usage

From source file:com.alliander.osgp.adapter.protocol.iec61850.infra.messaging.processors.PublicLightingSetTransitionRequestMessageProcessor.java

@Override
public void processMessage(final ObjectMessage message) {
    LOGGER.debug("Processing public lighting set transition request message");

    String correlationUid = null;
    String domain = null;//from   w  ww . j  a  v a 2s.  c  om
    String domainVersion = null;
    String messageType = null;
    String organisationIdentification = null;
    String deviceIdentification = null;
    String ipAddress = null;
    int retryCount = 0;
    boolean isScheduled = false;
    TransitionMessageDataContainerDto transitionMessageDataContainer = null;

    try {
        correlationUid = message.getJMSCorrelationID();
        domain = message.getStringProperty(Constants.DOMAIN);
        domainVersion = message.getStringProperty(Constants.DOMAIN_VERSION);
        messageType = message.getJMSType();
        organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION);
        deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION);
        ipAddress = message.getStringProperty(Constants.IP_ADDRESS);
        retryCount = message.getIntProperty(Constants.RETRY_COUNT);
        isScheduled = message.propertyExists(Constants.IS_SCHEDULED)
                ? message.getBooleanProperty(Constants.IS_SCHEDULED)
                : false;
        transitionMessageDataContainer = (TransitionMessageDataContainerDto) message.getObject();
    } catch (final JMSException e) {
        LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e);
        LOGGER.debug("correlationUid: {}", correlationUid);
        LOGGER.debug("domain: {}", domain);
        LOGGER.debug("domainVersion: {}", domainVersion);
        LOGGER.debug("messageType: {}", messageType);
        LOGGER.debug("organisationIdentification: {}", organisationIdentification);
        LOGGER.debug("deviceIdentification: {}", deviceIdentification);
        LOGGER.debug("ipAddress: {}", ipAddress);
        return;
    }

    final RequestMessageData requestMessageData = new RequestMessageData(transitionMessageDataContainer, domain,
            domainVersion, messageType, retryCount, isScheduled, correlationUid, organisationIdentification,
            deviceIdentification);

    final DeviceResponseHandler deviceResponseHandler = new DeviceResponseHandler() {

        @Override
        public void handleResponse(final DeviceResponse deviceResponse) {
            PublicLightingSetTransitionRequestMessageProcessor.this.handleEmptyDeviceResponse(deviceResponse,
                    PublicLightingSetTransitionRequestMessageProcessor.this.responseMessageSender,
                    requestMessageData.getDomain(), requestMessageData.getDomainVersion(),
                    requestMessageData.getMessageType(), requestMessageData.getRetryCount());
        }

        @Override
        public void handleException(final Throwable t, final DeviceResponse deviceResponse,
                final boolean expected) {

            if (expected) {
                PublicLightingSetTransitionRequestMessageProcessor.this.handleExpectedError(
                        new ConnectionFailureException(ComponentType.PROTOCOL_IEC61850, t.getMessage()),
                        requestMessageData.getCorrelationUid(),
                        requestMessageData.getOrganisationIdentification(),
                        requestMessageData.getDeviceIdentification(), requestMessageData.getDomain(),
                        requestMessageData.getDomainVersion(), requestMessageData.getMessageType());
            } else {
                PublicLightingSetTransitionRequestMessageProcessor.this.handleUnExpectedError(deviceResponse, t,
                        requestMessageData.getMessageData(), requestMessageData.getDomain(),
                        requestMessageData.getDomainVersion(), requestMessageData.getMessageType(),
                        requestMessageData.isScheduled(), requestMessageData.getRetryCount());
            }
        }
    };

    LOGGER.info("Calling DeviceService function: {} for domain: {} {}", messageType, domain, domainVersion);

    final SetTransitionDeviceRequest deviceRequest = new SetTransitionDeviceRequest(organisationIdentification,
            deviceIdentification, correlationUid, transitionMessageDataContainer, domain, domainVersion,
            messageType, ipAddress, retryCount, isScheduled);

    this.deviceService.setTransition(deviceRequest, deviceResponseHandler);
}

From source file:com.alliander.osgp.acceptancetests.devicemonitoring.GetPowerUsageHistorySteps.java

@DomainStep("a get power usage history response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetPowerUsageHistoryResponseMessageIsFoundInQueue(final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String fromDate,
        final String untilDate, final String recordTime, final String meterType,
        final String totalConsumedEnergy, final String actualConsumedPower,
        final String psldDataTotalLightHours, final String actualCurrent1, final String actualCurrent2,
        final String actualCurrent3, final String actualPower1, final String actualPower2,
        final String actualPower3, final String averagePowerFactor1, final String averagePowerFactor2,
        final String averagePowerFactor3, final String relayData1Index, final String relayData1LightingMinutes,
        final String relayData2Index, final String relayData2LightingMinutes, final Boolean isFound)
        throws ParseException {
    LOGGER.info(/*  w w  w  .  j  a  va2  s  .  co m*/
            "GIVEN: \"a get power usage history response message with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".",
            correlationId, deviceId, qresult, qdescription, isFound);

    if (isFound) {
        final ObjectMessage messageMock = mock(ObjectMessage.class);

        try {
            when(messageMock.getJMSCorrelationID()).thenReturn(correlationId);
            when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID);
            when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId);

            final MeterType metertype = StringUtils.isBlank(meterType) ? null
                    : Enum.valueOf(MeterType.class, meterType);

            DateTime dateTime = null;
            if (!recordTime.equals("")) {
                final Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(recordTime);
                dateTime = new DateTime(date);
            }

            final com.alliander.osgp.domain.core.valueobjects.PowerUsageData powerUsageData = new com.alliander.osgp.domain.core.valueobjects.PowerUsageData(
                    dateTime, metertype, Long.parseLong(totalConsumedEnergy),
                    Long.parseLong(actualConsumedPower));

            final List<com.alliander.osgp.domain.core.valueobjects.RelayData> list = new ArrayList<>();
            list.add(new com.alliander.osgp.domain.core.valueobjects.RelayData(Integer.valueOf(relayData1Index),
                    Integer.valueOf(relayData1LightingMinutes)));
            list.add(new com.alliander.osgp.domain.core.valueobjects.RelayData(Integer.valueOf(relayData2Index),
                    Integer.valueOf(relayData2LightingMinutes)));

            final com.alliander.osgp.domain.core.valueobjects.SsldData ssldData = new com.alliander.osgp.domain.core.valueobjects.SsldData(
                    Integer.valueOf(actualCurrent1), Integer.valueOf(actualCurrent2),
                    Integer.valueOf(actualCurrent3), Integer.valueOf(actualPower1),
                    Integer.valueOf(actualPower2), Integer.valueOf(actualPower3),
                    Integer.valueOf(averagePowerFactor1), Integer.valueOf(averagePowerFactor2),
                    Integer.valueOf(averagePowerFactor3), list);

            powerUsageData.setSsldData(ssldData);

            final List<com.alliander.osgp.domain.core.valueobjects.PowerUsageData> powerUsageDatas = new ArrayList<com.alliander.osgp.domain.core.valueobjects.PowerUsageData>();
            powerUsageDatas.add(powerUsageData);

            final com.alliander.osgp.domain.core.valueobjects.PowerUsageHistoryResponse powerUsageHistoryResponse = new com.alliander.osgp.domain.core.valueobjects.PowerUsageHistoryResponse(
                    powerUsageDatas);

            final ResponseMessage message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId,
                    ResponseMessageResultType.valueOf(qresult), null, powerUsageHistoryResponse);

            when(messageMock.getObject()).thenReturn(message);

        } catch (final JMSException e) {
            LOGGER.error("JMSException", e);
        }

        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class)))
                .thenReturn(messageMock);
    } else {
        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null);
    }
}

From source file:com.alliander.osgp.acceptancetests.devicemonitoring.GetActualPowerUsageSteps.java

@DomainStep("a get actual power usage response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetActualPowerUsageResponseMessageIsFoundInQueue(final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String recordTime,
        final String meterType, final String totalConsumedEnergy, final String actualConsumedPower,
        final String psldDataTotalLightHours, final String actualCurrent1, final String actualCurrent2,
        final String actualCurrent3, final String actualPower1, final String actualPower2,
        final String actualPower3, final String averagePowerFactor1, final String averagePowerFactor2,
        final String averagePowerFactor3, final String relayData1Index, final String relayData1LightingMinutes,
        final String relayData2Index, final String relayData2LightingMinutes, final Boolean isFound) {
    LOGGER.info(//from   w  w  w  . ja v a2 s.  co m
            "GIVEN: \"a get actual power usage response message with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".",
            correlationId, deviceId, qresult, qdescription, isFound);

    if (isFound) {
        final ObjectMessage messageMock = mock(ObjectMessage.class);

        try {
            when(messageMock.getJMSCorrelationID()).thenReturn(correlationId);
            when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID);
            when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId);

            final ResponseMessageResultType result = ResponseMessageResultType.valueOf(qresult);
            Serializable dataObject = null;
            OsgpException exception = null;

            if (result.equals(ResponseMessageResultType.NOT_OK)) {
                dataObject = new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR,
                        ComponentType.UNKNOWN, new ValidationException());
                exception = (OsgpException) dataObject;
            } else {

                final MeterType metertype = StringUtils.isBlank(meterType) ? null
                        : Enum.valueOf(MeterType.class, meterType);

                DateTime dateTime = null;
                if (!recordTime.equals("")) {
                    final Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(recordTime);
                    dateTime = new DateTime(date);
                }

                PowerUsageData powerUsageData = null;
                if (!totalConsumedEnergy.equals("") && !actualConsumedPower.equals("")) {
                    powerUsageData = new PowerUsageData(dateTime, metertype,
                            Long.parseLong(totalConsumedEnergy), Long.parseLong(actualConsumedPower));

                    final PsldData psldData = new PsldData(Integer.valueOf(psldDataTotalLightHours));

                    final List<RelayData> relayDataList = new ArrayList<RelayData>();
                    // Create RelayData instances for relay indexes and
                    // minutes
                    // lighting time.
                    relayDataList.add(new RelayData(Integer.parseInt(relayData1Index),
                            Integer.parseInt(relayData1LightingMinutes)));
                    relayDataList.add(new RelayData(Integer.parseInt(relayData2Index),
                            Integer.parseInt(relayData2LightingMinutes)));

                    // Construct SsldData using the list of RelayData.
                    final SsldData ssldData = new SsldData(Integer.valueOf(actualCurrent1),
                            Integer.valueOf(actualCurrent2), Integer.valueOf(actualCurrent3),
                            Integer.valueOf(actualPower1), Integer.valueOf(actualPower2),
                            Integer.valueOf(actualPower3), Integer.valueOf(averagePowerFactor1),
                            Integer.valueOf(averagePowerFactor2), Integer.valueOf(averagePowerFactor3),
                            relayDataList);

                    powerUsageData.setPsldData(psldData);
                    powerUsageData.setSsldData(ssldData);

                    dataObject = powerUsageData;
                }
            }
            final ResponseMessage message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId,
                    result, exception, dataObject);

            when(messageMock.getObject()).thenReturn(message);

        } catch (final JMSException e) {
            LOGGER.error("JMSException", e);
        } catch (final ParseException e) {
            LOGGER.error("ParseException", e);
        }

        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class)))
                .thenReturn(messageMock);
    } else {
        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null);
    }
}

From source file:com.alliander.osgp.adapter.protocol.iec61850.infra.messaging.processors.PublicLightingGetPowerUsageHistoryRequestMessageProcessor.java

@Override
public void processMessage(final ObjectMessage message) {
    LOGGER.debug("Processing public lighting get power usage history request message");

    String correlationUid = null;
    String domain = null;//from ww w .j  a  v  a 2 s.c o m
    String domainVersion = null;
    String messageType = null;
    String organisationIdentification = null;
    String deviceIdentification = null;
    String ipAddress = null;
    Boolean isScheduled = null;
    int retryCount = 0;
    final int messagePriority;
    final Long scheduleTime;
    PowerUsageHistoryMessageDataContainerDto powerUsageHistoryMessageDataContainerDto;

    try {
        correlationUid = message.getJMSCorrelationID();
        domain = message.getStringProperty(Constants.DOMAIN);
        domainVersion = message.getStringProperty(Constants.DOMAIN_VERSION);
        messageType = message.getJMSType();
        organisationIdentification = message.getStringProperty(Constants.ORGANISATION_IDENTIFICATION);
        deviceIdentification = message.getStringProperty(Constants.DEVICE_IDENTIFICATION);
        ipAddress = message.getStringProperty(Constants.IP_ADDRESS);
        isScheduled = message.getBooleanProperty(Constants.IS_SCHEDULED);
        retryCount = message.getIntProperty(Constants.RETRY_COUNT);
        messagePriority = message.getJMSPriority();
        scheduleTime = message.propertyExists(Constants.SCHEDULE_TIME)
                ? message.getLongProperty(Constants.SCHEDULE_TIME)
                : null;
        powerUsageHistoryMessageDataContainerDto = (PowerUsageHistoryMessageDataContainerDto) message
                .getObject();

    } catch (final JMSException e) {
        LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e);
        LOGGER.debug("correlationUid: {}", correlationUid);
        LOGGER.debug("domain: {}", domain);
        LOGGER.debug("domainVersion: {}", domainVersion);
        LOGGER.debug("messageType: {}", messageType);
        LOGGER.debug("organisationIdentification: {}", organisationIdentification);
        LOGGER.debug("deviceIdentification: {}", deviceIdentification);
        LOGGER.debug("ipAddress: {}", ipAddress);
        LOGGER.debug("scheduled: {}", isScheduled);
        return;
    }

    final RequestMessageData requestMessageData = new RequestMessageData(
            powerUsageHistoryMessageDataContainerDto, domain, domainVersion, messageType, retryCount,
            isScheduled, correlationUid, organisationIdentification, deviceIdentification);

    final DeviceResponseHandler deviceResponseHandler = new DeviceResponseHandler() {

        @Override
        public void handleResponse(final DeviceResponse deviceResponse) {
            PublicLightingGetPowerUsageHistoryRequestMessageProcessor.this
                    .handleGetPowerUsageHistoryDeviceResponse(
                            (GetPowerUsageHistoryDeviceResponse) deviceResponse,
                            PublicLightingGetPowerUsageHistoryRequestMessageProcessor.this.responseMessageSender,
                            requestMessageData.getDomain(), requestMessageData.getDomainVersion(),
                            requestMessageData.getMessageType(), requestMessageData.getRetryCount(),
                            messagePriority, scheduleTime);
        }

        @Override
        public void handleException(final Throwable t, final DeviceResponse deviceResponse,
                final boolean expected) {

            if (expected) {
                PublicLightingGetPowerUsageHistoryRequestMessageProcessor.this.handleExpectedError(
                        new ConnectionFailureException(ComponentType.PROTOCOL_IEC61850, t.getMessage()),
                        requestMessageData.getCorrelationUid(),
                        requestMessageData.getOrganisationIdentification(),
                        requestMessageData.getDeviceIdentification(), requestMessageData.getDomain(),
                        requestMessageData.getDomainVersion(), requestMessageData.getMessageType());
            } else {
                PublicLightingGetPowerUsageHistoryRequestMessageProcessor.this.handleUnExpectedError(
                        deviceResponse, t, requestMessageData.getMessageData(), requestMessageData.getDomain(),
                        requestMessageData.getDomainVersion(), requestMessageData.getMessageType(),
                        requestMessageData.isScheduled(), requestMessageData.getRetryCount());
            }
        }
    };

    LOGGER.info("Calling DeviceService function: {} for domain: {} {}", messageType, domain, domainVersion);

    final GetPowerUsageHistoryDeviceRequest deviceRequest = new GetPowerUsageHistoryDeviceRequest(
            organisationIdentification, deviceIdentification, correlationUid,
            powerUsageHistoryMessageDataContainerDto, domain, domainVersion, messageType, ipAddress, retryCount,
            isScheduled);

    this.deviceService.getPowerUsageHistory(deviceRequest, deviceResponseHandler);
}

From source file:com.alliander.osgp.acceptancetests.adhocmanagement.GetStatusSteps.java

@DomainStep("a get status response message for domainType (.*) with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetStatusResponseMessageIsFoundInQueue(final String domainType, final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String preferredLinkType,
        final String actualLinkType, final String lightType, final String eventNotifications,
        final String index, final String on, final String dimValue, final Boolean isFound) {
    LOGGER.info(/* w w w .  j  a  v a2  s  . c  o  m*/
            "GIVEN: \"a get status response message for domainType {} with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".",
            domainType, correlationId, deviceId, qresult, qdescription, isFound);

    if (isFound) {
        final ObjectMessage messageMock = mock(ObjectMessage.class);

        try {
            when(messageMock.getJMSCorrelationID()).thenReturn(correlationId);
            when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID);
            when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId);

            final LinkType prefLinkType = StringUtils.isBlank(preferredLinkType) ? null
                    : Enum.valueOf(LinkType.class, preferredLinkType);
            final LinkType actLinkType = StringUtils.isBlank(actualLinkType) ? null
                    : Enum.valueOf(LinkType.class, actualLinkType);
            final LightType lt = StringUtils.isBlank(lightType) ? null
                    : Enum.valueOf(LightType.class, lightType);

            // EventNotificationTypes
            int mask = 0;
            if (StringUtils.isNotBlank(eventNotifications)) {
                for (final String event : eventNotifications.split(",")) {
                    mask += (Enum.valueOf(EventNotificationType.class, event)).getValue();
                }
            }

            final ResponseMessage message;

            final ResponseMessageResultType result = ResponseMessageResultType.valueOf(qresult);
            Serializable dataObject = null;

            if (result.equals(ResponseMessageResultType.NOT_OK)) {
                dataObject = new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR,
                        ComponentType.UNKNOWN, new ValidationException());
                message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId, result,
                        (OsgpException) dataObject, dataObject);
            } else {
                if (domainType.equals(DomainType.PUBLIC_LIGHTING.name())) {
                    // DomainType.PUBLIC_LIGHTING
                    dataObject = new DeviceStatus(null, prefLinkType, actLinkType, lt, mask);
                } else {
                    // DomainType.TARIFF_SWITCHING
                    dataObject = new DeviceStatusMapped(null, null, prefLinkType, actLinkType, lt, mask);
                }
                message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId, result, null,
                        dataObject);
            }

            when(messageMock.getObject()).thenReturn(message);
        } catch (final JMSException e) {
            e.printStackTrace();
        }

        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class)))
                .thenReturn(messageMock);
    } else {
        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null);
    }
}

From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java

@DomainStep("a get configuration response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetConfigurationResponseMessageIsFoundInQueue(final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String lightType,
        final String dcLights, final String dcMap, final String rcType, final String rcMap,
        final String shortInterval, final String preferredLinkType, final String meterType,
        final String longInterval, final String longIntervalType, final Boolean isFound) {
    LOGGER.info(/*w  w w .ja v  a 2s  .  c  o m*/
            "GIVEN: \"a get configuration response message with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".",
            correlationId, deviceId, qresult, qdescription, isFound);

    if (isFound) {
        final ObjectMessage messageMock = mock(ObjectMessage.class);

        try {
            when(messageMock.getJMSCorrelationID()).thenReturn(correlationId);
            when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID);
            when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId);

            final ResponseMessageResultType result = ResponseMessageResultType.valueOf(qresult);
            Serializable dataObject = null;
            OsgpException exception = null;

            if (result.equals(ResponseMessageResultType.NOT_OK)) {
                dataObject = new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR,
                        ComponentType.UNKNOWN, new ValidationException());
                exception = (OsgpException) dataObject;
            } else {

                final com.alliander.osgp.domain.core.valueobjects.LightType lighttype = StringUtils
                        .isBlank(lightType) ? null
                                : Enum.valueOf(com.alliander.osgp.domain.core.valueobjects.LightType.class,
                                        lightType);
                final Map<Integer, Integer> indexAddressMap = new HashMap<Integer, Integer>();

                final com.alliander.osgp.domain.core.valueobjects.DaliConfiguration daliconfiguration = new com.alliander.osgp.domain.core.valueobjects.DaliConfiguration(
                        22, indexAddressMap);

                final List<com.alliander.osgp.domain.core.valueobjects.RelayMap> relayMap = new ArrayList<>();
                final com.alliander.osgp.domain.core.valueobjects.RelayConfiguration relayConf = new com.alliander.osgp.domain.core.valueobjects.RelayConfiguration(
                        relayMap);

                final MeterType metertype = StringUtils.isBlank(meterType) ? null
                        : Enum.valueOf(MeterType.class, meterType);
                final LongTermIntervalType longtermintervalType = StringUtils.isBlank(longIntervalType) ? null
                        : Enum.valueOf(LongTermIntervalType.class, longIntervalType);

                final Integer shortinterval = StringUtils.isBlank(shortInterval) ? 0
                        : Integer.valueOf(shortInterval);
                final Integer longinterval = StringUtils.isBlank(longInterval) ? 0
                        : Integer.valueOf(longInterval);

                // construct new Configuration
                dataObject = new com.alliander.osgp.domain.core.valueobjects.Configuration(lighttype,
                        daliconfiguration, relayConf, shortinterval, LinkType.ETHERNET, metertype, longinterval,
                        longtermintervalType);
            }

            final ResponseMessage message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId,
                    result, exception, dataObject);

            when(messageMock.getObject()).thenReturn(message);

        } catch (final JMSException e) {
            e.printStackTrace();
        }

        when(this.commonResponsesJmsTemplateMock.receiveSelected(any(String.class))).thenReturn(messageMock);
    } else {
        when(this.commonResponsesJmsTemplateMock.receiveSelected(any(String.class))).thenReturn(null);
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsConsumer.java

public MessageContext receive() {
    boolean error;
    JMSException exception;/*from  w ww .j a  va 2s  .c  o  m*/
    if (!checkConnection()) {
        if (!reconnect()) {
            if (logger.isDebugEnabled()) {
                logger.debug(getId() + " cannot receive message from store. Cannot reconnect.");
            }
            return null;
        } else {
            logger.info(getId() + " reconnected to store.");
            isReceiveError = false;
        }

    }
    if (!checkConnection()) {
        if (logger.isDebugEnabled()) {
            logger.debug(getId() + " cannot receive message from store.");
        }
        return null;
    }
    try {
        Message message = consumer.receive(1);
        if (message == null) {
            return null;
        }
        if (!(message instanceof ObjectMessage)) {
            logger.warn(getId() + ". Did not receive a javax.jms.ObjectMessage");
            message.acknowledge(); // TODO:
            return null;
        }
        ObjectMessage msg = (ObjectMessage) message;
        String messageId = msg.getStringProperty(Constants.OriginalMessageID);
        if (!(msg.getObject() instanceof StorableMessage)) {
            logger.warn(getId() + ". Did not receive a valid message.");
            message.acknowledge();
            return null;
        }
        StorableMessage storableMessage = (StorableMessage) msg.getObject();
        org.apache.axis2.context.MessageContext axis2Mc = store.newAxis2Mc();
        MessageContext synapseMc = store.newSynapseMc(axis2Mc);
        synapseMc = MessageConverter.toMessageContext(storableMessage, axis2Mc, synapseMc);
        updateCache(message, synapseMc, messageId, false);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    getId() + " Received MessageId:" + messageId + " priority:" + message.getJMSPriority());
        }
        return synapseMc;
    } catch (JMSException e) {
        error = true;
        exception = e;
    }
    if (error) {
        if (!isReceiveError) {
            logger.error(
                    getId() + " cannot receive message from store. Error:" + exception.getLocalizedMessage());//, exception);
        }
        updateCache(null, null, "", true);
        cleanup();
        return null;
    }
    return null;
}

From source file:org.jbpm.bpel.integration.server.SoapHandler.java

public boolean handleRequest(MessageContext messageContext) throws JAXRPCException, SOAPFaultException {
    /*/*from  w  w w.  jav a 2  s. c o  m*/
     * WSEE 1.1 section 6.2.2.1: If Handler instances are pooled, they must be pooled by Port
     * component. This is because Handlers may retain non-client specific state across method calls
     * that are specific to the Port component.
     */
    if (integrationControl == null) {
        /*
         * COMPLIANCE NOTE: the state initialized in this call is port-component specific, but
         * non-client specific
         */
        lookupEndpointMetadata(messageContext);
    }

    JbpmContext jbpmContext = integrationControl.getIntegrationServiceFactory().getJbpmConfiguration()
            .createJbpmContext();
    try {
        Session jmsSession = integrationControl.createJmsSession();
        try {
            SOAPMessage soapMessage = ((SOAPMessageContext) messageContext).getMessage();
            ObjectMessage jmsRequest = sendRequest(soapMessage, jmsSession, jbpmContext);

            Destination replyTo = jmsRequest.getJMSReplyTo();
            if (replyTo != null) {
                ObjectMessage jmsResponse = receiveResponse(jmsSession, replyTo, jmsRequest.getJMSMessageID(),
                        jbpmContext);

                // remember operation name and message parts for handling response
                messageContext.setProperty(OPERATION_NAME_PROP,
                        jmsRequest.getStringProperty(IntegrationConstants.OPERATION_NAME_PROP));
                messageContext.setProperty(MESSAGE_PARTS_PROP, jmsResponse.getObject());

                // is response a fault?
                String faultName = jmsResponse.getStringProperty(IntegrationConstants.FAULT_NAME_PROP);
                if (faultName != null) {
                    // remember fault name for handling fault
                    messageContext.setProperty(FAULT_NAME_PROP, faultName);
                    throw new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE,
                            SoapBindConstants.BUSINESS_FAULTSTRING, null, null);
                }
            }
        } finally {
            jmsSession.close();
        }
    }
    /*
     * NO need to set jbpm context as rollback only for any exception, since operations in try-block
     * only read definitions from database
     */
    catch (SOAPFaultException e) {
        log.debug("request caused a fault", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP, e);
    } catch (SOAPException e) {
        /*
         * BP 1.2 R2724: If an INSTANCE receives an envelope that is inconsistent with its WSDL
         * description, it SHOULD generate a soap:Fault with a faultcode of "Client", unless a
         * "MustUnderstand" or "VersionMismatch" fault is generated.
         */
        log.debug("incoming soap message carries invalid content", e);
        messageContext.setProperty(FAULT_EXCEPTION_PROP,
                new SOAPFaultException(SoapBindConstants.CLIENT_FAULTCODE, e.getMessage(), null, null));
    } catch (JMSException e) {
        throw new JAXRPCException("message delivery failed", e);
    } finally {
        jbpmContext.close();
    }
    return true;
}

From source file:ru.runa.wfe.service.impl.ReceiveMessageBean.java

@Override
public void onMessage(Message jmsMessage) {
    List<ReceiveMessageData> handlers = Lists.newArrayList();
    ObjectMessage message = (ObjectMessage) jmsMessage;
    String messageString = Utils.toString(message, false);
    UserTransaction transaction = context.getUserTransaction();
    ErrorEventData errorEventData = null;
    try {/*from  ww w  . j av  a2  s .c  o  m*/
        log.debug("Received " + messageString);
        errorEventData = ErrorEventData.match(message);
        transaction.begin();
        List<Token> tokens;
        if (SystemProperties.isProcessExecutionMessagePredefinedSelectorEnabled()) {
            Map<String, String> routingData = getRoutingData(message);
            tokens = executionLogic.findTokensForMessageSelector(routingData);
            log.debug("Checking " + tokens.size() + " tokens by routingData = " + routingData);
        } else {
            tokens = tokenDao.findByNodeTypeAndExecutionStatusIsActive(NodeType.RECEIVE_MESSAGE);
            log.debug("Checking " + tokens.size() + " tokens");
        }
        for (Token token : tokens) {
            try {
                ProcessDefinition processDefinition = processDefinitionLoader
                        .getDefinition(token.getProcess().getDeployment().getId());
                BaseMessageNode receiveMessageNode = (BaseMessageNode) token.getNodeNotNull(processDefinition);
                ExecutionContext executionContext = new ExecutionContext(processDefinition, token);
                if (errorEventData != null) {
                    if (receiveMessageNode.getEventType() == MessageEventType.error
                            && receiveMessageNode.getParentElement() instanceof Node) {
                        Long processId = token.getProcess().getId();
                        String nodeId = ((Node) receiveMessageNode.getParentElement()).getNodeId();
                        if (processId.equals(errorEventData.processId)
                                && nodeId.equals(errorEventData.nodeId)) {
                            handlers.add(new ReceiveMessageData(executionContext, receiveMessageNode));
                            break;
                        }
                    }
                } else {
                    boolean suitable = true;
                    VariableProvider variableProvider = executionContext.getVariableProvider();
                    for (VariableMapping mapping : receiveMessageNode.getVariableMappings()) {
                        if (mapping.isPropertySelector()) {
                            String selectorValue = message.getStringProperty(mapping.getName());
                            String expectedValue = Utils.getMessageSelectorValue(variableProvider,
                                    receiveMessageNode, mapping);
                            if (!Objects.equal(expectedValue, selectorValue)) {
                                log.debug(message + " rejected in " + token + " due to diff in "
                                        + mapping.getName() + " (" + expectedValue + "!=" + selectorValue
                                        + ")");
                                suitable = false;
                                break;

                            }
                        }
                    }
                    if (suitable) {
                        handlers.add(new ReceiveMessageData(executionContext, receiveMessageNode));
                    }
                }
            } catch (Exception e) {
                log.error("Unable to handle " + token, e);
            }
        }
        transaction.commit();
    } catch (Exception e) {
        log.error("", e);
        Utils.rollbackTransaction(transaction);
        Throwables.propagate(e);
    }
    if (handlers.isEmpty()) {
        if (errorEventData != null) {
            String errorMessage = "Unexpected errorEvent in processId = " + errorEventData.processId
                    + ", nodeId = " + errorEventData.nodeId;
            log.error(errorMessage);
            Errors.addSystemError(new InternalApplicationException(errorMessage));
        } else {
            throw new MessagePostponedException(messageString);
        }
    }
    for (ReceiveMessageData data : handlers) {
        handleMessage(data, message);
    }
}

From source file:ru.runa.wfe.service.impl.ReceiveMessageBean.java

private Map<String, String> getRoutingData(ObjectMessage message) throws JMSException {
    Map<String, String> map = new HashMap<>();
    Enumeration<String> propertyNames = message.getPropertyNames();
    while (propertyNames.hasMoreElements()) {
        String propertyName = propertyNames.nextElement();
        if (!propertyName.startsWith("JMS")) {
            map.put(propertyName, message.getStringProperty(propertyName));
        }//from w  w  w  . j av  a2 s .com
    }
    return map;
}