code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package org.dna.mqtt.moquette.messaging.spi.impl.events; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription; /** * * @author andrea */ public class SubscribeEvent extends MessagingEvent { Subscription m_subscription; int m_messageID; public SubscribeEvent(Subscription subscription, int messageID) { m_subscription = subscription; m_messageID = messageID; } public Subscription getSubscription() { return m_subscription; } public int getMessageID() { return m_messageID; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/SubscribeEvent.java
Java
asf20
577
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** * Used to re-fire stored QoS1 QoS2 events once a client reconnects. */ public class RepublishEvent extends MessagingEvent { private String m_clientID; public RepublishEvent(String clientID) { this.m_clientID = clientID; } public String getClientID() { return m_clientID; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/RepublishEvent.java
Java
asf20
377
package org.dna.mqtt.moquette.messaging.spi.impl.events; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; /** * Event used to carry ProtocolMessages from front handler to event processor */ public class ProtocolEvent extends MessagingEvent { IoSession m_session; AbstractMessage message; public ProtocolEvent(IoSession session, AbstractMessage message) { this.m_session = session; this.message = message; } public IoSession getSession() { return m_session; } public AbstractMessage getMessage() { return message; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/ProtocolEvent.java
Java
asf20
647
package org.dna.mqtt.moquette.messaging.spi.impl.events; import org.apache.mina.core.session.IoSession; /** * * @author andrea */ public class DisconnectEvent extends MessagingEvent { IoSession m_session; public DisconnectEvent(IoSession session) { m_session = session; } public IoSession getSession() { return m_session; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/DisconnectEvent.java
Java
asf20
388
package org.dna.mqtt.moquette.messaging.spi.impl; import org.dna.mqtt.moquette.MQTTException; import org.dna.mqtt.moquette.messaging.spi.IMatchingCondition; import org.dna.mqtt.moquette.messaging.spi.IStorageService; import org.dna.mqtt.moquette.messaging.spi.impl.events.PublishEvent; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.server.Server; import org.fusesource.hawtbuf.codec.StringCodec; import org.fusesource.hawtdb.api.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.*; /** * Implementation of IStorageService backed by HawtDB */ public class HawtDBStorageService implements IStorageService { public static class StoredMessage implements Serializable { AbstractMessage.QOSType m_qos; byte[] m_payload; StoredMessage(byte[] message, AbstractMessage.QOSType qos) { m_qos = qos; m_payload = message; } AbstractMessage.QOSType getQos() { return m_qos; } byte[] getPayload() { return m_payload; } } private static final Logger LOG = LoggerFactory.getLogger(HawtDBStorageService.class); private MultiIndexFactory m_multiIndexFactory; private PageFileFactory pageFactory; //maps clientID to the list of pending messages stored private SortedIndex<String, List<PublishEvent>> m_persistentMessageStore; private SortedIndex<String, StoredMessage> m_retainedStore; //bind clientID+MsgID -> evt message published private SortedIndex<String, PublishEvent> m_inflightStore; //bind clientID+MsgID -> evt message published private SortedIndex<String, PublishEvent> m_qos2Store; //persistent Map of clientID, set of Subscriptions private SortedIndex<String, Set<Subscription>> m_persistentSubscriptions; public HawtDBStorageService() { String storeFile = Server.STORAGE_FILE_PATH; pageFactory = new PageFileFactory(); File tmpFile; try { tmpFile = new File(storeFile); tmpFile.createNewFile(); } catch (IOException ex) { LOG.error(null, ex); throw new MQTTException("Can't create temp file for subscriptions storage [" + storeFile + "]", ex); } pageFactory.setFile(tmpFile); pageFactory.open(); PageFile pageFile = pageFactory.getPageFile(); m_multiIndexFactory = new MultiIndexFactory(pageFile); } public void initStore() { initRetainedStore(); //init the message store for QoS 1/2 messages in clean sessions initPersistentMessageStore(); initInflightMessageStore(); initPersistentSubscriptions(); initPersistentQoS2MessageStore(); } private void initRetainedStore() { BTreeIndexFactory<String, StoredMessage> indexFactory = new BTreeIndexFactory<String, StoredMessage>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_retainedStore = (SortedIndex<String, StoredMessage>) m_multiIndexFactory.openOrCreate("retained", indexFactory); } private void initPersistentMessageStore() { BTreeIndexFactory<String, List<PublishEvent>> indexFactory = new BTreeIndexFactory<String, List<PublishEvent>>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_persistentMessageStore = (SortedIndex<String, List<PublishEvent>>) m_multiIndexFactory.openOrCreate("persistedMessages", indexFactory); } private void initPersistentSubscriptions() { BTreeIndexFactory<String, Set<Subscription>> indexFactory = new BTreeIndexFactory<String, Set<Subscription>>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_persistentSubscriptions = (SortedIndex<String, Set<Subscription>>) m_multiIndexFactory.openOrCreate("subscriptions", indexFactory); } /** * Initialize the message store used to handle the temporary storage of QoS 1,2 * messages in flight. */ private void initInflightMessageStore() { BTreeIndexFactory<String, PublishEvent> indexFactory = new BTreeIndexFactory<String, PublishEvent>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_inflightStore = (SortedIndex<String, PublishEvent>) m_multiIndexFactory.openOrCreate("inflight", indexFactory); } private void initPersistentQoS2MessageStore() { BTreeIndexFactory<String, PublishEvent> indexFactory = new BTreeIndexFactory<String, PublishEvent>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_qos2Store = (SortedIndex<String, PublishEvent>) m_multiIndexFactory.openOrCreate("qos2Store", indexFactory); } public void storeRetained(String topic, byte[] message, AbstractMessage.QOSType qos) { if (message.length == 0) { //clean the message from topic m_retainedStore.remove(topic); } else { //store the message to the topic m_retainedStore.put(topic, new StoredMessage(message, qos)); } } public Collection<StoredMessage> searchMatching(IMatchingCondition condition) { LOG.debug("searchMatching scanning all retained messages, presents are " + m_retainedStore.size()); List<StoredMessage> results = new ArrayList<StoredMessage>(); for (Map.Entry<String, StoredMessage> entry : m_retainedStore) { StoredMessage storedMsg = entry.getValue(); if (condition.match(entry.getKey())) { results.add(storedMsg); } } return results; } public void storePublishForFuture(PublishEvent evt) { LOG.debug("storePublishForFuture store evt " + evt); List<PublishEvent> storedEvents; String clientID = evt.getClientID(); if (!m_persistentMessageStore.containsKey(clientID)) { storedEvents = new ArrayList<PublishEvent>(); } else { storedEvents = m_persistentMessageStore.get(clientID); } storedEvents.add(evt); m_persistentMessageStore.put(clientID, storedEvents); } public List<PublishEvent> retrivePersistedPublishes(String clientID) { return m_persistentMessageStore.get(clientID); } public void cleanPersistedPublishes(String clientID) { m_persistentMessageStore.remove(clientID); } public void cleanInFlight(String msgID) { m_inflightStore.remove(msgID); } public void addInFlight(PublishEvent evt, String publishKey) { m_inflightStore.put(publishKey, evt); } public void addNewSubscription(Subscription newSubscription, String clientID) { if (!m_persistentSubscriptions.containsKey(clientID)) { m_persistentSubscriptions.put(clientID, new HashSet<Subscription>()); } Set<Subscription> subs = m_persistentSubscriptions.get(clientID); if (!subs.contains(newSubscription)) { subs.add(newSubscription); m_persistentSubscriptions.put(clientID, subs); } } public void removeAllSubscriptions(String clientID) { m_persistentSubscriptions.remove(clientID); } public List<Subscription> retrieveAllSubscriptions() { List<Subscription> allSubscriptions = new ArrayList<Subscription>(); for (Map.Entry<String, Set<Subscription>> entry : m_persistentSubscriptions) { allSubscriptions.addAll(entry.getValue()); } return allSubscriptions; } public void close() { try { pageFactory.close(); } catch (IOException ex) { LOG.error(null, ex); } } /*-------- QoS 2 storage management --------------*/ public void persistQoS2Message(String publishKey, PublishEvent evt) { LOG.debug(String.format("persistQoS2Message store pubKey %s, evt %s", publishKey, evt)); m_qos2Store.put(publishKey, evt); } public void removeQoS2Message(String publishKey) { m_qos2Store.remove(publishKey); } public PublishEvent retrieveQoS2Message(String publishKey) { return m_qos2Store.get(publishKey); } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/HawtDBStorageService.java
Java
asf20
8,310
package org.dna.mqtt.moquette.messaging.spi.impl; import com.lmax.disruptor.BatchEventProcessor; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.SequenceBarrier; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.messaging.spi.IMatchingCondition; import org.dna.mqtt.moquette.messaging.spi.IMessaging; import org.dna.mqtt.moquette.messaging.spi.IStorageService; import org.dna.mqtt.moquette.messaging.spi.impl.HawtDBStorageService.StoredMessage; import org.dna.mqtt.moquette.messaging.spi.impl.events.*; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.SubscriptionsStore; import org.dna.mqtt.moquette.proto.PubCompMessage; import org.dna.mqtt.moquette.proto.messages.*; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.server.ConnectionDescriptor; import org.dna.mqtt.moquette.server.Constants; import org.dna.mqtt.moquette.server.IAuthenticator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Singleton class that orchestrate the execution of the protocol. * * Uses the LMAX Disruptor to serialize the incoming, requests, because it work in a evented fashion. * * @author andrea */ public class SimpleMessaging implements IMessaging, EventHandler<ValueEvent> { private static final Logger LOG = LoggerFactory.getLogger(SimpleMessaging.class); private SubscriptionsStore subscriptions = new SubscriptionsStore(); private RingBuffer<ValueEvent> m_ringBuffer; // private INotifier m_notifier; private IStorageService m_storageService; Map<String, ConnectionDescriptor> m_clientIDs = new HashMap<String, ConnectionDescriptor>(); private IAuthenticator m_authenticator; private ExecutorService m_executor; BatchEventProcessor<ValueEvent> m_eventProcessor; private static SimpleMessaging INSTANCE; private SimpleMessaging() { } public static SimpleMessaging getInstance() { if (INSTANCE == null) { INSTANCE = new SimpleMessaging(); } return INSTANCE; } public void init() { m_executor = Executors.newFixedThreadPool(1); m_ringBuffer = new RingBuffer<ValueEvent>(ValueEvent.EVENT_FACTORY, 1024 * 32); SequenceBarrier barrier = m_ringBuffer.newBarrier(); m_eventProcessor = new BatchEventProcessor<ValueEvent>(m_ringBuffer, barrier, this); m_ringBuffer.setGatingSequences(m_eventProcessor.getSequence()); m_executor.submit(m_eventProcessor); disruptorPublish(new InitEvent()); } /* public void setNotifier(INotifier notifier) { m_notifier= notifier; } */ private void disruptorPublish(MessagingEvent msgEvent) { long sequence = m_ringBuffer.next(); ValueEvent event = m_ringBuffer.get(sequence); event.setEvent(msgEvent); m_ringBuffer.publish(sequence); } public void disconnect(IoSession session) { disruptorPublish(new DisconnectEvent(session)); } //method used by hte Notifier to re-put an event on the inbound queue private void refill(MessagingEvent evt) { disruptorPublish(evt); } public void republishStored(String clientID) { //create the event to push LOG.debug("republishStored invoked to publish soterd messages for clientID " + clientID); disruptorPublish(new RepublishEvent(clientID)); } public void handleProtocolMessage(IoSession session, AbstractMessage msg) { disruptorPublish(new ProtocolEvent(session, msg)); } /** * NOT SAFE Method, to be removed because used only in tests */ protected SubscriptionsStore getSubscriptions() { return subscriptions; } public void stop() { disruptorPublish(new StopEvent()); } public void onEvent(ValueEvent t, long l, boolean bln) throws Exception { MessagingEvent evt = t.getEvent(); LOG.debug("onEvent processing messaging event " + evt); if (evt instanceof PublishEvent) { processPublish((PublishEvent) evt); } else if (evt instanceof StopEvent) { processStop(); } else if (evt instanceof DisconnectEvent) { DisconnectEvent disEvt = (DisconnectEvent) evt; String clientID = (String) disEvt.getSession().getAttribute(Constants.ATTR_CLIENTID); processDisconnect(disEvt.getSession(), clientID); } else if (evt instanceof RepublishEvent) { processRepublish((RepublishEvent) evt); } else if (evt instanceof ProtocolEvent) { IoSession session = ((ProtocolEvent) evt).getSession(); AbstractMessage message = ((ProtocolEvent) evt).getMessage(); if (message instanceof ConnectMessage) { processConnect(session, (ConnectMessage) message); } else if (message instanceof PublishMessage) { PublishMessage pubMsg = (PublishMessage) message; PublishEvent pubEvt; String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); if (message.getQos() == QOSType.MOST_ONE) { pubEvt = new PublishEvent(pubMsg.getTopicName(), pubMsg.getQos(), pubMsg.getPayload(), pubMsg.isRetainFlag(), clientID, session); } else { pubEvt = new PublishEvent(pubMsg.getTopicName(), pubMsg.getQos(), pubMsg.getPayload(), pubMsg.isRetainFlag(), clientID, pubMsg.getMessageID(), session); } processPublish(pubEvt); } else if (message instanceof DisconnectMessage) { String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); boolean cleanSession = (Boolean) session.getAttribute(Constants.CLEAN_SESSION); if (cleanSession) { //cleanup topic subscriptions processRemoveAllSubscriptions(clientID); } //close the TCP connection //session.close(true); processDisconnect(session, clientID); } else if (message instanceof UnsubscribeMessage) { UnsubscribeMessage unsubMsg = (UnsubscribeMessage) message; String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); processUnsubscribe(session, clientID, unsubMsg.topics(), unsubMsg.getMessageID()); } else if (message instanceof SubscribeMessage) { String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); boolean cleanSession = (Boolean) session.getAttribute(Constants.CLEAN_SESSION); processSubscribe(session, (SubscribeMessage) message, clientID, cleanSession); } else if (message instanceof PubRelMessage) { String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); int messageID = ((PubRelMessage) message).getMessageID(); processPubRel(clientID, messageID); } else if (message instanceof PubRecMessage) { String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); int messageID = ((PubRecMessage) message).getMessageID(); processPubRec(clientID, messageID); } else if (message instanceof PubCompMessage) { String clientID = (String) session.getAttribute(Constants.ATTR_CLIENTID); int messageID = ((PubCompMessage) message).getMessageID(); processPubComp(clientID, messageID); } else { throw new RuntimeException("Illegal message received " + message); } } else if (evt instanceof InitEvent) { processInit(); } } private void processInit() { m_storageService = new HawtDBStorageService(); m_storageService.initStore(); subscriptions.init(m_storageService); } protected void processConnect(IoSession session, ConnectMessage msg) { if (msg.getProcotolVersion() != 0x03) { ConnAckMessage badProto = new ConnAckMessage(); badProto.setReturnCode(ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION); session.write(badProto); session.close(false); return; } if (msg.getClientID() == null || msg.getClientID().length() > 23) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.IDENTIFIER_REJECTED); session.write(okResp); return; } //if an old client with the same ID already exists close its session. if (m_clientIDs.containsKey(msg.getClientID())) { //clean the subscriptions if the old used a cleanSession = true IoSession oldSession = m_clientIDs.get(msg.getClientID()).getSession(); boolean cleanSession = (Boolean) oldSession.getAttribute(Constants.CLEAN_SESSION); if (cleanSession) { //cleanup topic subscriptions processRemoveAllSubscriptions(msg.getClientID()); } m_clientIDs.get(msg.getClientID()).getSession().close(false); } ConnectionDescriptor connDescr = new ConnectionDescriptor(msg.getClientID(), session, msg.isCleanSession()); m_clientIDs.put(msg.getClientID(), connDescr); int keepAlive = msg.getKeepAlive(); LOG.debug(String.format("Connect with keepAlive %d s", keepAlive)); session.setAttribute("keepAlive", keepAlive); session.setAttribute(Constants.CLEAN_SESSION, msg.isCleanSession()); //used to track the client in the subscription and publishing phases. session.setAttribute(Constants.ATTR_CLIENTID, msg.getClientID()); session.getConfig().setIdleTime(IdleStatus.READER_IDLE, Math.round(keepAlive * 1.5f)); //Handle will flag if (msg.isWillFlag()) { QOSType willQos = QOSType.values()[msg.getWillQos()]; PublishEvent pubEvt = new PublishEvent(msg.getWillTopic(), willQos, msg.getWillMessage().getBytes(), msg.isWillRetain(), msg.getClientID(), session); processPublish(pubEvt); } //handle user authentication if (msg.isUserFlag()) { String pwd = null; if (msg.isPasswordFlag()) { pwd = msg.getPassword(); } if (!m_authenticator.checkValid(msg.getUsername(), pwd)) { ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.BAD_USERNAME_OR_PASSWORD); session.write(okResp); return; } } subscriptions.activate(msg.getClientID()); //handle clean session flag if (msg.isCleanSession()) { //remove all prev subscriptions //cleanup topic subscriptions processRemoveAllSubscriptions(msg.getClientID()); } else { //force the republish of stored QoS1 and QoS2 republishStored(msg.getClientID()); } ConnAckMessage okResp = new ConnAckMessage(); okResp.setReturnCode(ConnAckMessage.CONNECTION_ACCEPTED); session.write(okResp); } /** * Second phase of a publish QoS2 protocol, sent by publisher to the broker. Search the stored message and publish * to all interested subscribers. * */ protected void processPubRel(String clientID, int messageID) { String publishKey = String.format("%s%d", clientID, messageID); PublishEvent evt = m_storageService.retrieveQoS2Message(publishKey); final String topic = evt.getTopic(); final QOSType qos = evt.getQos(); final byte[] message = evt.getMessage(); boolean retain = evt.isRetain(); publish2Subscribers(topic, qos, message, retain, evt.getMessageID()); m_storageService.removeQoS2Message(publishKey); if (retain) { m_storageService.storeRetained(topic, message, qos); } sendPubComp(clientID, messageID); } protected void processPublish(PublishEvent evt) { LOG.debug("processPublish invoked with " + evt); final String topic = evt.getTopic(); final QOSType qos = evt.getQos(); final byte[] message = evt.getMessage(); boolean retain = evt.isRetain(); String publishKey = null; if (qos == QOSType.LEAST_ONE) { //store the temporary message publishKey = String.format("%s%d", evt.getClientID(), evt.getMessageID()); m_storageService.addInFlight(evt, publishKey); } else if (qos == QOSType.EXACTLY_ONCE) { publishKey = String.format("%s%d", evt.getClientID(), evt.getMessageID()); //store the message in temp store m_storageService.persistQoS2Message(publishKey, evt); sendPubRec(evt.getClientID(), evt.getMessageID()); } publish2Subscribers(topic, qos, message, retain, evt.getMessageID()); if (qos == QOSType.LEAST_ONE) { assert publishKey != null; m_storageService.cleanInFlight(publishKey); sendPubAck(new PubAckEvent(evt.getMessageID(), evt.getClientID())); } if (retain) { m_storageService.storeRetained(topic, message, qos); } } /** * Flood the subscribers with the message to notify. MessageID is optional and should only used for QoS 1 and 2 * */ private void publish2Subscribers(String topic, QOSType qos, byte[] message, boolean retain, Integer messageID) { for (final Subscription sub : subscriptions.matches(topic)) { if (qos == QOSType.MOST_ONE) { //QoS 0 notify(new NotifyEvent(sub.getClientId(), topic, qos, message, false)); } else { //QoS 1 or 2 //if the target subscription is not clean session and is not connected => store it if (!sub.isCleanSession() && !sub.isActive()) { //clone the event with matching clientID PublishEvent newPublishEvt = new PublishEvent(topic, qos, message, retain, sub.getClientId(), messageID, null); m_storageService.storePublishForFuture(newPublishEvt); } else { //if QoS 2 then store it in temp memory if (qos ==QOSType.EXACTLY_ONCE) { String publishKey = String.format("%s%d", sub.getClientId(), messageID); PublishEvent newPublishEvt = new PublishEvent(topic, qos, message, retain, sub.getClientId(), messageID, null); m_storageService.addInFlight(newPublishEvt, publishKey); } //publish notify(new NotifyEvent(sub.getClientId(), topic, qos, message, false)); } } } } private void processPubRec(String clientID, int messageID) { //once received a PUBREC reply with a PUBREL(messageID) LOG.debug(String.format("processPubRec invoked for clientID %s ad messageID %d", clientID, messageID)); PubRelMessage pubRelMessage = new PubRelMessage(); pubRelMessage.setMessageID(messageID); m_clientIDs.get(clientID).getSession().write(pubRelMessage); } private void processPubComp(String clientID, int messageID) { //once received the PUBCOMP then remove the message from the temp memory String publishKey = String.format("%s%d", clientID, messageID); m_storageService.cleanInFlight(publishKey); } private void subscribeSingleTopic(Subscription newSubscription, final String topic) { subscriptions.add(newSubscription); //scans retained messages to be published to the new subscription Collection<StoredMessage> messages = m_storageService.searchMatching(new IMatchingCondition() { public boolean match(String key) { return SubscriptionsStore.matchTopics(key, topic); } }); for (StoredMessage storedMsg : messages) { //fire the as retained the message LOG.debug("Inserting NotifyEvent into outbound for topic " + topic); notify(new NotifyEvent(newSubscription.getClientId(), topic, storedMsg.getQos(), storedMsg.getPayload(), true)); } } protected void processSubscribe(IoSession session, SubscribeMessage msg, String clientID, boolean cleanSession) { LOG.debug("processSubscribe invoked"); for (SubscribeMessage.Couple req : msg.subscriptions()) { QOSType qos = AbstractMessage.QOSType.values()[req.getQos()]; Subscription newSubscription = new Subscription(clientID, req.getTopic(), qos, cleanSession); subscribeSingleTopic(newSubscription, req.getTopic()); } //ack the client SubAckMessage ackMessage = new SubAckMessage(); ackMessage.setMessageID(msg.getMessageID()); //TODO by now it handles only QoS 0 messages for (int i = 0; i < msg.subscriptions().size(); i++) { ackMessage.addType(QOSType.MOST_ONE); } LOG.info("replying with SubAct to MSG ID " + msg.getMessageID()); session.write(ackMessage); } /** * Remove the clientID from topic subscription, if not previously subscribed, * doesn't reply any error */ protected void processUnsubscribe(IoSession session, String clientID, List<String> topics, int messageID) { LOG.debug("processSubscribe invoked"); for (String topic : topics) { subscriptions.removeSubscription(topic, clientID); } //ack the client UnsubAckMessage ackMessage = new UnsubAckMessage(); ackMessage.setMessageID(messageID); LOG.info("replying with UnsubAck to MSG ID {0}", messageID); session.write(ackMessage); } protected void processRemoveAllSubscriptions(String clientID) { LOG.debug("processRemoveAllSubscriptions invoked"); subscriptions.removeForClient(clientID); //remove also the messages stored of type QoS1/2 m_storageService.cleanPersistedPublishes(clientID); } private void processDisconnect(IoSession session, String clientID) throws InterruptedException { // m_notifier.disconnect(evt.getSession()); m_clientIDs.remove(clientID); session.close(true); //de-activate the subscriptions for this ClientID // String clientID = (String) evt.getSession().getAttribute(Constants.ATTR_CLIENTID); subscriptions.deactivate(clientID); } private void processStop() { LOG.debug("processStop invoked"); m_storageService.close(); // m_eventProcessor.halt(); m_executor.shutdown(); } private void processRepublish(RepublishEvent evt) throws InterruptedException { LOG.debug("processRepublish invoked"); List<PublishEvent> publishedEvents = m_storageService.retrivePersistedPublishes(evt.getClientID()); if (publishedEvents == null) { LOG.debug("processRepublish, no stored publish events"); return; } for (PublishEvent pubEvt : publishedEvents) { notify(new NotifyEvent(pubEvt.getClientID(), pubEvt.getTopic(), pubEvt.getQos(), pubEvt.getMessage(), false, pubEvt.getMessageID())); } } private void notify(NotifyEvent evt) { LOG.debug("notify invoked with event " + evt); String clientId = evt.getClientId(); PublishMessage pubMessage = new PublishMessage(); pubMessage.setRetainFlag(evt.isRetained()); pubMessage.setTopicName(evt.getTopic()); pubMessage.setQos(evt.getQos()); pubMessage.setPayload(evt.getMessage()); if (pubMessage.getQos() != QOSType.MOST_ONE) { pubMessage.setMessageID(evt.getMessageID()); } try { assert m_clientIDs != null; LOG.debug("clientIDs are " + m_clientIDs); assert m_clientIDs.get(clientId) != null; LOG.debug("Session for clientId " + clientId + " is " + m_clientIDs.get(clientId).getSession()); m_clientIDs.get(clientId).getSession().write(pubMessage); }catch(Throwable t) { LOG.error(null, t); } } private void sendPubAck(PubAckEvent evt) { LOG.debug("sendPubAck invoked"); String clientId = evt.getClientID(); PubAckMessage pubAckMessage = new PubAckMessage(); pubAckMessage.setMessageID(evt.getMessageId()); try { assert m_clientIDs != null; LOG.debug("clientIDs are " + m_clientIDs); assert m_clientIDs.get(clientId) != null; LOG.debug("Session for clientId " + clientId + " is " + m_clientIDs.get(clientId).getSession()); m_clientIDs.get(clientId).getSession().write(pubAckMessage); }catch(Throwable t) { LOG.error(null, t); } } private void sendPubRec(String clientID, int messageID) { LOG.debug(String.format("sendPubRec invoked for clientID %s ad messageID %d", clientID, messageID)); PubRecMessage pubRecMessage = new PubRecMessage(); pubRecMessage.setMessageID(messageID); m_clientIDs.get(clientID).getSession().write(pubRecMessage); } private void sendPubComp(String clientID, int messageID) { LOG.debug(String.format("sendPubComp invoked for clientID %s ad messageID %d", clientID, messageID)); PubCompMessage pubCompMessage = new PubCompMessage(); pubCompMessage.setMessageID(messageID); m_clientIDs.get(clientID).getSession().write(pubCompMessage); } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/SimpleMessaging.java
Java
asf20
22,958
package org.dna.mqtt.moquette.messaging.spi.impl.subscriptions; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; class TreeNode { TreeNode m_parent; Token m_token; List<TreeNode> m_children = new ArrayList<TreeNode>(); List<Subscription> m_subscriptions = new ArrayList<Subscription>(); TreeNode(TreeNode parent) { this.m_parent = parent; } Token getToken() { return m_token; } void setToken(Token topic) { this.m_token = topic; } void addSubcription(Subscription s) { //avoid double registering if (m_subscriptions.contains(s)) { return; } m_subscriptions.add(s); } void addChild(TreeNode child) { m_children.add(child); } boolean isLeaf() { return m_children.isEmpty(); } /** * Search for children that has the specified token, if not found return * null; */ TreeNode childWithToken(Token token) { for (TreeNode child : m_children) { if (child.getToken().equals(token)) { return child; } } return null; } List<Subscription> subscriptions() { return m_subscriptions; } void matches(Queue<Token> tokens, List<Subscription> matchingSubs) { Token t = tokens.poll(); //check if t is null <=> tokens finished if (t == null) { matchingSubs.addAll(m_subscriptions); //check if it has got a MULTI child and add its subscriptions for (TreeNode n : m_children) { if (n.getToken() == Token.MULTI) { matchingSubs.addAll(n.subscriptions()); } } return; } //we are on MULTI, than add subscriptions and return if (m_token == Token.MULTI) { matchingSubs.addAll(m_subscriptions); return; } for (TreeNode n : m_children) { if (n.getToken().match(t)) { //Create a copy of token, alse if navigate 2 sibling it //consumes 2 elements on the queue instead of one n.matches(new LinkedBlockingQueue<Token>(tokens), matchingSubs); } } } /** * Return the number of registered subscriptions */ int size() { int res = m_subscriptions.size(); for (TreeNode child : m_children) { res += child.size(); } return res; } void removeClientSubscriptions(String clientID) { //collect what to delete and then delete to avoid ConcurrentModification List<Subscription> subsToRemove = new ArrayList<Subscription>(); for (Subscription s : m_subscriptions) { if (s.clientId.equals(clientID)) { subsToRemove.add(s); } } for (Subscription s : subsToRemove) { m_subscriptions.remove(s); } //go deep for (TreeNode child : m_children) { child.removeClientSubscriptions(clientID); } } /** * Deactivate all topic subscriptions for the given clientID. * */ void deactivate(String clientID) { for (Subscription s : m_subscriptions) { if (s.clientId.equals(clientID)) { s.setActive(false); } } //go deep for (TreeNode child : m_children) { child.deactivate(clientID); } } /** * Activate all topic subscriptions for the given clientID. * */ public void activate(String clientID) { for (Subscription s : m_subscriptions) { if (s.clientId.equals(clientID)) { s.setActive(true); } } //go deep for (TreeNode child : m_children) { child.deactivate(clientID); } } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/subscriptions/TreeNode.java
Java
asf20
3,988
package org.dna.mqtt.moquette.messaging.spi.impl.subscriptions; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import org.dna.mqtt.moquette.messaging.spi.IStorageService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a tree of topics subscriptions. * * @author andrea */ public class SubscriptionsStore { private TreeNode subscriptions = new TreeNode(null); private static final Logger LOG = LoggerFactory.getLogger(SubscriptionsStore.class); private IStorageService m_storageService; /** * Initialize basic store structures, like the FS storage to maintain * client's topics subscriptions */ public void init(IStorageService storageService) { LOG.debug("init invoked"); m_storageService = storageService; //reload any subscriptions persisted LOG.debug("Reloading all stored subscriptions..."); for (Subscription subscription : m_storageService.retrieveAllSubscriptions()) { LOG.debug("Re-subscribing " + subscription.getClientId() + " to topic " + subscription.getTopic()); addDirect(subscription); } LOG.debug("Finished loading"); } protected void addDirect(Subscription newSubscription) { TreeNode current = findMatchingNode(newSubscription.topic); current.addSubcription(newSubscription); } private TreeNode findMatchingNode(String topic) { List<Token> tokens = new ArrayList<Token>(); try { tokens = splitTopic(topic); } catch (ParseException ex) { //TODO handle the parse exception LOG.error(null, ex); // return; } TreeNode current = subscriptions; for (Token token : tokens) { TreeNode matchingChildren; //check if a children with the same token already exists if ((matchingChildren = current.childWithToken(token)) != null) { current = matchingChildren; } else { //create a new node for the newly inserted token matchingChildren = new TreeNode(current); matchingChildren.setToken(token); current.addChild(matchingChildren); current = matchingChildren; } } return current; } public void add(Subscription newSubscription) { addDirect(newSubscription); //log the subscription String clientID = newSubscription.getClientId(); m_storageService.addNewSubscription(newSubscription, clientID); // pageFile.flush(); } public void removeSubscription(String topic, String clientID) { TreeNode matchNode = findMatchingNode(topic); //search fr the subscription to remove Subscription toBeRemoved = null; for (Subscription sub : matchNode.subscriptions()) { if (sub.topic.equals(topic)) { toBeRemoved = sub; break; } } if (toBeRemoved != null) { matchNode.subscriptions().remove(toBeRemoved); } } /** * Visit the topics tree to remove matching subscriptions with clientID */ public void removeForClient(String clientID) { subscriptions.removeClientSubscriptions(clientID); //remove from log all subscriptions m_storageService.removeAllSubscriptions(clientID); } public void deactivate(String clientID) { subscriptions.deactivate(clientID); } public void activate(String clientID) { LOG.debug("activate re-activating subscriptions for clientID " + clientID); subscriptions.activate(clientID); } public List<Subscription> matches(String topic) { List<Token> tokens = new ArrayList<Token>(); try { tokens = splitTopic(topic); } catch (ParseException ex) { //TODO handle the parse exception LOG.error(null, ex); } Queue<Token> tokenQueue = new LinkedBlockingDeque<Token>(tokens); List<Subscription> matchingSubs = new ArrayList<Subscription>(); subscriptions.matches(tokenQueue, matchingSubs); return matchingSubs; } public boolean contains(Subscription sub) { return !matches(sub.topic).isEmpty(); } public int size() { return subscriptions.size(); } /** * Verify if the 2 topics matching respecting the rules of MQTT Appendix A */ public static boolean matchTopics(String msgTopic, String subscriptionTopic) { try { List<Token> msgTokens = SubscriptionsStore.splitTopic(msgTopic); List<Token> subscriptionTokens = SubscriptionsStore.splitTopic(subscriptionTopic); int i = 0; for (; i< subscriptionTokens.size(); i++) { Token subToken = subscriptionTokens.get(i); if (subToken != Token.MULTI && subToken != Token.SINGLE) { Token msgToken = msgTokens.get(i); if (!msgToken.equals(subToken)) { return false; } } else { if (subToken == Token.MULTI) { return true; } if (subToken == Token.SINGLE) { //skip a step forward } } } return i == msgTokens.size(); } catch (ParseException ex) { LOG.error(null, ex); throw new RuntimeException(ex); } } protected static List<Token> splitTopic(String topic) throws ParseException { List res = new ArrayList<Token>(); String[] splitted = topic.split("/"); if (splitted.length == 0) { res.add(Token.EMPTY); } for (int i = 0; i < splitted.length; i++) { String s = splitted[i]; if (s.isEmpty()) { if (i != 0) { throw new ParseException("Bad format of topic, expetec topic name between separators", i); } res.add(Token.EMPTY); } else if (s.equals("#")) { //check that multi is the last symbol if (i != splitted.length - 1) { throw new ParseException("Bad format of topic, the multi symbol (#) has to be the last one after a separator", i); } res.add(Token.MULTI); } else if (s.contains("#")) { throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i); } else if (s.equals("+")) { res.add(Token.SINGLE); } else if (s.contains("+")) { throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i); } else { res.add(new Token(s)); } } return res; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/subscriptions/SubscriptionsStore.java
Java
asf20
7,143
package org.dna.mqtt.moquette.messaging.spi.impl.subscriptions; import java.io.Serializable; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; /** * Maintain the information about which Topic a certain ClientID is subscribed * and at which QoS * * * @author andrea */ public class Subscription implements Serializable { QOSType requestedQos; String clientId; String topic; boolean cleanSession; boolean active = true; public Subscription(String clientId, String topic, QOSType requestedQos, boolean cleanSession) { this.requestedQos = requestedQos; this.clientId = clientId; this.topic = topic; this.cleanSession = cleanSession; } public String getClientId() { return clientId; } public QOSType getRequestedQos() { return requestedQos; } public String getTopic() { return topic; } public boolean isCleanSession() { return this.cleanSession; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Subscription other = (Subscription) obj; if (this.requestedQos != other.requestedQos) { return false; } if ((this.clientId == null) ? (other.clientId != null) : !this.clientId.equals(other.clientId)) { return false; } if ((this.topic == null) ? (other.topic != null) : !this.topic.equals(other.topic)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 37 * hash + (this.requestedQos != null ? this.requestedQos.hashCode() : 0); hash = 37 * hash + (this.clientId != null ? this.clientId.hashCode() : 0); hash = 37 * hash + (this.topic != null ? this.topic.hashCode() : 0); return hash; } /** * Trivial match method */ boolean match(String topic) { return this.topic.equals(topic); } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/subscriptions/Subscription.java
Java
asf20
2,268
package org.dna.mqtt.moquette.messaging.spi.impl.subscriptions; class Token { static final Token EMPTY = new Token(""); static final Token MULTI = new Token("#"); static final Token SINGLE = new Token("+"); String name; protected Token(String s) { name = s; } protected String name() { return name; } protected boolean match(Token t) { if (t == MULTI || t == SINGLE) { return false; } if (this == MULTI || this == SINGLE) { return true; } return equals(t); } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Token other = (Token) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public String toString() { return name; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/subscriptions/Token.java
Java
asf20
1,219
package org.dna.mqtt.moquette.messaging.spi.impl; import com.lmax.disruptor.EventFactory; import org.dna.mqtt.moquette.messaging.spi.impl.events.MessagingEvent; /** * Carrier value object for the RingBuffer. * * @author andrea */ public final class ValueEvent { private MessagingEvent m_event; public MessagingEvent getEvent() { return m_event; } public void setEvent(MessagingEvent event) { m_event = event; } public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() { public ValueEvent newInstance() { return new ValueEvent(); } }; }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/ValueEvent.java
Java
asf20
658
package org.dna.mqtt.moquette.messaging.spi; /** */ public interface IMatchingCondition { boolean match(String key); }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/IMatchingCondition.java
Java
asf20
126
package org.dna.mqtt.moquette.server; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.messaging.spi.IMessaging; import org.dna.mqtt.moquette.proto.Utils; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import static org.dna.mqtt.moquette.proto.messages.AbstractMessage.*; import org.dna.mqtt.moquette.proto.messages.PingRespMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MINA MQTT Handler used to route messages to protocol logic * * @author andrea */ public class MQTTHandler extends IoHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(MQTTHandler.class); private IMessaging m_messaging; @Override public void messageReceived(IoSession session, Object message) throws Exception { AbstractMessage msg = (AbstractMessage) message; LOG.info(String.format("Received a message of type %s", Utils.msgType2String(msg.getMessageType()))); try { switch (msg.getMessageType()) { case CONNECT: case SUBSCRIBE: case UNSUBSCRIBE: case PUBLISH: case PUBREC: case PUBCOMP: case PUBREL: case DISCONNECT: m_messaging.handleProtocolMessage(session, msg); break; case PINGREQ: PingRespMessage pingResp = new PingRespMessage(); session.write(pingResp); break; } } catch (Exception ex) { LOG.error("Bad error in processing the message", ex); } } @Override public void sessionIdle(IoSession session, IdleStatus status) { if (status == IdleStatus.READER_IDLE) { session.close(false); //TODO send a notification to messaging part to remove the bining clientID-ConnConfig } } public void setMessaging(IMessaging messaging) { m_messaging = messaging; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/server/MQTTHandler.java
Java
asf20
2,204
package org.dna.mqtt.moquette.server; import org.apache.mina.core.session.IoSession; /** * Maintains the information of single connection, like ClientID, IoSession, * and other connection related flags. * * * @author andrea */ public class ConnectionDescriptor { private String m_clientID; private IoSession m_session; private boolean m_cleanSession; public ConnectionDescriptor(String clientID, IoSession session, boolean cleanSession) { this.m_clientID = clientID; this.m_session = session; this.m_cleanSession = cleanSession; } public boolean isCleanSession() { return m_cleanSession; } public String getClientID() { return m_clientID; } public IoSession getSession() { return m_session; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/server/ConnectionDescriptor.java
Java
asf20
814
package org.dna.mqtt.moquette.server; /** * username and password checker * * @author andrea */ public interface IAuthenticator { boolean checkValid(String username, String password); }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/server/IAuthenticator.java
Java
asf20
197
package org.dna.mqtt.moquette.server; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoServiceStatistics; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.demux.DemuxingProtocolDecoder; import org.apache.mina.filter.codec.demux.DemuxingProtocolEncoder; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.dna.mqtt.commons.Constants; import org.dna.mqtt.moquette.messaging.spi.impl.SimpleMessaging; import org.dna.mqtt.moquette.proto.*; import org.dna.mqtt.moquette.proto.messages.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Launch a configured version of the server. * @author andrea */ public class Server { private static final Logger LOG = LoggerFactory.getLogger(Server.class); // public static final int PORT = 1883; // public static final int DEFAULT_CONNECT_TIMEOUT = 10; public static final String STORAGE_FILE_PATH = System.getProperty("user.home") + File.separator + "moquette_store.hawtdb"; //TODO one notifier per outbound queue, else no serialization of message flow is granted!! //private static final int NOTIFIER_POOL_SIZE = 1; private IoAcceptor m_acceptor; SimpleMessaging messaging; // Thread messagingEventLoop; //private ExecutorService m_notifierPool/* = Executors.newFixedThreadPool(NOTIFIER_POOL_SIZE)*/; public static void main(String[] args) throws IOException { new Server().startServer(); } protected void startServer() throws IOException { DemuxingProtocolDecoder decoder = new DemuxingProtocolDecoder(); decoder.addMessageDecoder(new ConnectDecoder()); decoder.addMessageDecoder(new PublishDecoder()); decoder.addMessageDecoder(new PubAckDecoder()); decoder.addMessageDecoder(new PubRelDecoder()); decoder.addMessageDecoder(new PubRecDecoder()); decoder.addMessageDecoder(new PubCompDecoder()); decoder.addMessageDecoder(new SubscribeDecoder()); decoder.addMessageDecoder(new UnsubscribeDecoder()); decoder.addMessageDecoder(new DisconnectDecoder()); decoder.addMessageDecoder(new PingReqDecoder()); DemuxingProtocolEncoder encoder = new DemuxingProtocolEncoder(); // encoder.addMessageEncoder(ConnectMessage.class, new ConnectEncoder()); encoder.addMessageEncoder(ConnAckMessage.class, new ConnAckEncoder()); encoder.addMessageEncoder(SubAckMessage.class, new SubAckEncoder()); encoder.addMessageEncoder(UnsubAckMessage.class, new UnsubAckEncoder()); encoder.addMessageEncoder(PubAckMessage.class, new PubAckEncoder()); encoder.addMessageEncoder(PubRecMessage.class, new PubRecEncoder()); encoder.addMessageEncoder(PubCompMessage.class, new PubCompEncoder()); encoder.addMessageEncoder(PubRelMessage.class, new PubRelEncoder()); encoder.addMessageEncoder(PublishMessage.class, new PublishEncoder()); encoder.addMessageEncoder(PingRespMessage.class, new PingRespEncoder()); m_acceptor = new NioSocketAcceptor(); m_acceptor.getFilterChain().addLast( "logger", new MQTTLoggingFilter("SERVER LOG") ); m_acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(encoder, decoder)); MQTTHandler handler = new MQTTHandler(); messaging = SimpleMessaging.getInstance(); messaging.init(); //TODO fix this hugly wiring handler.setMessaging(messaging); // messaging.setNotifier(handler); // messagingEventLoop = new Thread(messaging); // messagingEventLoop.setName("Event Loop" + System.currentTimeMillis()); // messagingEventLoop.start(); m_acceptor.setHandler(handler); ((NioSocketAcceptor)m_acceptor).setReuseAddress(true); ((NioSocketAcceptor)m_acceptor).getSessionConfig().setReuseAddress(true); m_acceptor.getSessionConfig().setReadBufferSize( 2048 ); m_acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, Constants.DEFAULT_CONNECT_TIMEOUT ); m_acceptor.getStatistics().setThroughputCalculationInterval(10); m_acceptor.getStatistics().updateThroughput(System.currentTimeMillis()); m_acceptor.bind( new InetSocketAddress(Constants.PORT) ); LOG.info("Server binded"); //Bind a shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { stopServer(); } }); } protected void stopServer() { LOG.info("Server stopping..."); messaging.stop(); //messaging.stop(); // messagingEventLoop.interrupt(); // LOG.info("shutting down evet loop"); // try { // messagingEventLoop.join(); // } catch (InterruptedException ex) { // LOG.error(null, ex); // } /*m_notifierPool.shutdown();*/ //log statistics IoServiceStatistics statistics = m_acceptor.getStatistics(); statistics.updateThroughput(System.currentTimeMillis()); System.out.println(String.format("Total read bytes: %d, read throughtput: %f (b/s)", statistics.getReadBytes(), statistics.getReadBytesThroughput())); System.out.println(String.format("Total read msgs: %d, read msg throughtput: %f (msg/s)", statistics.getReadMessages(), statistics.getReadMessagesThroughput())); for(IoSession session: m_acceptor.getManagedSessions().values()) { if(session.isConnected() && !session.isClosing()){ session.close(false); } } m_acceptor.unbind(); m_acceptor.dispose(); LOG.info("Server stopped"); } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/server/Server.java
Java
asf20
6,195
package org.dna.mqtt.moquette.server; /** * Server constants keeper */ public class Constants { public static final String ATTR_CLIENTID = "ClientID"; public static final String CLEAN_SESSION = "cleanSession"; }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/server/Constants.java
Java
asf20
223
package org.dna.mqtt.moquette.client; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.proto.messages.*; import static org.dna.mqtt.moquette.proto.messages.AbstractMessage.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class ClientMQTTHandler extends IoHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(ClientMQTTHandler.class); Client m_callback; ClientMQTTHandler(Client callback) { m_callback = callback; } @Override public void messageReceived(IoSession session, Object message) throws Exception { AbstractMessage msg = (AbstractMessage) message; LOG.debug("Received a message of type " + msg.getMessageType()); switch (msg.getMessageType()) { case CONNACK: handleConnectAck(session, (ConnAckMessage) msg); break; case SUBACK: handleSubscribeAck(session, (SubAckMessage) msg); break; case UNSUBACK: handleUnsubscribeAck(session, (UnsubAckMessage) msg); break; // case SUBSCRIBE: // handleSubscribe(session, (SubscribeMessage) msg); // break; case PUBLISH: handlePublish(session, (PublishMessage) msg); break; case PUBACK: handlePublishAck(session, (PubAckMessage) msg); break; case PINGRESP: break; } } private void handlePublishAck(IoSession session, PubAckMessage msg) { m_callback.publishAckCallback(msg.getMessageID()); } private void handleConnectAck(IoSession session, ConnAckMessage connAckMessage) { m_callback.connectionAckCallback(connAckMessage.getReturnCode()); } private void handleSubscribeAck(IoSession session, SubAckMessage subAckMessage) { m_callback.subscribeAckCallback(subAckMessage.getMessageID()); } private void handlePublish(IoSession session, PublishMessage pubMessage) { m_callback.publishCallback(pubMessage.getTopicName(), pubMessage.getPayload()); } private void handleUnsubscribeAck(IoSession session, UnsubAckMessage unsubAckMessage) { m_callback.unsubscribeAckCallback(unsubAckMessage.getMessageID()); } }
zzkzzk56-mqtt
client/src/main/java/org/dna/mqtt/moquette/client/ClientMQTTHandler.java
Java
asf20
2,462
package org.dna.mqtt.moquette.client; /** * * @author andrea */ public interface IPublishCallback { void published(String topic, byte[] message/*, boolean retained*/); }
zzkzzk56-mqtt
client/src/main/java/org/dna/mqtt/moquette/client/IPublishCallback.java
Java
asf20
179
package org.dna.mqtt.moquette.client; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.WriteFuture; import org.apache.mina.core.service.IoConnector; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.demux.DemuxingProtocolDecoder; import org.apache.mina.filter.codec.demux.DemuxingProtocolEncoder; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.dna.mqtt.commons.Constants; import org.dna.mqtt.commons.MessageIDGenerator; import org.dna.mqtt.moquette.ConnectionException; import org.dna.mqtt.moquette.MQTTException; import org.dna.mqtt.moquette.PublishException; import org.dna.mqtt.moquette.SubscribeException; import org.dna.mqtt.moquette.proto.*; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.ConnAckMessage; import org.dna.mqtt.moquette.proto.messages.ConnectMessage; import org.dna.mqtt.moquette.proto.messages.DisconnectMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; import org.dna.mqtt.moquette.proto.messages.PingReqMessage; import org.dna.mqtt.moquette.proto.messages.PublishMessage; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage; import org.dna.mqtt.moquette.proto.messages.UnsubscribeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The API to connect to a MQTT server. * * Pass to the constructor the host and port to connect, invoke the connect * message, invoke publish to send notifications messages, invoke subscribe with * a callback to be notified when something happen on the desired topic. * * NB this class is not thread safe so MUST be used by only one thread at time. * * @author andrea */ public final class Client { final static int DEFAULT_RETRIES = 3; final static int RETRIES_QOS_GT0 = 3; private static final Logger LOG = LoggerFactory.getLogger(Client.class); // private static final String HOSTNAME = /*"localhost"*/ "127.0.0.1"; // private static final int PORT = Server.PORT; private static final long CONNECT_TIMEOUT = 3 * 1000L; // 3 seconds private static final long SUBACK_TIMEOUT = 4 * 1000L; private static final int KEEPALIVE_SECS = 3; private static final int NUM_SCHEDULER_TIMER_THREAD = 1; private int m_connectRetries = DEFAULT_RETRIES; private String m_hostname; private int m_port; //internal management used for conversation with the server private IoConnector m_connector; private IoSession m_session; private CountDownLatch m_connectBarrier; private CountDownLatch m_subscribeBarrier; private int m_receivedSubAckMessageID; private byte m_returnCode; //TODO synchronize the access //Refact the da model should be a list of callback for each topic private Map<String, IPublishCallback> m_subscribersList = new HashMap<String, IPublishCallback>(); private ScheduledExecutorService m_scheduler; private ScheduledFuture m_pingerHandler; private String m_macAddress; private MessageIDGenerator m_messageIDGenerator = new MessageIDGenerator(); /**Maintain the list of in flight messages for QoS > 0*/ // private Set<Integer> m_inflightIDs = new HashSet<Integer>(); private String m_clientID; final Runnable pingerDeamon = new Runnable() { public void run() { LOG.debug("Pingreq sent"); //send a ping req m_session.write(new PingReqMessage()); } }; public Client(String host, int port) { m_hostname = host; m_port = port; init(); } /** * Constructor in which the user could provide it's own ClientID */ public Client(String host, int port, String clientID) { this(host, port); m_clientID = clientID; } protected void init() { DemuxingProtocolDecoder decoder = new DemuxingProtocolDecoder(); decoder.addMessageDecoder(new ConnAckDecoder()); decoder.addMessageDecoder(new SubAckDecoder()); decoder.addMessageDecoder(new UnsubAckDecoder()); decoder.addMessageDecoder(new PublishDecoder()); decoder.addMessageDecoder(new PubAckDecoder()); decoder.addMessageDecoder(new PingRespDecoder()); DemuxingProtocolEncoder encoder = new DemuxingProtocolEncoder(); encoder.addMessageEncoder(ConnectMessage.class, new ConnectEncoder()); encoder.addMessageEncoder(PublishMessage.class, new PublishEncoder()); encoder.addMessageEncoder(SubscribeMessage.class, new SubscribeEncoder()); encoder.addMessageEncoder(UnsubscribeMessage.class, new UnsubscribeEncoder()); encoder.addMessageEncoder(DisconnectMessage.class, new DisconnectEncoder()); encoder.addMessageEncoder(PingReqMessage.class, new PingReqEncoder()); m_connector = new NioSocketConnector(); // m_connector.getFilterChain().addLast("logger", new LoggingFilter()); m_connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(encoder, decoder)); m_connector.setHandler(new ClientMQTTHandler(this)); m_connector.getSessionConfig().setReadBufferSize(2048); m_connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Constants.DEFAULT_CONNECT_TIMEOUT); m_scheduler = Executors.newScheduledThreadPool(NUM_SCHEDULER_TIMER_THREAD); m_macAddress = readMACAddress(); } /** * Connects to the server with clean session set to true, do not maintains * client topic subscriptions */ public void connect() throws MQTTException { connect(true); } public void connect(boolean cleanSession) throws MQTTException { int retries = 0; try { ConnectFuture future = m_connector.connect(new InetSocketAddress(m_hostname, m_port)); LOG.debug("Client waiting to connect to server"); future.awaitUninterruptibly(); m_session = future.getSession(); } catch (RuntimeIoException e) { LOG.debug("Failed to connect, retry " + retries + " of (" + m_connectRetries + ")", e); } if (retries == m_connectRetries) { throw new MQTTException("Can't connect to the server after " + retries + "retries"); } m_connectBarrier = new CountDownLatch(1); //send a message over the session ConnectMessage connMsg = new ConnectMessage(); connMsg.setKeepAlive(KEEPALIVE_SECS); if (m_clientID == null) { m_clientID = generateClientID(); } connMsg.setClientID(m_clientID); connMsg.setCleanSession(cleanSession); m_session.write(connMsg); //suspend until the server respond with CONN_ACK boolean unlocked = false; try { unlocked = m_connectBarrier.await(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); //TODO parametrize } catch (InterruptedException ex) { throw new ConnectionException(ex); } //if not arrive into certain limit, raise an error if (!unlocked) { throw new ConnectionException("Connection timeout elapsed unless server responded with a CONN_ACK"); } //also raise an error when CONN_ACK is received with some error code inside if (m_returnCode != ConnAckMessage.CONNECTION_ACCEPTED) { String errMsg; switch (m_returnCode) { case ConnAckMessage.UNNACEPTABLE_PROTOCOL_VERSION: errMsg = "Unacceptable protocol version"; break; case ConnAckMessage.IDENTIFIER_REJECTED: errMsg = "Identifier rejected"; break; case ConnAckMessage.SERVER_UNAVAILABLE: errMsg = "Server unavailable"; break; case ConnAckMessage.BAD_USERNAME_OR_PASSWORD: errMsg = "Bad username or password"; break; case ConnAckMessage.NOT_AUTHORIZED: errMsg = "Not authorized"; break; default: errMsg = "Not idetified erro code " + m_returnCode; } throw new ConnectionException(errMsg); } updatePinger(); } /** * Publish to the connected server the payload message to the given topic. * It's admitted to publish a 0 -length payload. */ public void publish(String topic, byte[] payload) throws PublishException { publish(topic, payload, false); } /** * Publish by default with QoS 0 * */ public void publish(String topic, byte[] payload, boolean retain) throws PublishException { publish(topic, payload, AbstractMessage.QOSType.MOST_ONE, retain); } public void publish(String topic, byte[] payload, AbstractMessage.QOSType qos, boolean retain) throws PublishException { PublishMessage msg = new PublishMessage(); msg.setRetainFlag(retain); msg.setTopicName(topic); msg.setPayload(payload); //Untill the server could handle all the Qos 2 level if (qos != AbstractMessage.QOSType.MOST_ONE) { msg.setQos(AbstractMessage.QOSType.LEAST_ONE); int messageID = m_messageIDGenerator.next(); msg.setMessageID(messageID); try { manageSendQoS1(msg); } catch (Throwable ex) { throw new MQTTException(ex); } } else { //QoS 0 case msg.setQos(AbstractMessage.QOSType.MOST_ONE); WriteFuture wf = m_session.write(msg); try { wf.await(); } catch (InterruptedException ex) { LOG.debug(null, ex); throw new PublishException(ex); } Throwable ex = wf.getException(); if (ex != null) { throw new PublishException(ex); } } updatePinger(); } public void subscribe(String topic, IPublishCallback publishCallback) { LOG.info("subscribe invoked"); SubscribeMessage msg = new SubscribeMessage(); msg.addSubscription(new SubscribeMessage.Couple((byte) AbstractMessage.QOSType.MOST_ONE.ordinal(), topic)); msg.setQos(AbstractMessage.QOSType.LEAST_ONE); int messageID = m_messageIDGenerator.next(); msg.setMessageID(messageID); // m_inflightIDs.add(messageID); register(topic, publishCallback); try { manageSendQoS1(msg); } catch(Throwable ex) { //in case errors arise, remove the registration because the subscription // hasn't get well unregister(topic); throw new MQTTException(ex); } updatePinger(); } public void unsubscribe(String... topics) { LOG.info("unsubscribe invoked"); UnsubscribeMessage msg = new UnsubscribeMessage(); for (String topic : topics) { msg.addTopic(topic); } msg.setQos(AbstractMessage.QOSType.LEAST_ONE); int messageID = m_messageIDGenerator.next(); msg.setMessageID(messageID); // m_inflightIDs.add(messageID); // register(topic, publishCallback); try { manageSendQoS1(msg); } catch(Throwable ex) { //in case errors arise, remove the registration because the subscription // hasn't get well // unregister(topic); throw new MQTTException(ex); } for (String topic : topics) { unregister(topic); } // register(topic, publishCallback); updatePinger(); } private void manageSendQoS1(MessageIDMessage msg) throws Throwable{ int messageID = msg.getMessageID(); boolean unlocked = false; for (int retries = 0; retries < RETRIES_QOS_GT0 || !unlocked; retries++) { LOG.debug("manageSendQoS1 retry " + retries); if (retries > 0) { msg.setDupFlag(true); } WriteFuture wf = m_session.write(msg); wf.await(); LOG.info("message sent"); Throwable ex = wf.getException(); if (ex != null) { throw ex; } //wait for the SubAck m_subscribeBarrier = new CountDownLatch(1); //suspend until the server respond with CONN_ACK LOG.info("subscribe waiting for suback"); unlocked = m_subscribeBarrier.await(SUBACK_TIMEOUT, TimeUnit.MILLISECONDS); //TODO parametrize } //if not arrive into certain limit, raise an error if (!unlocked) { throw new SubscribeException(String.format("Server doesn't replyed with a SUB_ACK after %d replies", RETRIES_QOS_GT0)); } else { //check if message ID match if (m_receivedSubAckMessageID != messageID) { throw new SubscribeException(String.format("Server replyed with " + "a broken MessageID in SUB_ACK, expected %d but received %d", messageID, m_receivedSubAckMessageID)); } } } /** * TODO extract this SPI method in a SPI */ protected void connectionAckCallback(byte returnCode) { LOG.info("connectionAckCallback invoked"); m_returnCode = returnCode; m_connectBarrier.countDown(); } protected void subscribeAckCallback(int messageID) { LOG.info("subscribeAckCallback invoked"); m_subscribeBarrier.countDown(); m_receivedSubAckMessageID = messageID; } void unsubscribeAckCallback(int messageID) { LOG.info("unsubscribeAckCallback invoked"); //NB we share the barrier because in futur will be a single barrier for all m_subscribeBarrier.countDown(); m_receivedSubAckMessageID = messageID; } void publishAckCallback(Integer messageID) { LOG.info("publishAckCallback invoked"); m_subscribeBarrier.countDown(); m_receivedSubAckMessageID = messageID; } protected void publishCallback(String topic, byte[] payload) { IPublishCallback callback = m_subscribersList.get(topic); if (callback == null) { String msg = String.format("Can't find any publish callback fr topic %s", topic); LOG.error(msg); throw new MQTTException(msg); } callback.published(topic, payload); } /** * In the current pinger is not ye executed, then cancel it and schedule * another by KEEPALIVE_SECS */ private void updatePinger() { if (m_pingerHandler != null) { m_pingerHandler.cancel(false); } m_pingerHandler = m_scheduler.scheduleWithFixedDelay(pingerDeamon, KEEPALIVE_SECS, KEEPALIVE_SECS, TimeUnit.SECONDS); } private String readMACAddress() { try { NetworkInterface network = NetworkInterface.getNetworkInterfaces().nextElement(); byte[] mac = network.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], "")); } return sb.toString(); } catch (Exception ex) { throw new MQTTException("Can't retrieve host MAC address", ex); } } private String generateClientID() { double rnd = Math.random(); String id = "Moque" + m_macAddress + Math.round(rnd*1000); LOG.debug("Generated ClientID " + id); return id; } public void close() { //stop the pinger m_pingerHandler.cancel(false); //send the CLOSE message m_session.write(new DisconnectMessage()); // wait until the summation is done m_session.getCloseFuture().awaitUninterruptibly(); // m_connector.dispose(); } public void shutdown() { m_connector.dispose(); } /** * Used only to re-register the callback with the topic, not to send any * subscription message to the server, used when a client reconnect to an * existing session on the server */ public void register(String topic, IPublishCallback publishCallback) { //register the publishCallback in some registry to be notified m_subscribersList.put(topic, publishCallback); } //Remove the registration of the callback from the topic private void unregister(String topic) { m_subscribersList.remove(topic); } }
zzkzzk56-mqtt
client/src/main/java/org/dna/mqtt/moquette/client/Client.java
Java
asf20
17,301
package org.dna.mqtt.moquette.client; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); static boolean received; public static void main(String[] args) throws IOException, InterruptedException { Client client = new Client("test.mosquitto.org", 1883); client.connect(); client.subscribe("/topic", new IPublishCallback() { public void published(String topic, byte[] message) { received = true; } }); Thread.sleep(5000); client.publish("/topic", "Test my payload".getBytes()); client.close(); } }
zzkzzk56-mqtt
client/src/main/java/org/dna/mqtt/moquette/client/Main.java
Java
asf20
815
@Grab(group='org.fusesource.hawtdb', module='hawtdb', version='1.6') import org.fusesource.hawtbuf.codec.StringCodec import org.fusesource.hawtdb.api.IndexFactory import org.fusesource.hawtdb.api.HashIndexFactory import org.fusesource.hawtdb.api.BTreeIndexFactory import org.fusesource.hawtdb.api.PageFile import org.fusesource.hawtdb.api.PageFileFactory import org.fusesource.hawtdb.api.MultiIndexFactory import org.fusesource.hawtdb.api.SortedIndex File tmpFile = new File(System.getProperty("user.home") + File.separator + "test_hawtdb.dat") //tmpFile.createNewFile() def writeSomeData(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() MultiIndexFactory multiIndexFactory = new MultiIndexFactory(pageFile); BTreeIndexFactory<String, String> indexFactory = new BTreeIndexFactory<String, String>() indexFactory.setKeyCodec(StringCodec.INSTANCE) BTreeIndexFactory<String, String> indexFactory2 = new BTreeIndexFactory<String, String>() SortedIndex<String, String> writeIndex = multiIndexFactory.openOrCreate("subscriptions", indexFactory) SortedIndex<String, String> retainedIndex = multiIndexFactory.openOrCreate("retained", indexFactory2) println "Hawt opened, try to read" println "Size: ${writeIndex.size()}" println "write something" writeIndex.put("titolo", "capucetto rosso") retainedIndex.put("autore", "leggenda popolare") pageFile.flush() println "check after write content: ${writeIndex.get("titolo")}, size ${writeIndex.size()}" //pageFile.close() factory.close() } def readAllFileContents(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() MultiIndexFactory multiIndexFactory = new MultiIndexFactory(pageFile); IndexFactory<String, String> indexFactory = new BTreeIndexFactory<String, String>() BTreeIndexFactory<String, String> indexFactory2 = new BTreeIndexFactory<String, String>() indexFactory.setKeyCodec(StringCodec.INSTANCE) SortedIndex<String, String> readingIndex = multiIndexFactory.openOrCreate("subscriptions", indexFactory) SortedIndex<String, String> retainedIndex = multiIndexFactory.openOrCreate("retained", indexFactory2) println "read something, size ${readingIndex.size()}" for (def entry : readingIndex) { println "read k, v -> ${entry.key}, ${entry.value} " } for (def entry : retainedIndex) { println "read k, v -> ${entry.key}, ${entry.value} " } factory.close() } writeSomeData(tmpFile) readAllFileContents(tmpFile)
zzkzzk56-mqtt
tools_scripts/hawtdb_multindex.groovy
Groovy
asf20
2,744
/** * Script used to reconstruct statistics */ Map populateWithTimings(reportFile, timingsMap) { reportFile.eachLine {String line -> if (line.startsWith("msg ID")) { return } def tab = line.split(",") int msgId = tab[0].trim() as int long time = tab[1].trim() as long //TODO notify an alert in case of collisions timingsMap[msgId] = time } timingsMap } Map calculateTransportTime(prodMap, consMap) { Map transportMap = [:] consMap.each {msgId, arrivalTime -> long time = arrivalTime - prodMap[msgId] transportMap[msgId] = time } transportMap } Map consumerTimings = [:] println "Load consumer receive timings" def consumerReport = new File("/home/andrea/workspace/moquette/consumer_bechmark.txt"); populateWithTimings(consumerReport, consumerTimings) println "consumer timings loaded ${consumerTimings.size()} records" Map producerTimings = [:] def producerReport1 = new File("/home/andrea/workspace/moquette/producer_bechmark_Prod1.txt"); def producerReport2 = new File("/home/andrea/workspace/moquette/producer_bechmark_Prod2.txt"); populateWithTimings(producerReport1, producerTimings) println "producer 1 timings loaded ${producerTimings.size()} records" populateWithTimings(producerReport2, producerTimings) println "producer 2 timings loaded ${producerTimings.size()} records" Map report = calculateTransportTime(producerTimings, consumerTimings) File reportFile = new File("/home/andrea/workspace/moquette/report.txt") def minTime = report.min {it.value}.value / (10 ** 6) def maxTime = report.max {it.value}.value / (10 ** 6) def totalTime = 0 report = report.sort() report.each {msgID, time -> totalTime += time reportFile << "$msgID, $time\n" } def meanTime = (totalTime / report.size() ) / (10 ** 6) reportFile << "min $minTime \n max $maxTime \n mean $meanTime \n" println "created report file $reportFile" //reportFile.close()
zzkzzk56-mqtt
tools_scripts/benchmarkReportGenerator.groovy
Groovy
asf20
1,978
@Grab(group='org.fusesource.hawtdb', module='hawtdb', version='1.6') import org.fusesource.hawtbuf.codec.StringCodec import org.fusesource.hawtdb.api.BTreeIndexFactory import org.fusesource.hawtdb.api.PageFile import org.fusesource.hawtdb.api.PageFileFactory import org.fusesource.hawtdb.api.SortedIndex File tmpFile = new File(System.getProperty("user.home") + File.separator + "test_hawtdb.dat") //tmpFile.createNewFile() def writeSomeData(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() BTreeIndexFactory<String, String> indexFactory = new BTreeIndexFactory<String, String>() indexFactory.setKeyCodec(StringCodec.INSTANCE) SortedIndex<String, String> writeIndex = indexFactory.openOrCreate(pageFile) println "Hawt opened, try to read" println "Size: ${writeIndex.size()}" println "write something" writeIndex.put("titolo", "capucetto rosso") pageFile.flush() println "check after write content: ${writeIndex.get("titolo")}, size ${writeIndex.size()}" //pageFile.close() factory.close() } def readAllFileContents(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() BTreeIndexFactory<String, String> indexFactory = new BTreeIndexFactory<String, String>() indexFactory.setKeyCodec(StringCodec.INSTANCE) SortedIndex<String, String> readingIndex = indexFactory.openOrCreate(pageFile) println "read something, size ${readingIndex.size()}" for (def entry : readingIndex) { println "read k, v -> ${entry.key}, ${entry.value} " } factory.close() } writeSomeData(tmpFile) readAllFileContents(tmpFile)
zzkzzk56-mqtt
tools_scripts/hawtdb_play.groovy
Groovy
asf20
1,826
@Grab(group='org.fusesource.hawtdb', module='hawtdb', version='1.6') import org.fusesource.hawtbuf.codec.StringCodec import org.fusesource.hawtdb.api.BTreeIndexFactory import org.fusesource.hawtdb.api.PageFile import org.fusesource.hawtdb.api.PageFileFactory import org.fusesource.hawtdb.api.SortedIndex import org.fusesource.hawtbuf.Buffer File tmpFile = new File(System.getProperty("user.home") + File.separator + "test_hawtdb.dat") //tmpFile.createNewFile() def writeSomeData(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() int pageIdx = pageFile.alloc() pageFile.write(pageIdx, new Buffer("Test".getBytes())) println "writed at page index ${pageIdx}" pageFile.flush() pageFile.close() } def readTest(tmpFile) { def factory = new PageFileFactory() factory.file = tmpFile factory.open() def pageFile = factory.getPageFile() println "page size is: " + pageFile.pageSize Buffer b = new Buffer(512) pageFile.read(0, b) println "content try read " + b pageFile.close() } writeSomeData(tmpFile) readTest(tmpFile)
zzkzzk56-mqtt
tools_scripts/hawtdb_raw_access.groovy
Groovy
asf20
1,191
package org.dna.mqtt.commons; import java.util.concurrent.atomic.AtomicInteger; /** * * @author andrea */ public class MessageIDGenerator { private AtomicInteger m_current; public MessageIDGenerator() { //NB we start at -1 because the first incAndGet has to return 0 m_current = new AtomicInteger(-1); } public int next() { return m_current.incrementAndGet(); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/commons/MessageIDGenerator.java
Java
asf20
423
package org.dna.mqtt.commons; /** * Contains some usefull constants. */ public class Constants { public static final int PORT = 1883; public static final int DEFAULT_CONNECT_TIMEOUT = 10; }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/commons/Constants.java
Java
asf20
201
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; import org.dna.mqtt.moquette.proto.messages.PubAckMessage; /** * * @author andrea */ public class PubAckDecoder extends MessageIDDecoder { @Override protected MessageIDMessage createMessage() { return new PubAckMessage(); } @Override public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PUBACK, in); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubAckDecoder.java
Java
asf20
730
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; /** * * @author andrea */ public class PubCompEncoder implements MessageEncoder<PubCompMessage> { public void encode(IoSession session, PubCompMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.PUBCOMP << 4)); buff.put(Utils.encodeRemainingLength(2)); Utils.writeWord(buff, message.getMessageID()); buff.flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubCompEncoder.java
Java
asf20
784
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; import org.dna.mqtt.moquette.proto.messages.PubRelMessage; /** * * @author andrea */ public class PubRelDecoder extends MessageIDDecoder { @Override protected MessageIDMessage createMessage() { return new PubRelMessage(); } @Override public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PUBREL, in); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubRelDecoder.java
Java
asf20
731
package org.dna.mqtt.moquette.proto; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; /** * * @author andrea */ public class PubCompMessage extends MessageIDMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubCompMessage.java
Java
asf20
188
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; import org.dna.mqtt.moquette.proto.messages.PubRecMessage; /** * * @author andrea */ public class PubRecDecoder extends MessageIDDecoder { @Override protected MessageIDMessage createMessage() { return new PubRecMessage(); } @Override public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PUBREC, in); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubRecDecoder.java
Java
asf20
730
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PingReqMessage; /** * * @author andrea */ public class PingReqDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PINGREQ, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part PingReqMessage message = new PingReqMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PingReqDecoder.java
Java
asf20
962
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PubAckMessage; /** * * @author andrea */ public class PubAckEncoder implements MessageEncoder<PubAckMessage> { public void encode(IoSession session, PubAckMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.PUBACK << 4)); buff.put(Utils.encodeRemainingLength(2)); Utils.writeWord(buff, message.getMessageID()); buff.flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubAckEncoder.java
Java
asf20
839
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.DisconnectMessage; /** * * @author andrea */ public class DisconnectDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.DISCONNECT, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part DisconnectMessage message = new DisconnectMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/DisconnectDecoder.java
Java
asf20
977
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; import org.dna.mqtt.moquette.proto.messages.UnsubAckMessage; /** * * @author andrea */ public class UnsubAckDecoder extends MessageIDDecoder { @Override protected MessageIDMessage createMessage() { return new UnsubAckMessage(); } @Override public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.UNSUBACK, in); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/UnsubAckDecoder.java
Java
asf20
739
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.ConnAckMessage; /** * * @author andrea */ public class ConnAckDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.CONNACK, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part ConnAckMessage message = new ConnAckMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } //skip reserved byte in.skip(1); //read return code message.setReturnCode(in.get()); out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/ConnAckDecoder.java
Java
asf20
1,094
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.PublishMessage; /** * * @author andrea */ public class PublishEncoder implements MessageEncoder<PublishMessage> { public void encode(IoSession session, PublishMessage message, ProtocolEncoderOutput out) throws Exception { if (message.getQos() == QOSType.RESERVED) { throw new IllegalArgumentException("Found a message with RESERVED Qos"); } if (message.getTopicName() == null || message.getTopicName().isEmpty()) { throw new IllegalArgumentException("Found a message with empty or null topic name"); } IoBuffer variableHeaderBuff = IoBuffer.allocate(2).setAutoExpand(true); variableHeaderBuff.put(Utils.encodeString(message.getTopicName())); if (message.getQos() == QOSType.LEAST_ONE || message.getQos() == QOSType.EXACTLY_ONCE ) { if (message.getMessageID() == null) { throw new IllegalArgumentException("Found a message with QOS 1 or 2 and not MessageID setted"); } Utils.writeWord(variableHeaderBuff, message.getMessageID()); } variableHeaderBuff.put(message.getPayload()); variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize).setAutoExpand(true);; buff.put((byte) (AbstractMessage.PUBLISH << 4 | flags)); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PublishEncoder.java
Java
asf20
2,096
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.PublishMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class PublishDecoder extends MqttDecoder { private static Logger LOG = LoggerFactory.getLogger(PublishDecoder.class); public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PUBLISH, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { LOG.debug("decode invoked with buffer " + in); int startPos = in.position(); //Common decoding part PublishMessage message = new PublishMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { LOG.info("decode ask for more data after " + in); return NEED_DATA; } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { return NEED_DATA; } message.setTopicName(topic); if (message.getQos() == QOSType.LEAST_ONE || message.getQos() == QOSType.EXACTLY_ONCE) { message.setMessageID(Utils.readWord(in)); } int stopPos = in.position(); //read the payload int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1); if (in.remaining() < payloadSize) { return NEED_DATA; } byte[] b = new byte[payloadSize]; in.get(b); message.setPayload(b); out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PublishDecoder.java
Java
asf20
2,206
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.UnsubscribeMessage; /** * * @author andrea */ public class UnsubscribeEncoder implements MessageEncoder<UnsubscribeMessage> { public void encode(IoSession session, UnsubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.topics().isEmpty()) { throw new IllegalArgumentException("Found an unsubscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (String topic : message.topics()) { variableHeaderBuff.put(Utils.encodeString(topic)); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.UNSUBSCRIBE << 4 | flags)); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/UnsubscribeEncoder.java
Java
asf20
1,710
package org.dna.mqtt.moquette.proto.messages; import java.util.ArrayList; import java.util.List; /** * * @author andrea */ public class UnsubscribeMessage extends MessageIDMessage { List<String> m_types = new ArrayList<String>(); public List<String> topics() { return m_types; } public void addTopic(String type) { m_types.add(type); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/UnsubscribeMessage.java
Java
asf20
381
package org.dna.mqtt.moquette.proto.messages; import java.util.ArrayList; import java.util.List; /** * * @author andrea */ public class SubAckMessage extends MessageIDMessage { List<QOSType> m_types = new ArrayList<QOSType>(); public List<QOSType> types() { return m_types; } public void addType(QOSType type) { m_types.add(type); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/SubAckMessage.java
Java
asf20
379
package org.dna.mqtt.moquette.proto.messages; /** * Basic abstract message for all MQTT protocol messages. * * @author andrea */ public abstract class AbstractMessage { public static final byte CONNECT = 1; // Client request to connect to Server public static final byte CONNACK = 2; // Connect Acknowledgment public static final byte PUBLISH = 3; // Publish message public static final byte PUBACK = 4; // Publish Acknowledgment public static final byte PUBREC = 5; //Publish Received (assured delivery part 1) public static final byte PUBREL = 6; // Publish Release (assured delivery part 2) public static final byte PUBCOMP = 7; //Publish Complete (assured delivery part 3) public static final byte SUBSCRIBE = 8; //Client Subscribe request public static final byte SUBACK = 9; // Subscribe Acknowledgment public static final byte UNSUBSCRIBE = 10; //Client Unsubscribe request public static final byte UNSUBACK = 11; // Unsubscribe Acknowledgment public static final byte PINGREQ = 12; //PING Request public static final byte PINGRESP = 13; //PING Response public static final byte DISCONNECT = 14; //Client is Disconnecting public static enum QOSType { MOST_ONE, LEAST_ONE, EXACTLY_ONCE, RESERVED; } //type protected boolean m_dupFlag; protected QOSType m_qos; protected boolean m_retainFlag; protected int m_remainingLength; protected byte m_messageType; public byte getMessageType() { return m_messageType; } public void setMessageType(byte messageType) { this.m_messageType = messageType; } public boolean isDupFlag() { return m_dupFlag; } public void setDupFlag(boolean dupFlag) { this.m_dupFlag = dupFlag; } public QOSType getQos() { return m_qos; } public void setQos(QOSType qos) { this.m_qos = qos; } public boolean isRetainFlag() { return m_retainFlag; } public void setRetainFlag(boolean retainFlag) { this.m_retainFlag = retainFlag; } /** * TOBE used only internally */ public int getRemainingLength() { return m_remainingLength; } /** * TOBE used only internally */ public void setRemainingLength(int remainingLength) { this.m_remainingLength = remainingLength; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/AbstractMessage.java
Java
asf20
2,390
package org.dna.mqtt.moquette.proto.messages; /** * The attributes Qos, Dup and Retain aren't used. * * @author andrea */ public class ConnAckMessage extends AbstractMessage { public static final byte CONNECTION_ACCEPTED = 0x00; public static final byte UNNACEPTABLE_PROTOCOL_VERSION = 0x01; public static final byte IDENTIFIER_REJECTED = 0x02; public static final byte SERVER_UNAVAILABLE = 0x03; public static final byte BAD_USERNAME_OR_PASSWORD = 0x04; public static final byte NOT_AUTHORIZED = 0x05; private byte m_returnCode; public byte getReturnCode() { return m_returnCode; } public void setReturnCode(byte returnCode) { this.m_returnCode = returnCode; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/ConnAckMessage.java
Java
asf20
742
package org.dna.mqtt.moquette.proto.messages; /** * The attributes Qos, Dup and Retain aren't used for Connect message * * @author andrea */ public class ConnectMessage extends AbstractMessage { String m_protocolName; byte m_procotolVersion; //Connection flags boolean m_cleanSession; boolean m_willFlag; byte m_willQos; boolean m_willRetain; boolean m_passwordFlag; boolean m_userFlag; int m_keepAlive; //Variable part String m_username; String m_password; String m_clientID; String m_willtopic; String m_willMessage; public boolean isCleanSession() { return m_cleanSession; } public void setCleanSession(boolean cleanSession) { this.m_cleanSession = cleanSession; } public int getKeepAlive() { return m_keepAlive; } public void setKeepAlive(int keepAlive) { this.m_keepAlive = keepAlive; } public boolean isPasswordFlag() { return m_passwordFlag; } public void setPasswordFlag(boolean passwordFlag) { this.m_passwordFlag = passwordFlag; } public byte getProcotolVersion() { return m_procotolVersion; } public void setProcotolVersion(byte procotolVersion) { this.m_procotolVersion = procotolVersion; } public String getProtocolName() { return m_protocolName; } public void setProtocolName(String protocolName) { this.m_protocolName = protocolName; } public boolean isUserFlag() { return m_userFlag; } public void setUserFlag(boolean userFlag) { this.m_userFlag = userFlag; } public boolean isWillFlag() { return m_willFlag; } public void setWillFlag(boolean willFlag) { this.m_willFlag = willFlag; } public byte getWillQos() { return m_willQos; } public void setWillQos(byte willQos) { this.m_willQos = willQos; } public boolean isWillRetain() { return m_willRetain; } public void setWillRetain(boolean willRetain) { this.m_willRetain = willRetain; } public String getPassword() { return m_password; } public void setPassword(String password) { this.m_password = password; } public String getUsername() { return m_username; } public void setUsername(String username) { this.m_username = username; } public String getClientID() { return m_clientID; } public void setClientID(String clientID) { this.m_clientID = clientID; } public String getWillTopic() { return m_willtopic; } public void setWillTopic(String topic) { this.m_willtopic = topic; } public String getWillMessage() { return m_willMessage; } public void setWillMessage(String willMessage) { this.m_willMessage = willMessage; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/ConnectMessage.java
Java
asf20
2,951
package org.dna.mqtt.moquette.proto.messages; /** * Placeholder for PUBREC message. * * @author andrea */ public class PubRecMessage extends MessageIDMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PubRecMessage.java
Java
asf20
173
package org.dna.mqtt.moquette.proto.messages; /** * Doesn't care DUP, QOS and RETAIN flags. * * @author andrea */ public class PingReqMessage extends ZeroLengthMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PingReqMessage.java
Java
asf20
178
package org.dna.mqtt.moquette.proto.messages; /** * * @author andrea */ public class PublishMessage extends MessageIDMessage { private String m_topicName; // private Integer m_messageID; //could be null if Qos is == 0 private byte[] m_payload; /*public Integer getMessageID() { return m_messageID; } public void setMessageID(Integer messageID) { this.m_messageID = messageID; }*/ public String getTopicName() { return m_topicName; } public void setTopicName(String topicName) { this.m_topicName = topicName; } public byte[] getPayload() { return m_payload; } public void setPayload(byte[] payload) { this.m_payload = payload; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PublishMessage.java
Java
asf20
748
package org.dna.mqtt.moquette.proto.messages; /** * Doesn't care DUP, QOS and RETAIN flags. * * @author andrea */ public class DisconnectMessage extends ZeroLengthMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/DisconnectMessage.java
Java
asf20
181
package org.dna.mqtt.moquette.proto.messages; /** * * @author andrea */ public abstract class ZeroLengthMessage extends AbstractMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/ZeroLengthMessage.java
Java
asf20
149
package org.dna.mqtt.moquette.proto.messages; import java.util.ArrayList; import java.util.List; /** * * @author andrea */ public class SubscribeMessage extends MessageIDMessage { public static class Couple { private byte m_qos; private String m_topic; public Couple(byte qos, String topic) { m_qos = qos; m_topic = topic; } public byte getQos() { return m_qos; } public String getTopic() { return m_topic; } } private List<Couple> m_subscriptions = new ArrayList<Couple>(); public SubscribeMessage() { //Subscribe has always QoS 1 m_qos = AbstractMessage.QOSType.LEAST_ONE; } public List<Couple> subscriptions() { return m_subscriptions; } public void addSubscription(Couple subscription) { m_subscriptions.add(subscription); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/SubscribeMessage.java
Java
asf20
936
package org.dna.mqtt.moquette.proto.messages; /** * * @author andrea */ public class UnsubAckMessage extends MessageIDMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/UnsubAckMessage.java
Java
asf20
135
package org.dna.mqtt.moquette.proto.messages; /** * Base class for alla the messages that carries only MessageID. (PUBACK, PUBREC, * PUBREL, PUBCOMP, UNSUBACK) * * The flags dup, QOS and Retained doesn't take care. * * @author andrea */ public abstract class MessageIDMessage extends AbstractMessage { private Integer m_messageID; //could be null if Qos is == 0 public Integer getMessageID() { return m_messageID; } public void setMessageID(Integer messageID) { this.m_messageID = messageID; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/MessageIDMessage.java
Java
asf20
545
package org.dna.mqtt.moquette.proto.messages; /** * * @author andrea */ public class PubRelMessage extends MessageIDMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PubRelMessage.java
Java
asf20
132
package org.dna.mqtt.moquette.proto.messages; /** * Placeholder for PUBACK message. * * @author andrea */ public class PubAckMessage extends MessageIDMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PubAckMessage.java
Java
asf20
168
package org.dna.mqtt.moquette.proto.messages; /** * Doesn't care DUP, QOS and RETAIN flags. * @author andrea */ public class PingRespMessage extends ZeroLengthMessage { }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/messages/PingRespMessage.java
Java
asf20
175
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.SubAckMessage; /** * * @author andrea */ public class SubAckEncoder implements MessageEncoder<SubAckMessage> { public void encode(IoSession session, SubAckMessage message, ProtocolEncoderOutput out) throws Exception { if (message.types().isEmpty()) { throw new IllegalArgumentException("Found a suback message with empty topics"); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (AbstractMessage.QOSType c : message.types()) { byte ord = (byte) c.ordinal(); variableHeaderBuff.put((byte)c.ordinal()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBACK << 4 )); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/SubAckEncoder.java
Java
asf20
1,413
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PingRespMessage; /** * * @author andrea */ public class PingRespDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PINGRESP, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part PingRespMessage message = new PingRespMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PingRespDecoder.java
Java
asf20
1,067
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PingRespMessage; /** * * @author andrea */ public class PingRespEncoder implements MessageEncoder<PingRespMessage> { public void encode(IoSession session, PingRespMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(2); buff.put((byte) (AbstractMessage.PINGRESP << 4)).put((byte)0).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PingRespEncoder.java
Java
asf20
744
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.DisconnectMessage; /** * * @author andrea */ public class DisconnectEncoder implements MessageEncoder<DisconnectMessage> { public void encode(IoSession session, DisconnectMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(2); buff.put((byte) (AbstractMessage.DISCONNECT << 4)).put((byte)0).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/DisconnectEncoder.java
Java
asf20
759
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PubRecMessage; /** * * @author andrea */ public class PubRecEncoder implements MessageEncoder<PubRecMessage> { public void encode(IoSession session, PubRecMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.PUBREC << 4)); buff.put(Utils.encodeRemainingLength(2)); Utils.writeWord(buff, message.getMessageID()); buff.flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubRecEncoder.java
Java
asf20
838
package org.dna.mqtt.moquette.proto; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.ConnectMessage; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; /** * * @author andrea */ public class ConnectEncoder implements MessageEncoder<ConnectMessage> { public void encode(IoSession session, ConnectMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer staticHeaderBuff = IoBuffer.allocate(12); staticHeaderBuff.put(Utils.encodeString("MQIsdp")); //version staticHeaderBuff.put((byte)0x03); //connection flags and Strings byte connectionFlags = 0; if (message.isCleanSession()) { connectionFlags |= 0x02; } if (message.isWillFlag()) { connectionFlags |= 0x04; } connectionFlags |= ((message.getWillQos() & 0x03) << 3); if (message.isWillRetain()) { connectionFlags |= 0x020; } if (message.isPasswordFlag()) { connectionFlags |= 0x040; } if (message.isUserFlag()) { connectionFlags |= 0x080; } staticHeaderBuff.put(connectionFlags); //Keep alive timer Utils.writeWord(staticHeaderBuff, message.getKeepAlive()); staticHeaderBuff.flip(); //Variable part IoBuffer variableHeaderBuff = IoBuffer.allocate(12).setAutoExpand(true); if (message.getClientID() != null) { variableHeaderBuff.put(Utils.encodeString(message.getClientID())); if (message.isWillFlag()) { variableHeaderBuff.put(Utils.encodeString(message.getWillTopic())); variableHeaderBuff.put(Utils.encodeString(message.getWillMessage())); } if (message.isUserFlag() && message.getUsername() != null) { variableHeaderBuff.put(Utils.encodeString(message.getUsername())); if (message.isPasswordFlag() && message.getPassword() != null) { variableHeaderBuff.put(Utils.encodeString(message.getPassword())); } } } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); IoBuffer buff = IoBuffer.allocate(14 + variableHeaderSize); buff.put((byte) (AbstractMessage.CONNECT << 4)); buff.put(Utils.encodeRemainingLength(12 + variableHeaderSize)); buff.put(staticHeaderBuff).put(variableHeaderBuff).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/ConnectEncoder.java
Java
asf20
2,741
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.UnsubAckMessage; /** * * @author andrea */ public class UnsubAckEncoder implements MessageEncoder<UnsubAckMessage> { public void encode(IoSession session, UnsubAckMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.UNSUBACK << 4)); buff.put(Utils.encodeRemainingLength(2)); Utils.writeWord(buff, message.getMessageID()); buff.flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/UnsubAckEncoder.java
Java
asf20
848
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; /** * * @author andrea */ public class PubCompDecoder extends MessageIDDecoder { @Override protected MessageIDMessage createMessage() { return new PubCompMessage(); } @Override public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.PUBCOMP, in); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubCompDecoder.java
Java
asf20
674
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PingReqMessage; /** * * @author andrea */ public class PingReqEncoder implements MessageEncoder<PingReqMessage> { public void encode(IoSession session, PingReqMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(2); buff.put((byte) (AbstractMessage.PINGREQ << 4)).put((byte)0).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PingReqEncoder.java
Java
asf20
739
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage.Couple; /** * * @author andrea */ public class SubscribeEncoder implements MessageEncoder<SubscribeMessage> { public void encode(IoSession session, SubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (Couple c : message.subscriptions()) { variableHeaderBuff.put(Utils.encodeString(c.getTopic())); variableHeaderBuff.put(c.getQos()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBSCRIBE << 4 | flags)); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeEncoder.java
Java
asf20
1,831
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.SubAckMessage; /** * QoS, DUP and RETAIN are NOT used. * * @author andrea */ public class SubAckDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.SUBACK, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part SubAckMessage message = new SubAckMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } int remainingLength = message.getRemainingLength(); //MessageID message.setMessageID(Utils.readWord(in)); remainingLength -= 2; //Qos array if (in.remaining() < remainingLength ) { return NEED_DATA; } for (int i = 0; i < remainingLength; i++) { byte qos = in.get(); message.addType(QOSType.values()[qos]); } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/SubAckDecoder.java
Java
asf20
1,512
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.filter.codec.demux.MessageDecoderAdapter; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; /** * Contains common code for all mqtt decoders. * * @author andrea */ public abstract class MqttDecoder extends MessageDecoderAdapter { protected MessageDecoderResult decodeCommonHeader(AbstractMessage message, IoBuffer in) { //Common decoding part if (in.remaining() < 2) { return NEED_DATA; } byte h1 = in.get(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1); byte qosLevel = (byte) ((h1 & 0x0006) >> 1); boolean retainFlag = ((byte) (h1 & 0x0001) == 1); int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return NEED_DATA; } message.setMessageType(messageType); message.setDupFlag(dupFlag); message.setQos(AbstractMessage.QOSType.values()[qosLevel]); message.setRetainFlag(retainFlag); message.setRemainingLength(remainingLength); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/MqttDecoder.java
Java
asf20
1,288
package org.dna.mqtt.moquette.proto; import java.io.UnsupportedEncodingException; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage; import org.dna.mqtt.moquette.proto.messages.UnsubscribeMessage; /** * * @author andrea */ public class UnsubscribeDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.UNSUBSCRIBE, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part UnsubscribeMessage message = new UnsubscribeMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } //check qos level if (message.getQos() != QOSType.LEAST_ONE) { return NOT_OK; } int start = in.position(); //read messageIDs message.setMessageID(Utils.readWord(in)); int readed = in.position() - start; while (readed < message.getRemainingLength()) { message.addTopic(Utils.decodeString(in)); readed = in.position() - start; } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/UnsubscribeDecoder.java
Java
asf20
1,630
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.AbstractIoBuffer; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.write.WriteRequest; import org.apache.mina.filter.logging.LogLevel; import org.apache.mina.filter.logging.LoggingFilter; import static org.dna.mqtt.moquette.proto.messages.AbstractMessage.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Apache MINA logging filter that pretty prints the header of messages * * @author andrea */ public class MQTTLoggingFilter extends LoggingFilter { private final Logger log; protected static String computeLoggerName(String name) { return name == null ? MQTTLoggingFilter.class.getName() : name; } /** * Default Constructor. */ public MQTTLoggingFilter() { this(LoggingFilter.class.getName()); } /** * Create a new NoopFilter using a class name * * @param clazz the class which name will be used to create the logger */ public MQTTLoggingFilter(Class<?> clazz) { this(clazz.getName()); } /** * Create a new NoopFilter using a name * * @param name the name used to create the logger. If null, will default to * "NoopFilter" */ public MQTTLoggingFilter(String name) { super(computeLoggerName(name)); log = LoggerFactory.getLogger(getName()); } protected String decodeCommonHeader(IoBuffer in) { StringBuilder sb = new StringBuilder(); byte h1 = in.get(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1); byte qosLevel = (byte) ((h1 & 0x0006) >> 1); boolean retainFlag = ((byte) (h1 & 0x0001) == 1); int remainingLength = Utils.decodeRemainingLenght(in); sb.append("type: ").append(decodeMessageType(messageType)).append(", "); sb.append("dup: ").append(Boolean.toString(dupFlag)).append(", "); sb.append("QoS: ").append(qosLevel).append(", "); sb.append("retain: ").append(Boolean.toString(retainFlag)); if (remainingLength != -1) { sb.append(", remainingLen: ").append(remainingLength); } in.rewind(); return sb.toString(); } protected String decodeMessageType(byte type) { switch (type) { case CONNECT: return "CONNECT"; case CONNACK: return "CONNACK"; case PUBLISH: return "PUBLISH"; case PUBACK: return "PUBACK"; case PUBREC: return "PUBREC"; case PUBREL: return "PUBREL"; case PUBCOMP: return "PUBCOMP"; case SUBSCRIBE: return "SUBSCRIBE"; case SUBACK: return "SUBACK"; case UNSUBSCRIBE: return "UNSUBSCRIBE"; case UNSUBACK: return "UNSUBACK"; case PINGREQ: return "PINGREQ"; case PINGRESP: return "PINGRESP"; case DISCONNECT: return "DISCONNECT"; default: return "undefined"; } } @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { if (message instanceof AbstractIoBuffer) { IoBuffer buff = (AbstractIoBuffer) message; log(getMessageReceivedLogLevel(), "RECEIVED: {}", decodeCommonHeader(buff)); } else { log(getMessageReceivedLogLevel(), "RECEIVED: {}", message); } nextFilter.messageReceived(session, message); } @Override public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { log(getMessageSentLogLevel(), "SENT: {}", writeRequest.getMessage()); nextFilter.messageSent(session, writeRequest); } /** * Copied by parent */ private void log(LogLevel eventLevel, String message, Object param) { switch (eventLevel) { case TRACE: log.trace(message, param); return; case DEBUG: log.debug(message, param); return; case INFO: log.info(message, param); return; case WARN: log.warn(message, param); return; case ERROR: log.error(message, param); return; default: return; } } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/MQTTLoggingFilter.java
Java
asf20
4,783
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.MessageIDMessage; /** * * @author andrea */ public abstract class MessageIDDecoder extends MqttDecoder { protected abstract MessageIDMessage createMessage(); public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part MessageIDMessage message = createMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } //read messageIDs message.setMessageID(Utils.readWord(in)); out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/MessageIDDecoder.java
Java
asf20
909
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.PubRelMessage; /** * * @author andrea */ public class PubRelEncoder implements MessageEncoder<PubRelMessage> { public void encode(IoSession session, PubRelMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.PUBREL << 4)); buff.put(Utils.encodeRemainingLength(2)); Utils.writeWord(buff, message.getMessageID()); buff.flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/PubRelEncoder.java
Java
asf20
838
package org.dna.mqtt.moquette.proto; import java.io.UnsupportedEncodingException; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage; /** * * @author andrea */ public class SubscribeDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.SUBSCRIBE, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part SubscribeMessage message = new SubscribeMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } //check qos level if (message.getQos() != QOSType.LEAST_ONE) { return NOT_OK; } int start = in.position(); //read messageIDs message.setMessageID(Utils.readWord(in)); int readed = in.position() - start; while (readed < message.getRemainingLength()) { decodeSubscription(in, message); readed = in.position() - start; } out.write(message); return OK; } /** * Populate the message with couple of Qos, topic */ private void decodeSubscription(IoBuffer in, SubscribeMessage message) throws UnsupportedEncodingException { String topic = Utils.decodeString(in); byte qos = (byte)(in.get() & 0x03); message.addSubscription(new SubscribeMessage.Couple(qos, topic)); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeDecoder.java
Java
asf20
1,909
package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.ConnAckMessage; /** * * @author andrea */ public class ConnAckEncoder implements MessageEncoder<ConnAckMessage> { public void encode(IoSession session, ConnAckMessage message, ProtocolEncoderOutput out) throws Exception { IoBuffer buff = IoBuffer.allocate(4); buff.put((byte) (AbstractMessage.CONNACK << 4)); buff.put(Utils.encodeRemainingLength(2)); buff.put((byte) 0); buff.put(message.getReturnCode()).flip(); out.write(buff); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/ConnAckEncoder.java
Java
asf20
847
package org.dna.mqtt.moquette.proto; import java.io.UnsupportedEncodingException; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.filter.codec.demux.MessageDecoderResult; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.slf4j.LoggerFactory; /** * Common utils methodd used in codecs. * * @author andrea */ public class Utils { public static final int MAX_LENGTH_LIMIT = 268435455; /** * Read 2 bytes from in buffer first MSB, and then LSB returning as int. */ static int readWord(IoBuffer in) { int msb = in.get() & 0x00FF; //remove sign extension due to casting int lsb = in.get() & 0x00FF; msb = (msb << 8) | lsb ; return msb; } /** * Writes as 2 bytes the int value into buffer first MSB, and then LSB. */ static void writeWord(IoBuffer out, int value) { out.put((byte) ((value & 0xFF00) >> 8)); //msb out.put((byte) (value & 0x00FF)); //lsb } /** * Decode the variable remaining lenght as defined in MQTT v3.1 specification * (section 2.1). * * @return the decoded length or -1 if needed more data to decode the length field. */ static int decodeRemainingLenght(IoBuffer in) { int multiplier = 1; int value = 0; byte digit; do { if (in.remaining() < 1) { return -1; } digit = in.get(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); return value; } /** * Return the number of bytes to encode the gicen remaining length value */ static int numBytesToEncode(int len) { if (0 <= len && len <= 127) return 1; if (128 <= len && len <= 16383) return 2; if (16384 <= len && len <= 2097151) return 3; if (2097152 <= len && len <= 268435455) return 4; throw new IllegalArgumentException("value shoul be in the range [0..268435455]"); } /** * Encode the value in the format defined in specification as variable length * array. * * @throws IllegalArgumentException if the value is not in the specification bounds * [0..268435455]. */ static IoBuffer encodeRemainingLength(int value) throws IllegalAccessException { if (value > MAX_LENGTH_LIMIT || value < 0) { throw new IllegalAccessException("Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } IoBuffer encoded = IoBuffer.allocate(4); byte digit; do { digit = (byte) (value % 128); value = value / 128; // if there are more digits to encode, set the top bit of this digit if (value > 0) { digit = (byte) (digit | 0x80); } encoded.put(digit); } while (value > 0); encoded.flip(); return encoded; } static MessageDecoderResult checkDecodable(byte type, IoBuffer in) { if (in.remaining() < 1) { return MessageDecoderResult.NEED_DATA; } byte h1 = in.get(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return MessageDecoderResult.NEED_DATA; } //check remaining length if (in.remaining() < remainingLength) { return MessageDecoderResult.NEED_DATA; } return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK; } /** * Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded * string content. */ static IoBuffer encodeString(String str) { IoBuffer out = IoBuffer.allocate(2).setAutoExpand(true); byte[] raw; try { raw = str.getBytes("UTF-8"); //NB every Java platform has got UTF-8 encoding by default, so this //exception are never raised. } catch (UnsupportedEncodingException ex) { LoggerFactory.getLogger(ConnectEncoder.class).error(null, ex); return null; } Utils.writeWord(out, raw.length); out.put(raw).flip(); return out; } /** * Load a string from the given buffer, reading first the two bytes of len * and then the UTF-8 bytes of the string. * * @return the decoded string or null if NEED_DATA */ static String decodeString(IoBuffer in) throws UnsupportedEncodingException { if (in.remaining() < 2) { return null; } int strLen = Utils.readWord(in); if (in.remaining() < strLen) { return null; } byte[] strRaw = new byte[strLen]; in.get(strRaw); return new String(strRaw, "UTF-8"); } static byte encodeFlags(AbstractMessage message) { byte flags = 0; if (message.isDupFlag()) { flags |= 0x08; } if (message.isRetainFlag()) { flags |= 0x01; } flags |= ((message.getQos().ordinal() & 0x03) << 1); return flags; } /** * Converts MQTT message type to a textual description. * */ public static String msgType2String(int type) { switch (type) { case AbstractMessage.CONNECT: return "CONNECT"; case AbstractMessage.CONNACK: return "CONNACK"; case AbstractMessage.PUBLISH: return "PUBLISH"; case AbstractMessage.PUBACK: return "PUBACK"; case AbstractMessage.PUBREC: return "PUBREC"; case AbstractMessage.PUBREL: return "PUBREL"; case AbstractMessage.PUBCOMP: return "PUBCOMP"; case AbstractMessage.SUBSCRIBE: return "SUBSCRIBE"; case AbstractMessage.SUBACK: return "SUBACK"; case AbstractMessage.UNSUBSCRIBE: return "UNSUBSCRIBE"; case AbstractMessage.UNSUBACK: return "UNSUBACK"; case AbstractMessage.PINGREQ: return "PINGREQ"; case AbstractMessage.PINGRESP: return "PINGRESP"; case AbstractMessage.DISCONNECT: return "DISCONNECT"; default: throw new RuntimeException("Can't decode message type " + type); } } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/Utils.java
Java
asf20
6,611
package org.dna.mqtt.moquette.proto; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.ConnectMessage; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.demux.MessageDecoderResult; /** * Decoder for the CONNECT message * * @author andrea */ public class ConnectDecoder extends MqttDecoder { public MessageDecoderResult decodable(IoSession session, IoBuffer in) { return Utils.checkDecodable(AbstractMessage.CONNECT, in); } public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { //Common decoding part ConnectMessage message = new ConnectMessage(); if (decodeCommonHeader(message, in) == NEED_DATA) { return NEED_DATA; } int remainingLength = message.getRemainingLength(); int start = in.position(); //Connect specific decoding part //ProtocolName 8 bytes if (in.remaining() < 12) { return NEED_DATA; } byte[] encProtoName = new byte[6]; in.skip(2); //size, is 0x06 in.get(encProtoName); String protoName = new String(encProtoName, "UTF-8"); if (!"MQIsdp".equals(protoName)) { return NOT_OK; } message.setProtocolName(protoName); //ProtocolVersion 1 byte (value 0x03) message.setProcotolVersion(in.get()); //Connection flag byte connFlags = in.get(); boolean cleanSession = ((connFlags & 0x02) >> 1) == 1 ? true : false; boolean willFlag = ((connFlags & 0x04) >> 2) == 1 ? true : false; byte willQos = (byte) ((connFlags & 0x18) >> 3); if (willQos > 2) { return NOT_OK; //admitted values for willqos are 0, 1, 2 } boolean willRetain = ((connFlags & 0x20) >> 5) == 1 ? true : false; boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1 ? true : false; boolean userFlag = ((connFlags & 0x80) >> 7) == 1 ? true : false; //a password is true iff user is true. if (!userFlag && passwordFlag) { return NOT_OK; } message.setCleanSession(cleanSession); message.setWillFlag(willFlag); message.setWillQos(willQos); message.setWillRetain(willRetain); message.setPasswordFlag(passwordFlag); message.setUserFlag(userFlag); //Keep Alive timer 2 bytes int keepAlive = Utils.readWord(in); message.setKeepAlive(keepAlive); if (remainingLength == 12) { out.write(message); return OK; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { return NEED_DATA; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { return NEED_DATA; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { String willMessage = Utils.decodeString(in); if (willMessage == null) { return NEED_DATA; } message.setWillMessage(willMessage); } //Compatibility check wieth v3.0, remaining length has precedence over //the user and password flags int readed = in.position() - start; if (readed == remainingLength) { out.write(message); return OK; } //Decode username if (userFlag) { String userName = Utils.decodeString(in); if (userName == null) { return NEED_DATA; } message.setUsername(userName); } readed = in.position() - start; if (readed == remainingLength) { out.write(message); return OK; } //Decode password if (passwordFlag) { String password = Utils.decodeString(in); if (password == null) { return NEED_DATA; } message.setPassword(password); } out.write(message); return OK; } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/proto/ConnectDecoder.java
Java
asf20
4,435
package org.dna.mqtt.moquette; /** * * @author andrea */ public class ConnectionException extends MQTTException { public ConnectionException(String msg) { super(msg); } public ConnectionException(Throwable e) { super(e); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/ConnectionException.java
Java
asf20
263
package org.dna.mqtt.moquette; /** * * @author andrea */ public class SubscribeException extends ConnectionException { public SubscribeException(String msg) { super(msg); } public SubscribeException(Throwable e) { super(e); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/SubscribeException.java
Java
asf20
266
package org.dna.mqtt.moquette; /** * * @author andrea */ public class PublishException extends ConnectionException { public PublishException(String msg) { super(msg); } public PublishException(Throwable e) { super(e); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/PublishException.java
Java
asf20
260
package org.dna.mqtt.moquette; /** * * @author andrea */ public class MQTTException extends RuntimeException { public MQTTException() { super(); } public MQTTException(String msg) { super(msg); } public MQTTException(Throwable cause) { super(cause); } public MQTTException(String msg, Throwable cause) { super(msg, cause); } }
zzkzzk56-mqtt
parser/src/main/java/org/dna/mqtt/moquette/MQTTException.java
Java
asf20
407
#include <stdio.h> int main() { printf("Hello, world"); return 0; }
zzm-test-project
trunk/main.cpp
C++
asf20
68
#include <UnitTest++.h> #include <LibraryConfig.hpp> #if defined(ZZZ_LIB_ZLIB) #include <zlib.h> #include <string.h> #include <stdlib.h> #include <Math/Array1.hpp> #define TESTFILE "foo.gz" #define CHECK_ERR(err, msg) CHECK(err == Z_OK) const char hello[] = "hello, hello!"; const char dictionary[] = "hello"; uLong dictId; /* Adler32 value of the dictionary */ void test_compress OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_gzio OF((const char *fname, Byte *uncompr, uLong uncomprLen)); void test_deflate OF((Byte *compr, uLong comprLen)); void test_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_deflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_flush OF((Byte *compr, uLong *comprLen)); void test_sync OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_dict_deflate OF((Byte *compr, uLong comprLen)); void test_dict_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); int main OF((int argc, char *argv[])); /* =========================================================================== * Test read/write of .gz files */ void test_gzio( const char *fname, /* compressed file name */ Byte *uncompr, uLong uncomprLen) { #ifdef NO_GZCOMPRESS fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); #else int err; int len = (int)strlen(hello)+1; gzFile file; z_off_t pos; file = gzopen(fname, "wb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } gzputc(file, 'h'); if (gzputs(file, "ello") != 4) { fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); exit(1); } if (gzprintf(file, ", %s!", "hello") != 8) { fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); exit(1); } gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ gzclose(file); file = gzopen(fname, "rb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } strcpy((char*)uncompr, "garbage"); if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); exit(1); } else { printf("gzread(): %s\n", (char*)uncompr); } pos = gzseek(file, -8L, SEEK_CUR); if (pos != 6 || gztell(file) != pos) { fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", (long)pos, (long)gztell(file)); exit(1); } if (gzgetc(file) != ' ') { fprintf(stderr, "gzgetc error\n"); exit(1); } if (gzungetc(' ', file) != ' ') { fprintf(stderr, "gzungetc error\n"); exit(1); } gzgets(file, (char*)uncompr, (int)uncomprLen); if (strlen((char*)uncompr) != 7) { /* " hello!" */ fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello + 6)) { fprintf(stderr, "bad gzgets after gzseek\n"); exit(1); } else { printf("gzgets() after gzseek: %s\n", (char*)uncompr); } gzclose(file); #endif } /* =========================================================================== * Test deflate() with small buffers */ void test_deflate( Byte *compr, uLong comprLen) { z_stream c_stream; /* compression stream */ int err; uLong len = (uLong)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; while (c_stream.total_in != len && c_stream.total_out < comprLen) { c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); } /* Finish the stream, still forcing small buffers: */ for (; ;) { c_stream.avail_out = 1; err = deflate(&c_stream, Z_FINISH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with small buffers */ void test_inflate( Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 0; d_stream.next_out = uncompr; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate\n"); exit(1); } else { printf("inflate(): %s\n", (char *)uncompr); } } /* =========================================================================== * Test deflate() with large buffers and dynamic change of compression level */ void test_large_deflate( Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_SPEED); CHECK_ERR(err, "deflateInit"); c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; /* At this point, uncompr is still mostly zeroes, so it should compress * very well: */ c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); if (c_stream.avail_in != 0) { fprintf(stderr, "deflate not greedy\n"); exit(1); } /* Feed in already compressed data and switch to no compression: */ deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); c_stream.next_in = compr; c_stream.avail_in = (uInt)comprLen/2; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); /* Switch back to compressing mode: */ deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with large buffers */ void test_large_inflate( Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); for (; ;) { d_stream.next_out = uncompr; /* discard the output */ d_stream.avail_out = (uInt)uncomprLen; err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "large inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (d_stream.total_out != 2*uncomprLen + comprLen/2) { fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); exit(1); } else { printf("large_inflate(): OK\n"); } } /* =========================================================================== * Test deflate() with full flush */ void test_flush( Byte *compr, uLong *comprLen) { z_stream c_stream; /* compression stream */ int err; uInt len = (uInt)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; c_stream.avail_in = 3; c_stream.avail_out = (uInt)*comprLen; err = deflate(&c_stream, Z_FULL_FLUSH); CHECK_ERR(err, "deflate"); compr[3]++; /* force an error in first compressed block */ c_stream.avail_in = len - 3; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); *comprLen = c_stream.total_out; } /* =========================================================================== * Test inflateSync() */ void test_sync( Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 2; /* just read the zlib header */ err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; inflate(&d_stream, Z_NO_FLUSH); CHECK_ERR(err, "inflate"); d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ err = inflateSync(&d_stream); /* but skip the damaged part */ CHECK_ERR(err, "inflateSync"); err = inflate(&d_stream, Z_FINISH); if (err != Z_DATA_ERROR) { fprintf(stderr, "inflate should report DATA_ERROR\n"); /* Because of incorrect adler32 */ exit(1); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); printf("after inflateSync(): hel%s\n", (char *)uncompr); } /* =========================================================================== * Test deflate() with preset dictionary */ void test_dict_deflate( Byte *compr, uLong comprLen) { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_COMPRESSION); CHECK_ERR(err, "deflateInit"); err = deflateSetDictionary(&c_stream, (const Bytef*)dictionary, sizeof(dictionary)); CHECK_ERR(err, "deflateSetDictionary"); dictId = c_stream.adler; c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; c_stream.next_in = (Bytef*)hello; c_stream.avail_in = (uInt)strlen(hello)+1; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with a preset dictionary */ void test_dict_inflate( Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; for (; ;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; if (err == Z_NEED_DICT) { if (d_stream.adler != dictId) { fprintf(stderr, "unexpected dictionary"); exit(1); } err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, sizeof(dictionary)); } CHECK_ERR(err, "inflate with dict"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate with dict\n"); exit(1); } else { printf("inflate with dictionary: %s\n", (char *)uncompr); } } /* =========================================================================== * Usage: example [output.gz [input.gz]] */ SUITE(zLibTest) { struct TestSetup { zzz::Array1c compr, uncompr; uLong comprLen, uncomprLen; TestSetup() { comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ uncomprLen = comprLen; static const char* myVersion = ZLIB_VERSION; // Check Lib and .h consistency CHECK(zlibVersion()[0] == myVersion[0]); compr.SetSize(comprLen); uncompr.SetSize(comprLen); } ~TestSetup() { } }; TEST_FIXTURE(TestSetup, zLibCompressTest) { int err; uLong len = (uLong)strlen(hello)+1; err = compress((Bytef*)compr.Data(), &comprLen, (const Bytef*)hello, len); CHECK(err == Z_OK); strcpy(uncompr.Data(), "garbage"); err = uncompress((Bytef*)uncompr.Data(), &uncomprLen, (const Bytef*)compr.Data(), comprLen); CHECK(err == Z_OK); CHECK(strcmp(hello, uncompr.Data())==0); } TEST(ZLibTest) { Byte *compr, *uncompr; uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ uLong uncomprLen = comprLen; static const char* myVersion = ZLIB_VERSION; // Check Lib and .h consistency CHECK(zlibVersion()[0] == myVersion[0]); compr = (Byte*)calloc((uInt)comprLen, 1); uncompr = (Byte*)calloc((uInt)uncomprLen, 1); /* compr and uncompr are cleared to avoid reading uninitialized * data and to ensure that uncompr compresses well. */ if (compr == Z_NULL || uncompr == Z_NULL) { printf("out of memory\n"); exit(1); } test_deflate(compr, comprLen); test_inflate(compr, comprLen, uncompr, uncomprLen); test_large_deflate(compr, comprLen, uncompr, uncomprLen); test_large_inflate(compr, comprLen, uncompr, uncomprLen); test_flush(compr, &comprLen); test_sync(compr, comprLen, uncompr, uncomprLen); comprLen = uncomprLen; test_dict_deflate(compr, comprLen); test_dict_inflate(compr, comprLen, uncompr, uncomprLen); free(compr); free(uncompr); } } #endif // ZZZ_LIB_ZLIB
zzz-engine
EngineTest/MathTest/ZLibTest.cpp
C++
gpl3
15,845
#include <zMat.hpp> #include <UnitTest++.h> #ifdef ZZZ_LIB_LAPACK SUITE(zMatrixMathTest) { TEST(LU) { zzz::zMatrix<double> x(3,3); x(0,0)=1; x(0,1)=2; x(0,2)=3; x(1,0)=3; x(1,1)=2; x(1,2)=1; x(2,0)=3; x(2,1)=1; x(2,2)=2; zzz::zMatrix<long> IPIV; CHECK(LUFactorization(x,IPIV)); CHECK_CLOSE(3.0000,x(0,0),0.0001); CHECK_CLOSE(2.0000,x(0,1),0.0001); CHECK_CLOSE(1.0000,x(0,2),0.0001); CHECK_CLOSE(0.3333,x(1,0),0.0001); CHECK_CLOSE(1.3333,x(1,1),0.0001); CHECK_CLOSE(2.6667,x(1,2),0.0001); CHECK_CLOSE(1.0000,x(2,0),0.0001); CHECK_CLOSE(-0.7500,x(2,1),0.0001); CHECK_CLOSE(3.0000,x(2,2),0.0001); } TEST(INVERT) { zzz::zMatrix<double> x(3,3); x(0,0)=1; x(0,1)=2; x(0,2)=3; x(1,0)=3; x(1,1)=2; x(1,2)=1; x(2,0)=3; x(2,1)=1; x(2,2)=2; zzz::zMatrix<double> ix(x); Invert(ix); CHECK_CLOSE(-0.2500,ix(0,0),0.0001); CHECK_CLOSE(0.0833,ix(0,1),0.0001); CHECK_CLOSE(0.3333,ix(0,2),0.0001); CHECK_CLOSE(0.2500,ix(1,0),0.0001); CHECK_CLOSE(0.5833,ix(1,1),0.0001); CHECK_CLOSE(-0.6667,ix(1,2),0.0001); CHECK_CLOSE(0.2500,ix(2,0),0.0001); CHECK_CLOSE(-0.4167,ix(2,1),0.0001); CHECK_CLOSE(0.3333,ix(2,2),0.0001); zzz::zMatrix<double> a(x*ix); CHECK_CLOSE(1,a(0,0),0.0001); CHECK_CLOSE(0,a(0,1),0.0001); CHECK_CLOSE(0,a(0,2),0.0001); CHECK_CLOSE(0,a(1,0),0.0001); CHECK_CLOSE(1,a(1,1),0.0001); CHECK_CLOSE(0,a(1,2),0.0001); CHECK_CLOSE(0,a(2,0),0.0001); CHECK_CLOSE(0,a(2,1),0.0001); CHECK_CLOSE(1,a(2,2),0.0001); } TEST(SVD) { zzz::zMatrix<double> x(3,3); x(0,0)=1; x(0,1)=2; x(0,2)=3; x(1,0)=3; x(1,1)=2; x(1,2)=1; x(2,0)=3; x(2,1)=1; x(2,2)=2; zzz::zMatrix<double> U,S,VT; zzz::zMatrix<double> x1(x); CHECK(SVD(x1,U,S,VT)); x1=U*zzz::Diag(S)*VT; for (zzz::zuint r=0; r<x.Size(0); r++) for (zzz::zuint c=0; c<x.Size(1); c++) CHECK_CLOSE(x(r,c),x1(r,c),zzz::EPSILON); } TEST(DET) { zzz::zMatrix<double> x(3,3); x(0,0)=1; x(0,1)=2; x(0,2)=3; x(1,0)=3; x(1,1)=2; x(1,2)=1; x(2,0)=3; x(2,1)=1; x(2,2)=2; double d=Det(x); CHECK_CLOSE(-12,d,zzz::EPSILON); } TEST(EIGEN) { zzz::zMatrix<double> x(3,3); x(0,0)=1; x(0,1)=2; x(0,2)=3; x(1,0)=2; x(1,1)=4; x(1,2)=5; x(2,0)=3; x(2,1)=5; x(2,2)=6; zzz::zMatrix<double> eigen; CHECK(EigenSym(x,eigen)); CHECK_CLOSE(0.7370,x(0,0),0.0001); CHECK_CLOSE(0.5910,x(0,1),0.0001); CHECK_CLOSE(0.3280,x(0,2),0.0001); CHECK_CLOSE(0.3280,x(1,0),0.0001); CHECK_CLOSE(-0.7370,x(1,1),0.0001); CHECK_CLOSE(0.5910,x(1,2),0.0001); CHECK_CLOSE(-0.5910,x(2,0),0.0001); CHECK_CLOSE(0.3280,x(2,1),0.0001); CHECK_CLOSE(0.7370,x(2,2),0.0001); CHECK_CLOSE(-0.5157,eigen[0],0.0001); CHECK_CLOSE(0.1709,eigen[1],0.0001); CHECK_CLOSE(11.3448,eigen[2],0.0001); } } #endif // ZZZ_LIB_LAPACK
zzz-engine
EngineTest/MathTest/zMatrixMathTest.cpp
C++
gpl3
3,165
#include <UnitTest++.h> #include <Utility/RecordFile.hpp> #include <Math/Vector3.hpp> #include <Math/Vector2.hpp> #include <Math/Array1.hpp> using namespace zzz; SUITE(RecordFileTest) { TEST(WriteAndRead) { int x=123; float y=456; Vector3d z(1,2,3); vector<Vector2i> w; w.push_back(Vector2i(2,3)); w.push_back(Vector2i(22,33)); const zint32 RF_X=1; const zint32 RF_Y=2; const zint32 RF_Z=3; const zint32 RF_W=4; const zint32 RF_MYDATA=5; const zint32 RF_MYDATA_POS=1; const zint32 RF_MYDATA_COLOR=2; const zint32 RF_ARR=6; struct MyData { Vector3f pos_; Vector3uc color_; }my_data; my_data.pos_=Vector3f(1,2,3); my_data.color_=Vector3uc(128,255,0); Array<1,double> arr(10); for (zuint i=0; i<10; i++) arr[i]=i*2; RecordFile rf; rf.SaveFileBegin("recordtest.rf"); IOObject<int>::WriteFileR(rf, RF_X, x); IOObject<float>::WriteFileR(rf, RF_Y, y); IOObject<Vector3d>::WriteFileR(rf, RF_Z, z); IOObject<vector<Vector2i>>::WriteFileR(rf, RF_W, w); rf.WriteChildBegin(RF_MYDATA); IOObject<Vector3f>::WriteFileR(rf, RF_MYDATA_POS, my_data.pos_); IOObject<Vector3uc>::WriteFileR(rf, RF_MYDATA_COLOR, my_data.color_); rf.WriteChildEnd(); IOObject<Array<1,double> >::WriteFileR(rf, RF_ARR, arr); rf.SaveFileEnd(); rf.LoadFileBegin("recordtest.rf"); int rx; float ry; Vector3d rz; vector<Vector2i> rw; MyData rmy_data; Array<1,double> rarr; IOObject<vector<Vector2i>>::ReadFileR(rf, RF_W, rw); IOObject<int>::ReadFileR(rf, RF_X, rx); IOObject<Vector3d>::ReadFileR(rf, RF_Z, rz); IOObject<float>::ReadFileR(rf, RF_Y, ry); rf.ReadChildBegin(RF_MYDATA); IOObject<Vector3f>::ReadFileR(rf, RF_MYDATA_POS, rmy_data.pos_); IOObject<Vector3uc>::ReadFileR(rf, RF_MYDATA_COLOR, rmy_data.color_); rf.ReadChildEnd(); IOObject<Array<1,double> >::ReadFileR(rf, RF_ARR, rarr); int tmp; IOObject<int>::ReadFileR(rf, 99999, tmp); rf.LoadFileEnd(); CHECK_EQUAL(x,rx); CHECK_EQUAL(y,ry); CHECK_EQUAL(z,rz); CHECK_EQUAL(w.size(), rw.size()); for (zuint i=0; i<w.size(); i++) CHECK_EQUAL(w[i], rw[i]); CHECK_EQUAL(my_data.pos_, rmy_data.pos_); CHECK_EQUAL(my_data.color_, rmy_data.color_); for (zuint i=0; i<w.size(); i++) CHECK_EQUAL(w[i], rw[i]); } TEST(RepeatReadAndWrite) { struct MyData{ int x; float y; }; vector<MyData> data; const zint32 RF_DATA=1; const zint32 RF_DATA_SIZE=1; const zint32 RF_DATA_MYDATA=2; const zint32 RF_DATA_MYDATA_X=1; const zint32 RF_DATA_MYDATA_Y=2; const zint32 RF_ANOTHER=2; double another = C_PI; for (zuint i=0; i<10; i++) { data.push_back(MyData()); data.back().x=i; data.back().y=i*2.5f; } RecordFile rf; rf.SaveFileBegin("recordtest2.rf"); rf.WriteChildBegin(RF_DATA); IOObject<zuint>::WriteFileR(rf, RF_DATA_SIZE, data.size()); rf.WriteRepeatBegin(RF_DATA_MYDATA); for (zuint i=0; i<data.size(); i++) { rf.WriteRepeatChild(); IOObject<int>::WriteFileR(rf, RF_DATA_MYDATA_X, data[i].x); IOObject<float>::WriteFileR(rf, RF_DATA_MYDATA_Y, data[i].y); } rf.WriteRepeatEnd(); rf.WriteChildEnd(); IOObject<double>::WriteFileR(rf, RF_ANOTHER, another); rf.SaveFileEnd(); vector<MyData> rdata; double ranother; rf.LoadFileBegin("recordtest2.rf"); IOObject<double>::ReadFileR(rf, RF_ANOTHER, ranother); CHECK_EQUAL(another, ranother); zuint tmp; rf.ReadChildBegin(RF_DATA); IOObject<zuint>::ReadFileR(rf, RF_DATA_SIZE, tmp); CHECK_EQUAL(data.size(), tmp); rf.ReadRepeatBegin(RF_DATA_MYDATA); while(rf.ReadRepeatChild()) { int x; float y; IOObject<int>::ReadFileR(rf, RF_DATA_MYDATA_X, x); IOObject<float>::ReadFileR(rf, RF_DATA_MYDATA_Y, y); rdata.push_back(MyData()); rdata.back().x = x; rdata.back().y = y; CHECK_EQUAL(data[rdata.size()-1].x, rdata.back().x); CHECK_EQUAL(data[rdata.size()-1].y, rdata.back().y); } rf.ReadRepeatEnd(); CHECK_EQUAL(data.size(), rdata.size()); rf.ReadChildEnd(); rf.LoadFileEnd(); } }
zzz-engine
EngineTest/MathTest/RecordFileTest.cpp
C++
gpl3
4,488
#include <UnitTest++.h> #include <XML/XML.hpp> #ifdef ZZZ_LIB_TINYXML using namespace zzz; /* <?xml version="1.0" ?> <MyApp> <Messages> <Welcome>Welcome to MyApp</Welcome> <Farewell>Thank you for using MyApp</Farewell> </Messages> <Windows> <Window name="MainFrame" x="5" y="15" w="400" h="250" /> </Windows> <Connection ip="192.168.0.1" timeout="123.456000" /> </MyApp> */ SUITE(XMLTest) { TEST(XMLWrite) { XML xml; //write XMLNode head=xml.AppendNode("MyApp"); XMLNode messages=head.AppendNode("Messages"); XMLNode welcome=messages.AppendNode("Welcome"); welcome<<"Welcome to MyApp"; XMLNode farewell=messages.AppendNode("Farewell"); farewell.SetText("Thank you for using MyApp"); XMLNode windows=head.AppendNode("Windows"); XMLNode window=windows.AppendNode("Window"); window<<make_pair("name","MainFrame"); window<<make_pair("x",5); window<<make_pair("y",15); window<<make_pair("w","400"); window<<make_pair("h","250"); XMLNode connection=head.AppendNode("Connection"); connection.SetAttribute("ip","192.168.0.1"); connection.SetAttribute("timeout","123.456000"); xml.SaveFile("test.xml"); } TEST(XMLRead) { //read XML xml; xml.LoadFile("test.xml"); CHECK_EQUAL(1,xml.NodeNumber()); XMLNode rhead=xml.GetNode("MyApp"); CHECK(rhead.IsValid()); CHECK_EQUAL(3,rhead.NodeNumber()); XMLNode rmessages=rhead.GetNode((zuint)0); CHECK(rmessages.IsValid()); CHECK_EQUAL(2,rmessages.NodeNumber()); XMLNode rwelcome=rmessages.GetNode("Welcome"); CHECK(rwelcome.IsValid()); CHECK(strcmp(rwelcome.GetText(),"Welcome to MyApp")==0); string str(rmessages.GetNode("Farewell").GetText()); CHECK(str=="Thank you for using MyApp"); XMLNode rwindows=rhead.GetNode("Windows"); CHECK(rwindows.IsValid()); XMLNode rwindow=rwindows.GetNode((zuint)0); CHECK(rwindow.IsValid()); CHECK(strcmp(rwindow.GetAttribute("name"),"MainFrame")==0); CHECK_EQUAL(5,FromString<int>(rwindow.GetAttribute("x"))); CHECK_EQUAL(15,FromString<int>(rwindow.GetAttribute("y"))); CHECK_EQUAL(400,FromString<int>(rwindow.GetAttribute("w"))); CHECK_EQUAL(250,FromString<int>(rwindow.GetAttribute("h"))); XMLNode rconnection=rhead.GetNode("Connection"); CHECK(rconnection.IsValid()); CHECK(strcmp(rconnection.GetAttribute("ip"),"192.168.0.1")==0); CHECK_EQUAL(123.456,FromString<double>(rconnection.GetAttribute("timeout"))); CHECK(!rhead.HasNode("not exist")); } } #endif // ZZZ_LIB_TINYXML
zzz-engine
EngineTest/MathTest/XMLTest.cpp
C++
gpl3
2,656
#include <Math/Math.hpp> #include <Math/Random.hpp> #include <UnitTest++.h> using namespace zzz; SUITE(MATHTEST) { TEST(IsNaNTest) { double c=0; double a=1.0/c; float b=1.0f/c; CHECK(IsInf(a)); CHECK(IsInf(b)); CHECK(!IsInf(c)); CHECK(IsNaN(a-b)); CHECK(IsBad(a)); CHECK(IsBad(b-a)); } TEST(StaticIntPow) { const int r=StaticPow<2,3>::RESULT; CHECK_EQUAL(8,r); } TEST(MagicSqrt) { RandomReal<float> r(0,999999); for (int i=0; i<10; i++) { float x=r.Rand(); float root0=Sqrt(x); float root1=MagicSqrt(x); CHECK_CLOSE(root0,root1,x/1000000.0f); CHECK_CLOSE(1.0f/root0,MagicInvSqrt(x),x/1000000.0f); CHECK_CLOSE(1.0f/root0,MagicInvSqrt2(x),x/1000000.0f); } } }
zzz-engine
EngineTest/MathTest/MathTest.cpp
C++
gpl3
813
#include <UnitTest++.h> #include <Math/Random.hpp> #include <Math/Statistics.hpp> using namespace zzz; SUITE(RandTest) { TEST(CommonRandomTest) { RandomLCG r; zuint last=0; for (zuint i=0; i<100; i++) { CHECK(last!=r.Rand()); last=r.Rand(); } r.Seed(TimeSeed()); for (zuint i=0; i<100; i++) { CHECK(last!=r.Rand()); last=r.Rand(); } RandomLFSRMix r2; for (zuint i=0; i<100; i++) { CHECK(last!=r2.Rand()); last=r.Rand(); } r.Seed(TimeSeed()); for (zuint i=0; i<100; i++) { CHECK(last!=r2.Rand()); last=r.Rand(); } RandomReal<double> r3(0.0,9.9); for (zuint i=0; i<100; i++) { double x=r3.Rand(); CHECK(x>=0.0 && x<=9.9); } RandomInteger<long> r4(54321,987654321); for (zuint i=0; i<100; i++) { long x=r4.Rand(); CHECK(x>=54321 && x<=987654321); } } TEST(SphereRandomTest) { RandomSphere<double> r; for (zuint i=0; i<100; i++) { Vector3d x=r.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } } TEST(HyperSphereRandomTest) { //2d RandomHyperSphere<2,double> r; for (zuint i=0; i<100; i++) { Vector<2,double> x=r.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //3d RandomHyperSphere<3,double> r2; for (zuint i=0; i<100; i++) { Vector<3,double> x=r2.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //8d RandomHyperSphere<8,double> r3; for (zuint i=0; i<100; i++) { Vector<8,double> x=r3.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //rand on dim for (zuint i=0; i<100; i++) { Vector<8,double> x=r3.RandOnDim(3); CHECK_CLOSE(1.0,x.Len(),EPSILON); for (zuint j=3; j<8; j++) CHECK_EQUAL(0,x[j]); } } TEST(HyperSphereRandom2Test) { //2d RandomHyperSphere2<2,double> r; for (zuint i=0; i<100; i++) { Vector<2,double> x=r.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //3d RandomHyperSphere2<3,double> r2; for (zuint i=0; i<100; i++) { Vector<3,double> x=r2.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //8d RandomHyperSphere2<8,double> r3; for (zuint i=0; i<100; i++) { Vector<8,double> x=r3.Rand(); CHECK_CLOSE(1.0,x.Len(),EPSILON); } //rand on dim for (zuint i=0; i<100; i++) { Vector<8,double> x=r3.RandOnDim(3); CHECK_CLOSE(1.0,x.Len(),EPSILON); for (zuint j=3; j<8; j++) CHECK_EQUAL(0,x[j]); } } TEST(RandStatisticsTest) { RandomReal<double> r(0.0,1.0); vector<double> sample; sample.reserve(1000000); for(int i=0; i<1000000; i++) sample.push_back(r.Rand()); CHECK_CLOSE(500000.0/1000001.0,Mean(sample),0.001); } TEST(RandomNormalTest) { RandomNormal<double> r(0.0,1.0); vector<double> sample; sample.reserve(1000000); for(int i=0; i<1000000; i++) sample.push_back(r.Rand()); CHECK_CLOSE(0.0,Mean(sample),0.01); CHECK_CLOSE(1.0,Variance(sample),0.01); } }
zzz-engine
EngineTest/MathTest/RandTest.cpp
C++
gpl3
3,241
FILE(GLOB_RECURSE ExeSrc *.cpp) #MESSAGE(STATUS "files ${ExeSrc}") SET(THISEXE MathTest) FILE(GLOB TestSrc "src/tests/*.cpp") IF( "${DEBUG_MODE}" EQUAL "1") SET(THISEXE ${THISEXE}D) ENDIF() IF( "${BIT_MODE}" EQUAL "64" ) SET(THISEXE ${THISEXE}_X64) ENDIF() ADD_EXECUTABLE(${THISEXE} ${ExeSrc}) TARGET_LINK_LIBRARIES(${THISEXE} ${THISLIB}) TARGET_LINK_LIBRARIES(${THISEXE} zCore zGraphics zMatrix zVision zImage UnitTestPP)
zzz-engine
EngineTest/MathTest/CMakeLists.txt
CMake
gpl3
440
#include <UnitTest++.h> #include <Math/Vector2.hpp> #include <Math/Vector3.hpp> #include <SfM/CoordNormalizer.hpp> using namespace zzz; SUITE(SfMTest) { TEST(CoordNormalizerTest) { CoordNormalizer normalizer(Vector2ui(432,345)); Vector2f ori(11,43); Vector2f nor(ori); normalizer.Normalize(nor); Vector2d nor2d(normalizer.GetT()*Vector3d(ori[0],ori[1],1.0)); Vector2f nor2(nor2d); CHECK_EQUAL(nor,nor2); normalizer.Restore(nor); CHECK_CLOSE(ori[0],nor[0],0.00001); CHECK_CLOSE(ori[1],nor[1],0.00001); } }
zzz-engine
EngineTest/MathTest/SfMTest.cpp
C++
gpl3
572
#include <UnitTest++.h> #include <Utility/TextProgress.hpp> #include <Utility/Timer.hpp> #include <Math/Vector3.hpp> #include <Utility/Tools.hpp> #include <Math/Vector4.hpp> using namespace zzz; using namespace std; SUITE(TOOLSTEST) { TEST(TEXTPROGRESS) { // TextProgress tp("Text Progress %s->%b %n = %p",122,0); // tp.ShowProgressBegin(); // for (int i=0; i<123; i++) // { // tp.ShowProgress(i); // } // tp.ShowProgressEnd(); } TEST(TimerTest) { Timer t; int n=0; t.Sleep(100); double thistime=t.Elapsed(); t.Pause(); t.Sleep(100); CHECK_EQUAL(thistime,t.Elapsed()); t.Resume(); t.Sleep(100); CHECK(thistime<t.Elapsed()); } TEST(SafeEqualTest) { Vector3f a(1,2,3), b(1,2,3), c(1,3,2); CHECK(SafeEqual(a.begin(),a.end(), b.begin(),b.end())); CHECK(!SafeEqual(a.begin(),a.end(), c.begin(),c.end())); Vector4f d(1,2,3,4); CHECK(SafeEqual(a.begin(),a.end(), d.begin(),d.end())); CHECK(!SafeEqual(d.begin(),d.end(), a.begin(),a.end())); } TEST(BitTest) { int BIT1=1; int BIT2=1<<2; int BIT3=1<<10; int a = BIT2; SetBit(a, BIT1); CHECK_EQUAL(BIT1+BIT2,a); CHECK(CheckBit(a, BIT1)); CHECK(CheckBit(a, BIT2)); CHECK(!CheckBit(a, BIT3)); ClearBit(a, BIT2); CHECK(!CheckBit(a, BIT2)); } }
zzz-engine
EngineTest/MathTest/ToolsTest.cpp
C++
gpl3
1,410
#include <zMat.hpp> #include <UnitTest++.h> using namespace zzz; SUITE(zSparseMatrixTest) { TEST(SetAndGet) { zSparseMatrix<double> mat(1000,1000); CHECK_EQUAL(1000, mat.Size(0)); CHECK_EQUAL(1000, mat.Size(1)); CHECK(!mat.CheckExist(10,100)); CHECK_EQUAL(0, mat(10,100)); mat.AddData(10,100,1); CHECK(mat.CheckExist(10,100)); CHECK_EQUAL(1, mat(10,100)); mat.MustGet(100,100)=2; CHECK_EQUAL(2, mat(100,100)); CHECK_EQUAL(2, mat.DataSize()); } TEST(AssignFromMatrix) { zMatrix<double> mat(Zerosd(100,100)); mat(50,50)=10; mat(40,60)=20; zSparseMatrix<double> smat(mat); CHECK_EQUAL(2, smat.DataSize()); CHECK_EQUAL(10, smat(50,50)); CHECK_EQUAL(20, smat(40,60)); } TEST(ATA) { zMatrix<double> a(Zerosd(4,4)); // 1 2 0 4 // 3 0 3 0 // 0 0 1 2 a(0,0)=1; a(0,1)=2; a(0,3)=4; a(1,0)=3; a(1,2)=3; a(2,2)=1; a(2,3)=2; zMatrix<double> ata(Trans(a)*a); zSparseMatrix<double> sa(a); zMatrix<double> sata(Trans(sa)*sa); zSparseMatrix<double> ssata(ATA(sa)); CHECK_EQUAL(14, ssata.DataSize()); CHECK(ata==sata); CHECK(sata==ssata); CHECK(Trans(ssata)==ssata); } }
zzz-engine
EngineTest/MathTest/zSparseMatrixTest.cpp
C++
gpl3
1,281
#include <Math/Matrix2x2.hpp> #include <Math/Matrix3x3.hpp> #include <Math/Matrix4x4.hpp> #include <Math/Math.hpp> #include <UnitTest++.h> SUITE(MatrixTest) { //matrix class is not complete yet }
zzz-engine
EngineTest/MathTest/MatrixTest.cpp
C++
gpl3
198
#include <UnitTest++.h> #include <Utility/StringTools.hpp> #include <Math/Vector3.hpp> using namespace zzz; SUITE(StringTest) { TEST(StringConvertTest) { CHECK_EQUAL("123",ToString(123)); CHECK_EQUAL("123.456",ToString(123.456)); CHECK_EQUAL("123 456 789 ",ToString(Vector3i(123,456,789))); CHECK_EQUAL(123,FromString<int>(string("123"))); CHECK_EQUAL(123.456,FromString<double>(string("123.456"))); CHECK_EQUAL(Vector3i(123,456,789),FromString<Vector3i>(string("123 456 789"))); CHECK_EQUAL(123,FromString<int>("123")); CHECK_EQUAL(123.456,FromString<double>("123.456")); CHECK_EQUAL(Vector3i(123,456,789),FromString<Vector3i>("123 456 789")); } TEST(Base64) { string str="Welcome to zzzEngine"; string code; Base64Encode(str.c_str(),str.size(),code); CHECK(code=="V2VsY29tZSB0byB6enpFbmdpbmU="); char *data=new char[code.size()]; data[Base64Decode(code,data,code.size())]='\0'; CHECK(str==data); delete[] data; } TEST(StringOperatorTest) { string x; x<<"abc"; CHECK(x=="abc"); int a=1; x<<a; CHECK(x=="abc1"); x<<" "<<':'<<1234<<" "<<1.1234<<'\n'; CHECK(x=="abc1 :1234 1.1234\n"); } TEST(StringReplacementTest) { CHECK_EQUAL(string("This is not a test!"),Replace("This is a test!"," is "," is not ")); } TEST(TrimTest) { string test = "\t \t \nxyz\r\t "; CHECK_EQUAL(string("xyz"), Trim(test)); } }
zzz-engine
EngineTest/MathTest/StringTest.cpp
C++
gpl3
1,515
#include <zMat.hpp> #include <Math/Vector3.hpp> #include <Math/Matrix3x3.hpp> #include <UnitTest++.h> using namespace zzz; SUITE(zMatrixDressTest) { TEST(VectorDress) { Vector3f a(1,2,3),b(4,5,6); CHECK_EQUAL(1,Dress(a)(0,0)); CHECK_EQUAL(2,Dress(a)(1,0)); CHECK_EQUAL(3,Dress(a)(2,0)); Dress(a)=Dress(b); CHECK_ARRAY_EQUAL(b.Data(),a.Data(),3); const Vector3f &c=b; Dress(a)=Dress(c)(Colon(2,0,-1)); CHECK_EQUAL(6,a[0]); CHECK_EQUAL(5,a[1]); CHECK_EQUAL(4,a[2]); } TEST(MatrixDress) { Matrix3x3f a(1,2,3,4,5,6,7,8,9),b(10,11,12,13,14,15,16,17,18); CHECK_EQUAL(1,Dress(a)(0,0)); CHECK_EQUAL(5,Dress(a)(1,1)); CHECK_EQUAL(9,Dress(a)(2,2)); Dress(a)=Dress(b); Dress(a)=Dress(b)(Colon(),Colon()); CHECK_ARRAY_EQUAL(b.Data(),a.Data(),9); const Matrix3x3f &c=b; Dress(a)=Dress(c)(Colon(2,0,-1),Colon()); CHECK_ARRAY_EQUAL(b.Data()+6,a.Data(),3); CHECK_ARRAY_EQUAL(b.Data()+3,a.Data()+3,3); CHECK_ARRAY_EQUAL(b.Data(),a.Data()+6,3); } #ifdef ZZZ_LIB_LAPACK TEST(UsezMatrixToCalculate) { Matrix3x3d a(1,2,4,2,3,4,5,3,1); Matrix3x3d U,VT,b; Vector3d S; zMatrix<double> za,zu,zvt,zs; za=Dress(a); CHECK(SVD(za,zu,zs,zvt)); Dress(U)=zu; Dress(VT)=zvt; Dress(S)=zs; Dress(b)=Dress(U)*Diag(Dress(S))*Dress(VT); CHECK_ARRAY_CLOSE(a.Data(),b.Data(),9,EPSILON); } #endif TEST(ArrayDress) { Array<2,double> v; Dress(v)=Ones<double>(10,10); CHECK_EQUAL(10,v.Size(0)); CHECK_EQUAL(10,v.Size(1)); for (zuint i=0; i<v.size(); i++) CHECK_EQUAL(1,v[i]); } TEST(CastDress) { zMatrix<double> a(Ones<double>(10,10)),b(Colond(0.0,0.9+EPSILON,0.1)); a(Cast<int>(b*10.0),0)=Zeros<double>(10,1); for (zuint i=0; i<10; i++) CHECK_EQUAL(0,a(i,0)); } TEST(StdVectorDress) { vector<int> x; Dress(x)=Colon(5,10); for (zuint i=0; i<x.size(); i++) CHECK_EQUAL(x[i], i+5); } }
zzz-engine
EngineTest/MathTest/zMatrixDressTest.cpp
C++
gpl3
2,056
#include <UnitTest++.h> #include <iostream> #include <iomanip> #include <cassert> #include <3rdParty/EXIF.hpp> using namespace std; // using namespace zzz; SUITE(EXIFTest) { TEST(Exiv2Print) { // const string &filename="d:/data/stereo/room1.jpg"; // Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(filename); // assert(image.get() != 0); // image->readMetadata(); // Exiv2::ExifData &exifData = image->exifData(); // if (exifData.empty()) // { // std::string error(filename); // error += ": No Exif data found in the file"; // cerr<<error<<endl; // } // else // { // Exiv2::ExifData::const_iterator end = exifData.end(); // for (Exiv2::ExifData::const_iterator i = exifData.begin(); i != end; ++i) // { // const string & tn = i->typeName(); // std::cout << std::setw(44) << std::setfill(' ') << std::left // << i->key() << " " // << "0x" << std::setw(4) << std::setfill('0') << std::right // << std::hex << i->tag() << " " // << std::setw(9) << std::setfill(' ') << std::left // << (tn ? tn : "Unknown") << " " // << std::dec << std::setw(3) // << std::setfill(' ') << std::right // << i->count() << " " // << std::dec << i->value() // << "\n"; // } // } } TEST(Exiv2Test) { // EXIF exif("d:/data/stereo/room1.jpg"); // vector<EXIF::EXIFInfo> info; // exif.GetAllEXIF(info); // for (zuint i=0; i<info.size(); i++) // cout<<info[i].key<<" : "<<info[i].value<<endl; // cout<<exif.CCDSize()<<endl; } }
zzz-engine
EngineTest/MathTest/EXIFTest.cpp
C++
gpl3
1,708
#include <Math/Matrix2x2.hpp> #include <Math/Statistics.hpp> #include <UnitTest++.h> using namespace zzz; SUITE(StatisticsTest) { TEST(PCA) { vector<Vector2d> data; data.push_back(Vector2d(2.5, 2.4)); data.push_back(Vector2d(0.5, 0.7)); data.push_back(Vector2d(2.2, 2.9)); data.push_back(Vector2d(1.9, 2.2)); data.push_back(Vector2d(3.1, 3.0)); data.push_back(Vector2d(2.3, 2.7)); data.push_back(Vector2d(2.0, 1.6)); data.push_back(Vector2d(1.0, 1.1)); data.push_back(Vector2d(1.5, 1.6)); data.push_back(Vector2d(1.1, 0.9)); Matrix2x2d cov; Covariance(data, cov); CHECK_EQUAL(cov(0,1),cov(1,0)); CHECK_CLOSE(0.616555556,cov(0,0),EPSILON); CHECK_CLOSE(0.615444444,cov(0,1),EPSILON); CHECK_CLOSE(0.716555556,cov(1,1),EPSILON); Vector2d evalue; Matrix<2,2,double> evector; PCA(data,evector,evalue); CHECK_CLOSE(1.28402771,evalue[0],EPSILON); CHECK_CLOSE(0.0490833989,evalue[1],EPSILON); } }
zzz-engine
EngineTest/MathTest/StatisticsTest.cpp
C++
gpl3
1,020
#include <UnitTest++.h> #include <Math/Vector3.hpp> using namespace zzz; SUITE(BasicCppTest) { TEST(SizeofTest) { int x[10]={}; CHECK_EQUAL(10, sizeof(x)/sizeof(x[0])); Vector3uc y[20]={}; CHECK_EQUAL(20, sizeof(y)/sizeof(y[0])); int z[]={1,2,3}; CHECK_EQUAL(3, sizeof(z)/sizeof(z[0])); } }
zzz-engine
EngineTest/MathTest/BasicCppSupport.cpp
C++
gpl3
323
#include <UnitTest++.h> #include <Utility/BraceFile.hpp> #include <Utility/BraceNode.hpp> using namespace zzz; /* This is the first line MyApp { Messages msg1{ Welcome to MyApp Thank you for using MyApp } Window {name MainFrame pos [5 15] size [400,250]} Connection{ ip "192. 168. 0.1" timeout 123.456000} } */ SUITE(BraceFileTest) { TEST(BraceWrite) { BraceFile bf("{}[]"); //write BraceNode head=bf.AppendNode("MyApp",'{','}'); BraceNode messages=head.AppendNode("Messages",'{','}'); BraceNode welcome=messages.AppendNode("Welcome to MyApp"); messages<<"Thank you for using MyApp"; BraceNode window=head.AppendNode("Window",'{','}'); window<<"name MainFrame"; window.AppendNode("pos",'[',']')<<"5 15"; window.AppendNode("size",'[',']')<<"400,250"; BraceNode connection=head.AppendNode("Connection",'{','}'); connection.AppendNode("ip \"192.168.0.1\""); connection.AppendNode("timeout 123.456000"); } }
zzz-engine
EngineTest/MathTest/BraceFileTest.cpp
C++
gpl3
1,034
#include <UnitTest++.h> #include <Utility/Any.hpp> #include <Utility/AnyStack.hpp> using namespace zzz; SUITE(AnyTest) { TEST(Store) { int a=5; double b=10; char c='a'; string x("abcde"); Any av=a; Any ap=&a; Any bv=b; Any bp=&b; Any cv=c; Any cp=&c; Any xv=x; Any xp=&x; CHECK_EQUAL(a,any_cast<int>(av)); CHECK_EQUAL(&a,any_cast<int*>(ap)); CHECK_EQUAL(b,any_cast<double>(bv)); CHECK_EQUAL(&b,any_cast<double*>(bp)); CHECK_EQUAL(c,any_cast<char>(cv)); CHECK_EQUAL(&c,any_cast<char*>(cp)); CHECK_EQUAL(x,any_cast<string>(xv)); CHECK_EQUAL(&x,any_cast<string*>(xp)); } TEST(GlobalStackTest) { int a=5, a2; double b=10, b2; char c='a', c2; string x("abcde"), x2; int ori_size = ZGS.Size(); ZGS.Push(a); ZGS.Push(b); ZGS.Push(c); ZGS.Push(x); CHECK_EQUAL(ori_size+4, ZGS.Size()); ZGS.Pop(x2); ZGS.Pop(c2); ZGS.Pop(b2); ZGS.Pop(a2); CHECK_EQUAL(a, a2); CHECK_EQUAL(b, b2); CHECK_EQUAL(c, c2); CHECK_EQUAL(x, x2); CHECK_EQUAL(ori_size, ZGS.Size()); } }
zzz-engine
EngineTest/MathTest/AnyTest.cpp
C++
gpl3
1,117
#include <UnitTest++.h> #include <Math/Matrix.hpp> #include <Math/Random.hpp> #include <Algorithm/GramSchmidt.hpp> #include <GraphicsAlgo/RotationMatrix.hpp> using namespace zzz; SUITE(RotationMatrixTest) { TEST(GramSchmidtTest) { Matrix<8,8,double> mat,mat2; RandomReal<double> r; for (int i=0; i<64; i++) mat[i]=r.Rand(); GramSchmidt<double>::Process(mat,mat2); for (int i=0; i<8; i++) for (int j=i; j<8; j++) { if (i==j) CHECK_CLOSE(1,FastDot(mat2.Row(i),mat2.Row(j)),EPSILON); else CHECK_CLOSE(0,FastDot(mat2.Row(i),mat2.Row(j)),EPSILON); } } TEST(QRDecompositionTest) { Matrix<8,8,double> mat; RandomReal<double> r; for (int i=0; i<64; i++) mat[i]=r.Rand(); Matrix<8,8,double> Q,R; GramSchmidt<double>::QRDecomposition(mat,Q,R); CHECK(mat.DistTo(Q*R)<EPSILON); } template<int D> void CheckRotationMatrix(const Vector<D,double> &from, const Vector<D,double> &to) { Vector<D,double> to2(to); Matrix<D,D,double> rot=GetRotationBetweenVectors(from,to); to2=rot*from; for (zuint i=0; i<D; i++) CHECK_CLOSE(to[i],to2[i],EPSILON); for (zuint i=0; i<D; i++) CHECK_CLOSE(1.0,rot.Row(i).Len(),EPSILON); for (zuint i=0; i<D; i++) for (zuint j=0; j<i; j++) if (i==j) CHECK_CLOSE(1.0,FastDot(rot.Row(i),rot.Row(j)),EPSILON); else CHECK_CLOSE(0.0,FastDot(rot.Row(i),rot.Row(j)),EPSILON); } TEST(NDRotationMatrixTest) { #define DIM (8) RandomReal<double> r; Vector<DIM,double> from,to,to2; for (zuint i=0; i<DIM; i++) { from[i]=r.Rand(); to[i]=r.Rand(); } from[0]=0; from.Normalize(); to[0]=0; to[1]=0; to.Normalize(); CheckRotationMatrix<DIM>(from,to); to=from; CheckRotationMatrix<DIM>(from,to); to=-from; CheckRotationMatrix<DIM>(from,to); } TEST(2DRotationMatrixTest) { Vector2d from(1,1),to(1,-1); from.Normalize(); to.Normalize(); CheckRotationMatrix<2>(from,to); } TEST(3DRotationMatrixTest) { Vector3d from(1,1,0),to(1,-1,0); from.Normalize(); to.Normalize(); CheckRotationMatrix<3>(from,to); } }
zzz-engine
EngineTest/MathTest/RotationMatrixTest.cpp
C++
gpl3
2,279