/*
Реализация спецификаций CLDC версии 1.1 (JSR-139), MIDP версии 2.1 (JSR-118)
и других спецификаций для функционирования компактных приложений на языке
Java (мидлетов) в среде программного обеспечения Малик Эмулятор.
Copyright © 2016–2017, 2019–2023, 2025 Малик Разработчик
Это свободная программа: вы можете перераспространять ее и/или изменять
ее на условиях Меньшей Стандартной общественной лицензии GNU в том виде,
в каком она была опубликована Фондом свободного программного обеспечения;
либо версии 3 лицензии, либо (по вашему выбору) любой более поздней версии.
Эта программа распространяется в надежде, что она будет полезной,
но БЕЗО ВСЯКИХ ГАРАНТИЙ; даже без неявной гарантии ТОВАРНОГО ВИДА
или ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННЫХ ЦЕЛЕЙ. Подробнее см. в Меньшей Стандартной
общественной лицензии GNU.
Вы должны были получить копию Меньшей Стандартной общественной лицензии GNU
вместе с этой программой. Если это не так, см.
<https://www.gnu.org/licenses/>.
*/
package malik.emulator.microedition.system.protocol.sms;
import java.io.*;
import javax.wireless.messaging.*;
import malik.emulator.microedition.io.*;
import malik.emulator.microedition.system.protocol.*;
import malik.emulator.util.*;
public class ServerMessageConnection extends ClientMessageConnection implements InboundConnection
{
private final int localPort;
private MessageListener listener;
private final ObjectQueue inboundMessages;
public ServerMessageConnection(String localAddress, int localPort) {
super(localAddress);
this.localPort = localPort;
this.inboundMessages = new ObjectQueue();
InboundConnections.instance.registerInboundConnection(InboundConnections.UDP, localPort, this);
}
public void setMessageListener(MessageListener listener) throws IOException {
if(isConnectionClosed())
{
throw new ConnectionClosedException("MessageConnection.setMessageListener: соединение закрыто.");
}
this.listener = listener;
}
public Message receive() throws IOException {
int error;
Message result;
ObjectQueue queue;
if(isConnectionClosed())
{
throw new ConnectionClosedException("MessageConnection.receive: соединение закрыто.");
}
error = 0;
synchronized(queue = inboundMessages)
{
for(; ; )
{
if(!queue.isEmpty())
{
result = (Message) queue.peekHeadObject();
((Queue) queue).removeHeadElement();
break;
}
if(isConnectionClosed())
{
error = 1;
result = null;
break;
}
try
{
queue.wait();
}
catch(InterruptedException e)
{
e.printRealStackTrace();
}
}
}
if(error == 1)
{
throw new InterruptedIOException("MessageConnection.receive: соединение закрыто.");
}
return result;
}
public Message newMessage(String type) {
if(BINARY_MESSAGE.equals(type)) return new BinaryShortMessage(this, false, super.getURL(), null, ShortMessage.EMPTY_TIMESTAMP, null);
if(TEXT_MESSAGE.equals(type)) return new TextShortMessage(this, false, super.getURL(), null, ShortMessage.EMPTY_TIMESTAMP, null);
throw new IllegalArgumentException("MessageConnection.newMessage: аргумент type имеет недопустимое значение.");
}
public Message newMessage(String type, String address) {
if(BINARY_MESSAGE.equals(type)) return new BinaryShortMessage(this, false, super.getURL(), address, ShortMessage.EMPTY_TIMESTAMP, null);
if(TEXT_MESSAGE.equals(type)) return new TextShortMessage(this, false, super.getURL(), address, ShortMessage.EMPTY_TIMESTAMP, null);
throw new IllegalArgumentException("MessageConnection.newMessage: аргумент type имеет недопустимое значение.");
}
public void receiveData(Object data) {
if(data instanceof Message)
{
ObjectQueue queue;
MessageListener listener;
synchronized(queue = inboundMessages)
{
queue.addTailElement(data);
queue.notifyAll();
}
if((listener = this.listener) != null) listener.notifyIncomingMessage(this);
}
}
protected void closeConnection() throws IOException {
Object monitor;
synchronized(monitor = inboundMessages)
{
monitor.notifyAll();
}
listener = null;
InboundConnections.instance.unregisterInboundConnection(InboundConnections.UDP, localPort);
}
}