View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package net.anyflow.lannister.packetreceiver;
18  
19  import io.netty.channel.ChannelHandlerContext;
20  import net.anyflow.lannister.message.OutboundMessageStatus;
21  import net.anyflow.lannister.plugin.DeliveredEventArgs;
22  import net.anyflow.lannister.plugin.DeliveredEventListener;
23  import net.anyflow.lannister.plugin.Plugins;
24  import net.anyflow.lannister.session.Session;
25  
26  public class PubRecReceiver {
27  	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PubRecReceiver.class);
28  
29  	public static final PubRecReceiver SHARED = new PubRecReceiver();
30  
31  	private PubRecReceiver() {
32  	}
33  
34  	protected void handle(ChannelHandlerContext ctx, Session session, int messageId) {
35  		OutboundMessageStatus status = OutboundMessageStatus.NEXUS.getBy(messageId, session.clientId());
36  		if (status == null || status.status() == OutboundMessageStatus.Status.TO_PUBLISH) {
37  			logger.error("PUBREC target does not exist or Invalid status [clientId={}, messageId={}]",
38  					session.clientId(), messageId);
39  			session.dispose(true); // [MQTT-3.3.5-2]
40  			return;
41  		}
42  
43  		if (status.status() == OutboundMessageStatus.Status.PUBLISHED) {
44  			ctx.channel().eventLoop().execute(() -> {
45  				Plugins.INSTANCE.get(DeliveredEventListener.class).delivered(new DeliveredEventArgs() {
46  					@Override
47  					public String clientId() {
48  						return session.clientId();
49  					}
50  
51  					@Override
52  					public int messageId() {
53  						return messageId;
54  					}
55  				});
56  			});
57  		}
58  
59  		OutboundMessageStatus.NEXUS.update(messageId, session.clientId(), OutboundMessageStatus.Status.PUBRECED);
60  
61  		session.send(MqttMessageFactory.pubrel(messageId), null);
62  	}
63  }