[Comsuite-svn] SF.net SVN: comsuite: [149] trunk/code/CSMiddleware/src/org/commsuite/ devices
                
                Brought to you by:
                
                    zduniak
                    
                
            
            
        
        
        
    | 
     
      
      
      From: <zd...@us...> - 2006-09-23 12:11:30
      
     
   | 
Revision: 149
          http://svn.sourceforge.net/comsuite/?rev=149&view=rev
Author:   zduniak
Date:     2006-09-23 05:11:16 -0700 (Sat, 23 Sep 2006)
Log Message:
-----------
Refactoring: more fine-grained synchronization during sending/receiving SMSes
Modified Paths:
--------------
    trunk/code/CSMiddleware/src/org/commsuite/devices/Device.java
    trunk/code/CSMiddleware/src/org/commsuite/devices/DeviceManager.java
    trunk/code/CSMiddleware/src/org/commsuite/devices/OutboundMessage.java
    trunk/code/CSMiddleware/src/org/commsuite/devices/sms/ReceivePollingJob.java
    trunk/code/CSMiddleware/src/org/commsuite/devices/sms/SmsDevice.java
Modified: trunk/code/CSMiddleware/src/org/commsuite/devices/Device.java
===================================================================
--- trunk/code/CSMiddleware/src/org/commsuite/devices/Device.java	2006-09-23 11:37:31 UTC (rev 148)
+++ trunk/code/CSMiddleware/src/org/commsuite/devices/Device.java	2006-09-23 12:11:16 UTC (rev 149)
@@ -398,6 +398,7 @@
     /**
      * @see java.lang.Object#toString()
      */
+    @Override
     public String toString() {
         return new ToStringBuilder(this).append("name", this.name).append("state", this.state)
                 .append("messagesReceived", this.messagesReceived).append("messagesSent",
Modified: trunk/code/CSMiddleware/src/org/commsuite/devices/DeviceManager.java
===================================================================
--- trunk/code/CSMiddleware/src/org/commsuite/devices/DeviceManager.java	2006-09-23 11:37:31 UTC (rev 148)
+++ trunk/code/CSMiddleware/src/org/commsuite/devices/DeviceManager.java	2006-09-23 12:11:16 UTC (rev 149)
@@ -28,8 +28,6 @@
 import org.commsuite.devices.OutboundMessage.State;
 import org.commsuite.messaging.ExDevRegister;
 
-import edu.emory.mathcs.backport.java.util.Collections;
-
 /**
  * Class used to manage (initialize and shutdown) all external devices used in CS.
  * 
Modified: trunk/code/CSMiddleware/src/org/commsuite/devices/OutboundMessage.java
===================================================================
--- trunk/code/CSMiddleware/src/org/commsuite/devices/OutboundMessage.java	2006-09-23 11:37:31 UTC (rev 148)
+++ trunk/code/CSMiddleware/src/org/commsuite/devices/OutboundMessage.java	2006-09-23 12:11:16 UTC (rev 149)
@@ -35,32 +35,34 @@
  * @author Rafał Malinowski
  */
 public abstract class OutboundMessage {
-	
+
 	/**
 	 * States of message.
 	 */
 	public static enum State {
-		SUBMITED,
-		DELIVERED,
-		FAILED
+		SUBMITED, DELIVERED, FAILED
 	}
-	
+
 	protected abstract List<String> getAcceptedMimeTypes();
-	
+
 	private Device device;
+
 	private String messageId = null;
+
 	private String contentMimeType;
-    private String destinationAddress;
-    
-    private byte[] content;
 
-    private Converter converter;
-	
-    /**
-     * Creates new outbound message.
-     * 
-     * @param device device which will send this message.
-     */
+	private String destinationAddress;
+
+	private byte[] content;
+
+	private Converter converter;
+
+	/**
+	 * Creates new outbound message.
+	 * 
+	 * @param device
+	 *            device which will send this message.
+	 */
 	public OutboundMessage(Device device) {
 		this.device = device;
 	}
@@ -71,7 +73,7 @@
 	public Device getDevice() {
 		return device;
 	}
-	
+
 	public void setMessageId(String messageId) {
 		this.messageId = messageId;
 	}
@@ -82,35 +84,41 @@
 	public String getMessageId() {
 		return messageId;
 	}
-	
+
 	/**
 	 * Checks if mimeType is supported. Currently only postscript is supported.
 	 * 
+	 * TODO: emphasize in JavaDoc that by invoking this method you also change
+	 * the object internal state (converter variable).
+	 * 
 	 * @return true, if mimeType is supported
 	 */
 	protected boolean isContentMimeTypeSupported() {
 		if (contentMimeType == null) {
 			return false;
 		}
-		
-		ConverterBuilder builder = (ConverterBuilder)SpringContext.getBean("converterBuilder");
+
+		ConverterBuilder builder = (ConverterBuilder) SpringContext
+				.getBean("converterBuilder");
 		converter = null;
-		
+
 		for (final String acceptedMimeType : getAcceptedMimeTypes()) {
 			try {
-				Converter newConverter = builder.getConverter(new Conversion(contentMimeType, acceptedMimeType));
-				
-				if (converter == null || converter.getQuality() < newConverter.getQuality()) {
+				Converter newConverter = builder.getConverter(new Conversion(
+						contentMimeType, acceptedMimeType));
+
+				if (converter == null
+						|| converter.getQuality() < newConverter.getQuality()) {
 					converter = newConverter;
 				}
 			} catch (ConversionImpossibleException e) {
 				// ignore, we dont care
-			}	
+			}
 		}
-		
+
 		return (converter != null);
 	}
-	
+
 	protected Converter getConverter() {
 		return converter;
 	}
@@ -118,46 +126,46 @@
 	/**
 	 * Sets message mime type.
 	 * 
-	 * @param contentMimeType mime type to set
+	 * @param contentMimeType
+	 *            mime type to set
 	 * @return true if given mime type is supported
 	 */
-    public boolean setContentMimeType(String contentMimeType) {
-        this.contentMimeType = contentMimeType;
+	public boolean setContentMimeType(String contentMimeType) {
+		this.contentMimeType = contentMimeType;
 
-        return isContentMimeTypeSupported();
-    }
+		return isContentMimeTypeSupported();
+	}
 
-    public String getContentMimeType() {
-        return contentMimeType;
-    }
-	
-    public void setDestinationAddress(String destinationAddress) {
-        this.destinationAddress = destinationAddress;
-    }
+	public String getContentMimeType() {
+		return contentMimeType;
+	}
 
-    public String getDestinationAddress() {
-        return destinationAddress;
-    }
- 
+	public void setDestinationAddress(String destinationAddress) {
+		this.destinationAddress = destinationAddress;
+	}
+
+	public String getDestinationAddress() {
+		return destinationAddress;
+	}
+
 	public byte[] getContent() {
 		return content;
 	}
-	
+
 	public void setContent(byte[] content) {
 		this.content = content;
 	}
-	
+
+	@Override
 	public boolean equals(Object obj) {
 		if (!(obj instanceof OutboundMessage)) {
 			return false;
 		}
-		
-		OutboundMessage message = (OutboundMessage)obj;
-		
-		return
-			device == message.device &&
-			messageId.equals(message.messageId) &&
-			contentMimeType.equals(message.contentMimeType) &&
-			content.equals(message.content);
+
+		final OutboundMessage message = (OutboundMessage) obj;
+
+		return device == message.device && messageId.equals(message.messageId)
+				&& contentMimeType.equals(message.contentMimeType)
+				&& content.equals(message.content);
 	}
 }
Modified: trunk/code/CSMiddleware/src/org/commsuite/devices/sms/ReceivePollingJob.java
===================================================================
--- trunk/code/CSMiddleware/src/org/commsuite/devices/sms/ReceivePollingJob.java	2006-09-23 11:37:31 UTC (rev 148)
+++ trunk/code/CSMiddleware/src/org/commsuite/devices/sms/ReceivePollingJob.java	2006-09-23 12:11:16 UTC (rev 149)
@@ -1,10 +1,14 @@
 package org.commsuite.devices.sms;
 
 import java.util.LinkedList;
+import java.util.List;
 
+import javolution.util.FastList;
+
 import org.apache.log4j.Logger;
 import org.commsuite.devices.fax.FaxDevice;
 import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
 import org.quartz.StatefulJob;
 import org.smslib.CIncomingMessage;
 
@@ -16,36 +20,39 @@
  */
 public class ReceivePollingJob implements StatefulJob {
 
-	private static final Logger logger = Logger.getLogger(ReceivePollingJob.class);
+	private static final Logger logger = Logger
+			.getLogger(ReceivePollingJob.class);
 
-    /**
-     * Executes job instance. This checks device buffer for new sms message. For each SMS message SmsDevice is informed about.
-     * 
-     * @see FaxDevice.notifyReceive
-     * @param context job context, contains SmsDevice
-     */
-    public void execute(JobExecutionContext context) {
-//    	logger.info("execute");
-    	
-    	synchronized (SmsDevice.class) {
-    		final SmsDevice smsDevice = (SmsDevice) (context.getJobDetail().getJobDataMap().get("SmsDevice"));
-    		
-			LinkedList messageList;
-			messageList = new LinkedList();
-			
-			SmsService smsService= smsDevice.getSmsService();
-			
+	/**
+	 * Executes job instance. This checks device buffer for new sms message. For
+	 * each SMS message SmsDevice is informed about.
+	 * 
+	 * @see FaxDevice.notifyReceive
+	 * @param context
+	 *            job context, contains SmsDevice
+	 */
+	public void execute(JobExecutionContext context) throws JobExecutionException {
+//		 logger.info("execute");
+
+		final SmsDevice smsDevice = (SmsDevice) context.getJobDetail()
+				.getJobDataMap().get("SmsDevice");
+		List messageList = new LinkedList();
+		SmsService smsService = smsDevice.getSmsService();
+
+		synchronized (SmsDevice.class) {
 			try {
-				smsService.readMessages(messageList, CIncomingMessage.CLASS_ALL);
+				smsService
+						.readMessages(messageList, CIncomingMessage.CLASS_ALL);
 			} catch (Exception e) {
 				logger.error("Error during reading messages", e);
 			}
-			
-			for (int i = 0; i < messageList.size(); i ++) {
-				CIncomingMessage message = (CIncomingMessage) messageList.get(i);
+
+			for (int i = 0; i < messageList.size(); i++) {
+				CIncomingMessage message = (CIncomingMessage) messageList
+						.get(i);
 				smsService.received(message);
 			}
-    	}
-    }
-    
+		}
+	}
+
 }
Modified: trunk/code/CSMiddleware/src/org/commsuite/devices/sms/SmsDevice.java
===================================================================
--- trunk/code/CSMiddleware/src/org/commsuite/devices/sms/SmsDevice.java	2006-09-23 11:37:31 UTC (rev 148)
+++ trunk/code/CSMiddleware/src/org/commsuite/devices/sms/SmsDevice.java	2006-09-23 12:11:16 UTC (rev 149)
@@ -55,477 +55,535 @@
  */
 public final class SmsDevice extends Device {
 
-    private static final Logger logger = Logger.getLogger(SmsDevice.class);
+	private static final Logger logger = Logger.getLogger(SmsDevice.class);
 
-    protected String port;
+	protected String port;
 
-    protected String gsmDeviceManufacturer;
+	protected String gsmDeviceManufacturer;
 
-    protected String gsmDeviceModel;
+	protected String gsmDeviceModel;
 
-    protected int baud;
+	protected int baud;
 
-    protected boolean changeUTFCharacters;
+	protected boolean changeUTFCharacters;
 
-    protected int maxMessageLength;
+	protected int maxMessageLength;
 
-    protected String warningsReceiver;
+	protected String warningsReceiver;
 
-    protected int warningBatteryLevel;
+	protected int warningBatteryLevel;
 
-    protected int warningSignalLevel;
+	protected int warningSignalLevel;
 
-    // 30 minutes by default:
-    protected int warningsInterval = 60 * 30;
+	// 30 minutes by default:
+	protected int warningsInterval = 60 * 30;
 
-    private long lastBatteryWarning;
+	private long lastBatteryWarning;
 
-    private long lastSignalWarning;
+	private long lastSignalWarning;
 
-    private SmsService service;
+	private SmsService service;
 
 	private Scheduler scheduler;
 
-    /**
-     * Creates new SmsDevice.
-     * 
-     * @param name unique name of device
-     */
-    public SmsDevice(String name) {
-        super(name);
-        setState(Device.State.OFF);
-    }
+	/**
+	 * Creates new SmsDevice.
+	 * 
+	 * @param name
+	 *            unique name of device
+	 */
+	public SmsDevice(String name) {
+		super(name);
+		setState(Device.State.OFF);
+	}
 
-    /**
-     * Connects to GSM modem.
-     * 
-     * @throws DeviceInitializationFailedException when connection failed
-     */
-    @Override
-    public void init() throws DeviceInitializationFailedException {
-        setState(Device.State.INITIALIZING);
+	/**
+	 * Connects to GSM modem.
+	 * 
+	 * @throws DeviceInitializationFailedException
+	 *             when connection failed
+	 */
+	@Override
+	public void init() throws DeviceInitializationFailedException {
+		setState(Device.State.INITIALIZING);
 
-        try {
-            synchronized (SmsDevice.class) {
-                service = new SmsService(this, getPort(), getBaud(), getGsmDeviceManufacturer(),
-                        getGsmDeviceModel());
-                logger.info("Using " + CService._name + " " + CService._version);
+		try {
+			synchronized (SmsDevice.class) {
+				service = new SmsService(this, getPort(), getBaud(),
+						getGsmDeviceManufacturer(), getGsmDeviceModel());
+				logger
+						.info("Using " + CService._name + " "
+								+ CService._version);
 
-                // service.setReceiveMode(SmsService.RECEIVE_MODE_ASYNC_POLL);
-                service.setReceiveMode(SmsService.RECEIVE_MODE_SYNC);
+				// service.setReceiveMode(SmsService.RECEIVE_MODE_ASYNC_POLL);
+				service.setReceiveMode(SmsService.RECEIVE_MODE_SYNC);
 
-                service.setSimPin("");
-                service.connect();
+				service.setSimPin("");
+				service.connect();
 
-                logger.debug("IsConnected: " + service.getConnected());
+				logger.debug("IsConnected: " + service.getConnected());
 
-                if (service.getConnected()) {
-                    setState(Device.State.ON);
+				if (service.getConnected()) {
+					setState(Device.State.ON);
 
-                    service.setSmscNumber("");
-                    service.refreshDeviceInfo();
+					service.setSmscNumber("");
+					service.refreshDeviceInfo();
 
-                    // Print out GSM device info...
-                    if (logger.isInfoEnabled()) {
-                        logger.info("Mobile Device Information: ");
-                        logger.info("Manufacturer : " + service.getDeviceInfo().getManufacturer());
-                        logger.info("Model : " + service.getDeviceInfo().getModel());
-                        logger.info("Serial No : " + service.getDeviceInfo().getSerialNo());
-                        logger.info("IMSI : " + service.getDeviceInfo().getImsi());
-                        logger.info("S/W Version : " + service.getDeviceInfo().getSwVersion());
-                        logger.info("Battery Level : " + service.getDeviceInfo().getBatteryLevel()
-                                + "%");
-                        logger.info("Signal Level : " + service.getDeviceInfo().getSignalLevel()
-                                + "%");
-                    }
-                } else {
-                    setState(Device.State.OFF);
-                }
-            }
-        } catch (Throwable t) {
-            logger.error("", t);
+					// Print out GSM device info...
+					if (logger.isInfoEnabled()) {
+						logger.info("Mobile Device Information: ");
+						logger.info("Manufacturer : "
+								+ service.getDeviceInfo().getManufacturer());
+						logger.info("Model : "
+								+ service.getDeviceInfo().getModel());
+						logger.info("Serial No : "
+								+ service.getDeviceInfo().getSerialNo());
+						logger.info("IMSI : "
+								+ service.getDeviceInfo().getImsi());
+						logger.info("S/W Version : "
+								+ service.getDeviceInfo().getSwVersion());
+						logger.info("Battery Level : "
+								+ service.getDeviceInfo().getBatteryLevel()
+								+ "%");
+						logger.info("Signal Level : "
+								+ service.getDeviceInfo().getSignalLevel()
+								+ "%");
+					}
+				} else {
+					setState(Device.State.OFF);
+				}
+			}
+		} catch (Throwable t) {
+			logger.error("", t);
 
-            setState(Device.State.OFF);
-            throw new DeviceInitializationFailedException(t);
-        }
-        
-        initNotification();
-    }
+			setState(Device.State.OFF);
+			throw new DeviceInitializationFailedException(t);
+		}
 
+		initNotification();
+	}
 
-    /**
-     * Disconnects from GSM modem.
-     * 
-     * @throws DeviceShutdownFailedException when disconnection failed
-     */
-    @Override
-    public void shutdown() throws DeviceShutdownFailedException {
-        try {
-        	shutdownNotification();
-        	
-            // TODO: kod bezpiecznie zamykający urządzenie
-            service.disconnect();
+	/**
+	 * Disconnects from GSM modem.
+	 * 
+	 * @throws DeviceShutdownFailedException
+	 *             when disconnection failed
+	 */
+	@Override
+	public void shutdown() throws DeviceShutdownFailedException {
+		try {
+			shutdownNotification();
 
-            setState(Device.State.OFF);
-        } catch (Throwable t) {
-            logger.error("", t);
-            setState(Device.State.OFF);
-            throw new DeviceShutdownFailedException(t);
-        }
-    }
+			// TODO: kod bezpiecznie zamykający urządzenie
+			service.disconnect();
 
-    public String getGsmDeviceManufacturer() {
-        return gsmDeviceManufacturer;
-    }
+			setState(Device.State.OFF);
+		} catch (Throwable t) {
+			logger.error("", t);
+			setState(Device.State.OFF);
+			throw new DeviceShutdownFailedException(t);
+		}
+	}
 
-    public void setGsmDeviceManufacturer(String gsmDeviceManufacturer) {
-        this.gsmDeviceManufacturer = gsmDeviceManufacturer;
-    }
+	public String getGsmDeviceManufacturer() {
+		return gsmDeviceManufacturer;
+	}
 
-    public String getGsmDeviceModel() {
-        return gsmDeviceModel;
-    }
+	public void setGsmDeviceManufacturer(String gsmDeviceManufacturer) {
+		this.gsmDeviceManufacturer = gsmDeviceManufacturer;
+	}
 
-    public void setGsmDeviceModel(String gsmDeviceModel) {
-        this.gsmDeviceModel = gsmDeviceModel;
-    }
+	public String getGsmDeviceModel() {
+		return gsmDeviceModel;
+	}
 
-    public String getPort() {
-        return port;
-    }
+	public void setGsmDeviceModel(String gsmDeviceModel) {
+		this.gsmDeviceModel = gsmDeviceModel;
+	}
 
-    public void setPort(String port) {
-        this.port = port;
-    }
+	public String getPort() {
+		return port;
+	}
 
-    public int getBaud() {
-        return baud;
-    }
+	public void setPort(String port) {
+		this.port = port;
+	}
 
-    public void setBaud(int baud) {
-        this.baud = baud;
-    }
+	public int getBaud() {
+		return baud;
+	}
 
-    public void setChangeUTFCharacters(boolean changeUTFCharacters) {
-        this.changeUTFCharacters = changeUTFCharacters;
-    }
+	public void setBaud(int baud) {
+		this.baud = baud;
+	}
 
-    public boolean getChangeUTFCharacters() {
-        return changeUTFCharacters;
-    }
+	public void setChangeUTFCharacters(boolean changeUTFCharacters) {
+		this.changeUTFCharacters = changeUTFCharacters;
+	}
 
-    public void setMaxMessageLength(int maxMessageLength) {
-        this.maxMessageLength = maxMessageLength;
-    }
+	public boolean getChangeUTFCharacters() {
+		return changeUTFCharacters;
+	}
 
-    public int getMaxMessageLenght() {
-        return maxMessageLength;
-    }
+	public void setMaxMessageLength(int maxMessageLength) {
+		this.maxMessageLength = maxMessageLength;
+	}
 
-    public void setWarningsReceiver(String warningsReciever) {
-        this.warningsReceiver = warningsReciever;
-    }
+	public int getMaxMessageLenght() {
+		return maxMessageLength;
+	}
 
-    public String getWarningsReceiver() {
-        return warningsReceiver;
-    }
+	public void setWarningsReceiver(String warningsReciever) {
+		this.warningsReceiver = warningsReciever;
+	}
 
-    public void setWarningBatteryLevel(int warningBatteryLevel) {
-        this.warningBatteryLevel = warningBatteryLevel;
-    }
+	public String getWarningsReceiver() {
+		return warningsReceiver;
+	}
 
-    public int getWarningBatteryLevel() {
-        return warningBatteryLevel;
-    }
+	public void setWarningBatteryLevel(int warningBatteryLevel) {
+		this.warningBatteryLevel = warningBatteryLevel;
+	}
 
-    public void setWarningSignalLevel(int warningSignalLevel) {
-        this.warningSignalLevel = warningSignalLevel;
-    }
+	public int getWarningBatteryLevel() {
+		return warningBatteryLevel;
+	}
 
-    public int getWarningSignalLevel() {
-        return warningSignalLevel;
-    }
+	public void setWarningSignalLevel(int warningSignalLevel) {
+		this.warningSignalLevel = warningSignalLevel;
+	}
 
-    /**
-     * Set interval in seconds.
-     * 
-     * By default 30 minutes.
-     * 
-     * @int warningsInterval warnings interval in seconds
-     */
-    public void setWarningsInterval(int warningsInterval) {
-        this.warningsInterval = warningsInterval;
-    }
+	public int getWarningSignalLevel() {
+		return warningSignalLevel;
+	}
 
-    /**
-     * Get interval in seconds.
-     * 
-     * @return warnings interval in seconds
-     */
-    public int getWarningsInterval() {
-        return warningsInterval;
-    }
+	/**
+	 * Set interval in seconds.
+	 * 
+	 * By default 30 minutes.
+	 * 
+	 * @int warningsInterval warnings interval in seconds
+	 */
+	public void setWarningsInterval(int warningsInterval) {
+		this.warningsInterval = warningsInterval;
+	}
 
-    /**
-     * Creates new message that can be sent using this device.
-     * 
-     * @return new message that can be sent using this device
-     */
-    @Override
-    public OutboundMessage createOutboundMessage() {
-        return new SmsOutboundMessage(this);
-    }
+	/**
+	 * Get interval in seconds.
+	 * 
+	 * @return warnings interval in seconds
+	 */
+	public int getWarningsInterval() {
+		return warningsInterval;
+	}
 
-    /**
-     * Sends message throught GSM modem. Message can only have plain/text data.
-     * 
-     * @throws DeviceInvalidOutboundMessageException message was created on another device
-     * @throws OutboundMessageInvalidContentMimeTypeException message does not have text/plain data
-     * @throws OutboundMessageInvalidContentException message is too long
-     * @throws OutboundMessageSendException an error occured
-     */
-    @Override
-    public void send(OutboundMessage message) throws DeviceInvalidOutboundMessageException,
-            OutboundMessageInvalidContentMimeTypeException, OutboundMessageInvalidContentException,
-            OutboundMessageInvalidDestinationAddressException, OutboundMessageSendException,
-            OutboundMessageConversionFailedException {
-        if (!(message instanceof SmsOutboundMessage)) {
-            throw new DeviceInvalidOutboundMessageException(
-                    "SmsDevice can handle only SmsOutboundMessage");
-        }
+	/**
+	 * Creates new message that can be sent using this device.
+	 * 
+	 * @return new message that can be sent using this device
+	 */
+	@Override
+	public OutboundMessage createOutboundMessage() {
+		return new SmsOutboundMessage(this);
+	}
 
-        if (message.getDevice() != this) {
-            throw new DeviceInvalidOutboundMessageException(
-                    "SmsDevice can handle only SmsOutboundMessage that it created");
-        }
+	/**
+	 * Sends message throught GSM modem. Message can only have plain/text data.
+	 * 
+	 * @throws DeviceInvalidOutboundMessageException
+	 *             message was created on another device
+	 * @throws OutboundMessageInvalidContentMimeTypeException
+	 *             message does not have text/plain data
+	 * @throws OutboundMessageInvalidContentException
+	 *             message is too long
+	 * @throws OutboundMessageSendException
+	 *             an error occured
+	 */
+	@Override
+	public void send(OutboundMessage message)
+			throws DeviceInvalidOutboundMessageException,
+			OutboundMessageInvalidContentMimeTypeException,
+			OutboundMessageInvalidContentException,
+			OutboundMessageInvalidDestinationAddressException,
+			OutboundMessageSendException,
+			OutboundMessageConversionFailedException {
+		if (!(message instanceof SmsOutboundMessage)) {
+			throw new DeviceInvalidOutboundMessageException(
+					"SmsDevice can handle only SmsOutboundMessage");
+		}
 
-        final byte[] data = message.getContent();
-        String text;
-        try {
-            text = new String(data, "UTF-8");
-        } catch (UnsupportedEncodingException e) {
-            logger.warn("Exception during internally converting SMS into String", e);
-            // default charset:
-            text = new String(data);
-        }
+		if (message.getDevice() != this) {
+			throw new DeviceInvalidOutboundMessageException(
+					"SmsDevice can handle only SmsOutboundMessage that it created");
+		}
 
-        if (text.length() > maxMessageLength) {
-            throw new OutboundMessageInvalidContentException(
-                    "SMS message is too long, cannot be sent");
-        }
+		final byte[] data = message.getContent();
+		String text;
+		try {
+			text = new String(data, "UTF-8");
+		} catch (UnsupportedEncodingException e) {
+			logger
+					.warn(
+							"Exception during internally converting SMS into String",
+							e);
+			// default charset:
+			text = new String(data);
+		}
 
-        try {
-            if (changeUTFCharacters) {
-                text = removeUTFCharacters(text);
-            }
-        } catch (UnsupportedEncodingException e) {
-            logger.fatal("", e);
-        }
+		if (text.length() > maxMessageLength) {
+			throw new OutboundMessageInvalidContentException(
+					"SMS message is too long, cannot be sent");
+		}
 
-        final int batteryCurrentLevel = service.getDeviceInfo().getBatteryLevel();
-        if (batteryCurrentLevel < warningBatteryLevel) {
-            final Date now = new Date();
-            final long seconds = now.getTime() / 1000L;
+		try {
+			if (changeUTFCharacters) {
+				text = removeUTFCharacters(text);
+			}
+		} catch (UnsupportedEncodingException e) {
+			logger.fatal("", e);
+		}
 
-            if (seconds - lastBatteryWarning >= warningsInterval) {
-                final TextBuilder tb = new TextBuilder();
-                tb.append("CS: Battery level ").append(batteryCurrentLevel).append(
-                        "% is lower than ").append(warningBatteryLevel).append("%");
-                final String warningMsg = tb.toString();
+		final int batteryCurrentLevel = service.getDeviceInfo()
+				.getBatteryLevel();
+		if (batteryCurrentLevel < warningBatteryLevel) {
+			final Date now = new Date();
+			final long seconds = now.getTime() / 1000L;
 
-                logger.warn(warningMsg);
+			if (seconds - lastBatteryWarning >= warningsInterval) {
+				final TextBuilder tb = new TextBuilder();
+				tb.append("CS: Battery level ").append(batteryCurrentLevel)
+						.append("% is lower than ").append(warningBatteryLevel)
+						.append("%");
+				final String warningMsg = tb.toString();
 
-                if (null != warningsReceiver && !"".equals(warningsReceiver)) {
-                    sendSMSMessage(warningMsg, warningsReceiver);
-                }
-            }
+				logger.warn(warningMsg);
 
-            lastBatteryWarning = seconds;
-        }
+				if (null != warningsReceiver && !"".equals(warningsReceiver)) {
+					sendSMSMessage(warningMsg, warningsReceiver);
+				}
+			}
 
-        final int signalCurrentLevel = service.getDeviceInfo().getSignalLevel();
-        if (signalCurrentLevel < warningSignalLevel) {
-            final Date now = new Date();
-            final long seconds = now.getTime() / 1000L;
+			lastBatteryWarning = seconds;
+		}
 
-            if (seconds - lastSignalWarning >= warningsInterval) {
-                final TextBuilder tb = new TextBuilder();
-                tb.append("CS: Signal level ").append(signalCurrentLevel)
-                        .append("% is lower than ").append(warningSignalLevel).append("%");
-                final String warningMsg = tb.toString();
+		final int signalCurrentLevel = service.getDeviceInfo().getSignalLevel();
+		if (signalCurrentLevel < warningSignalLevel) {
+			final Date now = new Date();
+			final long seconds = now.getTime() / 1000L;
 
-                logger.warn(warningMsg);
+			if (seconds - lastSignalWarning >= warningsInterval) {
+				final TextBuilder tb = new TextBuilder();
+				tb.append("CS: Signal level ").append(signalCurrentLevel)
+						.append("% is lower than ").append(warningSignalLevel)
+						.append("%");
+				final String warningMsg = tb.toString();
 
-                if (null != warningsReceiver && !"".equals(warningsReceiver)) {
-                    sendSMSMessage(warningMsg, warningsReceiver);
-                }
-            }
+				logger.warn(warningMsg);
 
-            lastSignalWarning = seconds;
-        }
+				if (null != warningsReceiver && !"".equals(warningsReceiver)) {
+					sendSMSMessage(warningMsg, warningsReceiver);
+				}
+			}
 
-        final String messageId = sendSMSMessage(text, message.getDestinationAddress());
+			lastSignalWarning = seconds;
+		}
 
-        if (null != messageId) {
-            message.setMessageId(messageId);
-        } else {
-            logger.fatal("SMS messageId obtained during sending process is null");
-            throw new OutboundMessageSendException(
-                    "Error during sending SMS: SMS messageId obtained during sending process is null");
-        }
-    }
+		final String messageId = sendSMSMessage(text, message
+				.getDestinationAddress());
 
-    /**
-     * Removes polish UTF character and replaces it with latin1 characters.
-     * 
-     * @param text string with UTF characters
-     * @return text without UTF characters
-     * 
-     * @throws UnsupportedEncodingException never
-     */
-    private static String removeUTFCharacters(String text) throws UnsupportedEncodingException {
-        logger.debug("Converting :" + text);
+		if (null != messageId) {
+			message.setMessageId(messageId);
+		} else {
+			logger
+					.fatal("SMS messageId obtained during sending process is null");
+			throw new OutboundMessageSendException(
+					"Error during sending SMS: SMS messageId obtained during sending process is null");
+		}
+	}
 
-        // TODO: [RM] przemyslec i zaproponowac rozwiazanie ogolne dla takiej konwersji, dla znakow
-        // diakrytycznych rowniez innych jezykow. Byc moze istnieja do tego jakies biblioteki.
-        final String result = text.replace('\u0105', 'a').replace('\u0104', 'A').replace('\u0107',
-                'c').replace('\u0105', 'C').replace('\u0119', 'e').replace('\u0118', 'E').replace(
-                '\u0142', 'l').replace('\u0141', 'L').replace('\u0144', 'n').replace('\u0143', 'N')
-                .replace('\u00f3', 'o').replace('\u00d3', 'O').replace('\u015b', 's').replace(
-                        '\u015a', 'S').replace('\u017a', 'z').replace('\u0179', 'Z').replace(
-                        '\u017c', 'z').replace('\u017b', 'z');
+	/**
+	 * Removes polish UTF character and replaces it with latin1 characters.
+	 * 
+	 * @param text
+	 *            string with UTF characters
+	 * @return text without UTF characters
+	 * 
+	 * @throws UnsupportedEncodingException
+	 *             never
+	 */
+	private String removeUTFCharacters(String text)
+			throws UnsupportedEncodingException {
+		logger.debug("Converting from: " + text);
 
-        logger.debug("Converted to :" + result);
+		// TODO: [RM] przemyslec i zaproponowac rozwiazanie ogolne dla takiej
+		// konwersji, dla znakow
+		// diakrytycznych rowniez innych jezykow. Byc moze istnieja do tego
+		// jakies biblioteki.
+		final String result = text.replace('\u0105', 'a')
+				.replace('\u0104', 'A').replace('\u0107', 'c').replace(
+						'\u0105', 'C').replace('\u0119', 'e').replace('\u0118',
+						'E').replace('\u0142', 'l').replace('\u0141', 'L')
+				.replace('\u0144', 'n').replace('\u0143', 'N').replace(
+						'\u00f3', 'o').replace('\u00d3', 'O').replace('\u015b',
+						's').replace('\u015a', 'S').replace('\u017a', 'z')
+				.replace('\u0179', 'Z').replace('\u017c', 'z').replace(
+						'\u017b', 'z');
 
-        return result;
-    }
+		logger.debug("Converted to: " + result);
 
-    /**
-     * Send SMS message.
-     * 
-     * @param text sms message to send
-     * @param phone phone address of receiver
-     * @return unique message-id of sent SMS
-     * 
-     * @throws OutboundMessageSendException when sms device failed to send message
-     */
-    private String sendSMSMessage(String text, String phone) throws OutboundMessageSendException {
+		return result;
+	}
 
-        // REFACTOR: Kod laczacy sie z modemem GSM i incujacy polaczenia
-        // nalezy przeniesc do metody #init(), a tutaj jedynie weryfikowac czy polaczenie
-        // jest nadal aktywne. Jesli nie jest aktywne to np. sprobowac 2 razy je ponownie
-        // zainicjowac - jesli sie nie uda to zrobic tak by ten SmsDevice byl nieaktywny i wrzucic
-        // stosowny fatal do logow.
+	/**
+	 * Send SMS message.
+	 * 
+	 * @param text
+	 *            sms message to send
+	 * @param phone
+	 *            phone address of receiver
+	 * @return unique message-id of sent SMS
+	 * 
+	 * @throws OutboundMessageSendException
+	 *             when sms device failed to send message
+	 */
+	private String sendSMSMessage(String text, String phone)
+			throws OutboundMessageSendException {
 
-        int messageId;
+		// REFACTOR: Kod laczacy sie z modemem GSM i incujacy polaczenia
+		// nalezy przeniesc do metody #init(), a tutaj jedynie weryfikowac czy
+		// polaczenie
+		// jest nadal aktywne. Jesli nie jest aktywne to np. sprobowac 2 razy je
+		// ponownie
+		// zainicjowac - jesli sie nie uda to zrobic tak by ten SmsDevice byl
+		// nieaktywny i wrzucic
+		// stosowny fatal do logow.
 
-        if (logger.isDebugEnabled()) {
-            logger.debug("Sending message to: " + phone);
-            logger.debug("Message text to send: " + text);
-        }
+		int messageId;
 
-        if (phone.startsWith("+")) {
-            phone = phone.substring(1);
-        }
+		if (logger.isDebugEnabled()) {
+			logger.debug("Sending message to: " + phone);
+			logger.debug("Message text to send: " + text);
+		}
 
-        // Create a COutgoingMessage object.
-        final COutgoingMessage msg = new COutgoingMessage(phone, text);
+		if (phone.startsWith("+")) {
+			phone = phone.substring(1);
+		}
 
-        // Character set is 7bit by default.
-        msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_7BIT);
+		// Create a COutgoingMessage object.
+		final COutgoingMessage msg = new COutgoingMessage(phone, text);
 
-        // TODO: We are interested in status reports, so we should switch below
-        // option to 'true' state in next version of this software
-        // TODO: When message is sending we should check if in database are messages with internalId
-        // equal to uniqueId of message
-        // If they exists, we should set insternalId's of them to internalId + ':' + GUID
-        // So we will have unique internalId, and we will get status reports properly.
-        // internalId conists of refNr and destinationAddress of SMS
-        msg.setStatusReport(true);
-        msg.setFlashSms(false);
-        msg.setDate(new Date()); // current time
+		// Character set is 7bit by default.
+		msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_7BIT);
 
-        // REVIEW: [RM] czy to jest poprawne miejsce do synchronizacji ? Byc moze mogli bysmy
-        // mniejsza czesc procesu wysylania SMSa zsynchronizowac, np. dopiero od wywolania metody:
-        // srv.connect() ?
+		// TODO: We are interested in status reports, so we should switch below
+		// option to 'true' state in next version of this software
+		// TODO: When message is sending we should check if in database are
+		// messages with internalId
+		// equal to uniqueId of message.
+		// If they exists, we should set insternalId's of them to internalId +
+		// ':' + GUID
+		// So we will have unique internalId, and we will get status reports
+		// properly.
+		// internalId conists of refNr and destinationAddress of SMS
+		msg.setStatusReport(true);
+		msg.setFlashSms(false);
+		msg.setDate(new Date()); // current time
 
-        // NOTE: We assume that there might be more than one object of type {@link SmsDevice}
-        // therefore we are synchronizing by class and not by object of this class.
-        synchronized (SmsDevice.class) {
-            try {
-                if (!service.getConnected()) {
-                    init(); // reconnect
-                }
+		// REVIEW: [RM] czy to jest poprawne miejsce do synchronizacji ? Byc
+		// moze mogli bysmy
+		// mniejsza czesc procesu wysylania SMSa zsynchronizowac, np. dopiero od
+		// wywolania metody:
+		// srv.connect() ?
 
-                if (!service.getConnected()) {
-                    throw new OutboundMessageSendException("Cannot connect to SmsDevie");
-                }
+		// NOTE: We assume that there might be more than one object of type
+		// {@link SmsDevice}
+		// therefore we are synchronizing by class and not by object of this
+		// class.
+		synchronized (SmsDevice.class) {
+			try {
+				if (!service.getConnected()) {
+					init(); // reconnect
+				}
 
-                service.sendMessage(msg);
+				if (!service.getConnected()) {
+					throw new OutboundMessageSendException(
+							"Cannot connect to SmsDevie");
+				}
 
-                // {@link COutgoingMessage#getRefNo()} returns the Reference Number of the
-                // message. The Reference Number is returned from the SMSC upon succesful
-                // dispatch of a message:
-                messageId = msg.getRefNo();
-            } catch (Throwable t1) {
-                logger.fatal("Exception during sending SMS", t1);
-                throw new OutboundMessageSendException("Cannot connect to SmsDevie", t1);
-            }
-        }
+				service.sendMessage(msg);
 
-        if (logger.isDebugEnabled()) {
-            logger.debug("messageId is: " + Integer.toString(messageId) + "@" + phone);
-        }
-        
-        // TODO: [RM] make it more unique:
-        if (messageId == -1) {
-        	return null;
-        }
-        else {
-        	return Integer.toString(messageId) + "@" + phone;
-        }
-    }
+				// {@link COutgoingMessage#getRefNo()} returns the Reference
+				// Number of the
+				// message. The Reference Number is returned from the SMSC upon
+				// succesful
+				// dispatch of a message:
+				messageId = msg.getRefNo();
+			} catch (Throwable t1) {
+				logger.fatal("Exception during sending SMS", t1);
+				throw new OutboundMessageSendException(
+						"Cannot connect to SmsDevie", t1);
+			}
+		}
 
-    /**
-     * Returns FormatType.SMS.
-     * 
-     * @return FormatType.SMS
-     */
-    @Override
-    public FormatType getFormatType() {
-        return FormatType.SMS;
-    }
-	
+		if (logger.isDebugEnabled()) {
+			logger.debug("messageId is: " + Integer.toString(messageId) + "@"
+					+ phone);
+		}
+
+		// TODO: [RM] make it more unique:
+		if (messageId == -1) {
+			return null;
+		} else {
+			return Integer.toString(messageId) + "@" + phone;
+		}
+	}
+
 	/**
+	 * Returns FormatType.SMS.
+	 * 
+	 * @return FormatType.SMS
+	 */
+	@Override
+	public FormatType getFormatType() {
+		return FormatType.SMS;
+	}
+
+	/**
 	 * Starts Quartz jobs to poll receive smses.
 	 * 
-	 * @throws DeviceInitializationFailedException when quarts fails
+	 * @throws DeviceInitializationFailedException
+	 *             when quarts fails
 	 */
-	protected void initNotification() throws DeviceInitializationFailedException {
-		final SchedulerFactory shedulerFactory = new org.quartz.impl.StdSchedulerFactory();  
-		final JobDetail receivePollingJobDetail = new JobDetail(getName() + "_receivePollingJobDetail", null, ReceivePollingJob.class);
+	protected void initNotification()
+			throws DeviceInitializationFailedException {
+		final SchedulerFactory shedulerFactory = new org.quartz.impl.StdSchedulerFactory();
+		final JobDetail receivePollingJobDetail = new JobDetail(getName()
+				+ "_receivePollingJobDetail", null, ReceivePollingJob.class);
 		receivePollingJobDetail.getJobDataMap().put("SmsDevice", this);
-		
+
 		final Date plus2Seconds = new Date();
 		plus2Seconds.setTime(plus2Seconds.getTime() + 2500);
-        
+
 		// fire every 5 seconds
-		final SimpleTrigger receivePollingTrigger = new SimpleTrigger(getName() + "_receivePollingTrigger", null,
-				new Date(), null, SimpleTrigger.REPEAT_INDEFINITELY, 5000);
-		
+		final SimpleTrigger receivePollingTrigger = new SimpleTrigger(getName()
+				+ "_receivePollingTrigger", null, new Date(), null,
+				SimpleTrigger.REPEAT_INDEFINITELY, 5000);
+
 		try {
 			scheduler = shedulerFactory.getScheduler();
 			scheduler.start();
-			scheduler.scheduleJob(receivePollingJobDetail, receivePollingTrigger);
+			scheduler.scheduleJob(receivePollingJobDetail,
+					receivePollingTrigger);
 		} catch (SchedulerException e) {
 			throw new DeviceInitializationFailedException(e);
 		}
 	}
-	
+
 	/**
 	 * Stops Quartz jobs to poll receive smses.
 	 * 
-	 * @throws DeviceInitializationFailedException when quarts fails
+	 * @throws DeviceInitializationFailedException
+	 *             when quarts fails
 	 */
 	protected void shutdownNotification() throws DeviceShutdownFailedException {
 		try {
@@ -536,7 +594,7 @@
 			scheduler = null;
 		}
 	}
-	
+
 	public SmsService getSmsService() {
 		return service;
 	}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
 |