Search in sources :

Example 1 with MmqException

use of org.monkey.mmq.core.exception.MmqException in project mmqtt by MrHKing.

the class BrokerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object obj) {
    MqttMessage msg = (MqttMessage) obj;
    // Do something with msg
    try {
        if (msg == null) {
            Loggers.BROKER_SERVER.error("解码错误");
            return;
        }
        // 消息解码器出现异常
        if (msg.decoderResult().isFailure()) {
            Throwable cause = msg.decoderResult().cause();
            Loggers.BROKER_SERVER.error(cause.getMessage());
            if (cause instanceof MqttUnacceptableProtocolVersionException) {
                // 不支持的协议版本
                MqttConnAckMessage connAckMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION, false), null);
                ctx.writeAndFlush(connAckMessage);
                ctx.close();
                return;
            } else if (cause instanceof MqttIdentifierRejectedException) {
                // 不合格的clientId
                MqttConnAckMessage connAckMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null);
                ctx.writeAndFlush(connAckMessage);
                ctx.close();
                return;
            }
            ctx.close();
            return;
        }
        switch(msg.fixedHeader().messageType()) {
            case CONNECT:
                // protocolProcess.getConnectExecutor().submit(() -> {
                try {
                    protocolProcess.connect().processConnect(ctx.channel(), (MqttConnectMessage) msg);
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                    SystemMessage systemMessage = new SystemMessage();
                    systemMessage.setTopic(MODULES);
                    systemMessage.setPayload(e.getMessage());
                    systemMessage.setMqttQoS(MqttQoS.AT_LEAST_ONCE);
                    ActorSelection actorRef = actorSystem.actorSelection("/user/" + ((MqttConnectMessage) msg).payload().clientIdentifier());
                    actorRef.tell(systemMessage, ActorRef.noSender());
                    // 此处对断网进行了处理
                    ctx.channel().close();
                }
                // });
                break;
            case CONNACK:
                break;
            case PUBLISH:
                // protocolProcess.getPubExecutor().submit(() -> {
                try {
                    protocolProcess.publish().processPublish(ctx.channel(), (MqttPublishMessage) msg);
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                }
                // });
                break;
            case PUBACK:
                // protocolProcess.getPubExecutor().submit(() -> {
                try {
                    protocolProcess.pubAck().processPubAck(ctx.channel(), (MqttMessageIdVariableHeader) msg.variableHeader());
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                }
                // });
                break;
            case PUBREC:
                // protocolProcess.getSubExecutor().submit(() -> {
                try {
                    protocolProcess.pubRec().processPubRec(ctx.channel(), (MqttMessageIdVariableHeader) msg.variableHeader());
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                }
                break;
            case PUBREL:
                // protocolProcess.getPubExecutor().submit(() -> {
                protocolProcess.pubRel().processPubRel(ctx.channel(), (MqttMessageIdVariableHeader) msg.variableHeader());
                // });
                break;
            case PUBCOMP:
                // protocolProcess.getSubExecutor().submit(() -> {
                try {
                    protocolProcess.pubComp().processPubComp(ctx.channel(), (MqttMessageIdVariableHeader) msg.variableHeader());
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                }
                // });
                break;
            case SUBSCRIBE:
                // protocolProcess.getSubExecutor().submit(() -> {
                protocolProcess.subscribe().processSubscribe(ctx.channel(), (MqttSubscribeMessage) msg);
                // });
                break;
            case SUBACK:
                break;
            case UNSUBSCRIBE:
                // protocolProcess.getSubExecutor().submit(() -> {
                protocolProcess.unSubscribe().processUnSubscribe(ctx.channel(), (MqttUnsubscribeMessage) msg);
                // });
                break;
            case UNSUBACK:
                break;
            case PINGREQ:
                // protocolProcess.getPingExecutor().submit(() -> {
                protocolProcess.pingReq().processPingReq(ctx.channel(), msg);
                // });
                break;
            case PINGRESP:
                break;
            case DISCONNECT:
                // protocolProcess.getConnectExecutor().submit(() -> {
                try {
                    protocolProcess.disConnect().processDisConnect(ctx.channel(), msg);
                } catch (MmqException e) {
                    Loggers.BROKER_SERVER.error(e.getErrMsg());
                }
                // });
                break;
            default:
                break;
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : SystemMessage(org.monkey.mmq.core.actor.message.SystemMessage) ActorSelection(akka.actor.ActorSelection) MmqException(org.monkey.mmq.core.exception.MmqException)

Example 2 with MmqException

use of org.monkey.mmq.core.exception.MmqException in project mmqtt by MrHKing.

the class Subscribe method processSubscribe.

public void processSubscribe(Channel channel, MqttSubscribeMessage msg) {
    List<MqttTopicSubscription> topicSubscriptions = msg.payload().topicSubscriptions();
    if (this.validTopicFilter(topicSubscriptions)) {
        String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
        List<Integer> mqttQoSList = new ArrayList<Integer>();
        topicSubscriptions.forEach(topicSubscription -> {
            String topicFilter = topicSubscription.topicName();
            MqttQoS mqttQoS = topicSubscription.qualityOfService();
            SubscribeMateData subscribeStore = new SubscribeMateData(clientId, topicFilter, mqttQoS.value());
            try {
                subscribeStoreService.put(topicFilter, subscribeStore);
            } catch (MmqException e) {
                LoggerUtils.printIfDebugEnabled(Loggers.BROKER_PROTOCOL, "Subscribe - clientId: {}, subscribe: {}", channel.attr(AttributeKey.valueOf("clientId")).get(), topicFilter);
            }
            mqttQoSList.add(mqttQoS.value());
            LoggerUtils.printIfDebugEnabled(Loggers.BROKER_PROTOCOL, "SUBSCRIBE - clientId: {}, topFilter: {}, QoS: {}", clientId, topicFilter, mqttQoS.value());
        });
        MqttSubAckMessage subAckMessage = (MqttSubAckMessage) MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(msg.variableHeader().messageId()), new MqttSubAckPayload(mqttQoSList));
        channel.writeAndFlush(subAckMessage);
        // 发布保留消息
        topicSubscriptions.forEach(topicSubscription -> {
            String topicFilter = topicSubscription.topicName();
            MqttQoS mqttQoS = topicSubscription.qualityOfService();
            this.sendRetainMessage(channel, topicFilter, mqttQoS, msg.variableHeader().messageId());
        });
    } else {
        channel.close();
    }
}
Also used : MmqException(org.monkey.mmq.core.exception.MmqException) ArrayList(java.util.ArrayList) SubscribeMateData(org.monkey.mmq.core.actor.metadata.subscribe.SubscribeMateData)

Example 3 with MmqException

use of org.monkey.mmq.core.exception.MmqException in project mmqtt by MrHKing.

the class DriverActor method createReceive.

@Override
public Receive createReceive() {
    return receiveBuilder().match(DriverMessage.class, msg -> {
        try {
            DriverFactory.getResourceDriverByEnum(msg.getResourcesMateData().getType()).handle(msg.getProperty(), msg.getResourcesMateData(), msg.getRuleEngineMessage().getMessage().getTopic(), msg.getRuleEngineMessage().getMessage().getMqttQoS(), msg.getRuleEngineMessage().getMessage().getAddress(), msg.getRuleEngineMessage().getUsername());
        } catch (MmqException e) {
            SystemMessage systemMessage = new SystemMessage();
            systemMessage.setTopic(RULE_ENGINE);
            systemMessage.setPayload(e.getMessage());
            systemMessage.setMqttQoS(MqttQoS.AT_LEAST_ONCE);
            ActorSelection actorRef = actorSystem.actorSelection("/user/driver");
            actorRef.tell(systemMessage, ActorRef.noSender());
        }
    }).build();
}
Also used : MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) DriverFactory(org.monkey.mmq.config.driver.DriverFactory) SystemMessage(org.monkey.mmq.core.actor.message.SystemMessage) MmqException(org.monkey.mmq.core.exception.MmqException) ActorRef(akka.actor.ActorRef) ActorSystem(akka.actor.ActorSystem) AbstractActor(akka.actor.AbstractActor) DriverMessage(org.monkey.mmq.config.matedata.DriverMessage) ActorSelection(akka.actor.ActorSelection) RULE_ENGINE(org.monkey.mmq.core.common.Constants.RULE_ENGINE) SystemMessage(org.monkey.mmq.core.actor.message.SystemMessage) ActorSelection(akka.actor.ActorSelection) DriverMessage(org.monkey.mmq.config.matedata.DriverMessage) MmqException(org.monkey.mmq.core.exception.MmqException)

Example 4 with MmqException

use of org.monkey.mmq.core.exception.MmqException in project mmqtt by MrHKing.

the class KafkaDriver method handle.

@Override
public void handle(Map property, ResourcesMateData resourcesMateData, String topic, int qos, String address, String username) throws MmqException {
    try {
        Producer<String, String> producer = this.getDriver(resourcesMateData.getResourceID());
        Map<String, Object> payload = new HashMap<>();
        payload.put("topic", topic);
        payload.put("payload", property);
        payload.put("address", address);
        payload.put("qos", qos);
        producer.send(new ProducerRecord<>(resourcesMateData.getResource().get("topic").toString(), JacksonUtils.toJson(payload)));
    } catch (Exception e) {
        throw new MmqException(e.hashCode(), e.getMessage());
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MmqException(org.monkey.mmq.core.exception.MmqException) MmqException(org.monkey.mmq.core.exception.MmqException)

Example 5 with MmqException

use of org.monkey.mmq.core.exception.MmqException in project mmqtt by MrHKing.

the class PersistentServiceProcessor method put.

@Override
public void put(String key, Record value) throws MmqException {
    final BatchWriteRequest req = new BatchWriteRequest();
    Datum datum = Datum.createDatum(key, value);
    req.append(ByteUtils.toBytes(key), serializer.serialize(datum));
    final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req))).setGroup(this.raftGroup).setOperation(Op.Write.desc).build();
    try {
        protocol.write(request);
    } catch (Exception e) {
        throw new MmqException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage());
    }
}
Also used : Datum(org.monkey.mmq.core.consistency.matedata.Datum) MmqException(org.monkey.mmq.core.exception.MmqException) WriteRequest(org.monkey.mmq.core.entity.WriteRequest) MmqException(org.monkey.mmq.core.exception.MmqException)

Aggregations

MmqException (org.monkey.mmq.core.exception.MmqException)16 Connection (java.sql.Connection)5 SQLException (java.sql.SQLException)5 WriteRequest (org.monkey.mmq.core.entity.WriteRequest)4 ExpressionParser (org.springframework.expression.ExpressionParser)4 TemplateParserContext (org.springframework.expression.common.TemplateParserContext)4 SpelExpressionParser (org.springframework.expression.spel.standard.SpelExpressionParser)4 ActorSelection (akka.actor.ActorSelection)2 ArrayList (java.util.ArrayList)2 SystemMessage (org.monkey.mmq.core.actor.message.SystemMessage)2 Datum (org.monkey.mmq.core.consistency.matedata.Datum)2 ReadRequest (org.monkey.mmq.core.entity.ReadRequest)2 Response (org.monkey.mmq.core.entity.Response)2 AbstractActor (akka.actor.AbstractActor)1 ActorRef (akka.actor.ActorRef)1 ActorSystem (akka.actor.ActorSystem)1 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)1 ResultSet (java.sql.ResultSet)1 Statement (java.sql.Statement)1 HashMap (java.util.HashMap)1