SMPP - Reduce Sonar Violations - If Stmts Must Use Braces

This commit is contained in:
Gunnar Hillert
2013-05-29 00:25:41 -04:00
parent dac93edfc4
commit 0665dc9a86
7 changed files with 456 additions and 375 deletions

View File

@@ -55,17 +55,20 @@ public final class SmppParserUtils {
+sessionAttribute+"' has been specified", context.extractSource(sessionElement));
}
builder.addPropertyReference(propName, sessionRef);
} else if(sessionElement != null) {
}
else if(sessionElement != null) {
final String ref = sessionElement.getAttribute("ref");
//
BeanComponentDefinition innerBean = IntegrationNamespaceUtils
.parseInnerHandlerDefinition(sessionElement, context);
if (StringUtils.hasText(ref)) {
builder.addPropertyReference(propName, ref);
} else if (innerBean != null) {
}
else if (innerBean != null) {
builder.addPropertyValue(propName, innerBean);
}
} else {
}
else {
context.getReaderContext().error("Child element '"+sessionChild+"' or '"+sessionAttribute+"' attribute "
+ "need to be specified", context.extractSource(e));
}
@@ -102,31 +105,65 @@ public final class SmppParserUtils {
}
private static byte getByteTon(String t) {
if ("ABBREVIATED".equals(t)) return SMPPConstant.TON_ABBREVIATED;
if ("ALPHANUMERIC".equals(t)) return SMPPConstant.TON_ALPHANUMERIC;
if ("SUBSCRIBER_NUMBER".equals(t))return SMPPConstant.TON_SUBSCRIBER_NUMBER;
if ("NETWORK_SPECIFIC".equals(t))return SMPPConstant.TON_NETWORK_SPECIFIC;
if ("NATIONAL".equals(t)) return SMPPConstant.TON_NATIONAL;
if ("INTERNATIONAL".equals(t))return SMPPConstant.TON_INTERNATIONAL;
if ("ABBREVIATED".equals(t)) {
return SMPPConstant.TON_ABBREVIATED;
}
if ("ALPHANUMERIC".equals(t)) {
return SMPPConstant.TON_ALPHANUMERIC;
}
if ("SUBSCRIBER_NUMBER".equals(t)) {
return SMPPConstant.TON_SUBSCRIBER_NUMBER;
}
if ("NETWORK_SPECIFIC".equals(t)) {
return SMPPConstant.TON_NETWORK_SPECIFIC;
}
if ("NATIONAL".equals(t)) {
return SMPPConstant.TON_NATIONAL;
}
if ("INTERNATIONAL".equals(t)) {
return SMPPConstant.TON_INTERNATIONAL;
}
return SMPPConstant.TON_UNKNOWN;
}
private static byte getByteNpi(String n) {
if ("WAP".equals(n)) return SMPPConstant.NPI_WAP;
if ("INTERNET".equals(n)) return SMPPConstant.NPI_INTERNET;
if ("ERMES".equals(n)) return SMPPConstant.NPI_ERMES;
if ("PRIVATE".equals(n)) return SMPPConstant.NPI_PRIVATE;
if ("NATIONAL".equals(n)) return SMPPConstant.NPI_NATIONAL;
if ("LAND_MOBILE".equals(n)) return SMPPConstant.NPI_LAND_MOBILE;
if ("TELEX".equals(n)) return SMPPConstant.NPI_TELEX;
if ("DATA".equals(n)) return SMPPConstant.NPI_DATA;
if ("ISDN".equals(n)) return SMPPConstant.NPI_ISDN;
if ("WAP".equals(n)) {
return SMPPConstant.NPI_WAP;
}
if ("INTERNET".equals(n)) {
return SMPPConstant.NPI_INTERNET;
}
if ("ERMES".equals(n)) {
return SMPPConstant.NPI_ERMES;
}
if ("PRIVATE".equals(n)) {
return SMPPConstant.NPI_PRIVATE;
}
if ("NATIONAL".equals(n)) {
return SMPPConstant.NPI_NATIONAL;
}
if ("LAND_MOBILE".equals(n)) {
return SMPPConstant.NPI_LAND_MOBILE;
}
if ("TELEX".equals(n)) {
return SMPPConstant.NPI_TELEX;
}
if ("DATA".equals(n)) {
return SMPPConstant.NPI_DATA;
}
if ("ISDN".equals(n)) {
return SMPPConstant.NPI_ISDN;
}
return SMPPConstant.NPI_UNKNOWN;
}
private static byte getByteBind(String b) {
if ("BIND_RX".equals(b)) return SMPPConstant.CID_BIND_RECEIVER;
if ("BIND_TX".equals(b)) return SMPPConstant.CID_BIND_TRANSMITTER;
if ("BIND_RX".equals(b)) {
return SMPPConstant.CID_BIND_RECEIVER;
}
if ("BIND_TX".equals(b)) {
return SMPPConstant.CID_BIND_TRANSMITTER;
}
return SMPPConstant.CID_BIND_TRANSCEIVER;
}

View File

@@ -61,7 +61,7 @@ public class SmesMessageSpecification {
private byte smDefaultMsgId;
private byte[] shortMessage;
private ClientSession smppSession;
private OptionalParameter messagePayloadParameter;
private OptionalParameter messagePayloadParameter;
/**
* this method takes an inbound SMS message and converts it to a Spring Integration message
@@ -124,7 +124,9 @@ public class SmesMessageSpecification {
* @return a {@link SmesMessageSpecification}
*/
public static SmesMessageSpecification fromMessage(ClientSession smppSession, Message<?> msg) {
if (log.isDebugEnabled()) log.debug("Message: "+msg);
if (log.isDebugEnabled()) {
log.debug("Message: "+msg);
}
String srcAddy = valueIfHeaderExists(SRC_ADDR, msg);
String dstAddy = valueIfHeaderExists(DST_ADDR, msg);
String smsTxt = valueIfHeaderExists(SMS_MSG, msg);
@@ -134,20 +136,21 @@ public class SmesMessageSpecification {
smsTxt = (String) payload;
}
}
final DataCoding dataCodingFromHeader = SmesMessageSpecification.dataCodingFromHeader(msg);
final SmesMessageSpecification spec = new SmesMessageSpecification()
.reset()
.setSmppSession(smppSession)
.setSourceAddress(srcAddy)
.setDestinationAddress(dstAddy)
.setDataCoding(dataCodingFromHeader);
spec.setMaxLengthSmsMessages(maximumCharactersFromHeader(msg));
spec.setEsmClass(SmesMessageSpecification.esmClassFromHeader(msg));
if (msg.getHeaders().containsKey(SmppConstants.USE_MSG_PAYLOAD_PARAM)) {
spec.setShortMessageUsingPayload(smsTxt);
} else {
spec.setShortTextMessage(smsTxt);
}
final DataCoding dataCodingFromHeader = SmesMessageSpecification.dataCodingFromHeader(msg);
final SmesMessageSpecification spec = new SmesMessageSpecification()
.reset()
.setSmppSession(smppSession)
.setSourceAddress(srcAddy)
.setDestinationAddress(dstAddy)
.setDataCoding(dataCodingFromHeader);
spec.setMaxLengthSmsMessages(maximumCharactersFromHeader(msg));
spec.setEsmClass(SmesMessageSpecification.esmClassFromHeader(msg));
if (msg.getHeaders().containsKey(SmppConstants.USE_MSG_PAYLOAD_PARAM)) {
spec.setShortMessageUsingPayload(smsTxt);
}
else {
spec.setShortTextMessage(smsTxt);
}
spec.setDestinationAddressNumberingPlanIndicator(SmesMessageSpecification.<NumberingPlanIndicator>valueIfHeaderExists(DST_NPI, msg));
spec.setSourceAddressNumberingPlanIndicator(SmesMessageSpecification.<NumberingPlanIndicator>valueIfHeaderExists(SRC_NPI, msg));
spec.setDestinationAddressTypeOfNumber(SmesMessageSpecification.<TypeOfNumber>valueIfHeaderExists(DST_TON, msg));
@@ -158,20 +161,24 @@ public class SmesMessageSpecification {
// byte landmine. autoboxing causes havoc with <em>null</em> bytes.
Byte priorityFlag1 = SmesMessageSpecification.<Byte>valueIfHeaderExists(PRIORITY_FLAG, msg);
if (priorityFlag1 != null)
if (priorityFlag1 != null) {
spec.setPriorityFlag(priorityFlag1);
}
Byte smDefaultMsgId1 = SmesMessageSpecification.<Byte>valueIfHeaderExists(SM_DEFAULT_MSG_ID, msg);
if (smDefaultMsgId1 != null)
if (smDefaultMsgId1 != null) {
spec.setSmDefaultMsgId(smDefaultMsgId1);
}
Byte replaceIfPresentFlag1 = SmesMessageSpecification.<Byte>valueIfHeaderExists(REPLACE_IF_PRESENT_FLAG, msg);
if (replaceIfPresentFlag1 != null)
if (replaceIfPresentFlag1 != null) {
spec.setReplaceIfPresentFlag(replaceIfPresentFlag1);
}
Byte protocolId1 = SmesMessageSpecification.<Byte>valueIfHeaderExists(PROTOCOL_ID, msg);
if (null != protocolId1)
if (null != protocolId1) {
spec.setProtocolId(protocolId1);
}
spec.setRegisteredDelivery(registeredDeliveryFromHeader(msg));
@@ -190,32 +197,35 @@ public class SmesMessageSpecification {
return null ;
}
/**
* Getting maximum characters from header. This will allow checking maximum character based on
* {@link SmppConstants#MAXIMUM_CHARACTERS} header or determine the maximum character based on data coding
* header {@link SmppConstants#DATA_CODING}.
* <p/>
* The order of the selection is
* <ol>
* <li>If {@link SmppConstants#MAXIMUM_CHARACTERS} is set, use it</li>
* <li>If {@link SmppConstants#DATA_CODING} is set, find maximum character for the data coding</li>
* <li>Using default maximum character which is 140</li>
* </ol>
* @param msg the Spring Integration message
* @return maximum character can be sent through the session
*/
private static int maximumCharactersFromHeader(Message<?> msg) {
if (msg.getHeaders().containsKey(MAXIMUM_CHARACTERS))
return msg.getHeaders().get(MAXIMUM_CHARACTERS, Integer.class);
if (msg.getHeaders().containsKey(DATA_CODING)) {
final Object dc = msg.getHeaders().get(DATA_CODING);
if (dc instanceof Byte)
return DataCodingSpecification.getMaxCharacters((Byte)dc);
else
return DataCodingSpecification.getMaxCharacters(((DataCoding)dc).toByte());
}
return 140;
}
/**
* Getting maximum characters from header. This will allow checking maximum character based on
* {@link SmppConstants#MAXIMUM_CHARACTERS} header or determine the maximum character based on data coding
* header {@link SmppConstants#DATA_CODING}.
* <p/>
* The order of the selection is
* <ol>
* <li>If {@link SmppConstants#MAXIMUM_CHARACTERS} is set, use it</li>
* <li>If {@link SmppConstants#DATA_CODING} is set, find maximum character for the data coding</li>
* <li>Using default maximum character which is 140</li>
* </ol>
* @param msg the Spring Integration message
* @return maximum character can be sent through the session
*/
private static int maximumCharactersFromHeader(Message<?> msg) {
if (msg.getHeaders().containsKey(MAXIMUM_CHARACTERS)) {
return msg.getHeaders().get(MAXIMUM_CHARACTERS, Integer.class);
}
if (msg.getHeaders().containsKey(DATA_CODING)) {
final Object dc = msg.getHeaders().get(DATA_CODING);
if (dc instanceof Byte) {
return DataCodingSpecification.getMaxCharacters((Byte)dc);
}
else {
return DataCodingSpecification.getMaxCharacters(((DataCoding)dc).toByte());
}
}
return 140;
}
/**
* need to be a little flexibile about what we take in as {@link SmppConstants#REGISTERED_DELIVERY_MODE}. The value can
@@ -276,8 +286,9 @@ public class SmesMessageSpecification {
@SuppressWarnings("unchecked")
static private <T> T valueIfHeaderExists(String h, Message<?> msg) {
if (msg != null && msg.getHeaders().containsKey(h))
if (msg != null && msg.getHeaders().containsKey(h)) {
return (T) msg.getHeaders().get(h);
}
return null;
}
@@ -330,8 +341,9 @@ public class SmesMessageSpecification {
* @return this
*/
public SmesMessageSpecification setSourceAddressTypeOfNumberIfRequired(TypeOfNumber sourceAddressTypeOfNumberIfRequired) {
if (this.sourceAddressTypeOfNumber == null)
if (this.sourceAddressTypeOfNumber == null) {
this.sourceAddressTypeOfNumber = sourceAddressTypeOfNumberIfRequired;
}
return this;
}
@@ -345,9 +357,9 @@ public class SmesMessageSpecification {
*/
public String send() throws Exception {
validate();
final String msgId;
if (messagePayloadParameter == null) {
msgId = this.smppSession.submitShortMessage(
final String msgId;
if (messagePayloadParameter == null) {
msgId = this.smppSession.submitShortMessage(
this.serviceType,
this.sourceAddressTypeOfNumber,
this.sourceAddressNumberingPlanIndicator,
@@ -367,32 +379,33 @@ public class SmesMessageSpecification {
this.dataCoding,
this.smDefaultMsgId,
this.shortMessage);
} else {
// SPEC 3.2.3
log.debug("Sending message using message_payload");
msgId = this.smppSession.submitShortMessage(
this.serviceType,
this.sourceAddressTypeOfNumber,
this.sourceAddressNumberingPlanIndicator,
this.sourceAddress,
}
else {
// SPEC 3.2.3
log.debug("Sending message using message_payload");
msgId = this.smppSession.submitShortMessage(
this.serviceType,
this.sourceAddressTypeOfNumber,
this.sourceAddressNumberingPlanIndicator,
this.sourceAddress,
this.destinationAddressTypeOfNumber,
this.destinationAddressNumberingPlanIndicator,
this.destinationAddress,
this.destinationAddressTypeOfNumber,
this.destinationAddressNumberingPlanIndicator,
this.destinationAddress,
this.esmClass,
this.protocolId,
this.priorityFlag,
this.scheduleDeliveryTime,
this.validityPeriod,
this.registeredDelivery,
this.replaceIfPresentFlag,
this.dataCoding,
this.smDefaultMsgId,
new byte[0],
this.messagePayloadParameter
);
}
this.esmClass,
this.protocolId,
this.priorityFlag,
this.scheduleDeliveryTime,
this.validityPeriod,
this.registeredDelivery,
this.replaceIfPresentFlag,
this.dataCoding,
this.smDefaultMsgId,
new byte[0],
this.messagePayloadParameter
);
}
return msgId;
}
@@ -400,16 +413,18 @@ public class SmesMessageSpecification {
protected void validate() {
Assert.notNull(this.sourceAddress, "the source address must not be null");
Assert.notNull(this.destinationAddress, "the destination address must not be null");
final boolean shortMessageSet = this.shortMessage != null && this.shortMessage.length > 0;
Assert.isTrue(messagePayloadParameter != null ^ shortMessageSet,
"message can only be set in payload or short message. cannot be both");
if (messagePayloadParameter == null)
Assert.isTrue(shortMessageSet, "the message must not be null");
final boolean shortMessageSet = this.shortMessage != null && this.shortMessage.length > 0;
Assert.isTrue(messagePayloadParameter != null ^ shortMessageSet,
"message can only be set in payload or short message. cannot be both");
if (messagePayloadParameter == null) {
Assert.isTrue(shortMessageSet, "the message must not be null");
}
}
public SmesMessageSpecification setSourceAddress(String sourceAddr) {
if (!nullHeaderWillOverwriteDefault(sourceAddr))
if (!nullHeaderWillOverwriteDefault(sourceAddr)) {
this.sourceAddress = sourceAddr;
}
return this;
}
@@ -425,26 +440,30 @@ public class SmesMessageSpecification {
}
public SmesMessageSpecification setServiceType(String serviceType) {
if (!nullHeaderWillOverwriteDefault(serviceType))
if (!nullHeaderWillOverwriteDefault(serviceType)) {
this.serviceType = serviceType;
}
return this;
}
public SmesMessageSpecification setSourceAddressTypeOfNumber(TypeOfNumber sourceAddrTon) {
if (!nullHeaderWillOverwriteDefault(sourceAddrTon))
if (!nullHeaderWillOverwriteDefault(sourceAddrTon)) {
this.sourceAddressTypeOfNumber = sourceAddrTon;
}
return this;
}
public SmesMessageSpecification setSourceAddressNumberingPlanIndicator(NumberingPlanIndicator sourceAddrNpi) {
if (!nullHeaderWillOverwriteDefault(sourceAddrNpi))
if (!nullHeaderWillOverwriteDefault(sourceAddrNpi)) {
this.sourceAddressNumberingPlanIndicator = sourceAddrNpi;
}
return this;
}
public SmesMessageSpecification setDestinationAddressTypeOfNumber(TypeOfNumber destAddrTon) {
if (!nullHeaderWillOverwriteDefault(destAddrTon))
if (!nullHeaderWillOverwriteDefault(destAddrTon)) {
this.destinationAddressTypeOfNumber = destAddrTon;
}
return this;
}
@@ -456,33 +475,39 @@ public class SmesMessageSpecification {
*/
private boolean nullHeaderWillOverwriteDefault(Object v) {
if (v == null) {
if (log.isDebugEnabled()) log.debug("There is a default in place for this property; don't overwrite it with null");
if (log.isDebugEnabled()) {
log.debug("There is a default in place for this property; don't overwrite it with null");
}
return true;
}
return false;
}
public SmesMessageSpecification setDestinationAddressNumberingPlanIndicator(NumberingPlanIndicator destAddrNpi) {
if (!nullHeaderWillOverwriteDefault(destAddrNpi))
if (!nullHeaderWillOverwriteDefault(destAddrNpi)) {
this.destinationAddressNumberingPlanIndicator = destAddrNpi;
}
return this;
}
public SmesMessageSpecification setEsmClass(ESMClass esmClass) {
if (!nullHeaderWillOverwriteDefault(esmClass))
if (!nullHeaderWillOverwriteDefault(esmClass)) {
this.esmClass = esmClass;
}
return this;
}
public SmesMessageSpecification setProtocolId(byte protocolId) {
if (!nullHeaderWillOverwriteDefault(protocolId))
if (!nullHeaderWillOverwriteDefault(protocolId)) {
this.protocolId = protocolId;
}
return this;
}
public SmesMessageSpecification setPriorityFlag(byte pf) {
if (!nullHeaderWillOverwriteDefault(pf))
if (!nullHeaderWillOverwriteDefault(pf)) {
this.priorityFlag = pf;
}
return this;
}
@@ -505,32 +530,37 @@ public class SmesMessageSpecification {
* @return the current SmesMessageSpecification
*/
public SmesMessageSpecification setValidityPeriod(String v) {
if (!nullHeaderWillOverwriteDefault(v))
if (!nullHeaderWillOverwriteDefault(v)) {
this.validityPeriod = v;
}
return this;
}
public SmesMessageSpecification setScheduleDeliveryTime(Date d) {
if (!nullHeaderWillOverwriteDefault(d))
if (!nullHeaderWillOverwriteDefault(d)) {
this.scheduleDeliveryTime = timeFormatter.format(d);
}
return this;
}
public SmesMessageSpecification setRegisteredDelivery(RegisteredDelivery rd) {
if (!nullHeaderWillOverwriteDefault(rd))
if (!nullHeaderWillOverwriteDefault(rd)) {
this.registeredDelivery = rd;
}
return this;
}
public SmesMessageSpecification setReplaceIfPresentFlag(byte replaceIfPresentFlag) {
if (!nullHeaderWillOverwriteDefault(replaceIfPresentFlag))
if (!nullHeaderWillOverwriteDefault(replaceIfPresentFlag)) {
this.replaceIfPresentFlag = replaceIfPresentFlag;
}
return this;
}
public SmesMessageSpecification setDataCoding(DataCoding dataCoding) {
if (!nullHeaderWillOverwriteDefault(dataCoding))
if (!nullHeaderWillOverwriteDefault(dataCoding)) {
this.dataCoding = dataCoding;
}
return this;
}
@@ -540,43 +570,45 @@ public class SmesMessageSpecification {
}
public SmesMessageSpecification setTimeFormatter(TimeFormatter timeFormatter) {
if (!nullHeaderWillOverwriteDefault(timeFormatter))
if (!nullHeaderWillOverwriteDefault(timeFormatter)) {
this.timeFormatter = timeFormatter;
}
return this;
}
/**
* Setting short message. This will take into account if {@link #dataCoding} or if {@link #maxLengthSmsMessages}
* is set through header to validate the maximum characters can be set.
* Setting short message. This will take into account if {@link #dataCoding} or if {@link #maxLengthSmsMessages}
* is set through header to validate the maximum characters can be set.
*
* @param s the text message body
* @return the SmesMessageSpecification
*/
public SmesMessageSpecification setShortTextMessage(String s) {
Assert.notNull(s, "the SMS message payload must not be null");
if (esmClass != null && GSMSpecificFeature.UDHI.containedIn(esmClass)) {
log.debug("Setting short message with UDH");
this.shortMessage = UdhUtil.getMessageWithUdhInBytes(s, dataCoding.toByte());
} else {
Assert.isTrue(s.length() <= this.maxLengthSmsMessages,
"the SMS message payload must be " + maxLengthSmsMessages + " characters or less.");
this.shortMessage = DataCodingSpecification.getMessageInBytes(s, dataCoding.toByte());
}
if (esmClass != null && GSMSpecificFeature.UDHI.containedIn(esmClass)) {
log.debug("Setting short message with UDH");
this.shortMessage = UdhUtil.getMessageWithUdhInBytes(s, dataCoding.toByte());
}
else {
Assert.isTrue(s.length() <= this.maxLengthSmsMessages,
"the SMS message payload must be " + maxLengthSmsMessages + " characters or less.");
this.shortMessage = DataCodingSpecification.getMessageInBytes(s, dataCoding.toByte());
}
return this;
}
/**
* Setting short message using message_payload ({@link org.jsmpp.bean.OptionalParameter.Tag#MESSAGE_PAYLOAD})
* optional parameter
* @param s the text messages body
* @return the SmesMessageSpecification
*/
public SmesMessageSpecification setShortMessageUsingPayload(String s) {
final byte[] content = DataCodingSpecification.getMessageInBytes(s, dataCoding.toByte());
this.messagePayloadParameter =
new OptionalParameter.OctetString(OptionalParameter.Tag.MESSAGE_PAYLOAD.code(), content);
return this;
}
/**
* Setting short message using message_payload ({@link org.jsmpp.bean.OptionalParameter.Tag#MESSAGE_PAYLOAD})
* optional parameter
* @param s the text messages body
* @return the SmesMessageSpecification
*/
public SmesMessageSpecification setShortMessageUsingPayload(String s) {
final byte[] content = DataCodingSpecification.getMessageInBytes(s, dataCoding.toByte());
this.messagePayloadParameter =
new OptionalParameter.OctetString(OptionalParameter.Tag.MESSAGE_PAYLOAD.code(), content);
return this;
}
/**
* this is a good value, but not strictly speaking universal. This is intended only for exceptional configuration cases
@@ -621,13 +653,14 @@ public class SmesMessageSpecification {
smDefaultMsgId = 0;
shortMessage = null; // the bytes to the 140 character text message
smppSession = null;
messagePayloadParameter = null;
messagePayloadParameter = null;
return this;
}
public SmesMessageSpecification setSourceAddressIfRequired(String defaultSourceAddress) {
if (!StringUtils.hasText(this.sourceAddress))
if (!StringUtils.hasText(this.sourceAddress)) {
this.sourceAddress = defaultSourceAddress;
}
return this;
}
}

View File

@@ -112,19 +112,22 @@ public class SmppInboundGateway extends MessagingGatewaySupport {
String from = null, to = null;
if (request.getHeaders().containsKey(SmppConstants.SRC_ADDR)) {
to = (String) request.getHeaders().get(SmppConstants.SRC_ADDR);
if (StringUtils.hasText(to))
if (StringUtils.hasText(to)) {
smesMessageSpecification.setDestinationAddress(to);
}
}
if (request.getHeaders().containsKey(SmppConstants.DEST_ADDRESS)) {
from = (String) request.getHeaders().get(SmppConstants.DEST_ADDRESS);
if (StringUtils.hasText(from))
if (StringUtils.hasText(from)) {
smesMessageSpecification.setSourceAddress(from);
}
}
if (defaultSourceAddressTypeOfNumber != null)
if (defaultSourceAddressTypeOfNumber != null) {
smesMessageSpecification.setSourceAddressTypeOfNumberIfRequired(this.defaultSourceAddressTypeOfNumber);
if (StringUtils.hasText(this.defaultSourceAddress))
}
if (StringUtils.hasText(this.defaultSourceAddress)) {
smesMessageSpecification.setSourceAddressIfRequired(this.defaultSourceAddress);
}
return smesMessageSpecification;
}

View File

@@ -75,11 +75,12 @@ public class SmppOutboundChannelAdapter extends IntegrationObjectSupport impleme
private SmesMessageSpecification applyDefaultsIfNecessary(SmesMessageSpecification smsSpec) {
if (defaultSourceAddressTypeOfNumber != null)
if (defaultSourceAddressTypeOfNumber != null) {
smsSpec.setSourceAddressTypeOfNumberIfRequired(this.defaultSourceAddressTypeOfNumber);
if (StringUtils.hasText(this.defaultSourceAddress))
}
if (StringUtils.hasText(this.defaultSourceAddress)) {
smsSpec.setSourceAddressIfRequired(this.defaultSourceAddress);
}
return smsSpec;
}

View File

@@ -94,11 +94,12 @@ public class SmppOutboundGateway extends AbstractReplyProducingMessageHandler {
private SmesMessageSpecification applyDefaultsIfNecessary(SmesMessageSpecification smsSpec) {
if (defaultSourceAddressTypeOfNumber != null)
if (defaultSourceAddressTypeOfNumber != null) {
smsSpec.setSourceAddressTypeOfNumberIfRequired(this.defaultSourceAddressTypeOfNumber);
if (StringUtils.hasText(this.defaultSourceAddress))
}
if (StringUtils.hasText(this.defaultSourceAddress)) {
smsSpec.setSourceAddressIfRequired(this.defaultSourceAddress);
}
return smsSpec;
}

View File

@@ -56,8 +56,9 @@ public class ExtendedSmppSessionAdaptingDelegate implements /*Lifecycle,*/ Exten
public void start() {
if( this.running)
if( this.running) {
return;
}
lifecycle.start();
this.running = true;

View File

@@ -87,7 +87,7 @@ import java.util.concurrent.Executors;
* @since 1.0
*/
public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>, SmartLifecycle, InitializingBean,
DisposableBean {
DisposableBean {
private Set<MessageReceiverListener> messageReceiverListeners = new HashSet<MessageReceiverListener>();
private boolean autoStartup;
@@ -98,7 +98,7 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
private String host = "127.0.0.1";
private String addressRange;
private long timeout = 60 * 1000;// 1 minute
private long transactionTimeout = 2 * 1000; // 2 seconds
private long transactionTimeout = 2 * 1000; // 2 seconds
private int port = 2775; // good default though this has been known to change
private BindType bindType = BindType.BIND_TRX; // bind as a 'transceiver' - only 3.4 of the spec <em>requires</em> support for this
private String systemId = getClass().getSimpleName().toLowerCase(); // what would typically be called 'user' in a user/pw scheme
@@ -106,15 +106,15 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
private String systemType = "cp";
private TypeOfNumber addrTon = TypeOfNumber.UNKNOWN;
private NumberingPlanIndicator addrNpi = NumberingPlanIndicator.UNKNOWN;
private long reconnectInterval = 5 * 1000; // 5 seconds
private boolean reconnect = true; // flag whether we want to reconnect
private volatile boolean destroyed = false; // flag that this session factory has been disposed
private long reconnectInterval = 5 * 1000; // 5 seconds
private boolean reconnect = true; // flag whether we want to reconnect
private volatile boolean destroyed = false; // flag that this session factory has been disposed
private ExtendedSmppSessionAdaptingDelegate product;
private final ProxyFactoryBean sessionFactoryBean = new ProxyFactoryBean();
private final ProxyFactoryBean sessionFactoryBean = new ProxyFactoryBean();
private ExecutorService reconnectingExecutor;
private boolean reconnectingExecutorSet;
private ExecutorService reconnectingExecutor;
private boolean reconnectingExecutorSet;
public void setSsl(boolean ssl) {
this.ssl = ssl;
@@ -163,30 +163,30 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
this.addressRange = addressRange;
}
/**
* Setting timeout for the session. This value is used to establish connection to SMSC, e.g. trying to establish
* connection. (default is 1 minute). This should not be confused with {@link #setTransactionTimeout(long)} which
* is the timeout to perform request on the actual session after it has been established.
*
* @param timeout timeout in milliseconds
*/
/**
* Setting timeout for the session. This value is used to establish connection to SMSC, e.g. trying to establish
* connection. (default is 1 minute). This should not be confused with {@link #setTransactionTimeout(long)} which
* is the timeout to perform request on the actual session after it has been established.
*
* @param timeout timeout in milliseconds
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/**
* Setting transaction timeout preforming request on the session. ({@link SMPPSession#setTransactionTimer(long)}.
* This transaction timeout is similar to the concept of send timeout / request timeout. (default 2 seconds).
* If you receive a lot of {@link org.jsmpp.extra.ResponseTimeoutException} for waiting response from your SMSC,
* this indicates you need to increase this value.
*
* @param transactionTimeout transaction timeout in milliseconds
*/
public void setTransactionTimeout(long transactionTimeout) {
this.transactionTimeout = transactionTimeout;
}
/**
* Setting transaction timeout preforming request on the session. ({@link SMPPSession#setTransactionTimer(long)}.
* This transaction timeout is similar to the concept of send timeout / request timeout. (default 2 seconds).
* If you receive a lot of {@link org.jsmpp.extra.ResponseTimeoutException} for waiting response from your SMSC,
* this indicates you need to increase this value.
*
* @param transactionTimeout transaction timeout in milliseconds
*/
public void setTransactionTimeout(long transactionTimeout) {
this.transactionTimeout = transactionTimeout;
}
public void setSessionStateListener(SessionStateListener sessionStateListener) {
public void setSessionStateListener(SessionStateListener sessionStateListener) {
this.sessionStateListener = sessionStateListener;
}
@@ -194,50 +194,50 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
this.messageReceiverListeners = messageReceiverListeners;
}
/**
* Creating new SMPPSession. This will create default SMPPSession for non-SSL connection or create SMPPSession
* using different factory for SSL connection.
* @return SMPP session
*/
private SMPPSession createNewSession() {
final SMPPSession newSession;
if (!ssl) {
newSession = new SMPPSession();
} else {
newSession = new SMPPSession(new SynchronizedPDUSender(new DefaultPDUSender(
new DefaultComposer())), new DefaultPDUReader(), sslConnectionFactory);
}
newSession.setTransactionTimer(transactionTimeout);
return newSession;
}
/**
* Creating new SMPPSession. This will create default SMPPSession for non-SSL connection or create SMPPSession
* using different factory for SSL connection.
* @return SMPP session
*/
private SMPPSession createNewSession() {
final SMPPSession newSession;
if (!ssl) {
newSession = new SMPPSession();
} else {
newSession = new SMPPSession(new SynchronizedPDUSender(new DefaultPDUSender(
new DefaultComposer())), new DefaultPDUReader(), sslConnectionFactory);
}
newSession.setTransactionTimer(transactionTimeout);
return newSession;
}
/**
* Logic to build smpp session
* Logic to build smpp session
* @return the configured SMPPSession
* @throws Exception should anything go wrong
*/
private ExtendedSmppSessionAdaptingDelegate buildSmppSession() throws Exception {
final SMPPSession smppSession = createNewSession();
final ExtendedSmppSessionAdaptingDelegate extendedSmppSessionAdaptingDelegate;
if (reconnect) {
sessionFactoryBean.setAutodetectInterfaces(false);
sessionFactoryBean.setTarget(smppSession);
final SMPPSession proxiedSession = (SMPPSession)sessionFactoryBean.getObject();
if (reconnect) {
sessionFactoryBean.setAutodetectInterfaces(false);
sessionFactoryBean.setTarget(smppSession);
final SMPPSession proxiedSession = (SMPPSession)sessionFactoryBean.getObject();
extendedSmppSessionAdaptingDelegate = new ExtendedSmppSessionAdaptingDelegate(
proxiedSession, new AutoReconnectLifecycle(proxiedSession));
} else {
extendedSmppSessionAdaptingDelegate = new ExtendedSmppSessionAdaptingDelegate(
smppSession, new ConnectingLifecycle(smppSession));
}
extendedSmppSessionAdaptingDelegate = new ExtendedSmppSessionAdaptingDelegate(
proxiedSession, new AutoReconnectLifecycle(proxiedSession));
} else {
extendedSmppSessionAdaptingDelegate = new ExtendedSmppSessionAdaptingDelegate(
smppSession, new ConnectingLifecycle(smppSession));
}
for (MessageReceiverListener mrl : this.messageReceiverListeners)
extendedSmppSessionAdaptingDelegate.addMessageReceiverListener(mrl);
// if session state listener not null, add it
if (sessionStateListener != null) {
extendedSmppSessionAdaptingDelegate.addSessionStateListener(sessionStateListener);
}
// if session state listener not null, add it
if (sessionStateListener != null) {
extendedSmppSessionAdaptingDelegate.addSessionStateListener(sessionStateListener);
}
extendedSmppSessionAdaptingDelegate.setBindType(this.bindType);
return extendedSmppSessionAdaptingDelegate;
@@ -268,9 +268,9 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
*/
public void start() {
log.debug("starting up in " + getClass().getName() + "#start().");
if (reconnectingExecutor == null) {
this.reconnectingExecutor = Executors.newFixedThreadPool(1);
}
if (reconnectingExecutor == null) {
this.reconnectingExecutor = Executors.newFixedThreadPool(1);
}
( product).start();
this.running = true;
@@ -283,11 +283,11 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
log.debug("shutting down in " + getClass().getName() + "#stop().");
( product).stop();
// if we are running default executor, shut it down
if (!reconnectingExecutorSet && reconnectingExecutor != null) {
reconnectingExecutor.shutdown();
this.reconnectingExecutor = null;
}
// if we are running default executor, shut it down
if (!reconnectingExecutorSet && reconnectingExecutor != null) {
reconnectingExecutor.shutdown();
this.reconnectingExecutor = null;
}
this.running = false;
}
@@ -328,34 +328,34 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
return true;
}
/**
* Set whether we want to reconnect the session. Default is true.
*
* @param reconnect true/false
*/
public void setReconnect(boolean reconnect) {
this.reconnect = reconnect;
}
/**
* Set whether we want to reconnect the session. Default is true.
*
* @param reconnect true/false
*/
public void setReconnect(boolean reconnect) {
this.reconnect = reconnect;
}
/**
* Set session reconnection interval. Default is 5 seconds.
*
* @param reconnectInterval reconnection interval in milliseconds
*/
public void setReconnectInterval(long reconnectInterval) {
this.reconnectInterval = reconnectInterval;
}
/**
* Set session reconnection interval. Default is 5 seconds.
*
* @param reconnectInterval reconnection interval in milliseconds
*/
public void setReconnectInterval(long reconnectInterval) {
this.reconnectInterval = reconnectInterval;
}
/**
* Set executor service for performing SMPP reconnection.
* @param reconnectingExecutor executor service
*/
public void setReconnectingExecutor(ExecutorService reconnectingExecutor) {
this.reconnectingExecutor = reconnectingExecutor;
this.reconnectingExecutorSet = true;
}
/**
* Set executor service for performing SMPP reconnection.
* @param reconnectingExecutor executor service
*/
public void setReconnectingExecutor(ExecutorService reconnectingExecutor) {
this.reconnectingExecutor = reconnectingExecutor;
this.reconnectingExecutorSet = true;
}
/**
/**
* {@inheritDoc}
*/
public void afterPropertiesSet() throws Exception {
@@ -370,15 +370,15 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
this.product = buildSmppSession();
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() throws Exception {
this.destroyed = true;
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() throws Exception {
this.destroyed = true;
}
/**
/**
* singleton {@link ConnectionFactory} that handles SSL
*/
final private static ConnectionFactory sslConnectionFactory = new ConnectionFactory() {
@@ -427,149 +427,154 @@ public class SmppSessionFactoryBean implements FactoryBean<ExtendedSmppSession>,
session.connectAndBind(host, port, bindType, systemId, password, systemType, addrTon, addrNpi, addressRange, timeout);
this.running = true;
} catch (IOException e) {
if (log.isDebugEnabled())
log.error("Error happened when trying to connect to " + host + ":" + port, e);
else
log.error("Error happened when trying to connect to " + host + ":" + port + ". Cause: "
+ e.getMessage());
if (log.isDebugEnabled()) {
log.error("Error happened when trying to connect to " + host + ":" + port, e);
}
else {
log.error("Error happened when trying to connect to " + host + ":" + port + ". Cause: "
+ e.getMessage());
}
}
}
}
/**
* Lifecycle implementation that will try to re-establish connection with specific interval. At the start of the
* connection.
*
* @author Johanes Soetanto
*/
private class AutoReconnectLifecycle implements Lifecycle {
/**
* Lifecycle implementation that will try to re-establish connection with specific interval. At the start of the
* connection.
*
* @author Johanes Soetanto
*/
private class AutoReconnectLifecycle implements Lifecycle {
private final Logger log = LoggerFactory.getLogger(AutoReconnectLifecycle.class);
private final SMPPSession session;
private volatile boolean running;
private final Logger log = LoggerFactory.getLogger(AutoReconnectLifecycle.class);
private final SMPPSession session;
private volatile boolean running;
/**
* Creating auto reconnect lifecycle using SMPP session and reconnect interval in milliseconds
* @param smppSession reference to SMPP session
*/
private AutoReconnectLifecycle(SMPPSession smppSession) {
this.session = smppSession;
}
/**
* Creating auto reconnect lifecycle using SMPP session and reconnect interval in milliseconds
* @param smppSession reference to SMPP session
*/
private AutoReconnectLifecycle(SMPPSession smppSession) {
this.session = smppSession;
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public void stop() {
if (session != null) {
if (session.getSessionState().isBound()) {
try {
session.unbindAndClose();
} catch (Exception t) {
log.warn("Couldn't close and unbind the session", t);
}
}
} else {
log.warn("The smppSession given to close is null");
}
}
@Override
public void stop() {
if (session != null) {
if (session.getSessionState().isBound()) {
try {
session.unbindAndClose();
} catch (Exception t) {
log.warn("Couldn't close and unbind the session", t);
}
}
} else {
log.warn("The smppSession given to close is null");
}
}
@Override
public void start() {
connect();
@Override
public void start() {
connect();
if (!running) {
log.debug("Try to connect at later time. The delay is {}ms", reconnectInterval);
scheduleReconnect();
} else {
registerSessionCloseListener();
}
}
if (!running) {
log.debug("Try to connect at later time. The delay is {}ms", reconnectInterval);
scheduleReconnect();
} else {
registerSessionCloseListener();
}
}
/**
* Register session state listener to reconnect when session is closed by server.
*/
private void registerSessionCloseListener() {
log.debug("Registering session close listener");
session.addSessionStateListener(new SessionStateListener() {
@Override
public void onStateChange(SessionState newState, SessionState oldState, Object source) {
// when session is closed but client session has not been destroyed can indicates client
// lose connection to server
if (newState.equals(SessionState.CLOSED)) {
running = false;
if (!destroyed) {
log.info("Session to {}:{} has been closed. Try to reconnect later", host, port);
/**
* Register session state listener to reconnect when session is closed by server.
*/
private void registerSessionCloseListener() {
log.debug("Registering session close listener");
session.addSessionStateListener(new SessionStateListener() {
@Override
public void onStateChange(SessionState newState, SessionState oldState, Object source) {
// when session is closed but client session has not been destroyed can indicates client
// lose connection to server
if (newState.equals(SessionState.CLOSED)) {
running = false;
if (!destroyed) {
log.info("Session to {}:{} has been closed. Try to reconnect later", host, port);
final SMPPSession newSession = createNewSession();
newSession.setMessageReceiverListener(product.getDelegateMessageListener());
if (sessionStateListener != null) {
session.addSessionStateListener(sessionStateListener);
}
sessionFactoryBean.setTarget(newSession);
final SMPPSession newSession = createNewSession();
newSession.setMessageReceiverListener(product.getDelegateMessageListener());
if (sessionStateListener != null) {
session.addSessionStateListener(sessionStateListener);
}
sessionFactoryBean.setTarget(newSession);
scheduleReconnect();
}
}
}
});
}
scheduleReconnect();
}
}
}
});
}
/**
* Perform connection logic.
*/
private void connect() {
try {
session.connectAndBind(host, port, bindType, systemId, password, systemType,
addrTon, addrNpi, addressRange, timeout);
this.running = true;
/**
* Perform connection logic.
*/
private void connect() {
try {
session.connectAndBind(host, port, bindType, systemId, password, systemType,
addrTon, addrNpi, addressRange, timeout);
this.running = true;
} catch (IOException e) {
if (log.isDebugEnabled())
log.error("Error happened when trying to connect to " + host + ":" + port, e);
else
log.error("Error happened when trying to connect to {}:{}. Cause: {}",
new Object[]{host, port, e.getMessage()});
}
}
}
catch (IOException e) {
if (log.isDebugEnabled()) {
log.error("Error happened when trying to connect to " + host + ":" + port, e);
}
else {
log.error("Error happened when trying to connect to {}:{}. Cause: {}",
new Object[]{host, port, e.getMessage()});
}
}
}
/**
* Schedule a session reconnection.
*/
private void scheduleReconnect() {
/**
* Schedule a session reconnection.
*/
private void scheduleReconnect() {
reconnectingExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(reconnectInterval);
reconnectingExecutor.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(reconnectInterval);
int attempt = 0;
// if this session is still not run and the session has not been destroyed, re-connect
while (!running && !destroyed) {
log.info("Reconnecting attempt #{} ...", ++attempt);
connect();
int attempt = 0;
// if this session is still not run and the session has not been destroyed, re-connect
while (!running && !destroyed) {
log.info("Reconnecting attempt #{} ...", ++attempt);
connect();
if (!running) {
// if still not running, then perform another sleep
Thread.sleep(reconnectInterval);
}
}
if (!running) {
// if still not running, then perform another sleep
Thread.sleep(reconnectInterval);
}
}
if (running) {
log.info("Successfully reconnect at attempt #{}", attempt);
// if finish re-connection loop and session is run we register session close listener
registerSessionCloseListener();
}
if (running) {
log.info("Successfully reconnect at attempt #{}", attempt);
// if finish re-connection loop and session is run we register session close listener
registerSessionCloseListener();
}
} catch (InterruptedException e) {
log.info("Interrupted when trying to connect to {}:{}", host, port);
}
}
});
}
}
} catch (InterruptedException e) {
log.info("Interrupted when trying to connect to {}:{}", host, port);
}
}
});
}
}
}
}