diff --git a/.travis.yml b/.travis.yml index 44afb8c..a0129a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,11 +4,12 @@ services: jobs: include: - stage: run tests - dart: dev + dart: stable script: - export PATH=$PATH:"~/.pub-cache/bin" - pub get - pub global activate coverage + - dartfmt -n --set-exit-if-changed . - dartanalyzer --fatal-warnings --fatal-hints --fatal-lints ./ - cd test - bash run.sh diff --git a/example/hello/receive.dart b/example/hello/receive.dart index d1ba0b9..80e2407 100644 --- a/example/hello/receive.dart +++ b/example/hello/receive.dart @@ -2,7 +2,7 @@ import "dart:io"; import "package:dart_amqp/dart_amqp.dart"; void main() { - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -12,13 +12,13 @@ void main() { }); client - .channel() - .then((Channel channel) => channel.queue("hello")) - .then((Queue queue) => queue.consume()) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("hello")) + .then((Queue queue) => queue.consume()) + .then((Consumer consumer) { print(" [*] Waiting for messages. To exit, press CTRL+C"); consumer.listen((AmqpMessage message) { print(" [x] Received ${message.payloadAsString}"); }); }); -} \ No newline at end of file +} diff --git a/example/hello/send.dart b/example/hello/send.dart index 78ae666..4233ef0 100644 --- a/example/hello/send.dart +++ b/example/hello/send.dart @@ -1,13 +1,13 @@ import "package:dart_amqp/dart_amqp.dart"; -void main(){ - Client client = new Client(); +void main() { + Client client = Client(); client - .channel() - .then((Channel channel) => channel.queue("hello")) - .then((Queue queue){ - queue.publish("Hello World!"); - print(" [x] Sent 'Hello World!'"); - return client.close(); + .channel() + .then((Channel channel) => channel.queue("hello")) + .then((Queue queue) { + queue.publish("Hello World!"); + print(" [x] Sent 'Hello World!'"); + return client.close(); }); -} \ No newline at end of file +} diff --git a/example/pubsub/emit_log.dart b/example/pubsub/emit_log.dart index 6f975f6..9b3febc 100644 --- a/example/pubsub/emit_log.dart +++ b/example/pubsub/emit_log.dart @@ -1,15 +1,15 @@ import "package:dart_amqp/dart_amqp.dart"; void main(List args) { - Client client = new Client(); + Client client = Client(); client - .channel() - .then((Channel channel) => channel.exchange("logs", ExchangeType.FANOUT)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => channel.exchange("logs", ExchangeType.FANOUT)) + .then((Exchange exchange) { String message = args.join(' '); // We dont care about the routing key as our exchange type is FANOUT exchange.publish(message, null); print(" [x] Sent ${message}"); return client.close(); }); -} \ No newline at end of file +} diff --git a/example/pubsub/receive_logs.dart b/example/pubsub/receive_logs.dart index 54522c8..f890951 100644 --- a/example/pubsub/receive_logs.dart +++ b/example/pubsub/receive_logs.dart @@ -2,7 +2,7 @@ import "dart:io"; import "package:dart_amqp/dart_amqp.dart"; void main() { - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -12,14 +12,14 @@ void main() { }); client - .channel() - .then((Channel channel) => channel.exchange("logs", ExchangeType.FANOUT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(null)) - .then((Consumer consumer) { - print(" [*] Waiting for logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); + .channel() + .then((Channel channel) => channel.exchange("logs", ExchangeType.FANOUT)) + .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(null)) + .then((Consumer consumer) { + print( + " [*] Waiting for logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); consumer.listen((AmqpMessage message) { print(" [x] ${message.payloadAsString}"); }); }); - -} \ No newline at end of file +} diff --git a/example/routing/emit_log_direct.dart b/example/routing/emit_log_direct.dart index 34d371e..6c7409d 100644 --- a/example/routing/emit_log_direct.dart +++ b/example/routing/emit_log_direct.dart @@ -17,15 +17,16 @@ void main(List args) { String severity = args.first; - Client client = new Client(); + Client client = Client(); client - .channel() - .then((Channel channel) => channel.exchange("direct_logs", ExchangeType.DIRECT)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("direct_logs", ExchangeType.DIRECT)) + .then((Exchange exchange) { String message = args.sublist(1).join(' '); // Use 'severity' as our routing key exchange.publish(message, severity); print(" [x] Sent [${severity}] ${message}"); return client.close(); }); -} \ No newline at end of file +} diff --git a/example/routing/receive_logs_direct.dart b/example/routing/receive_logs_direct.dart index f5fe2c6..be2ac2d 100644 --- a/example/routing/receive_logs_direct.dart +++ b/example/routing/receive_logs_direct.dart @@ -3,7 +3,8 @@ import "package:dart_amqp/dart_amqp.dart"; void main(List args) { if (args.isEmpty || - !args.every((String arg) => ["info", "warning", "error"].indexOf(arg) != -1)) { + !args.every( + (String arg) => ["info", "warning", "error"].indexOf(arg) != -1)) { print(""" Error: invalid arguments. Please invoke as: @@ -19,7 +20,7 @@ void main(List args) { exit(1); } - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -29,14 +30,16 @@ void main(List args) { }); client - .channel() - .then((Channel channel) => channel.exchange("direct_logs", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(args)) - .then((Consumer consumer) { - print(" [*] Waiting for [${args.join(', ')}] logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); + .channel() + .then((Channel channel) => + channel.exchange("direct_logs", ExchangeType.DIRECT)) + .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(args)) + .then((Consumer consumer) { + print( + " [*] Waiting for [${args.join(', ')}] logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); consumer.listen((AmqpMessage message) { - print(" [x] [Exchange: ${message.exchangeName}] [${message.routingKey}] ${message.payloadAsString}"); + print( + " [x] [Exchange: ${message.exchangeName}] [${message.routingKey}] ${message.payloadAsString}"); }); }); - -} \ No newline at end of file +} diff --git a/example/rpc/rpc_client.dart b/example/rpc/rpc_client.dart index 02ab392..cc97b20 100644 --- a/example/rpc/rpc_client.dart +++ b/example/rpc/rpc_client.dart @@ -4,28 +4,28 @@ import "package:dart_amqp/dart_amqp.dart"; class FibonacciRpcClient { int _nextCorrelationId = 1; - final Completer connected = new Completer(); + final Completer connected = Completer(); final Client client; - final Map _pendingOperations = new Map(); + final Map _pendingOperations = Map(); Queue _serverQueue; String _replyQueueName; - FibonacciRpcClient() : client = new Client() { + FibonacciRpcClient() : client = Client() { client - .channel() - .then((Channel channel) => channel.queue("rpc_queue")) - .then((Queue rpcQueue) { - _serverQueue = rpcQueue; + .channel() + .then((Channel channel) => channel.queue("rpc_queue")) + .then((Queue rpcQueue) { + _serverQueue = rpcQueue; - // Allocate a private queue for server responses - return rpcQueue.channel.privateQueue(); - }) - .then((Queue queue) => queue.consume()) - .then((Consumer consumer) { - _replyQueueName = consumer.queue.name; - consumer.listen(handleResponse); - connected.complete(); - }); + // Allocate a private queue for server responses + return rpcQueue.channel.privateQueue(); + }) + .then((Queue queue) => queue.consume()) + .then((Consumer consumer) { + _replyQueueName = consumer.queue.name; + consumer.listen(handleResponse); + connected.complete(); + }); } void handleResponse(AmqpMessage message) { @@ -35,24 +35,23 @@ class FibonacciRpcClient { } _pendingOperations - .remove(message.properties.corellationId) - .complete(int.parse(message.payloadAsString)); + .remove(message.properties.corellationId) + .complete(int.parse(message.payloadAsString)); } Future call(int n) { // Make sure we are connected before sending the request - return connected.future - .then((_) { + return connected.future.then((_) { String uuid = "${_nextCorrelationId++}"; - Completer completer = new Completer(); + Completer completer = Completer(); - MessageProperties properties = new MessageProperties() + MessageProperties properties = MessageProperties() ..replyTo = _replyQueueName ..corellationId = uuid; - _pendingOperations[ uuid ] = completer; + _pendingOperations[uuid] = completer; - _serverQueue.publish({"n" : n}, properties : properties); + _serverQueue.publish({"n": n}, properties: properties); return completer.future; }); @@ -60,7 +59,8 @@ class FibonacciRpcClient { Future close() { // Kill any pending responses - _pendingOperations.forEach((_, Completer completer) => completer.completeError("RPC client shutting down")); + _pendingOperations.forEach((_, Completer completer) => + completer.completeError("RPC client shutting down")); _pendingOperations.clear(); return client.close(); @@ -68,17 +68,16 @@ class FibonacciRpcClient { } main(List args) { - FibonacciRpcClient client = new FibonacciRpcClient(); + FibonacciRpcClient client = FibonacciRpcClient(); - int n = args.isEmpty - ? 30 - : num.parse(args[0]); + int n = args.isEmpty ? 30 : num.parse(args[0]); // Make 10 parallel calls and get fib(1) to fib(10) - client.call(n) - .then((int res) { - print(" [x] fib(${n}) = ${res}"); - }) - .then((_) => client.close()) - .then((_) => exit(0)); -} \ No newline at end of file + client + .call(n) + .then((int res) { + print(" [x] fib(${n}) = ${res}"); + }) + .then((_) => client.close()) + .then((_) => exit(0)); +} diff --git a/example/rpc/rpc_server.dart b/example/rpc/rpc_server.dart index 5891e71..59f2668 100644 --- a/example/rpc/rpc_server.dart +++ b/example/rpc/rpc_server.dart @@ -12,8 +12,7 @@ int fib(int n) { } void main(List args) { - - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -23,11 +22,11 @@ void main(List args) { }); client - .channel() - .then((Channel channel) => channel.qos(0, 1)) - .then((Channel channel) => channel.queue("rpc_queue")) - .then((Queue queue) => queue.consume()) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.qos(0, 1)) + .then((Channel channel) => channel.queue("rpc_queue")) + .then((Queue queue) => queue.consume()) + .then((Consumer consumer) { print(" [x] Awaiting RPC request"); consumer.listen((AmqpMessage message) { int n = message.payloadAsJson["n"]; @@ -35,4 +34,4 @@ void main(List args) { message.reply(fib(n).toString()); }); }); -} \ No newline at end of file +} diff --git a/example/topics/emit_log_topic.dart b/example/topics/emit_log_topic.dart index c515693..663bb9e 100644 --- a/example/topics/emit_log_topic.dart +++ b/example/topics/emit_log_topic.dart @@ -17,15 +17,16 @@ void main(List args) { String routingKey = args.first; - Client client = new Client(); + Client client = Client(); client - .channel() - .then((Channel channel) => channel.exchange("topic_logs", ExchangeType.TOPIC)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("topic_logs", ExchangeType.TOPIC)) + .then((Exchange exchange) { String message = args.sublist(1).join(' '); // Use 'severity' as our routing key exchange.publish(message, routingKey); print(" [x] Sent [${routingKey}] ${message}"); return client.close(); }); -} \ No newline at end of file +} diff --git a/example/topics/receive_logs_topic.dart b/example/topics/receive_logs_topic.dart index 6743879..e1b785d 100644 --- a/example/topics/receive_logs_topic.dart +++ b/example/topics/receive_logs_topic.dart @@ -18,7 +18,7 @@ void main(List args) { exit(1); } - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -28,14 +28,16 @@ void main(List args) { }); client - .channel() - .then((Channel channel) => channel.exchange("topic_logs", ExchangeType.TOPIC)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(args)) - .then((Consumer consumer) { - print(" [*] Waiting for [${args.join(', ')}] logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); + .channel() + .then((Channel channel) => + channel.exchange("topic_logs", ExchangeType.TOPIC)) + .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(args)) + .then((Consumer consumer) { + print( + " [*] Waiting for [${args.join(', ')}] logs on private queue ${consumer.queue.name}. To exit, press CTRL+C"); consumer.listen((AmqpMessage message) { - print(" [x] [Exchange: ${message.exchangeName}] [${message.routingKey}] ${message.payloadAsString}"); + print( + " [x] [Exchange: ${message.exchangeName}] [${message.routingKey}] ${message.payloadAsString}"); }); }); - -} \ No newline at end of file +} diff --git a/example/workers/new_task.dart b/example/workers/new_task.dart index 00544e5..9d087a8 100644 --- a/example/workers/new_task.dart +++ b/example/workers/new_task.dart @@ -1,16 +1,14 @@ import "package:dart_amqp/dart_amqp.dart"; void main(List args) { - Client client = new Client(); + Client client = Client(); client - .channel() - .then((Channel channel) => channel.queue("task_queue", durable : true)) - .then((Queue queue) { - String message = args.length == 0 - ? "Hello World!" - : args.join(" "); - queue.publish(message, properties : new MessageProperties.persistentMessage()); + .channel() + .then((Channel channel) => channel.queue("task_queue", durable: true)) + .then((Queue queue) { + String message = args.length == 0 ? "Hello World!" : args.join(" "); + queue.publish(message, properties: MessageProperties.persistentMessage()); print(" [x] Sent ${message}"); return client.close(); }); -} \ No newline at end of file +} diff --git a/example/workers/worker.dart b/example/workers/worker.dart index 24cb20f..10a54d7 100644 --- a/example/workers/worker.dart +++ b/example/workers/worker.dart @@ -2,7 +2,7 @@ import "dart:io"; import "package:dart_amqp/dart_amqp.dart"; void main() { - Client client = new Client(); + Client client = Client(); // Setup a signal handler to cleanly exit if CTRL+C is pressed ProcessSignal.sigint.watch().listen((_) { @@ -12,22 +12,21 @@ void main() { }); client - .channel() - .then((Channel channel) => channel.qos(0, 1)) - .then((Channel channel) => channel.queue("task_queue", durable: true)) - .then((Queue queue) => queue.consume(noAck : false)) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.qos(0, 1)) + .then((Channel channel) => channel.queue("task_queue", durable: true)) + .then((Queue queue) => queue.consume(noAck: false)) + .then((Consumer consumer) { print(" [*] Waiting for messages. To exit, press CTRL+C"); consumer.listen((AmqpMessage message) { String payload = message.payloadAsString; print(" [x] Received ${payload}"); // Emulate a long task by sleeping 1 second for each '.' character in message - sleep(new Duration(seconds : payload.split(".").length)); + sleep(Duration(seconds: payload.split(".").length)); print(" [x] Done"); // Ack message so it is marked as processed message.ack(); }); }); - -} \ No newline at end of file +} diff --git a/lib/dart_amqp.dart b/lib/dart_amqp.dart index 4bfad5b..1f7371d 100644 --- a/lib/dart_amqp.dart +++ b/lib/dart_amqp.dart @@ -4,4 +4,4 @@ export "src/client.dart"; export "src/enums.dart"; export "src/exceptions.dart"; export "src/authentication.dart"; -export "src/protocol.dart" show MessageProperties; \ No newline at end of file +export "src/protocol.dart" show MessageProperties; diff --git a/lib/src/authentication.dart b/lib/src/authentication.dart index 941cf7e..c2d2965 100644 --- a/lib/src/authentication.dart +++ b/lib/src/authentication.dart @@ -6,4 +6,4 @@ import "protocol.dart"; part "authentication/authenticator.dart"; part "authentication/plain_authenticator.dart"; -part "authentication/amq_plain_authenticator.dart"; \ No newline at end of file +part "authentication/amq_plain_authenticator.dart"; diff --git a/lib/src/authentication/amq_plain_authenticator.dart b/lib/src/authentication/amq_plain_authenticator.dart index 073ba6d..2421970 100644 --- a/lib/src/authentication/amq_plain_authenticator.dart +++ b/lib/src/authentication/amq_plain_authenticator.dart @@ -1,35 +1,24 @@ part of dart_amqp.authentication; class AmqPlainAuthenticator implements Authenticator { - final String userName; final String password; - /** - * Create a new [PlainAuthenticator] with the specified [userName] and [password] - */ + /// Create a new [PlainAuthenticator] with the specified [userName] and [password] const AmqPlainAuthenticator(String this.userName, String this.password); - /** - * Get the class of this authenticator - */ + /// Get the class of this authenticator String get saslType => "AMQPLAIN"; - /** - * Process the [challenge] sent by the server and return a [String] response - */ + /// Process the [challenge] sent by the server and return a [String] response String answerChallenge(String challenge) { // Encode as a able - TypeEncoder encoder = new TypeEncoder(); - encoder.writeFieldTable( - { - "LOGIN" : userName, "PASSWORD" : password - } - ); + TypeEncoder encoder = TypeEncoder(); + encoder.writeFieldTable({"LOGIN": userName, "PASSWORD": password}); // The spec defines the challenge response as a string (with its own length as a prefix). We // need to skip the table length from our response so the length does not get written twice Uint8List res = encoder.writer.joinChunks(); - return new String.fromCharCodes(new Uint8List.view(res.buffer, 4)); + return String.fromCharCodes(Uint8List.view(res.buffer, 4)); } -} \ No newline at end of file +} diff --git a/lib/src/authentication/authenticator.dart b/lib/src/authentication/authenticator.dart index a0074bd..85bad41 100644 --- a/lib/src/authentication/authenticator.dart +++ b/lib/src/authentication/authenticator.dart @@ -1,14 +1,9 @@ part of dart_amqp.authentication; abstract class Authenticator { - /** - * Get the SASL type of this authenticator - */ + /// Get the SASL type of this authenticator String get saslType; - /** - * Process the [challenge] sent by the server and return a [String] response - */ + /// Process the [challenge] sent by the server and return a [String] response String answerChallenge(String challenge); - -} \ No newline at end of file +} diff --git a/lib/src/authentication/plain_authenticator.dart b/lib/src/authentication/plain_authenticator.dart index b89b7e8..63d9767 100644 --- a/lib/src/authentication/plain_authenticator.dart +++ b/lib/src/authentication/plain_authenticator.dart @@ -1,25 +1,18 @@ part of dart_amqp.authentication; class PlainAuthenticator implements Authenticator { - final String userName; final String password; - /** - * Create a new [PlainAuthenticator] with the specified [userName] and [password] - */ + /// Create a new [PlainAuthenticator] with the specified [userName] and [password] const PlainAuthenticator(String this.userName, String this.password); - /** - * Get the class of this authenticator - */ + /// Get the class of this authenticator String get saslType => "PLAIN"; - /** - * Process the [challenge] sent by the server and return a [String] response - */ + /// Process the [challenge] sent by the server and return a [String] response String answerChallenge(String challenge) { - StringBuffer sb = new StringBuffer() + StringBuffer sb = StringBuffer() ..writeCharCode(0) ..write(userName) ..writeCharCode(0) @@ -27,4 +20,4 @@ class PlainAuthenticator implements Authenticator { return sb.toString(); } -} \ No newline at end of file +} diff --git a/lib/src/client/amqp_message.dart b/lib/src/client/amqp_message.dart index a344168..662a844 100644 --- a/lib/src/client/amqp_message.dart +++ b/lib/src/client/amqp_message.dart @@ -1,71 +1,56 @@ part of dart_amqp.client; abstract class AmqpMessage { - /** - * Get the payload as a [Uint8List] - */ + /// Get the payload as a [Uint8List] Uint8List get payload; - /** - * Get the payload as a [String]. This method will pass - * the message [payload] through UTF8.decode and return - * the decoded string. - */ + /// Get the payload as a [String]. This method will pass + /// the message [payload] through UTF8.decode and return + /// the decoded string. String get payloadAsString; - /** - * Get the payload as a [Map]. This method will pass the - * message [payload] through a JSON decoded and return the - * decoded JSON data as a [Map]. - */ + /// Get the payload as a [Map]. This method will pass the + /// message [payload] through a JSON decoded and return the + /// decoded JSON data as a [Map]. Map get payloadAsJson; - /** - * Get the name of the exchange where this message arrived from. The - * method will return null if the message did not arrive through an - * exchange (e.g. posted directly to a queue). - */ + /// Get the name of the exchange where this message arrived from. The + /// method will return null if the message did not arrive through an + /// exchange (e.g. posted directly to a queue). String get exchangeName; - /** - * Get the routing key for this message. The - * method will return null if the message did not arrive through an - * exchange (e.g. posted directly to a queue). - */ + /// Get the routing key for this message. The + /// method will return null if the message did not arrive through an + /// exchange (e.g. posted directly to a queue). String get routingKey; - /** - * Get the [properties] that were included with the message metadata - */ + /// Get the [properties] that were included with the message metadata MessageProperties get properties; - /** - * Acknowledge this message. - */ + /// Acknowledge this message. void ack(); - /** - * Reply to the sender of this message with a new [message]. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. - * If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties - * (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will - * trigger an [ArgumentError]. - * - * You may specify additional message properties by setting the [properties] named parameter. - * - * If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise - * the server will drop un-routable messages. - * - * if the [immediate] flag is set, the server will immediately return undeliverable messages to the client - * if it cannot route them. If the flag is set to false, the server will queue the message even though - * there is no guarantee that it will ever be consumed. - */ - void reply(Object responseMessage, {MessageProperties properties, bool mandatory : false, bool immediate : false}); - - /** - * Reject this message because the client cannot process it. - * - * If the [requeue] flag is set, then the server will attempt to forward the rejected - * message to another client. - */ + /// Reply to the sender of this message with a new [message]. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. + /// If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties + /// (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will + /// trigger an [ArgumentError]. + /// + /// You may specify additional message properties by setting the [properties] named parameter. + /// + /// If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise + /// the server will drop un-routable messages. + /// + /// if the [immediate] flag is set, the server will immediately return undeliverable messages to the client + /// if it cannot route them. If the flag is set to false, the server will queue the message even though + /// there is no guarantee that it will ever be consumed. + void reply(Object responseMessage, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}); + + /// Reject this message because the client cannot process it. + /// + /// If the [requeue] flag is set, then the server will attempt to forward the rejected + /// message to another client. void reject(bool requeue); -} \ No newline at end of file +} diff --git a/lib/src/client/basicreturn_message.dart b/lib/src/client/basicreturn_message.dart index 554493d..89d2ef1 100644 --- a/lib/src/client/basicreturn_message.dart +++ b/lib/src/client/basicreturn_message.dart @@ -1,52 +1,34 @@ part of dart_amqp.client; -abstract class BasicReturnMessage{ - /** - * Get the payload as a [Uint8List] - */ +abstract class BasicReturnMessage { + /// Get the payload as a [Uint8List] Uint8List get payload; - /** - * Get the payload as a [String]. This method will pass - * the message [payload] through UTF8.decode and return - * the decoded string. - */ + /// Get the payload as a [String]. This method will pass + /// the message [payload] through UTF8.decode and return + /// the decoded string. String get payloadAsString; - /** - * Get the payload as a [Map]. This method will pass the - * message [payload] through a JSON decoded and return the - * decoded JSON data as a [Map]. - */ + /// Get the payload as a [Map]. This method will pass the + /// message [payload] through a JSON decoded and return the + /// decoded JSON data as a [Map]. Map get payloadAsJson; - /** - * Get the [properties] that were included with the message metadata - */ + /// Get the [properties] that were included with the message metadata MessageProperties get properties; - /** - * The reply code for the return message - */ + /// The reply code for the return message int get replyCode; - /** - * The localised reply text. This text can be logged as an aid to resolving issues. - */ + /// The localised reply text. This text can be logged as an aid to resolving issues. String get replyText; - - /** - * Get the name of the exchange where returned message was sent to. - */ + /// Get the name of the exchange where returned message was sent to. String get exchangeName; - /** - * Get the routing key for the returned message message. The - * method will return null if the message did not arrive through an - * exchange (e.g. posted directly to a queue). - */ + /// Get the routing key for the returned message message. The + /// method will return null if the message did not arrive through an + /// exchange (e.g. posted directly to a queue). String get routingKey; - -} \ No newline at end of file +} diff --git a/lib/src/client/channel.dart b/lib/src/client/channel.dart index 6b6b137..2a95544 100644 --- a/lib/src/client/channel.dart +++ b/lib/src/client/channel.dart @@ -1,108 +1,97 @@ part of dart_amqp.client; abstract class Channel { - - /** - * Close the channel, abort any pending operations and return a [Future] to be completed - * when the channel is closed. - * - * After closing the channel any attempt to send a message over it will cause a [StateError] - */ + /// Close the channel, abort any pending operations and return a [Future] to be completed + /// when the channel is closed. + /// + /// After closing the channel any attempt to send a message over it will cause a [StateError] Future close(); - /** - * Define a queue named [name]. Returns a [Future] to be completed when the queue is allocated. - * - * The [passive] flag can be used to test if the queue exists. When [passive] is set to true, the - * returned future will fail with a [QueueNotFoundException] if the queue does not exist. - * - * The [durable] flag will enable the queue to persist across server restarts. - * - * The [exclusive] flag will mark the connection as private and accessible only by the current connection. The - * server will automatically delete the queue when the connection closes. - * - * The [autoDelete] flag will notify the server that the queue should be deleted when no more connections - * are using it. - */ - Future queue(String name, {bool passive : false, bool durable : false, bool exclusive : false, bool autoDelete : false, bool noWait : false, Map arguments }); + /// Define a queue named [name]. Returns a [Future] to be completed when the queue is allocated. + /// + /// The [passive] flag can be used to test if the queue exists. When [passive] is set to true, the + /// returned future will fail with a [QueueNotFoundException] if the queue does not exist. + /// + /// The [durable] flag will enable the queue to persist across server restarts. + /// + /// The [exclusive] flag will mark the connection as private and accessible only by the current connection. The + /// server will automatically delete the queue when the connection closes. + /// + /// The [autoDelete] flag will notify the server that the queue should be deleted when no more connections + /// are using it. + Future queue(String name, + {bool passive = false, + bool durable = false, + bool exclusive = false, + bool autoDelete = false, + bool noWait = false, + Map arguments}); - /** - * A convenience method for allocating private queues. The client will allocate - * an exclusive queue with a random, server-assigned name and return a [Future] - * to be completed when the server responds. - */ - Future privateQueue({bool noWait : false, Map arguments }); + /// A convenience method for allocating private queues. The client will allocate + /// an exclusive queue with a random, server-assigned name and return a [Future] + /// to be completed when the server responds. + Future privateQueue( + {bool noWait = false, Map arguments}); - /** - * Define an exchange named [name] of type [type] and return a [Future] when the exchange is allocated. - * - * The [passive] flag can be used to test if the exchange exists. When [passive] is set to true, the - * returned future will fail with a [ExchangeNotFoundException] if the exchange does not exist. - * - * The [durable] flag will enable the exchange to persist across server restarts. - */ - Future exchange(String name, ExchangeType type, {bool passive : false, bool durable : false, bool noWait : false, Map arguments }); + /// Define an exchange named [name] of type [type] and return a [Future] when the exchange is allocated. + /// + /// The [passive] flag can be used to test if the exchange exists. When [passive] is set to true, the + /// returned future will fail with a [ExchangeNotFoundException] if the exchange does not exist. + /// + /// The [durable] flag will enable the exchange to persist across server restarts. + Future exchange(String name, ExchangeType type, + {bool passive = false, + bool durable = false, + bool noWait = false, + Map arguments}); - /** - * Setup the [prefetchSize] and [prefetchCount] QoS parameters. - * Returns a [Future] with the affected channel once the server - * confirms the updated QoS settings. - */ + /// Setup the [prefetchSize] and [prefetchCount] QoS parameters. + /// Returns a [Future] with the affected channel once the server + /// confirms the updated QoS settings. Future qos(int prefetchSize, int prefetchCount); - /** - * Acknowledge a [deliveryTag]. The [multiple] flag can be set to true - * to notify the server that the client ack-ed all pending messages up to [deliveryTag]. - * - * Generally you should not use this method directly but rather use the - * methods in [AmqpMessage] to handle acks - */ - void ack(int deliveryTag, {bool multiple : false}); + /// Acknowledge a [deliveryTag]. The [multiple] flag can be set to true + /// to notify the server that the client ack-ed all pending messages up to [deliveryTag]. + /// + /// Generally you should not use this method directly but rather use the + /// methods in [AmqpMessage] to handle acks + void ack(int deliveryTag, {bool multiple = false}); - /** - * Begin a transaction on the current channel. Returns a [Future] with - * the affected channel. - */ + /// Begin a transaction on the current channel. Returns a [Future] with + /// the affected channel. Future select(); - /** - * Commit an open transaction on the current channel. Returns a [Future] with - * the affected channel. - * - * This call will fail if [select] has not been invoked before committing. - */ + /// Commit an open transaction on the current channel. Returns a [Future] with + /// the affected channel. + /// + /// This call will fail if [select] has not been invoked before committing. Future commit(); - /** - * Rollback an open transaction on the current channel. Returns a [Future] with - * the affected channel. - * - * This call will fail if [select] has not been invoked before rolling back. - */ + /// Rollback an open transaction on the current channel. Returns a [Future] with + /// the affected channel. + /// + /// This call will fail if [select] has not been invoked before rolling back. Future rollback(); - /** - * Enable or disable the flow of messages to the client depending on [active] - * flag. This call should be used to notify the server that the - * client cannot handle the volume of incoming messages on the channel. - * - * Returns a [Future] with the affected channel. - */ + /// Enable or disable the flow of messages to the client depending on [active] + /// flag. This call should be used to notify the server that the + /// client cannot handle the volume of incoming messages on the channel. + /// + /// Returns a [Future] with the affected channel. Future flow(bool active); - /** - * Ask the server to re-deliver unacknowledged messages. If this [requeue] flag is false, - * the server will redeliver messages to the original recipient. If [requeue] is - * set to true, the server will attempt to requeue the message, potentially then - * delivering it to an alternative client. - * - * Returns a [Future] with the affected channel. - */ + /// Ask the server to re-deliver unacknowledged messages. If this [requeue] flag is false, + /// the server will redeliver messages to the original recipient. If [requeue] is + /// set to true, the server will attempt to requeue the message, potentially then + /// delivering it to an alternative client. + /// + /// Returns a [Future] with the affected channel. Future recover(bool requeue); - /** - * Register a listener for basicReturn Messages - */ - StreamSubscription basicReturnListener(void onData(BasicReturnMessage message), { Function onError, void onDone(), bool cancelOnError}); - + /// Register a listener for basicReturn Messages + StreamSubscription basicReturnListener( + void onData(BasicReturnMessage message), + {Function onError, + void onDone(), + bool cancelOnError}); } diff --git a/lib/src/client/client.dart b/lib/src/client/client.dart index 4b8d24d..e92e4a4 100644 --- a/lib/src/client/client.dart +++ b/lib/src/client/client.dart @@ -1,38 +1,29 @@ part of dart_amqp.client; abstract class Client { - - factory Client({ConnectionSettings settings}) => new _ClientImpl(settings : settings); + factory Client({ConnectionSettings settings}) => + _ClientImpl(settings: settings); // Configuration options ConnectionSettings get settings; TuningSettings get tuningSettings; - /** - * Check if a connection is currently in handshake state - */ + /// Check if a connection is currently in handshake state bool get handshaking; - /** - * Open a working connection to the server. Returns a [Future] to be completed on a successful protocol handshake - */ + /// Open a working connection to the server. Returns a [Future] to be completed on a successful protocol handshake Future connect(); - /** - * Shutdown any open channels and disconnect the socket. Return a [Future] to be completed - * when the client has shut down - */ + /// Shutdown any open channels and disconnect the socket. Return a [Future] to be completed + /// when the client has shut down Future close(); - /** - * Allocate and initialize a new [Channel]. Return a [Future] to be completed with - * the new [Channel] - */ + /// Allocate and initialize a new [Channel]. Return a [Future] to be completed with + /// the new [Channel] Future channel(); - /** - * Register listener for errors - */ - StreamSubscription errorListener(void onData(Exception error), { Function onError, void onDone(), bool cancelOnError }); + /// Register listener for errors + StreamSubscription errorListener(void onData(Exception error), + {Function onError, void onDone(), bool cancelOnError}); } diff --git a/lib/src/client/connection_settings.dart b/lib/src/client/connection_settings.dart index d48b798..37c53d2 100644 --- a/lib/src/client/connection_settings.dart +++ b/lib/src/client/connection_settings.dart @@ -1,7 +1,6 @@ part of dart_amqp.client; class ConnectionSettings { - // The host to connect to String host; @@ -30,19 +29,16 @@ class ConnectionSettings { TuningSettings tuningSettings; ConnectionSettings( - { - String this.host : "127.0.0.1" - , int this.port : 5672 - , String this.virtualHost : "/" - , Authenticator this.authProvider : const PlainAuthenticator("guest", "guest") - , int this.maxConnectionAttempts : 1 - , Duration this.reconnectWaitTime : const Duration(milliseconds : 1500) - , TuningSettings this.tuningSettings - } - ){ - if( this.tuningSettings == null){ - tuningSettings = new TuningSettings(); + {String this.host = "127.0.0.1", + int this.port = 5672, + String this.virtualHost = "/", + Authenticator this.authProvider = + const PlainAuthenticator("guest", "guest"), + int this.maxConnectionAttempts = 1, + Duration this.reconnectWaitTime = const Duration(milliseconds: 1500), + TuningSettings this.tuningSettings}) { + if (this.tuningSettings == null) { + tuningSettings = TuningSettings(); } } - -} \ No newline at end of file +} diff --git a/lib/src/client/consumer.dart b/lib/src/client/consumer.dart index a8651e9..cfa1f02 100644 --- a/lib/src/client/consumer.dart +++ b/lib/src/client/consumer.dart @@ -1,32 +1,22 @@ part of dart_amqp.client; abstract class Consumer { - - /** - * Get the consumer tag. - */ + /// Get the consumer tag. String get tag; - /** - * Get the [Channel] where this consumer was declared. - */ + /// Get the [Channel] where this consumer was declared. Channel get channel; - /** - * Get the [Queue] where this consumer is bound. - */ + /// Get the [Queue] where this consumer is bound. Queue get queue; - /** - * Bind [onData] listener to the stream of [AmqpMessage] that is emitted by the consumer. - * - * You can also define an optional [onError] method that will handle stream errors and an - * [onDone] method to be invoked when the stream closes. - */ - StreamSubscription listen(void onData(AmqpMessage event), { Function onError, void onDone(), bool cancelOnError}); + /// Bind [onData] listener to the stream of [AmqpMessage] that is emitted by the consumer. + /// + /// You can also define an optional [onError] method that will handle stream errors and an + /// [onDone] method to be invoked when the stream closes. + StreamSubscription listen(void onData(AmqpMessage event), + {Function onError, void onDone(), bool cancelOnError}); - /** - * Cancel the consumer and return a [Future] to the cancelled consumer. - */ - Future cancel({bool noWait : false}); + /// Cancel the consumer and return a [Future] to the cancelled consumer. + Future cancel({bool noWait = false}); } diff --git a/lib/src/client/exchange.dart b/lib/src/client/exchange.dart index 4669dc6..1406bc1 100644 --- a/lib/src/client/exchange.dart +++ b/lib/src/client/exchange.dart @@ -1,56 +1,47 @@ part of dart_amqp.client; abstract class Exchange { - - /** - * Get the name of the exchange - */ + /// Get the name of the exchange String get name; - /** - * Get the type of the exchange - */ + /// Get the type of the exchange ExchangeType get type; - /** - * Get the [Channel] where this exchange was declared - */ + /// Get the [Channel] where this exchange was declared Channel get channel; - /** - * Delete the exchange and return a [Future] to the deleted exchange. - * - * If the [ifUnsused] flag is set, the server will only delete the exchange if it has no queue-bindings. If the - * flag is set and the exchange has any queue bindings left, then the server will raise an exception. - */ - Future delete({bool ifUnused : false, bool noWait : false}); + /// Delete the exchange and return a [Future] to the deleted exchange. + /// + /// If the [ifUnsused] flag is set, the server will only delete the exchange if it has no queue-bindings. If the + /// flag is set and the exchange has any queue bindings left, then the server will raise an exception. + Future delete({bool ifUnused = false, bool noWait = false}); - /** - * Publish [message] to the exchange. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. - * If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties - * (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will - * trigger an [ArgumentError]. - * - * You may specify additional message properties by setting the [properties] named parameter. - * - * If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise - * the server will drop un-routable messages. - * - * if the [immediate] flag is set, the server will immediately return undeliverable messages to the client - * if it cannot route them. If the flag is set to false, the server will queue the message even though - * there is no guarantee that it will ever be consumed. - */ - void publish(Object message, String routingKey, { MessageProperties properties, bool mandatory : false, bool immediate : false}); + /// Publish [message] to the exchange. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. + /// If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties + /// (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will + /// trigger an [ArgumentError]. + /// + /// You may specify additional message properties by setting the [properties] named parameter. + /// + /// If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise + /// the server will drop un-routable messages. + /// + /// if the [immediate] flag is set, the server will immediately return undeliverable messages to the client + /// if it cannot route them. If the flag is set to false, the server will queue the message even though + /// there is no guarantee that it will ever be consumed. + void publish(Object message, String routingKey, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}); - /** - * Allocate a private [Queue], bind it to this exchange using the supplied [routingKeys], - * allocate a [Consumer] and return a [Future]. - * - * You may specify a [consumerTag] to label this consumer. If left unspecified, the server will assign a - * random tag to this consumer. Consumer tags are local to the current channel. - * - * The [noAck] flag will notify the server whether the consumer is expected to acknowledge incoming - * messages or not. - */ - Future bindPrivateQueueConsumer(List routingKeys, {String consumerTag, bool noAck: true}); + /// Allocate a private [Queue], bind it to this exchange using the supplied [routingKeys], + /// allocate a [Consumer] and return a [Future]. + /// + /// You may specify a [consumerTag] to label this consumer. If left unspecified, the server will assign a + /// random tag to this consumer. Consumer tags are local to the current channel. + /// + /// The [noAck] flag will notify the server whether the consumer is expected to acknowledge incoming + /// messages or not. + Future bindPrivateQueueConsumer(List routingKeys, + {String consumerTag, bool noAck = true}); } diff --git a/lib/src/client/impl/amqp_message_impl.dart b/lib/src/client/impl/amqp_message_impl.dart index c8ab00d..c2bf4c0 100644 --- a/lib/src/client/impl/amqp_message_impl.dart +++ b/lib/src/client/impl/amqp_message_impl.dart @@ -1,13 +1,13 @@ part of dart_amqp.client; class _AmqpMessageImpl implements AmqpMessage { - final _ConsumerImpl consumer; final DecodedMessage message; MessageProperties get properties => message.properties; - _AmqpMessageImpl.fromDecodedMessage(_ConsumerImpl this.consumer, DecodedMessage this.message); + _AmqpMessageImpl.fromDecodedMessage( + _ConsumerImpl this.consumer, DecodedMessage this.message); Uint8List get payload => message.payload; @@ -19,29 +19,33 @@ class _AmqpMessageImpl implements AmqpMessage { String get routingKey => (message.message as BasicDeliver).routingKey; - void reply(Object responseMessage, {MessageProperties properties, bool mandatory : false, bool immediate : false}) { + void reply(Object responseMessage, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}) { if (message.properties.replyTo == null) { - throw new ArgumentError("No reply-to property specified in the incoming message"); + throw ArgumentError( + "No reply-to property specified in the incoming message"); } - MessageProperties responseProperties = properties == null ? - new MessageProperties() - : properties; + MessageProperties responseProperties = + properties == null ? MessageProperties() : properties; responseProperties.corellationId = message.properties.corellationId; - BasicPublish pubRequest = new BasicPublish() + BasicPublish pubRequest = BasicPublish() ..reserved_1 = 0 ..routingKey = message.properties.replyTo // send to 'reply-to' ..exchange = "" ..mandatory = mandatory ..immediate = immediate; - consumer.channel.writeMessage(pubRequest, properties : responseProperties, payloadContent : responseMessage); + consumer.channel.writeMessage(pubRequest, + properties: responseProperties, payloadContent: responseMessage); } void reject(bool requeue) { - BasicReject rejectRequest = new BasicReject() + BasicReject rejectRequest = BasicReject() ..deliveryTag = (message.message as BasicDeliver).deliveryTag ..requeue = requeue; @@ -51,5 +55,4 @@ class _AmqpMessageImpl implements AmqpMessage { void ack() { consumer.channel.ack((message.message as BasicDeliver).deliveryTag); } - -} \ No newline at end of file +} diff --git a/lib/src/client/impl/basic_return_message_impl.dart b/lib/src/client/impl/basic_return_message_impl.dart index af77cae..68b4a12 100644 --- a/lib/src/client/impl/basic_return_message_impl.dart +++ b/lib/src/client/impl/basic_return_message_impl.dart @@ -1,8 +1,6 @@ part of dart_amqp.client; - class _BasicReturnMessageImpl implements BasicReturnMessage { - final DecodedMessage message; final BasicReturn basicReturn; @@ -23,5 +21,4 @@ class _BasicReturnMessageImpl implements BasicReturnMessage { String get replyText => basicReturn.replyText; MessageProperties get properties => message.properties; - -} \ No newline at end of file +} diff --git a/lib/src/client/impl/channel_impl.dart b/lib/src/client/impl/channel_impl.dart index c193695..55cc483 100644 --- a/lib/src/client/impl/channel_impl.dart +++ b/lib/src/client/impl/channel_impl.dart @@ -1,7 +1,6 @@ part of dart_amqp.client; class _ChannelImpl implements Channel { - // The allocated channel id final int channelId; @@ -14,18 +13,19 @@ class _ChannelImpl implements Channel { Map _consumers; Message _lastHandshakeMessage; Exception _channelCloseException; - final _basicReturnStream = new StreamController.broadcast(); + final _basicReturnStream = StreamController.broadcast(); _ChannelImpl(this.channelId, _ClientImpl this._client) { - _frameWriter = new FrameWriter(_client.tuningSettings); - _pendingOperations = new ListQueue(); - _pendingOperationPayloads = new ListQueue(); - _consumers = new Map(); + _frameWriter = FrameWriter(_client.tuningSettings); + _pendingOperations = ListQueue(); + _pendingOperationPayloads = ListQueue(); + _consumers = Map(); // If we are opening a user channel signal to the server; otherwise perform connection handshake if (channelId > 0) { - _channelOpened = new Completer(); - writeMessage(new ChannelOpen(), completer : _channelOpened, futurePayload : this); + _channelOpened = Completer(); + writeMessage(ChannelOpen(), + completer: _channelOpened, futurePayload: this); } else { writeProtocolHeader(); } @@ -37,7 +37,11 @@ class _ChannelImpl implements Channel { // Transmit handshake _frameWriter - ..writeProtocolHeader(_client.settings.amqpProtocolVersion, _client.settings.amqpMajorVersion, _client.settings.amqpMinorVersion, _client.settings.amqpRevision) + ..writeProtocolHeader( + _client.settings.amqpProtocolVersion, + _client.settings.amqpMajorVersion, + _client.settings.amqpMinorVersion, + _client.settings.amqpRevision) ..pipe(_client._socket); } @@ -48,35 +52,36 @@ class _ChannelImpl implements Channel { ..pipe(_client._socket); } - /** - * Encode and transmit [message] optionally accompanied by a server frame with [payloadContent]. - * - * A [StateError] will be thrown when trying to write a message to a closed channel - */ - void writeMessage(Message message, { MessageProperties properties, Object payloadContent, Completer completer, Object futurePayload }) { + /// Encode and transmit [message] optionally accompanied by a server frame with [payloadContent]. + /// + /// A [StateError] will be thrown when trying to write a message to a closed channel + void writeMessage(Message message, + {MessageProperties properties, + Object payloadContent, + Completer completer, + Object futurePayload}) { if (_channelClosed != null && (_channelClosed != completer)) { throw _channelCloseException == null - ? new StateError("Channel has been closed") - : _channelCloseException; + ? StateError("Channel has been closed") + : _channelCloseException; } // If an op completer is specified add it to the queue if (completer != null) { _pendingOperations.addLast(completer); - _pendingOperationPayloads.addLast(futurePayload != null ? futurePayload : true); + _pendingOperationPayloads + .addLast(futurePayload != null ? futurePayload : true); } _frameWriter - ..writeMessage(channelId, message, properties : properties, payloadContent : payloadContent) + ..writeMessage(channelId, message, + properties: properties, payloadContent: payloadContent) ..pipe(_client._socket); } - /** - * Implement the handshake flow specified by the AMQP spec by - * examining [serverFrame] and generating the appropriate response - */ + /// Implement the handshake flow specified by the AMQP spec by + /// examining [serverFrame] and generating the appropriate response void _processHandshake(DecodedMessage serverMessage) { - // Handshake process includes the following steps // 1) S : ConnectionStart, C : ConnectionStartOk // 2) (optional multiple) S : ConnectionSecure, C : ConnectionSecureOk @@ -84,24 +89,24 @@ class _ChannelImpl implements Channel { // 4) C : ConnectionOpen, S : ConnectionOpenOk switch (serverMessage.message.runtimeType) { case ConnectionStart: - ConnectionStart serverResponse = (serverMessage.message as ConnectionStart); + ConnectionStart serverResponse = + (serverMessage.message as ConnectionStart); // Check if the currently supplied authentication provider is supported by the server. - if (serverResponse.mechanisms.indexOf(_client.settings.authProvider.saslType) == -1) { - _client._handleException( - new FatalException( - "Selected authentication provider '${_client.settings.authProvider.saslType}' is unsupported by the server (server supports: ${serverResponse.mechanisms})" - ) - ); + if (serverResponse.mechanisms + .indexOf(_client.settings.authProvider.saslType) == + -1) { + _client._handleException(FatalException( + "Selected authentication provider '${_client.settings.authProvider.saslType}' is unsupported by the server (server supports: ${serverResponse.mechanisms})")); return; } - ConnectionStartOk clientResponse = new ConnectionStartOk() + ConnectionStartOk clientResponse = ConnectionStartOk() ..clientProperties = { - "product" : "Dart AMQP client", - "version" : "0.0.1", - "platform" : "Dart/${Platform.operatingSystem}" - } + "product": "Dart AMQP client", + "version": "0.0.1", + "platform": "Dart/${Platform.operatingSystem}" + } ..locale = 'en_US' ..mechanism = _client.settings.authProvider.saslType ..response = _client.settings.authProvider.answerChallenge(null); @@ -111,10 +116,12 @@ class _ChannelImpl implements Channel { writeMessage(clientResponse); break; case ConnectionSecure: - ConnectionSecure serverResponse = serverMessage.message as ConnectionSecure; + ConnectionSecure serverResponse = + serverMessage.message as ConnectionSecure; - ConnectionSecureOk clientResponse = new ConnectionSecureOk() - ..response = _client.settings.authProvider.answerChallenge(serverResponse.challenge); + ConnectionSecureOk clientResponse = ConnectionSecureOk() + ..response = _client.settings.authProvider + .answerChallenge(serverResponse.challenge); // Transmit handshake response _lastHandshakeMessage = clientResponse; @@ -126,11 +133,13 @@ class _ChannelImpl implements Channel { // Update tuning settings unless our client forces a specific value _client.tuningSettings ..maxFrameSize = serverResponse.frameMax - ..maxChannels = _client.tuningSettings.maxChannels > 0 ? _client.tuningSettings.maxChannels : serverResponse.channelMax - ..heartbeatPeriod = new Duration(seconds : 0); + ..maxChannels = _client.tuningSettings.maxChannels > 0 + ? _client.tuningSettings.maxChannels + : serverResponse.channelMax + ..heartbeatPeriod = Duration(seconds: 0); // Respond with the mirrored tuning settings - ConnectionTuneOk clientResponse = new ConnectionTuneOk() + ConnectionTuneOk clientResponse = ConnectionTuneOk() ..frameMax = serverResponse.frameMax ..channelMax = _client.tuningSettings.maxChannels ..heartbeat = 0; @@ -140,7 +149,7 @@ class _ChannelImpl implements Channel { // Also respond with a connection open request. The _channelOpened future has already been // pushed to the pending operations stack in the constructor so we do not need to do it here - ConnectionOpen openRequest = new ConnectionOpen() + ConnectionOpen openRequest = ConnectionOpen() ..virtualHost = _client.settings.virtualHost; _lastHandshakeMessage = clientResponse; writeMessage(openRequest); @@ -151,26 +160,28 @@ class _ChannelImpl implements Channel { _completeOperation(serverMessage.message); break; default: - throw new FatalException("Received unexpected message ${serverMessage.message.runtimeType} during handshake"); + throw FatalException( + "Received unexpected message ${serverMessage.message.runtimeType} during handshake"); } } - /** - * Close the channel with an optional [replyCode] and [replyText] and return a [Future] - * to be completed when the channel is closed. If the channel is closing due to an error - * from an incoming [classId] and [methodId] they should be included as well when invoking - * this method. - * - * After closing the channel any attempt to send a message over it will cause a [StateError] - */ - Future _close({ ErrorType replyCode, String replyText, int classId : 0, int methodId : 0}) { - + /// Close the channel with an optional [replyCode] and [replyText] and return a [Future] + /// to be completed when the channel is closed. If the channel is closing due to an error + /// from an incoming [classId] and [methodId] they should be included as well when invoking + /// this method. + /// + /// After closing the channel any attempt to send a message over it will cause a [StateError] + Future _close( + {ErrorType replyCode, + String replyText, + int classId = 0, + int methodId = 0}) { // Already closing / closed if (_channelClosed != null) { return _channelClosed.future; } - _channelClosed = new Completer(); + _channelClosed = Completer(); if (classId == null) { classId = 0; @@ -183,29 +194,27 @@ class _ChannelImpl implements Channel { Message closeRequest; if (channelId == 0) { - closeRequest = new ConnectionClose() + closeRequest = ConnectionClose() ..replyCode = replyCode.value ..replyText = replyText ..classId = classId ..methodId = methodId; - } else { - closeRequest = new ChannelClose() + closeRequest = ChannelClose() ..replyCode = replyCode.value ..replyText = replyText ..classId = classId ..methodId = methodId; } - writeMessage(closeRequest, completer : _channelClosed, futurePayload : this); - _channelClosed.future.then((_) => _basicReturnStream.close()).then((_)=>_client._removeChannel(channelId)); + writeMessage(closeRequest, completer: _channelClosed, futurePayload: this); + _channelClosed.future + .then((_) => _basicReturnStream.close()) + .then((_) => _client._removeChannel(channelId)); return _channelClosed.future; } - /** - * Process an incoming [serverFrame] sent to this channel - */ + /// Process an incoming [serverFrame] sent to this channel void handleMessage(DecodedMessage serverMessage) { - if (_client.handshaking) { _processHandshake(serverMessage); return; @@ -217,14 +226,14 @@ class _ChannelImpl implements Channel { } switch (serverMessage.message.runtimeType) { - // Connection + // Connection case ConnectionCloseOk: _completeOperation(serverMessage.message); break; - // Channels + // Channels case ChannelClose: - // Ack the closing of the channel - writeMessage(new ChannelCloseOk()); + // Ack the closing of the channel + writeMessage(ChannelCloseOk()); _completeOperationWithError(serverMessage.message); break; @@ -237,7 +246,7 @@ class _ChannelImpl implements Channel { case BasicRecoverOk: _completeOperation(serverMessage.message); break; - // Queues + // Queues case QueueDeclareOk: QueueDeclareOk serverResponse = serverMessage.message as QueueDeclareOk; (_pendingOperationPayloads.first as _QueueImpl) @@ -253,13 +262,15 @@ class _ChannelImpl implements Channel { case QueueUnbindOk: _completeOperation(serverMessage.message); break; - // Basic + // Basic case BasicQosOk: _completeOperation(serverMessage.message); break; case BasicConsumeOk: - BasicConsumeOk serverResponse = (serverMessage.message as BasicConsumeOk); - _ConsumerImpl consumer = (_pendingOperationPayloads.first as _ConsumerImpl) + BasicConsumeOk serverResponse = + (serverMessage.message as BasicConsumeOk); + _ConsumerImpl consumer = (_pendingOperationPayloads.first + as _ConsumerImpl) .._tag = serverResponse.consumerTag; _consumers[serverResponse.consumerTag] = consumer; _completeOperation(serverResponse); @@ -271,13 +282,16 @@ class _ChannelImpl implements Channel { break; case BasicReturn: BasicReturn serverResponse = (serverMessage.message as BasicReturn); - if (_basicReturnStream != null && _basicReturnStream.hasListener && !_basicReturnStream.isClosed) { - _basicReturnStream.add(new _BasicReturnMessageImpl.fromDecodedMessage(serverResponse, serverMessage)); + if (_basicReturnStream != null && + _basicReturnStream.hasListener && + !_basicReturnStream.isClosed) { + _basicReturnStream.add(_BasicReturnMessageImpl.fromDecodedMessage( + serverResponse, serverMessage)); } break; case BasicDeliver: BasicDeliver serverResponse = (serverMessage.message as BasicDeliver); - _ConsumerImpl target = _consumers[ serverResponse.consumerTag ]; + _ConsumerImpl target = _consumers[serverResponse.consumerTag]; // no cosumer with tag if (target == null) { @@ -286,7 +300,7 @@ class _ChannelImpl implements Channel { target.onMessage(serverMessage); break; - // Exchange + // Exchange case ExchangeDeclareOk: _completeOperation(serverMessage.message); break; @@ -296,30 +310,31 @@ class _ChannelImpl implements Channel { } } - /** - * Complete a pending operation with [result] after receiving [serverResponse] - * from the socket - */ + /// Complete a pending operation with [result] after receiving [serverResponse] + /// from the socket void _completeOperation(Message serverResponse) { if (_pendingOperations.isEmpty) { return; } // Complete the first pending operation in the queue with the first future payload - _pendingOperations.removeFirst().complete(_pendingOperationPayloads.removeFirst()); + _pendingOperations + .removeFirst() + .complete(_pendingOperationPayloads.removeFirst()); } - /** - * Complete a pending operation with [error] after receiving [serverResponse] - * from the socket - */ + /// Complete a pending operation with [error] after receiving [serverResponse] + /// from the socket void _completeOperationWithError(Message serverResponse) { - Exception ex; switch (serverResponse.runtimeType) { case ConnectionClose: ConnectionClose closeResponse = serverResponse as ConnectionClose; - ex = new ConnectionException(closeResponse.replyText, ErrorType.valueOf(closeResponse.replyCode), serverResponse.msgClassId, serverResponse.msgMethodId); + ex = ConnectionException( + closeResponse.replyText, + ErrorType.valueOf(closeResponse.replyCode), + serverResponse.msgClassId, + serverResponse.msgMethodId); // Complete the first pending operation in the queue with the first future payload _pendingOperationPayloads.removeFirst(); @@ -330,17 +345,22 @@ class _ChannelImpl implements Channel { ChannelClose closeResponse = serverResponse as ChannelClose; // If we got a NOT_FOUND error and we have a pending Queue or Exchange payload emit a QueueNotFoundException - if (closeResponse.replyCode == ErrorType.NOT_FOUND.value && _pendingOperationPayloads.first is Queue) { - ex = new QueueNotFoundException(closeResponse.replyText, channelId, ErrorType.valueOf(closeResponse.replyCode)); - } else if (closeResponse.replyCode == ErrorType.NOT_FOUND.value && _pendingOperationPayloads.first is Exchange) { - ex = new ExchangeNotFoundException(closeResponse.replyText, channelId, ErrorType.valueOf(closeResponse.replyCode)); + if (closeResponse.replyCode == ErrorType.NOT_FOUND.value && + _pendingOperationPayloads.first is Queue) { + ex = QueueNotFoundException(closeResponse.replyText, channelId, + ErrorType.valueOf(closeResponse.replyCode)); + } else if (closeResponse.replyCode == ErrorType.NOT_FOUND.value && + _pendingOperationPayloads.first is Exchange) { + ex = ExchangeNotFoundException(closeResponse.replyText, channelId, + ErrorType.valueOf(closeResponse.replyCode)); } else { - ex = new ChannelException(closeResponse.replyText, channelId, ErrorType.valueOf(closeResponse.replyCode)); + ex = ChannelException(closeResponse.replyText, channelId, + ErrorType.valueOf(closeResponse.replyCode)); } // Mark the channel as closed if (_channelClosed == null) { - _channelClosed = new Completer(); + _channelClosed = Completer(); } if (!_channelClosed.isCompleted) { _channelClosed.complete(); @@ -350,7 +370,6 @@ class _ChannelImpl implements Channel { break; } - // Complete any first pending operation in the queue with the error while (!_pendingOperations.isEmpty) { _pendingOperationPayloads.removeFirst(); @@ -358,9 +377,7 @@ class _ChannelImpl implements Channel { } } - /** - * Abort any pending operations with [exception] and mark the channel as closed - */ + /// Abort any pending operations with [exception] and mark the channel as closed void handleException(exception) { // Ignore exception if we are closed if (_channelClosed != null && _channelClosed.isCompleted) { @@ -372,11 +389,14 @@ class _ChannelImpl implements Channel { if (exception is FatalException || exception is ChannelException) { flagChannelAsClosed = true; } else if (exception is ConnectionException) { - // If this is channel 0 then we need to close the connection with the appropriate error code if (channelId == 0) { // Close connection (channel 0) with the appropriate error code and consider the operation completed - _close(replyCode : exception.errorType, replyText : exception.message, classId: exception.classId, methodId: exception.methodId); + _close( + replyCode: exception.errorType, + replyText: exception.message, + classId: exception.classId, + methodId: exception.methodId); _completeOperation(null); } else { // Non-zero channels should be marked as closed @@ -387,7 +407,7 @@ class _ChannelImpl implements Channel { // Mark the channel as closed if we need to if (flagChannelAsClosed) { if (_channelClosed == null) { - _channelClosed = new Completer(); + _channelClosed = Completer(); } if (!_channelClosed.isCompleted) { @@ -409,15 +429,20 @@ class _ChannelImpl implements Channel { _pendingOperationPayloads.clear(); } - /** - * Close the channel and return a [Future] to be completed when the channel is closed. - * - * After closing the channel any attempt to send a message over it will cause a [StateError] - */ - Future close() => _close(replyCode : ErrorType.SUCCESS, replyText : "Normal shutdown"); - - Future queue(String name, {bool passive : false, bool durable : false, bool exclusive : false, bool autoDelete : false, bool noWait : false, Map arguments }) { - QueueDeclare queueRequest = new QueueDeclare() + /// Close the channel and return a [Future] to be completed when the channel is closed. + /// + /// After closing the channel any attempt to send a message over it will cause a [StateError] + Future close() => + _close(replyCode: ErrorType.SUCCESS, replyText: "Normal shutdown"); + + Future queue(String name, + {bool passive = false, + bool durable = false, + bool exclusive = false, + bool autoDelete = false, + bool noWait = false, + Map arguments}) { + QueueDeclare queueRequest = QueueDeclare() ..reserved_1 = 0 ..queue = name ..passive = passive @@ -427,13 +452,15 @@ class _ChannelImpl implements Channel { ..noWait = noWait ..arguments = arguments; - Completer opCompleter = new Completer(); - writeMessage(queueRequest, completer : opCompleter, futurePayload : new _QueueImpl(this, name)); + Completer opCompleter = Completer(); + writeMessage(queueRequest, + completer: opCompleter, futurePayload: _QueueImpl(this, name)); return opCompleter.future; } - Future privateQueue({bool noWait : false, Map arguments }) { - QueueDeclare queueRequest = new QueueDeclare() + Future privateQueue( + {bool noWait = false, Map arguments}) { + QueueDeclare queueRequest = QueueDeclare() ..reserved_1 = 0 ..queue = null ..passive = false @@ -443,19 +470,24 @@ class _ChannelImpl implements Channel { ..noWait = noWait ..arguments = arguments; - Completer opCompleter = new Completer(); - writeMessage(queueRequest, completer : opCompleter, futurePayload : new _QueueImpl(this, "")); + Completer opCompleter = Completer(); + writeMessage(queueRequest, + completer: opCompleter, futurePayload: _QueueImpl(this, "")); return opCompleter.future; } - Future exchange(String name, ExchangeType type, {bool passive : false, bool durable : false, bool noWait : false, Map arguments }) { + Future exchange(String name, ExchangeType type, + {bool passive = false, + bool durable = false, + bool noWait = false, + Map arguments}) { if (name == null || name.isEmpty) { - throw new ArgumentError("The name of the exchange cannot be empty"); + throw ArgumentError("The name of the exchange cannot be empty"); } if (type == null) { - throw new ArgumentError("The type of the exchange needs to be specified"); + throw ArgumentError("The type of the exchange needs to be specified"); } - ExchangeDeclare exchangeRequest = new ExchangeDeclare() + ExchangeDeclare exchangeRequest = ExchangeDeclare() ..reserved_1 = 0 ..exchange = name ..type = type.value @@ -466,32 +498,40 @@ class _ChannelImpl implements Channel { ..noWait = noWait ..arguments = arguments; - Completer opCompleter = new Completer(); - writeMessage(exchangeRequest, completer : opCompleter, futurePayload : new _ExchangeImpl(this, name, type)); + Completer opCompleter = Completer(); + writeMessage(exchangeRequest, + completer: opCompleter, futurePayload: _ExchangeImpl(this, name, type)); return opCompleter.future; } - StreamSubscription basicReturnListener(void onData(BasicReturnMessage message), { Function onError, void onDone(), bool cancelOnError}) => _basicReturnStream.stream.listen(onData, onError : onError, onDone : onDone, cancelOnError : cancelOnError); + StreamSubscription basicReturnListener( + void onData(BasicReturnMessage message), + {Function onError, + void onDone(), + bool cancelOnError}) => + _basicReturnStream.stream.listen(onData, + onError: onError, onDone: onDone, cancelOnError: cancelOnError); - Future qos(int prefetchSize, int prefetchCount, {bool global : true}) { + Future qos(int prefetchSize, int prefetchCount, + {bool global = true}) { if (prefetchSize == null) { prefetchSize = 0; } if (prefetchCount == null) { prefetchCount = 0; } - BasicQos qosRequest = new BasicQos() + BasicQos qosRequest = BasicQos() ..prefetchSize = prefetchSize ..prefetchCount = prefetchCount ..global = global; - Completer opCompleter = new Completer(); - writeMessage(qosRequest, completer : opCompleter, futurePayload : this); + Completer opCompleter = Completer(); + writeMessage(qosRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } - void ack(int deliveryTag, {bool multiple : false}) { - BasicAck ackRequest = new BasicAck() + void ack(int deliveryTag, {bool multiple = false}) { + BasicAck ackRequest = BasicAck() ..deliveryTag = deliveryTag ..multiple = multiple; @@ -499,41 +539,39 @@ class _ChannelImpl implements Channel { } Future select() { - TxSelect selectRequest = new TxSelect(); - Completer opCompleter = new Completer(); - writeMessage(selectRequest, completer : opCompleter, futurePayload : this); + TxSelect selectRequest = TxSelect(); + Completer opCompleter = Completer(); + writeMessage(selectRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } Future commit() { - TxCommit commitRequest = new TxCommit(); - Completer opCompleter = new Completer(); - writeMessage(commitRequest, completer : opCompleter, futurePayload : this); + TxCommit commitRequest = TxCommit(); + Completer opCompleter = Completer(); + writeMessage(commitRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } Future rollback() { - TxRollback rollbackRequest = new TxRollback(); - Completer opCompleter = new Completer(); - writeMessage(rollbackRequest, completer : opCompleter, futurePayload : this); + TxRollback rollbackRequest = TxRollback(); + Completer opCompleter = Completer(); + writeMessage(rollbackRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } Future flow(bool active) { - ChannelFlow flowRequest = new ChannelFlow() - ..active = active; + ChannelFlow flowRequest = ChannelFlow()..active = active; - Completer opCompleter = new Completer(); - writeMessage(flowRequest, completer : opCompleter, futurePayload : this); + Completer opCompleter = Completer(); + writeMessage(flowRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } Future recover(bool requeue) { - BasicRecover recoverRequest = new BasicRecover() - ..requeue = requeue; + BasicRecover recoverRequest = BasicRecover()..requeue = requeue; - Completer opCompleter = new Completer(); - writeMessage(recoverRequest, completer : opCompleter, futurePayload : this); + Completer opCompleter = Completer(); + writeMessage(recoverRequest, completer: opCompleter, futurePayload: this); return opCompleter.future; } } diff --git a/lib/src/client/impl/client_impl.dart b/lib/src/client/impl/client_impl.dart index f372342..5bc7f2d 100644 --- a/lib/src/client/impl/client_impl.dart +++ b/lib/src/client/impl/client_impl.dart @@ -1,7 +1,6 @@ part of dart_amqp.client; class _ClientImpl implements Client { - // Configuration options ConnectionSettings settings; @@ -13,100 +12,98 @@ class _ClientImpl implements Client { Socket _socket; // The list of open channels. Channel 0 is always reserved for signaling - Map _channels = new Map(); + Map _channels = Map(); // Connection status Completer _connected; Completer _clientClosed; //Error Stream - final _error = new StreamController.broadcast(); + final _error = StreamController.broadcast(); _ClientImpl({ConnectionSettings settings}) { - // Use defaults if no settings specified - this.settings = settings == null - ? new ConnectionSettings() - : settings; + this.settings = settings == null ? ConnectionSettings() : settings; } - /** - * Attempt to reconnect to the server. If the attempt fails, it will be retried after - * [reconnectWaitTime] ms up to [maxConnectionAttempts] times. If all connection attempts - * fail, then the [_connected] [Future] returned by a call to [open[ will also fail - */ + /// Attempt to reconnect to the server. If the attempt fails, it will be retried after + /// [reconnectWaitTime] ms up to [maxConnectionAttempts] times. If all connection attempts + /// fail, then the [_connected] [Future] returned by a call to [open[ will also fail Future _reconnect() { if (_connected == null) { - _connected = new Completer(); + _connected = Completer(); } - connectionLogger.info("Trying to connect to ${settings.host}:${settings.port} [attempt ${_connectionAttempt + 1}/${settings.maxConnectionAttempts}]"); + connectionLogger.info( + "Trying to connect to ${settings.host}:${settings.port} [attempt ${_connectionAttempt + 1}/${settings.maxConnectionAttempts}]"); Socket.connect(settings.host, settings.port).then((Socket s) { _socket = s; // Bind processors and initiate handshake _socket - .transform(new RawFrameParser(tuningSettings).transformer) - .transform(new AmqpMessageDecoder().transformer) - .listen( - _handleMessage, - onError : _handleException, - onDone : () => _handleException(new SocketException("Socket closed")) - ); + .transform(RawFrameParser(tuningSettings).transformer) + .transform(AmqpMessageDecoder().transformer) + .listen(_handleMessage, + onError: _handleException, + onDone: () => _handleException(SocketException("Socket closed"))); // Allocate channel 0 for handshaking and transmit the AMQP header to bootstrap the handshake _channels.clear(); - _channels.putIfAbsent(0, () => new _ChannelImpl(0, this)); - - }) - .catchError((err, trace) { - + _channels.putIfAbsent(0, () => _ChannelImpl(0, this)); + }).catchError((err, trace) { // Connection attempt completed with an error (probably protocol mismatch) if (_connected.isCompleted) { return; } if (++_connectionAttempt >= settings.maxConnectionAttempts) { - String errorMessage = "Could not connect to ${settings.host}:${settings.port} after ${settings.maxConnectionAttempts} attempts. Giving up"; + String errorMessage = + "Could not connect to ${settings.host}:${settings.port} after ${settings.maxConnectionAttempts} attempts. Giving up"; connectionLogger.severe(errorMessage); - _connected.completeError(new ConnectionFailedException(errorMessage)); + _connected.completeError(ConnectionFailedException(errorMessage)); // Clear _connected future so the client can invoke open() in the future _connected = null; } else { // Retry after reconnectWaitTime ms - new Timer(settings.reconnectWaitTime, _reconnect); + Timer(settings.reconnectWaitTime, _reconnect); } }); return _connected.future; } - /** - * Check if a connection is currently in handshake state - */ - bool get handshaking => _socket != null && _connected != null && !_connected.isCompleted; + /// Check if a connection is currently in handshake state + bool get handshaking => + _socket != null && _connected != null && !_connected.isCompleted; void _handleMessage(DecodedMessage serverMessage) { try { // Heartbeat frames should be received on channel 0 if (serverMessage is HeartbeatFrameImpl && serverMessage.channel != 0) { - throw new ConnectionException("Received HEARTBEAT message on a channel > 0", ErrorType.COMMAND_INVALID, 0, 0); + throw ConnectionException("Received HEARTBEAT message on a channel > 0", + ErrorType.COMMAND_INVALID, 0, 0); } // If we are still handshaking and we receive a message on another channel this is an error if (!_connected.isCompleted && serverMessage.channel != 0) { - throw new FatalException("Received message for channel ${serverMessage.channel} while still handshaking"); + throw FatalException( + "Received message for channel ${serverMessage.channel} while still handshaking"); } // Connection-class messages should only be received on channel 0 - if (serverMessage.message.msgClassId == 10 && serverMessage.channel != 0) { - throw new ConnectionException("Received CONNECTION class message on a channel > 0", ErrorType.COMMAND_INVALID, serverMessage.message.msgClassId, serverMessage.message.msgMethodId); + if (serverMessage.message.msgClassId == 10 && + serverMessage.channel != 0) { + throw ConnectionException( + "Received CONNECTION class message on a channel > 0", + ErrorType.COMMAND_INVALID, + serverMessage.message.msgClassId, + serverMessage.message.msgMethodId); } // Fetch target channel and forward frame for processing - _ChannelImpl target = _channels[ serverMessage.channel ]; + _ChannelImpl target = _channels[serverMessage.channel]; if (target == null) { // message on unknown channel; ignore return; @@ -115,10 +112,15 @@ class _ClientImpl implements Client { // If we got a ConnectionClose message from the server, throw the appropriate exception if (serverMessage.message is ConnectionClose) { // Ack the closing of the connection - _channels[0].writeMessage(new ConnectionCloseOk()); - - ConnectionClose serverResponse = (serverMessage.message as ConnectionClose); - throw new ConnectionException(serverResponse.replyText, ErrorType.valueOf(serverResponse.replyCode), serverResponse.msgClassId, serverResponse.msgMethodId); + _channels[0].writeMessage(ConnectionCloseOk()); + + ConnectionClose serverResponse = + (serverMessage.message as ConnectionClose); + throw ConnectionException( + serverResponse.replyText, + ErrorType.valueOf(serverResponse.replyCode), + serverResponse.msgClassId, + serverResponse.msgMethodId); } // Deliver to channel @@ -128,17 +130,18 @@ class _ClientImpl implements Client { // force the other channels to close if (serverMessage.message is ConnectionCloseOk) { _channels.values - .where((_ChannelImpl channel) => channel._channelClosed != null && !channel._channelClosed.isCompleted) - .forEach((_ChannelImpl channel) => channel._completeOperation(serverMessage.message)); + .where((_ChannelImpl channel) => + channel._channelClosed != null && + !channel._channelClosed.isCompleted) + .forEach((_ChannelImpl channel) => + channel._completeOperation(serverMessage.message)); } - } catch (e) { _handleException(e); } } void _handleException(ex) { - // Ignore exceptions while shutting down if (_clientClosed != null) { return; @@ -147,15 +150,15 @@ class _ClientImpl implements Client { // If we are still handshaking, it could be that the server disconnected us // due to a failed SASL auth attempt. In this case we should trigger a connection // exception - if( ex is SocketException ){ + if (ex is SocketException) { // Wrap the exception - if (handshaking && _channels.containsKey(0) && - (_channels[0]._lastHandshakeMessage is ConnectionStartOk || - _channels[0]._lastHandshakeMessage is ConnectionSecureOk) - ) { - ex = new FatalException("Authentication failed"); + if (handshaking && + _channels.containsKey(0) && + (_channels[0]._lastHandshakeMessage is ConnectionStartOk || + _channels[0]._lastHandshakeMessage is ConnectionSecureOk)) { + ex = FatalException("Authentication failed"); } else { - ex = new FatalException("Lost connection to the server"); + ex = FatalException("Lost connection to the server"); } } @@ -177,17 +180,17 @@ class _ClientImpl implements Client { case FatalException: case ConnectionException: - // Forward to all channels and then shutdown - _channels - .values.toList() - .reversed - .forEach((_ChannelImpl channel) => channel.handleException(ex)); + // Forward to all channels and then shutdown + _channels.values + .toList() + .reversed + .forEach((_ChannelImpl channel) => channel.handleException(ex)); close(); break; case ChannelException: - // Forward to the appropriate channel and remove it from our list - _ChannelImpl target = _channels[ ex.channel ]; + // Forward to the appropriate channel and remove it from our list + _ChannelImpl target = _channels[ex.channel]; if (target != null) { target.handleException(ex); _channels.remove(ex.channel); @@ -197,10 +200,8 @@ class _ClientImpl implements Client { } } - /** - * Open a working connection to the server using [config.cqlVersion] and optionally select - * keyspace [defaultKeyspace]. Returns a [Future] to be completed on a successful protocol handshake - */ + /// Open a working connection to the server using [config.cqlVersion] and optionally select + /// keyspace [defaultKeyspace]. Returns a [Future] to be completed on a successful protocol handshake Future connect() { // Prevent multiple connection attempts @@ -212,50 +213,45 @@ class _ClientImpl implements Client { return _reconnect(); } - /** - * Shutdown any open channels and disconnect the socket. Return a [Future] to be completed - * when the client has shut down - */ - Future close(){ - if (_socket == null) { - return new Future.value(); - } + /// Shutdown any open channels and disconnect the socket. Return a [Future] to be completed + /// when the client has shut down + Future close() { + if (_socket == null) { + return Future.value(); + } - // Already shutting down - if (_clientClosed != null) { - return _clientClosed.future; - } + // Already shutting down + if (_clientClosed != null) { + return _clientClosed.future; + } - // Close all channels in reverse order so we send a connection close message when we close channel 0 - _clientClosed = new Completer(); - Future.wait( - _channels - .values - .toList() - .reversed - .map((_ChannelImpl channel) => channel.close()) - ) - .then((_) => _socket.flush()) - .then((_) => _socket.close(), onError : (e){ - // Mute exception as the socket may be already closed - }) - .whenComplete(() { - _socket.destroy(); - _socket = null; - _connected = null; - _error.close(); - _clientClosed.complete(); - }); + // Close all channels in reverse order so we send a connection close message when we close channel 0 + _clientClosed = Completer(); + Future.wait(_channels.values + .toList() + .reversed + .map((_ChannelImpl channel) => channel.close())) + .then((_) => _socket.flush()) + .then((_) => _socket.close(), onError: (e) { + // Mute exception as the socket may be already closed + }).whenComplete(() { + _socket.destroy(); + _socket = null; + _connected = null; + _error.close(); + _clientClosed.complete(); + }); - return _clientClosed.future; + return _clientClosed.future; } Future channel() { - return connect() - .then((_) { + return connect().then((_) { // Check if we have exceeded our channel limit (open channels excluding channel 0) - if (tuningSettings.maxChannels > 0 && _channels.length - 1 >= tuningSettings.maxChannels) { - return new Future.error(new StateError("Cannot allocate channel; channel limit exceeded (max ${tuningSettings.maxChannels})")); + if (tuningSettings.maxChannels > 0 && + _channels.length - 1 >= tuningSettings.maxChannels) { + return Future.error(StateError( + "Cannot allocate channel; channel limit exceeded (max ${tuningSettings.maxChannels})")); } // Find next available channel @@ -264,22 +260,26 @@ class _ClientImpl implements Client { while (nextChannelId < 65536) { if (!_channels.containsKey(++nextChannelId)) { // Found empty slot - userChannel = new _ChannelImpl(nextChannelId, this); - _channels[ nextChannelId ] = userChannel; + userChannel = _ChannelImpl(nextChannelId, this); + _channels[nextChannelId] = userChannel; break; } } // Run out of slots? if (userChannel == null) { - return new Future.error(new StateError("Cannot allocate channel; all channels are currently in use")); + return Future.error(StateError( + "Cannot allocate channel; all channels are currently in use")); } return userChannel._channelOpened.future; }); } - StreamSubscription errorListener(void onData(Exception error), { Function onError, void onDone(), bool cancelOnError}) => _error.stream.listen(onData, onError : onError, onDone : onDone, cancelOnError : cancelOnError); + StreamSubscription errorListener(void onData(Exception error), + {Function onError, void onDone(), bool cancelOnError}) => + _error.stream.listen(onData, + onError: onError, onDone: onDone, cancelOnError: cancelOnError); - _ChannelImpl _removeChannel(int channelId)=>_channels.remove(channelId); + _ChannelImpl _removeChannel(int channelId) => _channels.remove(channelId); } diff --git a/lib/src/client/impl/consumer_impl.dart b/lib/src/client/impl/consumer_impl.dart index 6f3fd54..15f78ec 100644 --- a/lib/src/client/impl/consumer_impl.dart +++ b/lib/src/client/impl/consumer_impl.dart @@ -2,23 +2,28 @@ part of dart_amqp.client; class _ConsumerImpl implements Consumer { String _tag; - final _controller = new StreamController(); + final _controller = StreamController(); final _ChannelImpl channel; final _QueueImpl queue; String get tag => _tag; - _ConsumerImpl(_ChannelImpl this.channel, _QueueImpl this.queue, String this._tag); + _ConsumerImpl( + _ChannelImpl this.channel, _QueueImpl this.queue, String this._tag); - StreamSubscription listen(void onData(AmqpMessage event), { Function onError, void onDone(), bool cancelOnError}) => _controller.stream.listen(onData, onError : onError, onDone : onDone, cancelOnError : cancelOnError); + StreamSubscription listen(void onData(AmqpMessage event), + {Function onError, void onDone(), bool cancelOnError}) => + _controller.stream.listen(onData, + onError: onError, onDone: onDone, cancelOnError: cancelOnError); - Future cancel({bool noWait : false}) { - BasicCancel cancelRequest = new BasicCancel() + Future cancel({bool noWait = false}) { + BasicCancel cancelRequest = BasicCancel() ..consumerTag = _tag ..noWait = noWait; - Completer completer = new Completer(); - channel.writeMessage(cancelRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(cancelRequest, + completer: completer, futurePayload: this); completer.future.then((_) => _controller.close()); return completer.future; } @@ -26,9 +31,9 @@ class _ConsumerImpl implements Consumer { void onMessage(DecodedMessageImpl serverMessage) { // Ensure that messate contains a non-null property object if (serverMessage.properties == null) { - serverMessage.properties = new MessageProperties(); + serverMessage.properties = MessageProperties(); } - _controller.add(new _AmqpMessageImpl.fromDecodedMessage(this, serverMessage)); + _controller.add(_AmqpMessageImpl.fromDecodedMessage(this, serverMessage)); } } diff --git a/lib/src/client/impl/exchange_impl.dart b/lib/src/client/impl/exchange_impl.dart index e2f5594..44083d2 100644 --- a/lib/src/client/impl/exchange_impl.dart +++ b/lib/src/client/impl/exchange_impl.dart @@ -9,49 +9,58 @@ class _ExchangeImpl implements Exchange { String get name => _name; - Future delete({bool ifUnused : false, bool noWait : false}) { - ExchangeDelete deleteRequest = new ExchangeDelete() + Future delete({bool ifUnused = false, bool noWait = false}) { + ExchangeDelete deleteRequest = ExchangeDelete() ..reserved_1 = 0 ..exchange = name ..ifUnused = ifUnused ..noWait = noWait; - Completer completer = new Completer(); - channel.writeMessage(deleteRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(deleteRequest, + completer: completer, futurePayload: this); return completer.future; } - void publish(Object message, String routingKey, { MessageProperties properties, bool mandatory : false, bool immediate : false}) { - if (!type.isCustom && type != ExchangeType.FANOUT && type != ExchangeType.HEADERS && (routingKey == null || routingKey.isEmpty)) { - throw new ArgumentError("A valid routing key needs to be specified"); + void publish(Object message, String routingKey, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}) { + if (!type.isCustom && + type != ExchangeType.FANOUT && + type != ExchangeType.HEADERS && + (routingKey == null || routingKey.isEmpty)) { + throw ArgumentError("A valid routing key needs to be specified"); } - BasicPublish pubRequest = new BasicPublish() + BasicPublish pubRequest = BasicPublish() ..reserved_1 = 0 ..routingKey = routingKey ..exchange = name ..mandatory = mandatory ..immediate = immediate; - channel.writeMessage(pubRequest, properties : properties, payloadContent : message); + channel.writeMessage(pubRequest, + properties: properties, payloadContent: message); } - Future bindPrivateQueueConsumer(List routingKeys, {String consumerTag, bool noAck: true}) { + Future bindPrivateQueueConsumer(List routingKeys, + {String consumerTag, bool noAck = true}) { // Fanout and headers exchanges do not need to specify any keys. Use the default one if none is specified - if ((type == ExchangeType.FANOUT || type == ExchangeType.HEADERS) && (routingKeys == null || routingKeys.isEmpty)) { + if ((type == ExchangeType.FANOUT || type == ExchangeType.HEADERS) && + (routingKeys == null || routingKeys.isEmpty)) { routingKeys = [""]; } if ((routingKeys == null || routingKeys.isEmpty)) { - throw new ArgumentError("One or more routing keys needs to be specified for this exchange type"); + throw ArgumentError( + "One or more routing keys needs to be specified for this exchange type"); } - return channel - .privateQueue() - .then((Queue queue) { - return Future - .forEach(routingKeys, (String routingKey) => queue.bind(this, routingKey)) - .then((_) => queue.consume(consumerTag : consumerTag, noAck : noAck)); + return channel.privateQueue().then((Queue queue) { + return Future.forEach( + routingKeys, (String routingKey) => queue.bind(this, routingKey)) + .then((_) => queue.consume(consumerTag: consumerTag, noAck: noAck)); }); } } diff --git a/lib/src/client/impl/queue_impl.dart b/lib/src/client/impl/queue_impl.dart index 81d12a1..5081449 100644 --- a/lib/src/client/impl/queue_impl.dart +++ b/lib/src/client/impl/queue_impl.dart @@ -14,44 +14,50 @@ class _QueueImpl implements Queue { int get consumerCount => _consumerCount; - Future delete({bool ifUnused : false, bool IfEmpty : false, bool noWait : false}) { - QueueDelete deleteRequest = new QueueDelete() + Future delete( + {bool ifUnused = false, bool IfEmpty = false, bool noWait = false}) { + QueueDelete deleteRequest = QueueDelete() ..reserved_1 = 0 ..queue = name ..ifUnused = ifUnused ..ifEmpty = IfEmpty ..noWait = noWait; - Completer completer = new Completer(); - channel.writeMessage(deleteRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(deleteRequest, + completer: completer, futurePayload: this); return completer.future; } - Future purge({bool noWait : false}) { - QueuePurge purgeRequest = new QueuePurge() + Future purge({bool noWait = false}) { + QueuePurge purgeRequest = QueuePurge() ..reserved_1 = 0 ..queue = name ..noWait = noWait; - Completer completer = new Completer(); - channel.writeMessage(purgeRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(purgeRequest, + completer: completer, futurePayload: this); return completer.future; } - Future bind(Exchange exchange, String routingKey, {bool noWait, Map arguments}) { + Future bind(Exchange exchange, String routingKey, + {bool noWait, Map arguments}) { if (exchange == null) { - throw new ArgumentError("Exchange cannot be null"); + throw ArgumentError("Exchange cannot be null"); } // Fanout and headers exchanges do not need to specify any keys. Use the default one if none is specified if (routingKey == null || routingKey.isEmpty) { - if (exchange.type == ExchangeType.FANOUT || exchange.type == ExchangeType.HEADERS) { + if (exchange.type == ExchangeType.FANOUT || + exchange.type == ExchangeType.HEADERS) { routingKey = ""; } else { - throw new ArgumentError("A routing key needs to be specified to bind to this exchange type"); + throw ArgumentError( + "A routing key needs to be specified to bind to this exchange type"); } } - QueueBind bindRequest = new QueueBind() + QueueBind bindRequest = QueueBind() ..reserved_1 = 0 ..queue = name ..exchange = exchange.name @@ -59,54 +65,71 @@ class _QueueImpl implements Queue { ..noWait = noWait ..arguments = arguments; - Completer completer = new Completer(); - channel.writeMessage(bindRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(bindRequest, + completer: completer, futurePayload: this); return completer.future; } - Future unbind(Exchange exchange, String routingKey, {bool noWait, Map arguments}) { + Future unbind(Exchange exchange, String routingKey, + {bool noWait, Map arguments}) { if (exchange == null) { - throw new ArgumentError("Exchange cannot be null"); + throw ArgumentError("Exchange cannot be null"); } // Fanout and headers exchanges do not need to specify any keys. Use the default one if none is specified if (routingKey == null || routingKey.isEmpty) { - if (exchange.type == ExchangeType.FANOUT || exchange.type == ExchangeType.HEADERS) { + if (exchange.type == ExchangeType.FANOUT || + exchange.type == ExchangeType.HEADERS) { routingKey = ""; } else { - throw new ArgumentError("A routing key needs to be specified to unbind from this exchange type"); + throw ArgumentError( + "A routing key needs to be specified to unbind from this exchange type"); } } - QueueUnbind unbindRequest = new QueueUnbind() + QueueUnbind unbindRequest = QueueUnbind() ..reserved_1 = 0 ..queue = name ..exchange = exchange.name ..routingKey = routingKey ..arguments = arguments; - Completer completer = new Completer(); - channel.writeMessage(unbindRequest, completer : completer, futurePayload : this); + Completer completer = Completer(); + channel.writeMessage(unbindRequest, + completer: completer, futurePayload: this); return completer.future; } - void publish(Object message, { MessageProperties properties, bool mandatory : false, bool immediate : false}) { - BasicPublish pubRequest = new BasicPublish() + void publish(Object message, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}) { + BasicPublish pubRequest = BasicPublish() ..reserved_1 = 0 ..routingKey = name // send to this queue ..exchange = "" // default exchange ..mandatory = mandatory ..immediate = immediate; - channel.writeMessage(pubRequest, properties : properties, payloadContent : message); + channel.writeMessage(pubRequest, + properties: properties, payloadContent: message); } - Future consume({String consumerTag, bool noLocal : false, bool noAck: true, bool exclusive : false, bool noWait : false, Map arguments}) { + Future consume( + {String consumerTag, + bool noLocal = false, + bool noAck = true, + bool exclusive = false, + bool noWait = false, + Map arguments}) { // If a consumer with the requested tag exists, return that - if (consumerTag != null && !consumerTag.isEmpty && channel._consumers.containsKey(consumerTag)) { - return new Future.value(channel._consumers[consumerTag]); + if (consumerTag != null && + !consumerTag.isEmpty && + channel._consumers.containsKey(consumerTag)) { + return Future.value(channel._consumers[consumerTag]); } - BasicConsume consumeRequest = new BasicConsume() + BasicConsume consumeRequest = BasicConsume() ..reserved_1 = 0 ..queue = name ..consumerTag = consumerTag @@ -116,9 +139,9 @@ class _QueueImpl implements Queue { ..exclusive = exclusive ..arguments = arguments; - Completer completer = new Completer(); - channel.writeMessage(consumeRequest, completer : completer, futurePayload : new _ConsumerImpl(channel, this, "")); + Completer completer = Completer(); + channel.writeMessage(consumeRequest, + completer: completer, futurePayload: _ConsumerImpl(channel, this, "")); return completer.future; } - } diff --git a/lib/src/client/queue.dart b/lib/src/client/queue.dart index 35e51d5..aedd998 100644 --- a/lib/src/client/queue.dart +++ b/lib/src/client/queue.dart @@ -1,86 +1,81 @@ part of dart_amqp.client; abstract class Queue { - - /** - * Get the queue name - */ + /// Get the queue name String get name; int get messageCount; int get consumerCount; - /** - * Get the [Channel] where this [Queue] was declared - */ + /// Get the [Channel] where this [Queue] was declared Channel get channel; - /** - * Delete the queue and return a [Future] for the deleted queue. - * - * If the [ifUnsused] flag is set, the server will only delete the queue if it has no consumers. If the - * flag is set and the queue has any consumer left, then the server will raise an exception. - * - * If the [ifEmpty] flag is set, the server will only delete the queue if it has no messages. If the - * flag is set and the queue has any messages on it, the server will raise an exception. - */ - Future delete({bool ifUnused : false, bool IfEmpty : false, bool noWait : false}); + /// Delete the queue and return a [Future] for the deleted queue. + /// + /// If the [ifUnsused] flag is set, the server will only delete the queue if it has no consumers. If the + /// flag is set and the queue has any consumer left, then the server will raise an exception. + /// + /// If the [ifEmpty] flag is set, the server will only delete the queue if it has no messages. If the + /// flag is set and the queue has any messages on it, the server will raise an exception. + Future delete( + {bool ifUnused = false, bool IfEmpty = false, bool noWait = false}); - /** - * Purge any queued messages that are not awaiting acknowledgment. - * - * Returns a [Future] for the purged queue. - */ - Future purge({bool noWait : false}); + /// Purge any queued messages that are not awaiting acknowledgment. + /// + /// Returns a [Future] for the purged queue. + Future purge({bool noWait = false}); - /** - * Bind this queue to [exchange] using [routingKey] and return a [Future] to the bound queue. - * - * The [routingKey] parameter cannot be empty or null unless [exchange] is of type [ExchangeType.FANOUT] or [ExchangeType.HEADERS]. - * For any other [exchange] type, passing an empty or null [routingKey] will cause an [ArgumentError] - * to be thrown. - */ - Future bind(Exchange exchange, String routingKey, {bool noWait, Map arguments}); + /// Bind this queue to [exchange] using [routingKey] and return a [Future] to the bound queue. + /// + /// The [routingKey] parameter cannot be empty or null unless [exchange] is of type [ExchangeType.FANOUT] or [ExchangeType.HEADERS]. + /// For any other [exchange] type, passing an empty or null [routingKey] will cause an [ArgumentError] + /// to be thrown. + Future bind(Exchange exchange, String routingKey, + {bool noWait, Map arguments}); - /** - * Unbind this queue from [exchange] with [routingKey] and return a [Future] to the unbound queue. - * - * The [routingKey] parameter cannot be empty or null unless [exchange] is of type [ExchangeType.FANOUT] or [ExchangeType.HEADERS]. - * For any other [exchange] type, passing an empty or null [routingKey] will cause an [ArgumentError] - * to be thrown. - */ - Future unbind(Exchange exchange, String routingKey, {bool noWait, Map arguments}); + /// Unbind this queue from [exchange] with [routingKey] and return a [Future] to the unbound queue. + /// + /// The [routingKey] parameter cannot be empty or null unless [exchange] is of type [ExchangeType.FANOUT] or [ExchangeType.HEADERS]. + /// For any other [exchange] type, passing an empty or null [routingKey] will cause an [ArgumentError] + /// to be thrown. + Future unbind(Exchange exchange, String routingKey, + {bool noWait, Map arguments}); - /** - * Publish [message] to the queue. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. - * If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties - * (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will - * trigger an [ArgumentError]. - * - * You may specify additional message properties by setting the [properties] named parameter. - * - * If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise - * the server will drop un-routable messages. - * - * if the [immediate] flag is set, the server will immediately return undeliverable messages to the client - * if it cannot route them. If the flag is set to false, the server will queue the message even though - * there is no guarantee that it will ever be consumed. - */ - void publish(Object message, { MessageProperties properties, bool mandatory : false, bool immediate : false}); + /// Publish [message] to the queue. [message] should be either a [Uint8List], a [String], a [Map] or [Iterable]. + /// If [message] is [Map] or [Iterable] it will be encoded as JSON and the appropriate message properties + /// (content-type and content-encoding) will be set on the outgoing message. Any other [message] value will + /// trigger an [ArgumentError]. + /// + /// You may specify additional message properties by setting the [properties] named parameter. + /// + /// If the [mandatory] flag is set, the server will return un-routable messages back to the client. Otherwise + /// the server will drop un-routable messages. + /// + /// if the [immediate] flag is set, the server will immediately return undeliverable messages to the client + /// if it cannot route them. If the flag is set to false, the server will queue the message even though + /// there is no guarantee that it will ever be consumed. + void publish(Object message, + {MessageProperties properties, + bool mandatory = false, + bool immediate = false}); - /** - * Create a consumer for processing queued messages and return a [Future] to the created - * consumer. - * - * You may specify a [consumerTag] to label this consumer. If left unspecified, the server will assign a - * random tag to this consumer. Consumer tags are local to the current channel. - * - * The [noAck] flag will notify the server whether the consumer is expected to acknowledge incoming - * messages or not. - * - * If the [exclusive] flag is set then only this consumer has access to the queue. If the flag is set - * and the queue already has attached consumers, then the server will raise an error. - */ - Future consume({String consumerTag, bool noLocal : false, bool noAck: true, bool exclusive : false, bool noWait : false, Map arguments}); + /// Create a consumer for processing queued messages and return a [Future] to the created + /// consumer. + /// + /// You may specify a [consumerTag] to label this consumer. If left unspecified, the server will assign a + /// random tag to this consumer. Consumer tags are local to the current channel. + /// + /// The [noAck] flag will notify the server whether the consumer is expected to acknowledge incoming + /// messages or not. + /// + /// If the [exclusive] flag is set then only this consumer has access to the queue. If the flag is set + /// and the queue already has attached consumers, then the server will raise an error. + Future consume( + {String consumerTag, + bool noLocal = false, + bool noAck = true, + bool exclusive = false, + bool noWait = false, + Map arguments}); } diff --git a/lib/src/enums/delivery_mode.dart b/lib/src/enums/delivery_mode.dart index 7c30dc5..8f67096 100644 --- a/lib/src/enums/delivery_mode.dart +++ b/lib/src/enums/delivery_mode.dart @@ -1,23 +1,25 @@ part of dart_amqp.enums; class DeliveryMode extends Enum { - static const DeliveryMode TRANSIENT = const DeliveryMode._(1); - static const DeliveryMode PERSISTENT = const DeliveryMode._(2); + static const DeliveryMode TRANSIENT = DeliveryMode._(1); + static const DeliveryMode PERSISTENT = DeliveryMode._(2); const DeliveryMode._(int value) : super(value); static DeliveryMode valueOf(int value) { - DeliveryMode fromValue = value == TRANSIENT._value ? TRANSIENT : - value == PERSISTENT._value ? PERSISTENT : null; + DeliveryMode fromValue = value == TRANSIENT._value + ? TRANSIENT + : value == PERSISTENT._value ? PERSISTENT : null; if (fromValue == null) { - throw new ArgumentError("Invalid delivery mode value ${value}"); + throw ArgumentError("Invalid delivery mode value ${value}"); } return fromValue; } static String nameOf(DeliveryMode value) { - return value == TRANSIENT ? "TRANSIENT" : - value == PERSISTENT ? "PERSISTENT" : null; + return value == TRANSIENT + ? "TRANSIENT" + : value == PERSISTENT ? "PERSISTENT" : null; } -} \ No newline at end of file +} diff --git a/lib/src/enums/enum.dart b/lib/src/enums/enum.dart index 5450c00..331d3e4 100644 --- a/lib/src/enums/enum.dart +++ b/lib/src/enums/enum.dart @@ -1,14 +1,10 @@ part of dart_amqp.enums; -/** - * An abstract class for modeling enums - */ +/// An abstract class for modeling enums abstract class Enum { - final T _value; const Enum(this._value); T get value => _value; - -} \ No newline at end of file +} diff --git a/lib/src/enums/error_type.dart b/lib/src/enums/error_type.dart index 793a1e0..fc563f1 100644 --- a/lib/src/enums/error_type.dart +++ b/lib/src/enums/error_type.dart @@ -1,79 +1,133 @@ part of dart_amqp.enums; class ErrorType extends Enum { - - static const ErrorType SUCCESS = const ErrorType._(200, false); - static const ErrorType CONTENT_TOO_LARGE = const ErrorType._(311, false); - static const ErrorType NO_CONSUMERS = const ErrorType._(313, false); - static const ErrorType CONNECTION_FORCED = const ErrorType._(320, true); - static const ErrorType INVALID_PATH = const ErrorType._(402, true); - static const ErrorType ACCESS_REFUSED = const ErrorType._(403, false); - static const ErrorType NOT_FOUND = const ErrorType._(404, false); - static const ErrorType RESOURCE_LOCKED = const ErrorType._(405, false); - static const ErrorType PRECONDITION_FAILED = const ErrorType._(406, false); - static const ErrorType FRAME_ERROR = const ErrorType._(501, true); - static const ErrorType SYNTAX_ERROR = const ErrorType._(502, true); - static const ErrorType COMMAND_INVALID = const ErrorType._(503, true); - static const ErrorType CHANNEL_ERROR = const ErrorType._(504, true); - static const ErrorType UNEXPECTED_FRAME = const ErrorType._(505, true); - static const ErrorType RESOURCE_ERROR = const ErrorType._(506, true); - static const ErrorType NOT_ALLOWED = const ErrorType._(530, true); - static const ErrorType NOT_IMPLEMENTED = const ErrorType._(540, true); - static const ErrorType INTERNAL_ERROR = const ErrorType._(541, true); + static const ErrorType SUCCESS = ErrorType._(200, false); + static const ErrorType CONTENT_TOO_LARGE = ErrorType._(311, false); + static const ErrorType NO_CONSUMERS = ErrorType._(313, false); + static const ErrorType CONNECTION_FORCED = ErrorType._(320, true); + static const ErrorType INVALID_PATH = ErrorType._(402, true); + static const ErrorType ACCESS_REFUSED = ErrorType._(403, false); + static const ErrorType NOT_FOUND = ErrorType._(404, false); + static const ErrorType RESOURCE_LOCKED = ErrorType._(405, false); + static const ErrorType PRECONDITION_FAILED = ErrorType._(406, false); + static const ErrorType FRAME_ERROR = ErrorType._(501, true); + static const ErrorType SYNTAX_ERROR = ErrorType._(502, true); + static const ErrorType COMMAND_INVALID = ErrorType._(503, true); + static const ErrorType CHANNEL_ERROR = ErrorType._(504, true); + static const ErrorType UNEXPECTED_FRAME = ErrorType._(505, true); + static const ErrorType RESOURCE_ERROR = ErrorType._(506, true); + static const ErrorType NOT_ALLOWED = ErrorType._(530, true); + static const ErrorType NOT_IMPLEMENTED = ErrorType._(540, true); + static const ErrorType INTERNAL_ERROR = ErrorType._(541, true); final bool isHardError; - const ErrorType._(int value, bool hardError) : isHardError = hardError, super(value); + const ErrorType._(int value, bool hardError) + : isHardError = hardError, + super(value); String toString() => "${value}"; static ErrorType valueOf(int value) { - ErrorType fromValue = value == SUCCESS._value ? SUCCESS : - value == CONTENT_TOO_LARGE._value ? CONTENT_TOO_LARGE : - value == NO_CONSUMERS._value ? NO_CONSUMERS : - value == CONNECTION_FORCED._value ? CONNECTION_FORCED : - value == INVALID_PATH._value ? INVALID_PATH : - value == ACCESS_REFUSED._value ? ACCESS_REFUSED : - value == NOT_FOUND._value ? NOT_FOUND : - value == RESOURCE_LOCKED._value ? RESOURCE_LOCKED : - value == PRECONDITION_FAILED._value ? PRECONDITION_FAILED : - value == FRAME_ERROR._value ? FRAME_ERROR : - value == SYNTAX_ERROR._value ? SYNTAX_ERROR : - value == COMMAND_INVALID._value ? COMMAND_INVALID : - value == CHANNEL_ERROR._value ? CHANNEL_ERROR : - value == UNEXPECTED_FRAME._value ? UNEXPECTED_FRAME : - value == RESOURCE_ERROR._value ? RESOURCE_ERROR : - value == NOT_ALLOWED._value ? NOT_ALLOWED : - value == NOT_IMPLEMENTED._value ? NOT_IMPLEMENTED : - value == INTERNAL_ERROR._value ? INTERNAL_ERROR : null; + ErrorType fromValue = value == SUCCESS._value + ? SUCCESS + : value == CONTENT_TOO_LARGE._value + ? CONTENT_TOO_LARGE + : value == NO_CONSUMERS._value + ? NO_CONSUMERS + : value == CONNECTION_FORCED._value + ? CONNECTION_FORCED + : value == INVALID_PATH._value + ? INVALID_PATH + : value == ACCESS_REFUSED._value + ? ACCESS_REFUSED + : value == NOT_FOUND._value + ? NOT_FOUND + : value == RESOURCE_LOCKED._value + ? RESOURCE_LOCKED + : value == PRECONDITION_FAILED._value + ? PRECONDITION_FAILED + : value == FRAME_ERROR._value + ? FRAME_ERROR + : value == SYNTAX_ERROR._value + ? SYNTAX_ERROR + : value == + COMMAND_INVALID._value + ? COMMAND_INVALID + : value == + CHANNEL_ERROR._value + ? CHANNEL_ERROR + : value == + UNEXPECTED_FRAME + ._value + ? UNEXPECTED_FRAME + : value == + RESOURCE_ERROR + ._value + ? RESOURCE_ERROR + : value == + NOT_ALLOWED + ._value + ? NOT_ALLOWED + : value == + NOT_IMPLEMENTED + ._value + ? NOT_IMPLEMENTED + : value == + INTERNAL_ERROR._value + ? INTERNAL_ERROR + : null; if (fromValue == null) { - throw new ArgumentError("Invalid error type value ${value}"); + throw ArgumentError("Invalid error type value ${value}"); } return fromValue; } static String nameOf(ErrorType value) { - String name = value == SUCCESS ? "SUCCESS" : - value == CONTENT_TOO_LARGE ? "CONTENT_TOO_LARGE" : - value == NO_CONSUMERS ? "NO_CONSUMERS" : - value == CONNECTION_FORCED ? "CONNECTION_FORCED" : - value == INVALID_PATH ? "INVALID_PATH" : - value == ACCESS_REFUSED ? "ACCESS_REFUSED" : - value == NOT_FOUND ? "NOT_FOUND" : - value == RESOURCE_LOCKED ? "RESOURCE_LOCKED" : - value == PRECONDITION_FAILED ? "PRECONDITION_FAILED" : - value == FRAME_ERROR ? "FRAME_ERROR" : - value == SYNTAX_ERROR ? "SYNTAX_ERROR" : - value == COMMAND_INVALID ? "COMMAND_INVALID" : - value == CHANNEL_ERROR ? "CHANNEL_ERROR" : - value == UNEXPECTED_FRAME ? "UNEXPECTED_FRAME" : - value == RESOURCE_ERROR ? "RESOURCE_ERROR" : - value == NOT_ALLOWED ? "NOT_ALLOWED" : - value == NOT_IMPLEMENTED ? "NOT_IMPLEMENTED" : - value == INTERNAL_ERROR ? "INTERNAL_ERROR" : null; + String name = value == SUCCESS + ? "SUCCESS" + : value == CONTENT_TOO_LARGE + ? "CONTENT_TOO_LARGE" + : value == NO_CONSUMERS + ? "NO_CONSUMERS" + : value == CONNECTION_FORCED + ? "CONNECTION_FORCED" + : value == INVALID_PATH + ? "INVALID_PATH" + : value == ACCESS_REFUSED + ? "ACCESS_REFUSED" + : value == NOT_FOUND + ? "NOT_FOUND" + : value == RESOURCE_LOCKED + ? "RESOURCE_LOCKED" + : value == PRECONDITION_FAILED + ? "PRECONDITION_FAILED" + : value == FRAME_ERROR + ? "FRAME_ERROR" + : value == SYNTAX_ERROR + ? "SYNTAX_ERROR" + : value == COMMAND_INVALID + ? "COMMAND_INVALID" + : value == CHANNEL_ERROR + ? "CHANNEL_ERROR" + : value == + UNEXPECTED_FRAME + ? "UNEXPECTED_FRAME" + : value == + RESOURCE_ERROR + ? "RESOURCE_ERROR" + : value == + NOT_ALLOWED + ? "NOT_ALLOWED" + : value == + NOT_IMPLEMENTED + ? "NOT_IMPLEMENTED" + : value == + INTERNAL_ERROR + ? "INTERNAL_ERROR" + : null; return name; } } - diff --git a/lib/src/enums/exchange_type.dart b/lib/src/enums/exchange_type.dart index 5abe9d7..124fbaf 100644 --- a/lib/src/enums/exchange_type.dart +++ b/lib/src/enums/exchange_type.dart @@ -1,10 +1,10 @@ part of dart_amqp.enums; class ExchangeType extends BaseExchange { - static const ExchangeType FANOUT = const ExchangeType._("fanout"); - static const ExchangeType DIRECT = const ExchangeType._("direct"); - static const ExchangeType TOPIC = const ExchangeType._("topic"); - static const ExchangeType HEADERS = const ExchangeType._("headers"); + static const ExchangeType FANOUT = ExchangeType._("fanout"); + static const ExchangeType DIRECT = ExchangeType._("direct"); + static const ExchangeType TOPIC = ExchangeType._("topic"); + static const ExchangeType HEADERS = ExchangeType._("headers"); const ExchangeType._(String value) : super._(value, false); @@ -13,29 +13,36 @@ class ExchangeType extends BaseExchange { String toString() => "${value}"; static ExchangeType valueOf(String value) { - ExchangeType fromValue = value == FANOUT._value ? FANOUT : - value == DIRECT._value ? DIRECT : - value == TOPIC._value ? TOPIC : - value == HEADERS._value ? HEADERS : new ExchangeType.custom(value); + ExchangeType fromValue = value == FANOUT._value + ? FANOUT + : value == DIRECT._value + ? DIRECT + : value == TOPIC._value + ? TOPIC + : value == HEADERS._value + ? HEADERS + : ExchangeType.custom(value); return fromValue; } static String nameOf(ExchangeType value) { - String name = value == FANOUT ? "FANOUT" : - value == DIRECT ? "DIRECT" : - value == TOPIC ? "TOPIC" : - value == HEADERS ? "HEADERS" : - value.isCustom ? "CUSTOM" : null; + String name = value == FANOUT + ? "FANOUT" + : value == DIRECT + ? "DIRECT" + : value == TOPIC + ? "TOPIC" + : value == HEADERS + ? "HEADERS" + : value.isCustom ? "CUSTOM" : null; return name; } } class BaseExchange extends Enum { - final bool isCustom; - const BaseExchange._(T value, this.isCustom) :super(value); - -} \ No newline at end of file + const BaseExchange._(T value, this.isCustom) : super(value); +} diff --git a/lib/src/enums/field_type.dart b/lib/src/enums/field_type.dart index 47878fd..7d672a7 100644 --- a/lib/src/enums/field_type.dart +++ b/lib/src/enums/field_type.dart @@ -1,71 +1,123 @@ part of dart_amqp.enums; class FieldType extends Enum { - static const FieldType BOOLEAN = const FieldType._(116); - static const FieldType SHORT_SHORT_INT = const FieldType._(98); - static const FieldType SHORT_SHORT_UINT = const FieldType._(66); - static const FieldType SHORT_INT = const FieldType._(85); - static const FieldType SHORT_UINT = const FieldType._(117); - static const FieldType LONG_INT = const FieldType._(73); - static const FieldType LONG_UINT = const FieldType._(105); - static const FieldType LONG_LONG_INT = const FieldType._(76); - static const FieldType LONG_LONG_UINT = const FieldType._(108); - static const FieldType FLOAT = const FieldType._(102); - static const FieldType DOUBLE = const FieldType._(100); - static const FieldType DECIMAL = const FieldType._(68); - static const FieldType SHORT_STRING = const FieldType._(115); - static const FieldType LONG_STRING = const FieldType._(83); - static const FieldType FIELD_ARRAY = const FieldType._(65); - static const FieldType TIMESTAMP = const FieldType._(84); - static const FieldType FIELD_TABLE = const FieldType._(70); - static const FieldType VOID = const FieldType._(86); + static const FieldType BOOLEAN = FieldType._(116); + static const FieldType SHORT_SHORT_INT = FieldType._(98); + static const FieldType SHORT_SHORT_UINT = FieldType._(66); + static const FieldType SHORT_INT = FieldType._(85); + static const FieldType SHORT_UINT = FieldType._(117); + static const FieldType LONG_INT = FieldType._(73); + static const FieldType LONG_UINT = FieldType._(105); + static const FieldType LONG_LONG_INT = FieldType._(76); + static const FieldType LONG_LONG_UINT = FieldType._(108); + static const FieldType FLOAT = FieldType._(102); + static const FieldType DOUBLE = FieldType._(100); + static const FieldType DECIMAL = FieldType._(68); + static const FieldType SHORT_STRING = FieldType._(115); + static const FieldType LONG_STRING = FieldType._(83); + static const FieldType FIELD_ARRAY = FieldType._(65); + static const FieldType TIMESTAMP = FieldType._(84); + static const FieldType FIELD_TABLE = FieldType._(70); + static const FieldType VOID = FieldType._(86); const FieldType._(int value) : super(value); static FieldType valueOf(int value) { - FieldType fromValue = value == BOOLEAN._value ? BOOLEAN : - value == SHORT_SHORT_INT._value ? SHORT_SHORT_INT : - value == SHORT_SHORT_UINT._value ? SHORT_SHORT_UINT : - value == SHORT_INT._value ? SHORT_INT : - value == SHORT_UINT._value ? SHORT_UINT : - value == LONG_INT._value ? LONG_INT : - value == LONG_UINT._value ? LONG_UINT : - value == LONG_LONG_INT._value ? LONG_LONG_INT : - value == LONG_LONG_UINT._value ? LONG_LONG_UINT : - value == FLOAT._value ? FLOAT : - value == DOUBLE._value ? DOUBLE : - value == DECIMAL._value ? DECIMAL : - value == SHORT_STRING._value ? SHORT_STRING : - value == LONG_STRING._value ? LONG_STRING : - value == FIELD_ARRAY._value ? FIELD_ARRAY : - value == TIMESTAMP._value ? TIMESTAMP : - value == FIELD_TABLE._value ? FIELD_TABLE : - value == VOID._value ? VOID : null; + FieldType fromValue = value == BOOLEAN._value + ? BOOLEAN + : value == SHORT_SHORT_INT._value + ? SHORT_SHORT_INT + : value == SHORT_SHORT_UINT._value + ? SHORT_SHORT_UINT + : value == SHORT_INT._value + ? SHORT_INT + : value == SHORT_UINT._value + ? SHORT_UINT + : value == LONG_INT._value + ? LONG_INT + : value == LONG_UINT._value + ? LONG_UINT + : value == LONG_LONG_INT._value + ? LONG_LONG_INT + : value == LONG_LONG_UINT._value + ? LONG_LONG_UINT + : value == FLOAT._value + ? FLOAT + : value == DOUBLE._value + ? DOUBLE + : value == DECIMAL._value + ? DECIMAL + : value == + SHORT_STRING._value + ? SHORT_STRING + : value == + LONG_STRING + ._value + ? LONG_STRING + : value == + FIELD_ARRAY + ._value + ? FIELD_ARRAY + : value == + TIMESTAMP + ._value + ? TIMESTAMP + : value == + FIELD_TABLE + ._value + ? FIELD_TABLE + : value == + VOID._value + ? VOID + : null; if (fromValue == null) { - throw new ArgumentError("Invalid field type value ${value}"); + throw ArgumentError("Invalid field type value ${value}"); } return fromValue; } static String nameOf(FieldType value) { - return value == BOOLEAN ? "BOOLEAN" : - value == SHORT_SHORT_INT ? "SHORT_SHORT_INT" : - value == SHORT_SHORT_UINT ? "SHORT_SHORT_UINT" : - value == SHORT_INT ? "SHORT_INT" : - value == SHORT_UINT ? "SHORT_UINT" : - value == LONG_INT ? "LONG_INT" : - value == LONG_UINT ? "LONG_UINT" : - value == LONG_LONG_INT ? "LONG_LONG_INT" : - value == LONG_LONG_UINT ? "LONG_LONG_UINT" : - value == FLOAT ? "FLOAT" : - value == DOUBLE ? "DOUBLE" : - value == DECIMAL ? "DECIMAL" : - value == SHORT_STRING ? "SHORT_STRING" : - value == LONG_STRING ? "LONG_STRING" : - value == FIELD_ARRAY ? "FIELD_ARRAY" : - value == TIMESTAMP ? "TIMESTAMP" : - value == FIELD_TABLE ? "FIELD_TABLE" : - value == VOID ? "VOID" : null; + return value == BOOLEAN + ? "BOOLEAN" + : value == SHORT_SHORT_INT + ? "SHORT_SHORT_INT" + : value == SHORT_SHORT_UINT + ? "SHORT_SHORT_UINT" + : value == SHORT_INT + ? "SHORT_INT" + : value == SHORT_UINT + ? "SHORT_UINT" + : value == LONG_INT + ? "LONG_INT" + : value == LONG_UINT + ? "LONG_UINT" + : value == LONG_LONG_INT + ? "LONG_LONG_INT" + : value == LONG_LONG_UINT + ? "LONG_LONG_UINT" + : value == FLOAT + ? "FLOAT" + : value == DOUBLE + ? "DOUBLE" + : value == DECIMAL + ? "DECIMAL" + : value == SHORT_STRING + ? "SHORT_STRING" + : value == LONG_STRING + ? "LONG_STRING" + : value == + FIELD_ARRAY + ? "FIELD_ARRAY" + : value == + TIMESTAMP + ? "TIMESTAMP" + : value == + FIELD_TABLE + ? "FIELD_TABLE" + : value == + VOID + ? "VOID" + : null; } -} \ No newline at end of file +} diff --git a/lib/src/enums/frame_type.dart b/lib/src/enums/frame_type.dart index b205223..ee31f87 100644 --- a/lib/src/enums/frame_type.dart +++ b/lib/src/enums/frame_type.dart @@ -1,33 +1,37 @@ part of dart_amqp.enums; class FrameType extends Enum { - static const FrameType METHOD = const FrameType._(1); - static const FrameType HEADER = const FrameType._(2); - static const FrameType BODY = const FrameType._(3); - static const FrameType HEARTBEAT = const FrameType._(8); + static const FrameType METHOD = FrameType._(1); + static const FrameType HEADER = FrameType._(2); + static const FrameType BODY = FrameType._(3); + static const FrameType HEARTBEAT = FrameType._(8); const FrameType._(int value) : super(value); String toString() => "${value}"; static FrameType valueOf(int value) { - FrameType fromValue = value == METHOD._value ? METHOD : - value == HEADER._value ? HEADER : - value == BODY._value ? BODY : - value == HEARTBEAT._value ? HEARTBEAT : null; + FrameType fromValue = value == METHOD._value + ? METHOD + : value == HEADER._value + ? HEADER + : value == BODY._value + ? BODY + : value == HEARTBEAT._value ? HEARTBEAT : null; if (fromValue == null) { - throw new ArgumentError("Invalid frame type value ${value}"); + throw ArgumentError("Invalid frame type value ${value}"); } return fromValue; } static String nameOf(FrameType value) { - String name = value == METHOD ? "METHOD" : - value == HEADER ? "HEADER" : - value == BODY ? "BODY" : - value == HEARTBEAT ? "HEARTBEAT" : null; + String name = value == METHOD + ? "METHOD" + : value == HEADER + ? "HEADER" + : value == BODY ? "BODY" : value == HEARTBEAT ? "HEARTBEAT" : null; return name; } -} \ No newline at end of file +} diff --git a/lib/src/exceptions/channel_exception.dart b/lib/src/exceptions/channel_exception.dart index 8e51504..1c0ba9e 100644 --- a/lib/src/exceptions/channel_exception.dart +++ b/lib/src/exceptions/channel_exception.dart @@ -5,7 +5,8 @@ class ChannelException implements Exception { final int channel; final ErrorType errorType; - ChannelException(String this.message, int this.channel, ErrorType this.errorType); + ChannelException( + String this.message, int this.channel, ErrorType this.errorType); String toString() { return "ChannelException(${ErrorType.nameOf(errorType)}): ${message}"; diff --git a/lib/src/exceptions/connection_exception.dart b/lib/src/exceptions/connection_exception.dart index 3375721..c727231 100644 --- a/lib/src/exceptions/connection_exception.dart +++ b/lib/src/exceptions/connection_exception.dart @@ -6,7 +6,8 @@ class ConnectionException implements Exception { final int classId; final int methodId; - ConnectionException(String this.message, ErrorType this.errorType, int this.classId, int this.methodId); + ConnectionException(String this.message, ErrorType this.errorType, + int this.classId, int this.methodId); String toString() { return "ConnectionException(${ErrorType.nameOf(errorType)}): ${message}"; diff --git a/lib/src/exceptions/exchange_not_found_exception.dart b/lib/src/exceptions/exchange_not_found_exception.dart index e7d1e88..f638cf5 100644 --- a/lib/src/exceptions/exchange_not_found_exception.dart +++ b/lib/src/exceptions/exchange_not_found_exception.dart @@ -1,9 +1,8 @@ part of dart_amqp.exceptions; class ExchangeNotFoundException extends ChannelException { - ExchangeNotFoundException(String message, int channel, ErrorType errorType) - : super(message, channel, errorType); + : super(message, channel, errorType); String toString() { return "ExchangeNotFoundException: ${message}"; diff --git a/lib/src/exceptions/queue_not_found_exception.dart b/lib/src/exceptions/queue_not_found_exception.dart index cd41f1b..db4d466 100644 --- a/lib/src/exceptions/queue_not_found_exception.dart +++ b/lib/src/exceptions/queue_not_found_exception.dart @@ -1,9 +1,8 @@ part of dart_amqp.exceptions; class QueueNotFoundException extends ChannelException { - QueueNotFoundException(String message, int channel, ErrorType errorType) - : super(message, channel, errorType); + : super(message, channel, errorType); String toString() { return "QueueNotFoundException: ${message}"; diff --git a/lib/src/logging.dart b/lib/src/logging.dart index f9964d5..4e5d349 100644 --- a/lib/src/logging.dart +++ b/lib/src/logging.dart @@ -7,6 +7,4 @@ import "package:logging/logging.dart"; part "logging/logger.dart"; // A indenting json encoder used by the toString() method of messages -JsonEncoder indentingJsonEncoder = new JsonEncoder.withIndent(" "); - - +JsonEncoder indentingJsonEncoder = JsonEncoder.withIndent(" "); diff --git a/lib/src/logging/logger.dart b/lib/src/logging/logger.dart index 258dce5..fc2dfd8 100644 --- a/lib/src/logging/logger.dart +++ b/lib/src/logging/logger.dart @@ -1,4 +1,4 @@ part of dart_amqp.logger; // Define hierarchical loggers -final Logger connectionLogger = new Logger("dart_amqp.Connection"); +final Logger connectionLogger = Logger("dart_amqp.Connection"); diff --git a/lib/src/protocol/frame/decoded_message.dart b/lib/src/protocol/frame/decoded_message.dart index 43bfad7..0a5b563 100644 --- a/lib/src/protocol/frame/decoded_message.dart +++ b/lib/src/protocol/frame/decoded_message.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; abstract class DecodedMessage { - int get channel; Message get message; diff --git a/lib/src/protocol/frame/impl/decoded_message_impl.dart b/lib/src/protocol/frame/impl/decoded_message_impl.dart index ff1588f..c9dc000 100644 --- a/lib/src/protocol/frame/impl/decoded_message_impl.dart +++ b/lib/src/protocol/frame/impl/decoded_message_impl.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class DecodedMessageImpl implements DecodedMessage { - final int channel; final Message message; ContentHeader contentHeader; @@ -10,7 +9,8 @@ class DecodedMessageImpl implements DecodedMessage { DecodedMessageImpl(this.channel, Message this.message); - MessageProperties get properties => contentHeader != null ? contentHeader.properties : null; + MessageProperties get properties => + contentHeader != null ? contentHeader.properties : null; set properties(MessageProperties properties) { if (contentHeader != null) { @@ -51,5 +51,4 @@ class DecodedMessageImpl implements DecodedMessage { Map get payloadAsJson { return json.decode(utf8.decode(payload)); } - } diff --git a/lib/src/protocol/frame/impl/heartbeat_frame_impl.dart b/lib/src/protocol/frame/impl/heartbeat_frame_impl.dart index 39787a1..087b6eb 100644 --- a/lib/src/protocol/frame/impl/heartbeat_frame_impl.dart +++ b/lib/src/protocol/frame/impl/heartbeat_frame_impl.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class HeartbeatFrameImpl implements DecodedMessage { - final int channel; HeartbeatFrameImpl(int this.channel); diff --git a/lib/src/protocol/frame/raw_frame.dart b/lib/src/protocol/frame/raw_frame.dart index d36a8b0..7193c23 100644 --- a/lib/src/protocol/frame/raw_frame.dart +++ b/lib/src/protocol/frame/raw_frame.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class RawFrame { - final FrameHeader header; final ByteData payload; diff --git a/lib/src/protocol/headers/content_header.dart b/lib/src/protocol/headers/content_header.dart index a899b7e..086a1c5 100644 --- a/lib/src/protocol/headers/content_header.dart +++ b/lib/src/protocol/headers/content_header.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class ContentHeader implements Header { - int classId; final int weight = 0; int bodySize; @@ -10,7 +9,7 @@ class ContentHeader implements Header { ContentHeader(); - ContentHeader.fromByteData(TypeDecoder decoder){ + ContentHeader.fromByteData(TypeDecoder decoder) { classId = decoder.readUInt16(); decoder.skipBytes(2); // Skip weight bodySize = decoder.readUInt64(); @@ -20,7 +19,7 @@ class ContentHeader implements Header { return; } - properties = new MessageProperties(); + properties = MessageProperties(); // Read properties depending on the property presence mask. // Property presense bits are stored from high -> low starting at bit 15 @@ -164,4 +163,4 @@ class ContentHeader implements Header { encoder.writeShortString(properties.appId); } } -} \ No newline at end of file +} diff --git a/lib/src/protocol/headers/frame_header.dart b/lib/src/protocol/headers/frame_header.dart index 53e3554..3b1b8e9 100644 --- a/lib/src/protocol/headers/frame_header.dart +++ b/lib/src/protocol/headers/frame_header.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class FrameHeader implements Header { - static const int LENGTH_IN_BYTES = 7; FrameType type; @@ -10,12 +9,13 @@ class FrameHeader implements Header { FrameHeader(); - FrameHeader.fromByteData(TypeDecoder decoder){ + FrameHeader.fromByteData(TypeDecoder decoder) { int typeValue = decoder.readUInt8(); try { type = FrameType.valueOf(typeValue); } catch (e) { - throw new FatalException("Received unknown frame type 0x${typeValue.toRadixString(16)}"); + throw FatalException( + "Received unknown frame type 0x${typeValue.toRadixString(16)}"); } channel = decoder.readUInt16(); size = decoder.readUInt32(); @@ -36,4 +36,4 @@ class FrameHeader implements Header { // channel : ${channel} // size : ${size}"""; // } -} \ No newline at end of file +} diff --git a/lib/src/protocol/headers/header.dart b/lib/src/protocol/headers/header.dart index a4b9cf3..48ac2f8 100644 --- a/lib/src/protocol/headers/header.dart +++ b/lib/src/protocol/headers/header.dart @@ -2,4 +2,4 @@ part of dart_amqp.protocol; abstract class Header { void serialize(TypeEncoder encoder); -} \ No newline at end of file +} diff --git a/lib/src/protocol/headers/protocol_header.dart b/lib/src/protocol/headers/protocol_header.dart index 302cd88..a4460df 100644 --- a/lib/src/protocol/headers/protocol_header.dart +++ b/lib/src/protocol/headers/protocol_header.dart @@ -10,7 +10,7 @@ class ProtocolHeader implements Header { ProtocolHeader(); - ProtocolHeader.fromByteData(TypeDecoder decoder){ + ProtocolHeader.fromByteData(TypeDecoder decoder) { // Skip AMQP string decoder.skipBytes(4); protocolVersion = decoder.readUInt8(); @@ -21,10 +21,10 @@ class ProtocolHeader implements Header { void serialize(TypeEncoder encoder) { encoder - ..writer.addLast(new Uint8List.fromList(ascii.encode("AMQP"))) + ..writer.addLast(Uint8List.fromList(ascii.encode("AMQP"))) ..writeUInt8(protocolVersion) ..writeUInt8(majorVersion) ..writeUInt8(minorVersion) ..writeUInt8(revision); } -} \ No newline at end of file +} diff --git a/lib/src/protocol/io/amqp_message_decoder.dart b/lib/src/protocol/io/amqp_message_decoder.dart index f233f17..7647068 100644 --- a/lib/src/protocol/io/amqp_message_decoder.dart +++ b/lib/src/protocol/io/amqp_message_decoder.dart @@ -1,16 +1,17 @@ part of dart_amqp.protocol; class AmqpMessageDecoder { + Map incompleteMessages = + Map(); - Map incompleteMessages = new Map(); + StreamTransformer get transformer => + StreamTransformer.fromHandlers( + handleData: handleData, + handleDone: handleDone, + handleError: handleError); - StreamTransformer get transformer => new StreamTransformer.fromHandlers( - handleData: handleData, - handleDone: handleDone, - handleError : handleError - ); - - void handleError(Object error, StackTrace stackTrace, EventSink sink) { + void handleError( + Object error, StackTrace stackTrace, EventSink sink) { sink.addError(error, stackTrace); } @@ -19,76 +20,100 @@ class AmqpMessageDecoder { } void handleData(RawFrame rawFrame, EventSink sink) { - TypeDecoder decoder = new TypeDecoder.fromBuffer(rawFrame.payload); + TypeDecoder decoder = TypeDecoder.fromBuffer(rawFrame.payload); switch (rawFrame.header.type) { case FrameType.METHOD: - DecodedMessageImpl decodedMessage = new DecodedMessageImpl( - rawFrame.header.channel, - new Message.fromStream(decoder) - ); + DecodedMessageImpl decodedMessage = DecodedMessageImpl( + rawFrame.header.channel, Message.fromStream(decoder)); // If we are already processing an incomplete frame then this is an error if (incompleteMessages.containsKey(decodedMessage.channel)) { - throw new ConnectionException("Received a new METHOD frame while processing an incomplete METHOD frame", ErrorType.UNEXPECTED_FRAME, decodedMessage.message.msgClassId, decodedMessage.message.msgMethodId); + throw ConnectionException( + "Received a new METHOD frame while processing an incomplete METHOD frame", + ErrorType.UNEXPECTED_FRAME, + decodedMessage.message.msgClassId, + decodedMessage.message.msgMethodId); } // If this message defines content add it to the incomplete frame buffer if (decodedMessage.message.msgHasContent) { - incompleteMessages[ decodedMessage.channel ] = decodedMessage; + incompleteMessages[decodedMessage.channel] = decodedMessage; } else { // Frame is complete; emit it sink.add(decodedMessage); } break; case FrameType.HEADER: - // Read the content header - ContentHeader contentHeader = new ContentHeader.fromByteData(decoder); + // Read the content header + ContentHeader contentHeader = ContentHeader.fromByteData(decoder); - DecodedMessageImpl decodedMessage = incompleteMessages[ rawFrame.header.channel ]; + DecodedMessageImpl decodedMessage = + incompleteMessages[rawFrame.header.channel]; // Check for errors if (decodedMessage == null) { - throw new ConnectionException("Received a HEADER frame without a matching METHOD frame", ErrorType.UNEXPECTED_FRAME, contentHeader.classId, 0); + throw ConnectionException( + "Received a HEADER frame without a matching METHOD frame", + ErrorType.UNEXPECTED_FRAME, + contentHeader.classId, + 0); } else if (decodedMessage.contentHeader != null) { - throw new ConnectionException("Received a duplicate HEADER frame for an incomplete METHOD frame", ErrorType.UNEXPECTED_FRAME, contentHeader.classId, 0); + throw ConnectionException( + "Received a duplicate HEADER frame for an incomplete METHOD frame", + ErrorType.UNEXPECTED_FRAME, + contentHeader.classId, + 0); } else if (decodedMessage.message.msgClassId != contentHeader.classId) { - throw new ConnectionException("Received a HEADER frame that does not match the METHOD frame class id", ErrorType.UNEXPECTED_FRAME, contentHeader.classId, 0); + throw ConnectionException( + "Received a HEADER frame that does not match the METHOD frame class id", + ErrorType.UNEXPECTED_FRAME, + contentHeader.classId, + 0); } // Store the content header and set the message properties to point to the parsed header properties - decodedMessage - ..contentHeader = contentHeader; + decodedMessage..contentHeader = contentHeader; // If the frame defines no content emit it now if (decodedMessage.contentHeader.bodySize == 0) { sink.add(incompleteMessages.remove(decodedMessage.channel)); } else { - decodedMessage.payloadBuffer = new ChunkedOutputWriter(); + decodedMessage.payloadBuffer = ChunkedOutputWriter(); } break; case FrameType.BODY: - DecodedMessageImpl decodedMessage = incompleteMessages[ rawFrame.header.channel ]; + DecodedMessageImpl decodedMessage = + incompleteMessages[rawFrame.header.channel]; // Check for errors if (decodedMessage == null) { - throw new ConnectionException("Received a BODY frame without a matching METHOD frame", ErrorType.UNEXPECTED_FRAME, 0, 0); + throw ConnectionException( + "Received a BODY frame without a matching METHOD frame", + ErrorType.UNEXPECTED_FRAME, + 0, + 0); } else if (decodedMessage.contentHeader == null) { - throw new ConnectionException("Received a BODY frame before a HEADER frame", ErrorType.UNEXPECTED_FRAME, decodedMessage.message.msgClassId, decodedMessage.message.msgMethodId); + throw ConnectionException( + "Received a BODY frame before a HEADER frame", + ErrorType.UNEXPECTED_FRAME, + decodedMessage.message.msgClassId, + decodedMessage.message.msgMethodId); } // Append the payload chunk - decodedMessage.payloadBuffer.addLast(new Uint8List.view(rawFrame.payload.buffer, 0, rawFrame.payload.lengthInBytes)); + decodedMessage.payloadBuffer.addLast(Uint8List.view( + rawFrame.payload.buffer, 0, rawFrame.payload.lengthInBytes)); // Are we done? - if (decodedMessage.payloadBuffer.lengthInBytes == decodedMessage.contentHeader.bodySize) { + if (decodedMessage.payloadBuffer.lengthInBytes == + decodedMessage.contentHeader.bodySize) { decodedMessage.finalizePayload(); sink.add(incompleteMessages.remove(decodedMessage.channel)); } break; case FrameType.HEARTBEAT: - sink.add(new HeartbeatFrameImpl(rawFrame.header.channel)); + sink.add(HeartbeatFrameImpl(rawFrame.header.channel)); break; } } - -} \ No newline at end of file +} diff --git a/lib/src/protocol/io/frame_writer.dart b/lib/src/protocol/io/frame_writer.dart index 5704b18..82df92d 100644 --- a/lib/src/protocol/io/frame_writer.dart +++ b/lib/src/protocol/io/frame_writer.dart @@ -1,9 +1,9 @@ part of dart_amqp.protocol; -final Uint8List FRAME_TERMINATOR_SEQUENCE = new Uint8List.fromList([ RawFrameParser.FRAME_TERMINATOR ]); +final Uint8List FRAME_TERMINATOR_SEQUENCE = + Uint8List.fromList([RawFrameParser.FRAME_TERMINATOR]); class FrameWriter { - final FrameHeader _frameHeader; final ContentHeader _contentHeader; final TypeEncoder _bufferEncoder; @@ -12,12 +12,13 @@ class FrameWriter { final TuningSettings _tuningSettings; FrameWriter(TuningSettings this._tuningSettings) - : _frameHeader = new FrameHeader(), - _contentHeader = new ContentHeader(), - _bufferEncoder = new TypeEncoder(), - _outputEncoder = new TypeEncoder(); + : _frameHeader = FrameHeader(), + _contentHeader = ContentHeader(), + _bufferEncoder = TypeEncoder(), + _outputEncoder = TypeEncoder(); - void writeMessage(int channelId, Message message, { MessageProperties properties, Object payloadContent }) { + void writeMessage(int channelId, Message message, + {MessageProperties properties, Object payloadContent}) { // Make sure our buffer contains no stale data from previous messages _outputEncoder.writer.clear(); @@ -39,20 +40,21 @@ class FrameWriter { // if a data payload is specified, encode it and append it before flushing the buffer if (payloadContent != null) { - // Serialize content Uint8List serializedContent; if (payloadContent is Uint8List) { serializedContent = payloadContent; } else if (payloadContent is Map || payloadContent is Iterable) { - serializedContent = new Uint8List.fromList(json.encode(payloadContent).codeUnits); - properties = (properties == null ? new MessageProperties() : properties) + serializedContent = + Uint8List.fromList(json.encode(payloadContent).codeUnits); + properties = (properties == null ? MessageProperties() : properties) ..contentType = "application/json" ..contentEncoding = "UTF-8"; } else if (payloadContent is String) { - serializedContent = new Uint8List.fromList(payloadContent.codeUnits); + serializedContent = Uint8List.fromList(payloadContent.codeUnits); } else { - throw new ArgumentError("Message payload should be either a Map, an Iterable, a String or an UInt8List instance"); + throw ArgumentError( + "Message payload should be either a Map, an Iterable, a String or an UInt8List instance"); } // Build the content header @@ -81,7 +83,9 @@ class FrameWriter { // Emit the payload data split in ceil( length / maxFrameLength ) chunks int contentLen = serializedContent.lengthInBytes; - for (int offset = 0; offset < contentLen; offset += _tuningSettings.maxFrameSize) { + for (int offset = 0; + offset < contentLen; + offset += _tuningSettings.maxFrameSize) { // Setup and encode the frame header _frameHeader ..type = FrameType.BODY @@ -90,14 +94,16 @@ class FrameWriter { // Encode the payload for the frame _outputEncoder.writer - ..addLast(new Uint8List.view(serializedContent.buffer, offset, _frameHeader.size)) + ..addLast(Uint8List.view( + serializedContent.buffer, offset, _frameHeader.size)) ..addLast(FRAME_TERMINATOR_SEQUENCE); } } } - void writeProtocolHeader(int protocolVersion, int majorVersion, int minorVersion, int revision) { - new ProtocolHeader() + void writeProtocolHeader( + int protocolVersion, int majorVersion, int minorVersion, int revision) { + ProtocolHeader() ..protocolVersion = protocolVersion ..majorVersion = majorVersion ..minorVersion = minorVersion @@ -106,16 +112,14 @@ class FrameWriter { } void writeHeartbeat() { - _outputEncoder.writer.addLast(new Uint8List.fromList([8, 0, 0, 0, 0, 0, 0, RawFrameParser.FRAME_TERMINATOR])); + _outputEncoder.writer.addLast(Uint8List.fromList( + [8, 0, 0, 0, 0, 0, 0, RawFrameParser.FRAME_TERMINATOR])); } - /** - * Pipe encoded frame data to [sink] - */ + /// Pipe encoded frame data to [sink] void pipe(Sink sink) { _outputEncoder.writer.pipe(sink); } TypeEncoder get outputEncoder => _outputEncoder; } - diff --git a/lib/src/protocol/io/raw_frame_parser.dart b/lib/src/protocol/io/raw_frame_parser.dart index d000fc9..00564c9 100644 --- a/lib/src/protocol/io/raw_frame_parser.dart +++ b/lib/src/protocol/io/raw_frame_parser.dart @@ -4,7 +4,7 @@ class RawFrameParser { static final int FRAME_TERMINATOR = 0xCE; TuningSettings tuningSettings; - final ChunkedInputReader _inputBuffer = new ChunkedInputReader(); + final ChunkedInputReader _inputBuffer = ChunkedInputReader(); FrameHeader _parsedHeader; Uint8List _bodyData; int _bodyWriteOffset = 0; @@ -35,26 +35,23 @@ class RawFrameParser { return; } - Uint8List headerBytes = - new Uint8List(ProtocolHeader.LENGTH_IN_BYTES); + Uint8List headerBytes = Uint8List(ProtocolHeader.LENGTH_IN_BYTES); _inputBuffer.read(headerBytes, ProtocolHeader.LENGTH_IN_BYTES); - ProtocolHeader protocolHeader = new ProtocolHeader.fromByteData( - new TypeDecoder.fromBuffer( - new ByteData.view(headerBytes.buffer))); - throw new FatalException( + ProtocolHeader protocolHeader = ProtocolHeader.fromByteData( + TypeDecoder.fromBuffer(ByteData.view(headerBytes.buffer))); + throw FatalException( "Could not negotiate a valid AMQP protocol version. Server supports AMQP ${protocolHeader.majorVersion}.${protocolHeader.minorVersion}.${protocolHeader.revision}"); } // Extract header bytes and parse them - Uint8List headerBytes = new Uint8List(FrameHeader.LENGTH_IN_BYTES); + Uint8List headerBytes = Uint8List(FrameHeader.LENGTH_IN_BYTES); _inputBuffer.read(headerBytes, FrameHeader.LENGTH_IN_BYTES); - _parsedHeader = new FrameHeader.fromByteData( - new TypeDecoder.fromBuffer( - new ByteData.view(headerBytes.buffer))); + _parsedHeader = FrameHeader.fromByteData( + TypeDecoder.fromBuffer(ByteData.view(headerBytes.buffer))); headerBytes = null; if (_parsedHeader.size > tuningSettings.maxFrameSize) { - throw new ConnectionException( + throw ConnectionException( "Frame size cannot be larger than ${tuningSettings.maxFrameSize} bytes. Server sent ${_parsedHeader.size} bytes", ErrorType.FRAME_ERROR, 0, @@ -62,7 +59,7 @@ class RawFrameParser { } // Allocate buffer for body (and frame terminator); then reset write offset - _bodyData = new Uint8List(_parsedHeader.size + 1); + _bodyData = Uint8List(_parsedHeader.size + 1); _bodyWriteOffset = 0; } else { // Copy pending body data + expected frame terminator (0xCE) @@ -74,15 +71,13 @@ class RawFrameParser { if (_bodyWriteOffset == _parsedHeader.size + 1) { // Ensure that the last byte of the payload is our frame terminator if (_bodyData.last != FRAME_TERMINATOR) { - throw new FatalException( + throw FatalException( "Frame did not end with the expected frame terminator (0xCE)"); } // Emit a raw frame excluding the frame terminator - sink.add(new RawFrame( - _parsedHeader, - new ByteData.view( - _bodyData.buffer, 0, _bodyData.lengthInBytes - 1))); + sink.add(RawFrame(_parsedHeader, + ByteData.view(_bodyData.buffer, 0, _bodyData.lengthInBytes - 1))); _parsedHeader = null; _bodyData = null; @@ -106,7 +101,7 @@ class RawFrameParser { } StreamTransformer, RawFrame> get transformer => - new StreamTransformer, RawFrame>.fromHandlers( + StreamTransformer, RawFrame>.fromHandlers( handleData: handleData, handleDone: handleDone, handleError: handleError); diff --git a/lib/src/protocol/io/tuning_settings.dart b/lib/src/protocol/io/tuning_settings.dart index fbb929a..85b5b2b 100644 --- a/lib/src/protocol/io/tuning_settings.dart +++ b/lib/src/protocol/io/tuning_settings.dart @@ -1,11 +1,9 @@ part of dart_amqp.protocol; class TuningSettings { - int maxChannels = 0; int maxFrameSize = 4096; - Duration heartbeatPeriod = new Duration(seconds : 0); - -} \ No newline at end of file + Duration heartbeatPeriod = Duration(seconds: 0); +} diff --git a/lib/src/protocol/messages/bindings/basic.dart b/lib/src/protocol/messages/bindings/basic.dart index 5ab0774..e9c6656 100644 --- a/lib/src/protocol/messages/bindings/basic.dart +++ b/lib/src/protocol/messages/bindings/basic.dart @@ -18,14 +18,13 @@ class BasicQos implements Message { BasicQos(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt32(prefetchSize) ..writeUInt16(prefetchCount) - ..writeBits([global]) - ; + ..writeBits([global]); } } @@ -36,11 +35,9 @@ class BasicQosOk implements Message { // Message arguments - BasicQosOk.fromStream( TypeDecoder decoder ){ - } + BasicQosOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class BasicConsume implements Message { @@ -60,7 +57,7 @@ class BasicConsume implements Message { BasicConsume(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) @@ -68,8 +65,7 @@ class BasicConsume implements Message { ..writeShortString(queue) ..writeShortString(consumerTag) ..writeBits([noLocal, noAck, exclusive, noWait]) - ..writeFieldTable(arguments) - ; + ..writeFieldTable(arguments); } } @@ -81,12 +77,11 @@ class BasicConsumeOk implements Message { // Message arguments String consumerTag; - BasicConsumeOk.fromStream( TypeDecoder decoder ){ + BasicConsumeOk.fromStream(TypeDecoder decoder) { consumerTag = decoder.readShortString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class BasicCancel implements Message { @@ -100,13 +95,12 @@ class BasicCancel implements Message { BasicCancel(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeShortString(consumerTag) - ..writeBits([noWait]) - ; + ..writeBits([noWait]); } } @@ -118,12 +112,11 @@ class BasicCancelOk implements Message { // Message arguments String consumerTag; - BasicCancelOk.fromStream( TypeDecoder decoder ){ + BasicCancelOk.fromStream(TypeDecoder decoder) { consumerTag = decoder.readShortString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class BasicPublish implements Message { @@ -140,15 +133,14 @@ class BasicPublish implements Message { BasicPublish(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(reserved_1) ..writeShortString(exchange) ..writeShortString(routingKey) - ..writeBits([mandatory, immediate]) - ; + ..writeBits([mandatory, immediate]); } } @@ -163,15 +155,14 @@ class BasicReturn implements Message { String exchange; String routingKey; - BasicReturn.fromStream( TypeDecoder decoder ){ + BasicReturn.fromStream(TypeDecoder decoder) { replyCode = decoder.readUInt16(); replyText = decoder.readShortString(); exchange = decoder.readShortString(); routingKey = decoder.readShortString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class BasicDeliver implements Message { @@ -186,7 +177,7 @@ class BasicDeliver implements Message { String exchange; String routingKey; - BasicDeliver.fromStream( TypeDecoder decoder ){ + BasicDeliver.fromStream(TypeDecoder decoder) { consumerTag = decoder.readShortString(); deliveryTag = decoder.readUInt64(); int _bitmask; @@ -196,8 +187,7 @@ class BasicDeliver implements Message { routingKey = decoder.readShortString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class BasicAck implements Message { @@ -211,13 +201,12 @@ class BasicAck implements Message { BasicAck(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt64(deliveryTag) - ..writeBits([multiple]) - ; + ..writeBits([multiple]); } } @@ -232,13 +221,12 @@ class BasicReject implements Message { BasicReject(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt64(deliveryTag) - ..writeBits([requeue]) - ; + ..writeBits([requeue]); } } @@ -252,12 +240,11 @@ class BasicRecover implements Message { BasicRecover(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeBits([requeue]) - ; + ..writeBits([requeue]); } } @@ -268,9 +255,7 @@ class BasicRecoverOk implements Message { // Message arguments - BasicRecoverOk.fromStream( TypeDecoder decoder ){ - } + BasicRecoverOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } diff --git a/lib/src/protocol/messages/bindings/channel.dart b/lib/src/protocol/messages/bindings/channel.dart index 8e2abda..25e0f36 100644 --- a/lib/src/protocol/messages/bindings/channel.dart +++ b/lib/src/protocol/messages/bindings/channel.dart @@ -16,12 +16,11 @@ class ChannelOpen implements Message { ChannelOpen(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeShortString(reserved_1) - ; + ..writeShortString(reserved_1); } } @@ -33,12 +32,11 @@ class ChannelOpenOk implements Message { // Message arguments String reserved_1; - ChannelOpenOk.fromStream( TypeDecoder decoder ){ + ChannelOpenOk.fromStream(TypeDecoder decoder) { reserved_1 = decoder.readLongString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ChannelFlow implements Message { @@ -50,17 +48,16 @@ class ChannelFlow implements Message { bool active; ChannelFlow(); - ChannelFlow.fromStream( TypeDecoder decoder ){ + ChannelFlow.fromStream(TypeDecoder decoder) { int _bitmask; _bitmask = decoder.readUInt8(); active = _bitmask & 0x1 != 0; } - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeBits([active]) - ; + ..writeBits([active]); } } @@ -73,17 +70,16 @@ class ChannelFlowOk implements Message { bool active; ChannelFlowOk(); - ChannelFlowOk.fromStream( TypeDecoder decoder ){ + ChannelFlowOk.fromStream(TypeDecoder decoder) { int _bitmask; _bitmask = decoder.readUInt8(); active = _bitmask & 0x1 != 0; } - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeBits([active]) - ; + ..writeBits([active]); } } @@ -99,21 +95,20 @@ class ChannelClose implements Message { int methodId; ChannelClose(); - ChannelClose.fromStream( TypeDecoder decoder ){ + ChannelClose.fromStream(TypeDecoder decoder) { replyCode = decoder.readUInt16(); replyText = decoder.readShortString(); classId = decoder.readUInt16(); methodId = decoder.readUInt16(); } - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(replyCode) ..writeShortString(replyText) ..writeUInt16(classId) - ..writeUInt16(methodId) - ; + ..writeUInt16(methodId); } } @@ -125,12 +120,8 @@ class ChannelCloseOk implements Message { // Message arguments ChannelCloseOk(); - ChannelCloseOk.fromStream( TypeDecoder decoder ){ - } - void serialize( TypeEncoder encoder ) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + ChannelCloseOk.fromStream(TypeDecoder decoder) {} + void serialize(TypeEncoder encoder) { + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } diff --git a/lib/src/protocol/messages/bindings/connection.dart b/lib/src/protocol/messages/bindings/connection.dart index ca854ae..27779bd 100644 --- a/lib/src/protocol/messages/bindings/connection.dart +++ b/lib/src/protocol/messages/bindings/connection.dart @@ -18,7 +18,7 @@ class ConnectionStart implements Message { String mechanisms; String locales; - ConnectionStart.fromStream( TypeDecoder decoder ){ + ConnectionStart.fromStream(TypeDecoder decoder) { versionMajor = decoder.readUInt8(); versionMinor = decoder.readUInt8(); serverProperties = decoder.readFieldTable("serverProperties"); @@ -26,8 +26,7 @@ class ConnectionStart implements Message { locales = decoder.readLongString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ConnectionStartOk implements Message { @@ -43,15 +42,14 @@ class ConnectionStartOk implements Message { ConnectionStartOk(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeFieldTable(clientProperties) ..writeShortString(mechanism) ..writeLongString(response) - ..writeShortString(locale) - ; + ..writeShortString(locale); } } @@ -63,12 +61,11 @@ class ConnectionSecure implements Message { // Message arguments String challenge; - ConnectionSecure.fromStream( TypeDecoder decoder ){ + ConnectionSecure.fromStream(TypeDecoder decoder) { challenge = decoder.readLongString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ConnectionSecureOk implements Message { @@ -81,12 +78,11 @@ class ConnectionSecureOk implements Message { ConnectionSecureOk(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeLongString(response) - ; + ..writeLongString(response); } } @@ -100,14 +96,13 @@ class ConnectionTune implements Message { int frameMax; int heartbeat; - ConnectionTune.fromStream( TypeDecoder decoder ){ + ConnectionTune.fromStream(TypeDecoder decoder) { channelMax = decoder.readUInt16(); frameMax = decoder.readUInt32(); heartbeat = decoder.readUInt16(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ConnectionTuneOk implements Message { @@ -122,14 +117,13 @@ class ConnectionTuneOk implements Message { ConnectionTuneOk(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(channelMax) ..writeUInt32(frameMax) - ..writeUInt16(heartbeat) - ; + ..writeUInt16(heartbeat); } } @@ -145,14 +139,13 @@ class ConnectionOpen implements Message { ConnectionOpen(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeShortString(virtualHost) ..writeShortString(reserved_1) - ..writeBits([reserved_2]) - ; + ..writeBits([reserved_2]); } } @@ -164,12 +157,11 @@ class ConnectionOpenOk implements Message { // Message arguments String reserved_1; - ConnectionOpenOk.fromStream( TypeDecoder decoder ){ + ConnectionOpenOk.fromStream(TypeDecoder decoder) { reserved_1 = decoder.readShortString(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ConnectionClose implements Message { @@ -184,21 +176,20 @@ class ConnectionClose implements Message { int methodId; ConnectionClose(); - ConnectionClose.fromStream( TypeDecoder decoder ){ + ConnectionClose.fromStream(TypeDecoder decoder) { replyCode = decoder.readUInt16(); replyText = decoder.readShortString(); classId = decoder.readUInt16(); methodId = decoder.readUInt16(); } - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(replyCode) ..writeShortString(replyText) ..writeUInt16(classId) - ..writeUInt16(methodId) - ; + ..writeUInt16(methodId); } } @@ -210,12 +201,8 @@ class ConnectionCloseOk implements Message { // Message arguments ConnectionCloseOk(); - ConnectionCloseOk.fromStream( TypeDecoder decoder ){ - } - void serialize( TypeEncoder encoder ) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + ConnectionCloseOk.fromStream(TypeDecoder decoder) {} + void serialize(TypeEncoder encoder) { + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } diff --git a/lib/src/protocol/messages/bindings/exchange.dart b/lib/src/protocol/messages/bindings/exchange.dart index f5192c1..b04a0d7 100644 --- a/lib/src/protocol/messages/bindings/exchange.dart +++ b/lib/src/protocol/messages/bindings/exchange.dart @@ -24,7 +24,7 @@ class ExchangeDeclare implements Message { ExchangeDeclare(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) @@ -32,8 +32,7 @@ class ExchangeDeclare implements Message { ..writeShortString(exchange) ..writeShortString(type) ..writeBits([passive, durable, reserved_2, reserved_3, noWait]) - ..writeFieldTable(arguments) - ; + ..writeFieldTable(arguments); } } @@ -44,11 +43,9 @@ class ExchangeDeclareOk implements Message { // Message arguments - ExchangeDeclareOk.fromStream( TypeDecoder decoder ){ - } + ExchangeDeclareOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class ExchangeDelete implements Message { @@ -64,14 +61,13 @@ class ExchangeDelete implements Message { ExchangeDelete(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(reserved_1) ..writeShortString(exchange) - ..writeBits([ifUnused, noWait]) - ; + ..writeBits([ifUnused, noWait]); } } @@ -82,9 +78,7 @@ class ExchangeDeleteOk implements Message { // Message arguments - ExchangeDeleteOk.fromStream( TypeDecoder decoder ){ - } + ExchangeDeleteOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } diff --git a/lib/src/protocol/messages/bindings/queue.dart b/lib/src/protocol/messages/bindings/queue.dart index b1680b3..bdd8b8c 100644 --- a/lib/src/protocol/messages/bindings/queue.dart +++ b/lib/src/protocol/messages/bindings/queue.dart @@ -23,15 +23,14 @@ class QueueDeclare implements Message { QueueDeclare(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(reserved_1) ..writeShortString(queue) ..writeBits([passive, durable, exclusive, autoDelete, noWait]) - ..writeFieldTable(arguments) - ; + ..writeFieldTable(arguments); } } @@ -45,14 +44,13 @@ class QueueDeclareOk implements Message { int messageCount; int consumerCount; - QueueDeclareOk.fromStream( TypeDecoder decoder ){ + QueueDeclareOk.fromStream(TypeDecoder decoder) { queue = decoder.readShortString(); messageCount = decoder.readUInt32(); consumerCount = decoder.readUInt32(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class QueueBind implements Message { @@ -70,7 +68,7 @@ class QueueBind implements Message { QueueBind(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) @@ -79,8 +77,7 @@ class QueueBind implements Message { ..writeShortString(exchange) ..writeShortString(routingKey) ..writeBits([noWait]) - ..writeFieldTable(arguments) - ; + ..writeFieldTable(arguments); } } @@ -91,11 +88,9 @@ class QueueBindOk implements Message { // Message arguments - QueueBindOk.fromStream( TypeDecoder decoder ){ - } + QueueBindOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class QueueUnbind implements Message { @@ -112,7 +107,7 @@ class QueueUnbind implements Message { QueueUnbind(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) @@ -120,8 +115,7 @@ class QueueUnbind implements Message { ..writeShortString(queue) ..writeShortString(exchange) ..writeShortString(routingKey) - ..writeFieldTable(arguments) - ; + ..writeFieldTable(arguments); } } @@ -132,11 +126,9 @@ class QueueUnbindOk implements Message { // Message arguments - QueueUnbindOk.fromStream( TypeDecoder decoder ){ - } + QueueUnbindOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class QueuePurge implements Message { @@ -151,14 +143,13 @@ class QueuePurge implements Message { QueuePurge(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(reserved_1) ..writeShortString(queue) - ..writeBits([noWait]) - ; + ..writeBits([noWait]); } } @@ -170,12 +161,11 @@ class QueuePurgeOk implements Message { // Message arguments int messageCount; - QueuePurgeOk.fromStream( TypeDecoder decoder ){ + QueuePurgeOk.fromStream(TypeDecoder decoder) { messageCount = decoder.readUInt32(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class QueueDelete implements Message { @@ -192,14 +182,13 @@ class QueueDelete implements Message { QueueDelete(); - void serialize( TypeEncoder encoder ) { + void serialize(TypeEncoder encoder) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) ..writeUInt16(reserved_1) ..writeShortString(queue) - ..writeBits([ifUnused, ifEmpty, noWait]) - ; + ..writeBits([ifUnused, ifEmpty, noWait]); } } @@ -211,10 +200,9 @@ class QueueDeleteOk implements Message { // Message arguments int messageCount; - QueueDeleteOk.fromStream( TypeDecoder decoder ){ + QueueDeleteOk.fromStream(TypeDecoder decoder) { messageCount = decoder.readUInt32(); } - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } diff --git a/lib/src/protocol/messages/bindings/tx.dart b/lib/src/protocol/messages/bindings/tx.dart index 07017e6..3ab3585 100644 --- a/lib/src/protocol/messages/bindings/tx.dart +++ b/lib/src/protocol/messages/bindings/tx.dart @@ -15,11 +15,8 @@ class TxSelect implements Message { TxSelect(); - void serialize( TypeEncoder encoder ) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + void serialize(TypeEncoder encoder) { + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } @@ -30,11 +27,9 @@ class TxSelectOk implements Message { // Message arguments - TxSelectOk.fromStream( TypeDecoder decoder ){ - } + TxSelectOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class TxCommit implements Message { @@ -46,11 +41,8 @@ class TxCommit implements Message { TxCommit(); - void serialize( TypeEncoder encoder ) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + void serialize(TypeEncoder encoder) { + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } @@ -61,11 +53,9 @@ class TxCommitOk implements Message { // Message arguments - TxCommitOk.fromStream( TypeDecoder decoder ){ - } + TxCommitOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } class TxRollback implements Message { @@ -77,11 +67,8 @@ class TxRollback implements Message { TxRollback(); - void serialize( TypeEncoder encoder ) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + void serialize(TypeEncoder encoder) { + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } @@ -92,9 +79,7 @@ class TxRollbackOk implements Message { // Message arguments - TxRollbackOk.fromStream( TypeDecoder decoder ){ - } + TxRollbackOk.fromStream(TypeDecoder decoder) {} - void serialize( TypeEncoder encoder ) { - } + void serialize(TypeEncoder encoder) {} } diff --git a/lib/src/protocol/messages/message.dart b/lib/src/protocol/messages/message.dart index d3af124..45f1bf5 100644 --- a/lib/src/protocol/messages/message.dart +++ b/lib/src/protocol/messages/message.dart @@ -9,7 +9,6 @@ part of dart_amqp.protocol; abstract class Message { - int get msgClassId; int get msgMethodId; @@ -18,92 +17,93 @@ abstract class Message { void serialize(TypeEncoder encoder); - factory Message.fromStream(TypeDecoder decoder){ + factory Message.fromStream(TypeDecoder decoder) { int msgClassId = decoder.readUInt16(); int msgMethodId = decoder.readUInt16(); - switch( msgClassId ){ - case 10: // Class: Connection - switch( msgMethodId ){ + switch (msgClassId) { + case 10: // Class: Connection + switch (msgMethodId) { case 10: - return new ConnectionStart.fromStream( decoder ); + return ConnectionStart.fromStream(decoder); case 20: - return new ConnectionSecure.fromStream( decoder ); + return ConnectionSecure.fromStream(decoder); case 30: - return new ConnectionTune.fromStream( decoder ); + return ConnectionTune.fromStream(decoder); case 41: - return new ConnectionOpenOk.fromStream( decoder ); + return ConnectionOpenOk.fromStream(decoder); case 50: - return new ConnectionClose.fromStream( decoder ); + return ConnectionClose.fromStream(decoder); case 51: - return new ConnectionCloseOk.fromStream( decoder ); + return ConnectionCloseOk.fromStream(decoder); } - break; - case 20: // Class: Channel - switch( msgMethodId ){ + break; + case 20: // Class: Channel + switch (msgMethodId) { case 11: - return new ChannelOpenOk.fromStream( decoder ); + return ChannelOpenOk.fromStream(decoder); case 20: - return new ChannelFlow.fromStream( decoder ); + return ChannelFlow.fromStream(decoder); case 21: - return new ChannelFlowOk.fromStream( decoder ); + return ChannelFlowOk.fromStream(decoder); case 40: - return new ChannelClose.fromStream( decoder ); + return ChannelClose.fromStream(decoder); case 41: - return new ChannelCloseOk.fromStream( decoder ); + return ChannelCloseOk.fromStream(decoder); } - break; - case 40: // Class: Exchange - switch( msgMethodId ){ + break; + case 40: // Class: Exchange + switch (msgMethodId) { case 11: - return new ExchangeDeclareOk.fromStream( decoder ); + return ExchangeDeclareOk.fromStream(decoder); case 21: - return new ExchangeDeleteOk.fromStream( decoder ); + return ExchangeDeleteOk.fromStream(decoder); } - break; - case 50: // Class: Queue - switch( msgMethodId ){ + break; + case 50: // Class: Queue + switch (msgMethodId) { case 11: - return new QueueDeclareOk.fromStream( decoder ); + return QueueDeclareOk.fromStream(decoder); case 21: - return new QueueBindOk.fromStream( decoder ); + return QueueBindOk.fromStream(decoder); case 51: - return new QueueUnbindOk.fromStream( decoder ); + return QueueUnbindOk.fromStream(decoder); case 31: - return new QueuePurgeOk.fromStream( decoder ); + return QueuePurgeOk.fromStream(decoder); case 41: - return new QueueDeleteOk.fromStream( decoder ); + return QueueDeleteOk.fromStream(decoder); } - break; - case 60: // Class: Basic - switch( msgMethodId ){ + break; + case 60: // Class: Basic + switch (msgMethodId) { case 11: - return new BasicQosOk.fromStream( decoder ); + return BasicQosOk.fromStream(decoder); case 21: - return new BasicConsumeOk.fromStream( decoder ); + return BasicConsumeOk.fromStream(decoder); case 31: - return new BasicCancelOk.fromStream( decoder ); + return BasicCancelOk.fromStream(decoder); case 50: - return new BasicReturn.fromStream( decoder ); + return BasicReturn.fromStream(decoder); case 60: - return new BasicDeliver.fromStream( decoder ); + return BasicDeliver.fromStream(decoder); case 111: - return new BasicRecoverOk.fromStream( decoder ); + return BasicRecoverOk.fromStream(decoder); } - break; - case 90: // Class: Tx - switch( msgMethodId ){ + break; + case 90: // Class: Tx + switch (msgMethodId) { case 11: - return new TxSelectOk.fromStream( decoder ); + return TxSelectOk.fromStream(decoder); case 21: - return new TxCommitOk.fromStream( decoder ); + return TxCommitOk.fromStream(decoder); case 31: - return new TxRollbackOk.fromStream( decoder ); + return TxRollbackOk.fromStream(decoder); } - break; + break; } // Message decoding failed; unknown message - throw new ArgumentError("Unknown message type (class: ${msgClassId}, method: ${msgMethodId})"); + throw ArgumentError( + "Unknown message type (class: ${msgClassId}, method: ${msgMethodId})"); } } diff --git a/lib/src/protocol/messages/message_properties.dart b/lib/src/protocol/messages/message_properties.dart index 6cf13ac..2a2e5db 100644 --- a/lib/src/protocol/messages/message_properties.dart +++ b/lib/src/protocol/messages/message_properties.dart @@ -1,7 +1,6 @@ part of dart_amqp.protocol; class MessageProperties { - String contentType; String contentEncoding; Map headers; @@ -18,14 +17,12 @@ class MessageProperties { MessageProperties(); - MessageProperties.persistentMessage(){ + MessageProperties.persistentMessage() { persistent = true; } - /** - * Flag the message as persistent or transient based on the value of - * [isPersistent] - */ + /// Flag the message as persistent or transient based on the value of + /// [isPersistent] set persistent(bool isPersistent) => deliveryMode = isPersistent ? 2 : 1; // String toString() { @@ -76,4 +73,4 @@ class MessageProperties { // // return sb.toString(); // } -} \ No newline at end of file +} diff --git a/lib/src/protocol/stream/chunked_input_reader.dart b/lib/src/protocol/stream/chunked_input_reader.dart index 4c76018..9af06f5 100644 --- a/lib/src/protocol/stream/chunked_input_reader.dart +++ b/lib/src/protocol/stream/chunked_input_reader.dart @@ -1,29 +1,20 @@ part of dart_amqp.protocol; class ChunkedInputReader { - - final _bufferedChunks = new ListQueue>(); + final _bufferedChunks = ListQueue>(); int _usedHeadBytes = 0; - /** - * Add a [chunk] to the buffer queue - */ + /// Add a [chunk] to the buffer queue void add(List chunk) => _bufferedChunks.add(chunk); - /** - * Get the total available bytes in all chunk buffers (excluding bytes already de-queued from head buffer). - */ + /// Get the total available bytes in all chunk buffers (excluding bytes already de-queued from head buffer). int get length => _bufferedChunks.fold( - -_usedHeadBytes, - (int count, List el) => count + el.length - ); + -_usedHeadBytes, (int count, List el) => count + el.length); - /** - * Return the next byte in the buffer without modifying the read pointer. - * Returns the [int] value of the next byte or null if no data is available - */ + /// Return the next byte in the buffer without modifying the read pointer. + /// Returns the [int] value of the next byte or null if no data is available int peekNextByte() { // No data available @@ -34,14 +25,11 @@ class ChunkedInputReader { return _bufferedChunks.first[_usedHeadBytes]; } - /** - * Try to read [count] bytes into [destination] at the specified [offset]. - * This method will automatically de-queue exhausted head buffers from the queue - * and will return the total number of bytes written - */ + /// Try to read [count] bytes into [destination] at the specified [offset]. + /// This method will automatically de-queue exhausted head buffers from the queue + /// and will return the total number of bytes written int read(List destination, int count, [int offset = 0]) { - int writeOffset = offset; while (count > 0) { // If we ran out of buffers we are done @@ -57,13 +45,15 @@ class ChunkedInputReader { // If the remaining head buffer can fill the destination entirely, copy it and de-queue head if (remainingHeadBytes <= count) { - destination.setRange(writeOffset, writeOffset + remainingHeadBytes, _bufferedChunks.removeFirst(), _usedHeadBytes); + destination.setRange(writeOffset, writeOffset + remainingHeadBytes, + _bufferedChunks.removeFirst(), _usedHeadBytes); _usedHeadBytes = 0; count -= remainingHeadBytes; writeOffset += remainingHeadBytes; } else { // Copy as much as we can skipping any already dequeued bytes - destination.setRange(writeOffset, writeOffset + count, _bufferedChunks.first, _usedHeadBytes); + destination.setRange(writeOffset, writeOffset + count, + _bufferedChunks.first, _usedHeadBytes); _usedHeadBytes += count; writeOffset += count; count = 0; diff --git a/lib/src/protocol/stream/chunked_output_writer.dart b/lib/src/protocol/stream/chunked_output_writer.dart index e6cf8aa..ba4f6fc 100644 --- a/lib/src/protocol/stream/chunked_output_writer.dart +++ b/lib/src/protocol/stream/chunked_output_writer.dart @@ -1,52 +1,39 @@ part of dart_amqp.protocol; class ChunkedOutputWriter { + final ListQueue _bufferedChunks = ListQueue(); - final ListQueue _bufferedChunks = new ListQueue(); - - /** - * Add a [chunk] to the head of the buffer queue - */ + /// Add a [chunk] to the head of the buffer queue void addFirst(Uint8List chunk) => _bufferedChunks.addFirst(chunk); - /** - * Append a [chunk] to the buffer queue - */ + /// Append a [chunk] to the buffer queue void addLast(Uint8List chunk) => _bufferedChunks.add(chunk); - /** - * Clear buffer - */ + /// Clear buffer void clear() => _bufferedChunks.clear(); - /** - * Get the total available bytes in all chunk buffers (excluding bytes already de-queued from head buffer). - */ + /// Get the total available bytes in all chunk buffers (excluding bytes already de-queued from head buffer). - int get lengthInBytes => _bufferedChunks.fold( - 0, (int count, el) => count + el.length - ); + int get lengthInBytes => + _bufferedChunks.fold(0, (int count, el) => count + el.length); - /** - * Pipe all buffered chunks to [destination] and clear the buffer queue - */ + /// Pipe all buffered chunks to [destination] and clear the buffer queue void pipe(Sink destination) { if (destination == null) { return; } - destination.add(joinChunks());//_bufferedChunks.forEach((Uint8List block) => destination.add(block)); + destination.add( + joinChunks()); //_bufferedChunks.forEach((Uint8List block) => destination.add(block)); clear(); } - /** - * Join all chunk blocks into a contiguous chunk - */ + /// Join all chunk blocks into a contiguous chunk Uint8List joinChunks() { - Uint8List out = new Uint8List(lengthInBytes); + Uint8List out = Uint8List(lengthInBytes); int offset = 0; _bufferedChunks.forEach((Uint8List block) { int len = block.lengthInBytes; diff --git a/lib/src/protocol/stream/type_decoder.dart b/lib/src/protocol/stream/type_decoder.dart index 36f8fe8..2b83f20 100644 --- a/lib/src/protocol/stream/type_decoder.dart +++ b/lib/src/protocol/stream/type_decoder.dart @@ -78,20 +78,18 @@ class TypeDecoder { String readShortString() { int len = readUInt8(); _offset += len; - return utf8.decode(new Uint8List.view(_buffer.buffer, _offset - len, len)); + return utf8.decode(Uint8List.view(_buffer.buffer, _offset - len, len)); } String readLongString() { int len = readUInt32(); _offset += len; - return utf8.decode(new Uint8List.view(_buffer.buffer, _offset - len, len)); + return utf8.decode(Uint8List.view(_buffer.buffer, _offset - len, len)); } DateTime readTimestamp() { int value = readUInt64(); - return value > 0 - ? new DateTime.fromMillisecondsSinceEpoch(value * 1000) - : null; + return value > 0 ? DateTime.fromMillisecondsSinceEpoch(value * 1000) : null; } Iterable readArray(String fieldName) { @@ -105,9 +103,9 @@ class TypeDecoder { Map readFieldTable(String fieldName) { int tableEndOffset = readInt32() + _offset; - Map items = new HashMap(); + Map items = HashMap(); while (_offset < tableEndOffset) { - items[ readShortString() ] = _readField(fieldName); + items[readShortString()] = _readField(fieldName); } return items; } @@ -117,8 +115,7 @@ class TypeDecoder { FieldType type = null; try { type = FieldType.valueOf(typeValue); - } catch (e) { - } + } catch (e) {} switch (type) { case FieldType.BOOLEAN: @@ -144,7 +141,7 @@ class TypeDecoder { case FieldType.DOUBLE: return readDouble(); case FieldType.DECIMAL: - throw new ArgumentError("Not implemented"); + throw ArgumentError("Not implemented"); break; case FieldType.SHORT_STRING: return readShortString(); @@ -159,7 +156,8 @@ class TypeDecoder { case FieldType.VOID: return null; default: - throw new ArgumentError("Could not decode field ${fieldName} with type 0x${typeValue.toRadixString(16)}"); + throw ArgumentError( + "Could not decode field ${fieldName} with type 0x${typeValue.toRadixString(16)}"); } } } diff --git a/lib/src/protocol/stream/type_encoder.dart b/lib/src/protocol/stream/type_encoder.dart index 38beef2..fc682b4 100644 --- a/lib/src/protocol/stream/type_encoder.dart +++ b/lib/src/protocol/stream/type_encoder.dart @@ -1,81 +1,80 @@ part of dart_amqp.protocol; class TypeEncoder { - ChunkedOutputWriter _writer; final Endian endianess = Endian.big; - TypeEncoder({ChunkedOutputWriter withWriter : null}) { - _writer = withWriter == null - ? new ChunkedOutputWriter() - : withWriter; + TypeEncoder({ChunkedOutputWriter withWriter = null}) { + _writer = withWriter == null ? ChunkedOutputWriter() : withWriter; } void writeInt8(int value) { - Uint8List buf = new Uint8List(1); - new ByteData.view(buf.buffer).setInt8(0, value); + Uint8List buf = Uint8List(1); + ByteData.view(buf.buffer).setInt8(0, value); _writer.addLast(buf); } void writeInt16(int value) { - Uint8List buf = new Uint8List(2); - new ByteData.view(buf.buffer).setInt16(0, value, endianess); + Uint8List buf = Uint8List(2); + ByteData.view(buf.buffer).setInt16(0, value, endianess); _writer.addLast(buf); } void writeInt32(int value) { - Uint8List buf = new Uint8List(4); - new ByteData.view(buf.buffer).setInt32(0, value, endianess); + Uint8List buf = Uint8List(4); + ByteData.view(buf.buffer).setInt32(0, value, endianess); _writer.addLast(buf); } void writeInt64(int value) { - Uint8List buf = new Uint8List(8); - new ByteData.view(buf.buffer).setInt64(0, value, endianess); + Uint8List buf = Uint8List(8); + ByteData.view(buf.buffer).setInt64(0, value, endianess); _writer.addLast(buf); } void writeUInt8(int value) { - Uint8List buf = new Uint8List(1); - new ByteData.view(buf.buffer).setUint8(0, value); + Uint8List buf = Uint8List(1); + ByteData.view(buf.buffer).setUint8(0, value); _writer.addLast(buf); } void writeUInt16(int value) { - Uint8List buf = new Uint8List(2); - new ByteData.view(buf.buffer).setUint16(0, value, endianess); + Uint8List buf = Uint8List(2); + ByteData.view(buf.buffer).setUint16(0, value, endianess); _writer.addLast(buf); } void writeUInt32(int value) { - Uint8List buf = new Uint8List(4); - new ByteData.view(buf.buffer).setUint32(0, value, endianess); + Uint8List buf = Uint8List(4); + ByteData.view(buf.buffer).setUint32(0, value, endianess); _writer.addLast(buf); } void writeUInt64(int value) { - Uint8List buf = new Uint8List(8); - new ByteData.view(buf.buffer).setUint64(0, value, endianess); + Uint8List buf = Uint8List(8); + ByteData.view(buf.buffer).setUint64(0, value, endianess); _writer.addLast(buf); } writeFloat(double value) { - Uint8List buf = new Uint8List(4); - new ByteData.view(buf.buffer).setFloat32(0, value, endianess); + Uint8List buf = Uint8List(4); + ByteData.view(buf.buffer).setFloat32(0, value, endianess); _writer.addLast(buf); } writeDouble(double value) { - Uint8List buf = new Uint8List(8); - new ByteData.view(buf.buffer).setFloat64(0, value, endianess); + Uint8List buf = Uint8List(8); + ByteData.view(buf.buffer).setFloat64(0, value, endianess); _writer.addLast(buf); } void writeBits(List bits) { int mask = 0; - for (int maskOffset = 0, index = 0; index < bits.length; maskOffset++, index++) { + for (int maskOffset = 0, index = 0; + index < bits.length; + maskOffset++, index++) { if (index > 0 && index % 8 == 0) { writeUInt8(mask); mask = 0; @@ -100,7 +99,7 @@ class TypeEncoder { List data = utf8.encode(value); if (data.length > 255) { - throw new ArgumentError("Short string values should have a length <= 255"); + throw ArgumentError("Short string values should have a length <= 255"); } // Write the length followed by the actual bytes @@ -137,7 +136,7 @@ class TypeEncoder { return; } - TypeEncoder buffer = new TypeEncoder(); + TypeEncoder buffer = TypeEncoder(); // Encode each keypair to the buffer table.forEach((String fieldName, Object value) { @@ -157,7 +156,7 @@ class TypeEncoder { return; } - TypeEncoder buffer = new TypeEncoder(); + TypeEncoder buffer = TypeEncoder(); value.forEach((Object v) => buffer._writeField(fieldName, v)); @@ -168,7 +167,6 @@ class TypeEncoder { } void _writeField(String fieldName, Object value) { - if (value is Map) { writeUInt8(FieldType.FIELD_TABLE.value); writeFieldTable(value); @@ -218,9 +216,9 @@ class TypeEncoder { } else if (value == null) { writeUInt8(FieldType.VOID.value); } else { - throw new ArgumentError("Could not encode field ${fieldName} with value ${value}"); + throw ArgumentError( + "Could not encode field ${fieldName} with value ${value}"); } - } // void dumpToFile(String outputFile) { diff --git a/test/lib/amqp_decoder_test.dart b/test/lib/amqp_decoder_test.dart index c1662cc..c888473 100644 --- a/test/lib/amqp_decoder_test.dart +++ b/test/lib/amqp_decoder_test.dart @@ -32,8 +32,7 @@ class ConnectionStartMock extends Mock implements ConnectionStart { ..writeUInt8(versionMinor) ..writeFieldTable(serverProperties) ..writeLongString(mechanisms) - ..writeLongString(locales) - ; + ..writeLongString(locales); } } @@ -53,8 +52,7 @@ class ConnectionTuneMock extends Mock implements ConnectionTune { ..writeUInt16(msgMethodId) ..writeUInt16(channelMax) ..writeUInt32(frameMax) - ..writeUInt16(heartbeat) - ; + ..writeUInt16(heartbeat); } } @@ -68,8 +66,7 @@ class ConnectionOpenOkMock extends Mock implements ConnectionOpenOk { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeShortString(reserved_1) - ; + ..writeShortString(reserved_1); } } @@ -93,40 +90,41 @@ class BasicDeliverMock extends Mock implements BasicDeliver { ..writeUInt64(deliveryTag) ..writeUInt8(0) ..writeShortString(exchange) - ..writeShortString(routingKey) - ; + ..writeShortString(routingKey); } } - -void generateHandshakeMessages(FrameWriter frameWriter, mock.MockServer server) { +void generateHandshakeMessages( + FrameWriter frameWriter, mock.MockServer server) { // Connection start - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection tune - frameWriter.writeMessage(0, new ConnectionTuneMock() - ..channelMax = 0 - ..frameMax = (new TuningSettings()).maxFrameSize - ..heartbeat = 0); + frameWriter.writeMessage( + 0, + ConnectionTuneMock() + ..channelMax = 0 + ..frameMax = (TuningSettings()).maxFrameSize + ..heartbeat = 0); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection open ok - frameWriter.writeMessage(0, new ConnectionOpenOkMock()); + frameWriter.writeMessage(0, ConnectionOpenOkMock()); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); } -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } @@ -139,83 +137,93 @@ main({bool enableLogger : true}) { TuningSettings tuningSettings; setUp(() { - tuningSettings = new TuningSettings(); - frameWriter = new FrameWriter(tuningSettings); + tuningSettings = TuningSettings(); + frameWriter = FrameWriter(tuningSettings); - controller = new StreamController(); - rawStream = controller - .stream - .transform(new AmqpMessageDecoder().transformer); + controller = StreamController(); + rawStream = controller.stream.transform(AmqpMessageDecoder().transformer); }); - test("HEADER frame with empty payload size should emit message without waiting for BODY frames", () { - rawStream - .listen(expectAsync1((data) { + test( + "HEADER frame with empty payload size should emit message without waiting for BODY frames", + () { + rawStream.listen(expectAsync1((data) { expect(data.payload, isNull); })); - new BasicDeliverMock() + BasicDeliverMock() ..routingKey = "" ..exchange = "" ..deliveryTag = 0 ..redelivered = false ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.METHOD; header.size = frameWriter.outputEncoder.writer.lengthInBytes; Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); // Header frame with 0 payload data - new ContentHeader() + ContentHeader() ..bodySize = 0 ..classId = 60 ..serialize(frameWriter.outputEncoder); - header = new FrameHeader(); + header = FrameHeader(); header.channel = 1; header.type = FrameType.HEADER; - header.size = frameWriter.outputEncoder.writer.lengthInBytes;; + header.size = frameWriter.outputEncoder.writer.lengthInBytes; + ; serializedData = frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); }); group("exception handling", () { test("METHOD frame while still processing previous METHOD frame", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a new METHOD frame while processing an incomplete METHOD frame")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a new METHOD frame while processing an incomplete METHOD frame")); })); - new BasicDeliverMock() + BasicDeliverMock() ..routingKey = "" ..exchange = "" ..deliveryTag = 0 ..redelivered = false ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.METHOD; header.size = frameWriter.outputEncoder.writer.lengthInBytes; - Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); + Uint8List serializedData = + frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); // The second method frame should trigger the exception controller.add(rawFrame); @@ -223,121 +231,139 @@ main({bool enableLogger : true}) { }); test("HEADER frame without a previous METHOD frame", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a HEADER frame without a matching METHOD frame")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a HEADER frame without a matching METHOD frame")); })); - new ContentHeader() + ContentHeader() ..bodySize = 0 ..classId = 1 ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.HEADER; header.size = frameWriter.outputEncoder.writer.lengthInBytes; - Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); + Uint8List serializedData = + frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); }); test("HEADER frame not matching previous METHOD frame class", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a HEADER frame that does not match the METHOD frame class id")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a HEADER frame that does not match the METHOD frame class id")); })); - new BasicDeliverMock() + BasicDeliverMock() ..routingKey = "" ..exchange = "" ..deliveryTag = 0 ..redelivered = false ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.METHOD; header.size = frameWriter.outputEncoder.writer.lengthInBytes; - Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); + Uint8List serializedData = + frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); // Write content header with different class id - new ContentHeader() + ContentHeader() ..bodySize = 0 ..classId = 0 ..serialize(frameWriter.outputEncoder); - header = new FrameHeader(); + header = FrameHeader(); header.channel = 1; header.type = FrameType.HEADER; header.size = frameWriter.outputEncoder.writer.lengthInBytes; serializedData = frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); }); test("duplicate HEADER frame for incomplete METHOD frame", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a duplicate HEADER frame for an incomplete METHOD frame")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a duplicate HEADER frame for an incomplete METHOD frame")); })); - new BasicDeliverMock() + BasicDeliverMock() ..routingKey = "" ..exchange = "" ..deliveryTag = 0 ..redelivered = false ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.METHOD; header.size = frameWriter.outputEncoder.writer.lengthInBytes; - Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); + Uint8List serializedData = + frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); // Write content header with different class id - new ContentHeader() + ContentHeader() ..bodySize = 1 ..classId = 60 ..serialize(frameWriter.outputEncoder); - header = new FrameHeader(); + header = FrameHeader(); header.channel = 1; header.type = FrameType.HEADER; header.size = frameWriter.outputEncoder.writer.lengthInBytes; serializedData = frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); // The second addition should trigger the error controller.add(rawFrame); @@ -345,60 +371,64 @@ main({bool enableLogger : true}) { }); test("BODY frame without matching METHOD frame", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a BODY frame without a matching METHOD frame")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a BODY frame without a matching METHOD frame")); })); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.BODY; header.size = 0; - rawFrame = new RawFrame(header, null); + rawFrame = RawFrame(header, null); controller.add(rawFrame); }); test("BODY frame without HEADER frame", () { - - rawStream - .listen((data) { + rawStream.listen((data) { fail("Expected exception to be thrown"); - }, - onError : expectAsync1((error) { + }, onError: expectAsync1((error) { expect(error, const TypeMatcher()); - expect(error.toString(), equals("ConnectionException(UNEXPECTED_FRAME): Received a BODY frame before a HEADER frame")); + expect( + error.toString(), + equals( + "ConnectionException(UNEXPECTED_FRAME): Received a BODY frame before a HEADER frame")); })); - new BasicDeliverMock() + BasicDeliverMock() ..routingKey = "" ..exchange = "" ..deliveryTag = 0 ..redelivered = false ..serialize(frameWriter.outputEncoder); - FrameHeader header = new FrameHeader(); + FrameHeader header = FrameHeader(); header.channel = 1; header.type = FrameType.METHOD; header.size = frameWriter.outputEncoder.writer.lengthInBytes; - Uint8List serializedData = frameWriter.outputEncoder.writer.joinChunks(); + Uint8List serializedData = + frameWriter.outputEncoder.writer.joinChunks(); frameWriter.outputEncoder.writer.clear(); - rawFrame = new RawFrame(header, new ByteData.view(serializedData.buffer, 0, serializedData.lengthInBytes)); + rawFrame = RawFrame( + header, + ByteData.view( + serializedData.buffer, 0, serializedData.lengthInBytes)); controller.add(rawFrame); // Write body - header = new FrameHeader(); + header = FrameHeader(); header.channel = 1; header.type = FrameType.BODY; header.size = 0; - rawFrame = new RawFrame(header, null); + rawFrame = RawFrame(header, null); controller.add(rawFrame); }); }); diff --git a/test/lib/auth_test.dart b/test/lib/auth_test.dart index 4b123ef..806c9ed 100644 --- a/test/lib/auth_test.dart +++ b/test/lib/auth_test.dart @@ -30,8 +30,7 @@ class ConnectionStartMock extends Mock implements ConnectionStart { ..writeUInt8(versionMinor) ..writeFieldTable(serverProperties) ..writeLongString(mechanisms) - ..writeLongString(locales) - ; + ..writeLongString(locales); } } @@ -47,8 +46,7 @@ class ConnectionSecureMock extends Mock implements ConnectionSecure { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeLongString(challenge) - ; + ..writeLongString(challenge); } } @@ -68,8 +66,7 @@ class ConnectionTuneMock extends Mock implements ConnectionTune { ..writeUInt16(msgMethodId) ..writeUInt16(channelMax) ..writeUInt32(frameMax) - ..writeUInt16(heartbeat) - ; + ..writeUInt16(heartbeat); } } @@ -83,8 +80,7 @@ class ConnectionOpenOkMock extends Mock implements ConnectionOpenOk { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeShortString(reserved_1) - ; + ..writeShortString(reserved_1); } } @@ -94,10 +90,7 @@ class ConnectionCloseOkMock extends Mock implements ConnectionCloseOk { final int msgMethodId = 51; void serialize(TypeEncoder encoder) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } @@ -107,19 +100,19 @@ class FooAuthProvider implements Authenticator { String answerChallenge(String challenge) { return null; } - } -void generateHandshakeMessages(FrameWriter frameWriter, mock.MockServer server, int numChapRounds) { +void generateHandshakeMessages( + FrameWriter frameWriter, mock.MockServer server, int numChapRounds) { // Connection start - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); @@ -127,29 +120,28 @@ void generateHandshakeMessages(FrameWriter frameWriter, mock.MockServer server, for (int round = 0; round < numChapRounds; round++) { // Connection secure frameWriter.writeMessage( - 0, - new ConnectionSecureMock() - ..challenge = "round${round}" - ); + 0, ConnectionSecureMock()..challenge = "round${round}"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); } // Connection tune - frameWriter.writeMessage(0, new ConnectionTuneMock() - ..channelMax = 0 - ..frameMax = (new TuningSettings()).maxFrameSize - ..heartbeat = 0); + frameWriter.writeMessage( + 0, + ConnectionTuneMock() + ..channelMax = 0 + ..frameMax = (TuningSettings()).maxFrameSize + ..heartbeat = 0); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection open ok - frameWriter.writeMessage(0, new ConnectionOpenOkMock()); + frameWriter.writeMessage(0, ConnectionOpenOkMock()); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); } -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } @@ -162,27 +154,19 @@ main({bool enableLogger : true}) { }); test("PLAIN authenticaion", () { - ConnectionSettings settings = new ConnectionSettings( - authProvider : new PlainAuthenticator("guest", "guest") - ); - client = new Client(settings : settings); - - client - .connect() - .then(expectAsync1((_) { - })); + ConnectionSettings settings = ConnectionSettings( + authProvider: PlainAuthenticator("guest", "guest")); + client = Client(settings: settings); + + client.connect().then(expectAsync1((_) {})); }); test("AMQPLAIN authenticaion", () { - ConnectionSettings settings = new ConnectionSettings( - authProvider : new AmqPlainAuthenticator("guest", "guest") - ); - client = new Client(settings : settings); - - client - .connect() - .then(expectAsync1((_) { - })); + ConnectionSettings settings = ConnectionSettings( + authProvider: AmqPlainAuthenticator("guest", "guest")); + client = Client(settings: settings); + + client.connect().then(expectAsync1((_) {})); }); }); @@ -193,30 +177,26 @@ main({bool enableLogger : true}) { TuningSettings tuningSettings; setUp(() { - tuningSettings = new TuningSettings(); - frameWriter = new FrameWriter(tuningSettings); - server = new mock.MockServer(); - client = new Client(settings : new ConnectionSettings(port : 9000)); + tuningSettings = TuningSettings(); + frameWriter = FrameWriter(tuningSettings); + server = mock.MockServer(); + client = Client(settings: ConnectionSettings(port: 9000)); return server.listen('127.0.0.1', 9000); }); tearDown(() { - return client.close() - .then( (_) => server.shutdown() ); + return client.close().then((_) => server.shutdown()); }); test("multiple challenge-response rounds", () { generateHandshakeMessages(frameWriter, server, 10); // Encode final connection close - frameWriter.writeMessage(0, new ConnectionCloseOkMock()); + frameWriter.writeMessage(0, ConnectionCloseOkMock()); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); - client - .connect() - .then(expectAsync1((_) { - })); + client.connect().then(expectAsync1((_) {})); }); }); @@ -228,26 +208,27 @@ main({bool enableLogger : true}) { }); test("unsupported SASL provider", () { - ConnectionSettings settings = new ConnectionSettings(authProvider : new FooAuthProvider()); + ConnectionSettings settings = + ConnectionSettings(authProvider: FooAuthProvider()); - client = new Client(settings : settings); + client = Client(settings: settings); - client - .connect() - .catchError(expectAsync1((e) { + client.connect().catchError(expectAsync1((e) { expect(e, const TypeMatcher()); - expect(e.message, startsWith("Selected authentication provider 'foo' is unsupported by the server")); + expect( + e.message, + startsWith( + "Selected authentication provider 'foo' is unsupported by the server")); })); }); test("invalid auth credentials", () { - ConnectionSettings settings = new ConnectionSettings(authProvider : new PlainAuthenticator("foo", "foo")); + ConnectionSettings settings = + ConnectionSettings(authProvider: PlainAuthenticator("foo", "foo")); - client = new Client(settings : settings); + client = Client(settings: settings); - client - .connect() - .catchError(expectAsync1((e) { + client.connect().catchError(expectAsync1((e) { expect(e, const TypeMatcher()); expect(e.message, equals("Authentication failed")); })); diff --git a/test/lib/channel_test.dart b/test/lib/channel_test.dart index 02baad5..b25c0c1 100644 --- a/test/lib/channel_test.dart +++ b/test/lib/channel_test.dart @@ -9,17 +9,16 @@ import "package:dart_amqp/src/exceptions.dart"; import "mocks/mocks.dart" as mock; // This test expects a local running rabbitmq instance at the default port -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } - group - ("Channels:", () { + group("Channels:", () { Client client; setUp(() { - client = new Client(); + client = Client(); }); tearDown(() { @@ -28,64 +27,70 @@ main({bool enableLogger : true}) { test("select() followed by commit()", () { return client - .channel() - .then((Channel channel) => channel.select()) - .then((Channel channel) => channel.commit()); + .channel() + .then((Channel channel) => channel.select()) + .then((Channel channel) => channel.commit()); }); test("select() followed by rollback()", () { return client - .channel() - .then((Channel channel) => channel.select()) - .then((Channel channel) => channel.rollback()); + .channel() + .then((Channel channel) => channel.select()) + .then((Channel channel) => channel.rollback()); }); test("flow control: off", () { // Rabbit does not support setting flow control to on - return client - .channel() - .then((Channel channel) => channel.flow(true)); + return client.channel().then((Channel channel) => channel.flow(true)); }); group("exceptions:", () { - test("sending data on a closed channel should raise an exception", () { return client - .channel() - .then((Channel channel) => channel.close()) - .then((Channel channel) { - expect(() => channel.privateQueue(), throwsA((e) => e is StateError && e.message == "Channel has been closed")); + .channel() + .then((Channel channel) => channel.close()) + .then((Channel channel) { + expect( + () => channel.privateQueue(), + throwsA((e) => + e is StateError && e.message == "Channel has been closed")); }); }); - - test("commit() on a non-transactional channel should raise a precondition-failed error", () { + test( + "commit() on a non-transactional channel should raise a precondition-failed error", + () { client - .channel() - .then((Channel channel) => channel.commit()) - .then((_) => fail("Expected an exception to be thrown")) - .catchError(expectAsync1((e) { + .channel() + .then((Channel channel) => channel.commit()) + .then((_) => fail("Expected an exception to be thrown")) + .catchError(expectAsync1((e) { expect(e, const TypeMatcher()); - expect((e as ChannelException).errorType, equals(ErrorType.PRECONDITION_FAILED)); + expect((e as ChannelException).errorType, + equals(ErrorType.PRECONDITION_FAILED)); })); }); - test("rollback() on a non-transactional channel should raise a precondition-failed error", () { + test( + "rollback() on a non-transactional channel should raise a precondition-failed error", + () { client - .channel() - .then((Channel channel) => channel.rollback()) - .then((_) => fail("Expected an exception to be thrown")) - .catchError(expectAsync1((e) { + .channel() + .then((Channel channel) => channel.rollback()) + .then((_) => fail("Expected an exception to be thrown")) + .catchError(expectAsync1((e) { expect(e, const TypeMatcher()); - expect((e as ChannelException).errorType, equals(ErrorType.PRECONDITION_FAILED)); - expect(e.toString(), startsWith("ChannelException(PRECONDITION_FAILED)")); + expect((e as ChannelException).errorType, + equals(ErrorType.PRECONDITION_FAILED)); + expect(e.toString(), + startsWith("ChannelException(PRECONDITION_FAILED)")); })); }); test("revocer()", () { return client - .channel() - .then((Channel channel) => channel.recover(true)); + .channel() + .then((Channel channel) => channel.recover(true)); }); }); }); diff --git a/test/lib/client_test.dart b/test/lib/client_test.dart index 8a718d0..eae94bb 100644 --- a/test/lib/client_test.dart +++ b/test/lib/client_test.dart @@ -10,7 +10,7 @@ import "package:dart_amqp/src/exceptions.dart"; import "mocks/mocks.dart" as mock; -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } @@ -23,24 +23,20 @@ main({bool enableLogger : true}) { }); test("fail to connect after 2 attempts", () { - ConnectionSettings settings = new ConnectionSettings( - port : 8765, - maxConnectionAttempts : 2, - reconnectWaitTime : const Duration(milliseconds : 10) - ); - client = new Client(settings : settings); - - client - .connect() - .catchError(expectAsync1((ex) { + ConnectionSettings settings = ConnectionSettings( + port: 8765, + maxConnectionAttempts: 2, + reconnectWaitTime: const Duration(milliseconds: 10)); + client = Client(settings: settings); + + client.connect().catchError(expectAsync1((ex) { expect(ex, const TypeMatcher()); expect(ex.toString(), startsWith('ConnectionFailedException')); })); - }); test("multiple open attampts should return the same future", () { - client = new Client(); + client = Client(); Future connectFuture = client.connect(); @@ -50,10 +46,9 @@ main({bool enableLogger : true}) { }); test("multiple close attampts should return the same future", () { - client = new Client(); + client = Client(); - return client.connect() - .then((_) { + return client.connect().then((_) { Future closeFuture = client.close(); expect(client.close(), equals(closeFuture)); @@ -63,21 +58,15 @@ main({bool enableLogger : true}) { }); test("exception when exceeding negotiated channel limit", () { + ConnectionSettings settings = + ConnectionSettings(tuningSettings: TuningSettings()..maxChannels = 1); + client = Client(settings: settings); - ConnectionSettings settings = new ConnectionSettings( - tuningSettings : new TuningSettings() - ..maxChannels = 1 - ); - client = new Client(settings : settings); - - return client - .channel() - .then((_) => client.channel()) - .catchError((ex) { + return client.channel().then((_) => client.channel()).catchError((ex) { expect(ex, const TypeMatcher()); - expect(ex.message, equals("Cannot allocate channel; channel limit exceeded (max 1)")); + expect(ex.message, + equals("Cannot allocate channel; channel limit exceeded (max 1)")); }); }); - }); -} \ No newline at end of file +} diff --git a/test/lib/encode_decode_test.dart b/test/lib/encode_decode_test.dart index 56a0370..4ef23aa 100644 --- a/test/lib/encode_decode_test.dart +++ b/test/lib/encode_decode_test.dart @@ -11,10 +11,11 @@ import "mocks/mocks.dart" as mock; TypeDecoder decoderFromEncoder(TypeEncoder encoder) { Uint8List data = encoder.writer.joinChunks(); - return new TypeDecoder.fromBuffer(new ByteData.view(data.buffer, 0, data.lengthInBytes)); + return TypeDecoder.fromBuffer( + ByteData.view(data.buffer, 0, data.lengthInBytes)); } -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } @@ -24,7 +25,7 @@ main({bool enableLogger : true}) { TypeDecoder decoder; setUp(() { - encoder = new TypeEncoder(); + encoder = TypeEncoder(); }); test("uint8", () { @@ -99,7 +100,8 @@ main({bool enableLogger : true}) { }); test("bitmap", () { - encoder.writeBits([false, true, false, true, false, true, false, true, false, true]); + encoder.writeBits( + [false, true, false, true, false, true, false, true, false, true]); decoder = decoderFromEncoder(encoder); // 0XAA = 10101010 @@ -126,9 +128,11 @@ main({bool enableLogger : true}) { }); test("shortString max length", () { - String longString = new String.fromCharCodes(new List.generate(256, (int index) => index)); + String longString = + String.fromCharCodes(List.generate(256, (int index) => index)); - expect(() => encoder.writeShortString(longString), throwsA((e) => e is ArgumentError)); + expect(() => encoder.writeShortString(longString), + throwsA((e) => e is ArgumentError)); }); test("longString", () { @@ -147,8 +151,9 @@ main({bool enableLogger : true}) { test("timestamp", () { // Use second accuracy - DateTime now = new DateTime.now(); - now = now.subtract(new Duration(milliseconds : now.millisecond, microseconds: now.microsecond)); + DateTime now = DateTime.now(); + now = now.subtract(Duration( + milliseconds: now.millisecond, microseconds: now.microsecond)); encoder.writeTimestamp(now); decoder = decoderFromEncoder(encoder); @@ -157,7 +162,6 @@ main({bool enableLogger : true}) { }); test("timestamp (null)", () { - encoder.writeTimestamp(null); decoder = decoderFromEncoder(encoder); @@ -175,31 +179,32 @@ main({bool enableLogger : true}) { test("table", () { // Use second accuracy - DateTime now = new DateTime.now(); - now = now.subtract(new Duration(milliseconds : now.millisecond, microseconds: now.microsecond)); + DateTime now = DateTime.now(); + now = now.subtract(Duration( + milliseconds: now.millisecond, microseconds: now.microsecond)); final tableData = { - "map" : { - "list" : ["foo", "bar", "baz"] + "map": { + "list": ["foo", "bar", "baz"] }, - "bool" : true, - "unsigned" : { - "uint8" : 0xFF, - "uint16" : 0xFFFF, - "uint32" : 0xFFFFFFFF, - "uint64" : 0xFFFFFFFFFFFFFFFF + "bool": true, + "unsigned": { + "uint8": 0xFF, + "uint16": 0xFFFF, + "uint32": 0xFFFFFFFF, + "uint64": 0xFFFFFFFFFFFFFFFF }, - "signed" : { - "int8" : -0x80, - "int16" : -0x8000, - "int32" : -0x80000000, - "int64" : -0x800000000000000 + "signed": { + "int8": -0x80, + "int16": -0x8000, + "int32": -0x80000000, + "int64": -0x800000000000000 }, - "string" : "Hello world", - "float" : -3.141, - "double" : 3.14151617, - "timestamp" : now, - "void" : null + "string": "Hello world", + "float": -3.141, + "double": 3.14151617, + "timestamp": now, + "void": null }; encoder.writeFieldTable(tableData); @@ -210,15 +215,17 @@ main({bool enableLogger : true}) { test("table (unsupported field exception)", () { // Use second accuracy - DateTime now = new DateTime.now(); - now = now.subtract(new Duration(milliseconds : now.millisecond, microseconds: now.microsecond)); + DateTime now = DateTime.now(); + now = now.subtract(Duration( + milliseconds: now.millisecond, microseconds: now.microsecond)); - final tableData = { - "unsupported" : new StreamController() - }; + final tableData = {"unsupported": StreamController()}; - expect(() => encoder.writeFieldTable(tableData), throwsA((ex) => ex is ArgumentError && ex.message.startsWith("Could not encode field unsupported"))); + expect( + () => encoder.writeFieldTable(tableData), + throwsA((ex) => + ex is ArgumentError && + ex.message.startsWith("Could not encode field unsupported"))); }); - }); } diff --git a/test/lib/enum_test.dart b/test/lib/enum_test.dart index 7f20d87..40a7662 100644 --- a/test/lib/enum_test.dart +++ b/test/lib/enum_test.dart @@ -13,14 +13,13 @@ Type _getGenericType(ClassMirror classMirror) { return classMirror.superclass.typeArguments.first.reflectedType; } -main({bool enableLogger : true}) { - +main({bool enableLogger = true}) { List enumClasses = [ - DeliveryMode - , ErrorType - , ExchangeType - , FieldType - , FrameType + DeliveryMode, + ErrorType, + ExchangeType, + FieldType, + FrameType ]; for (Type enumClass in enumClasses) { @@ -32,7 +31,10 @@ main({bool enableLogger : true}) { // Run a first pass to detect which methods we can use cm.declarations.forEach((Symbol enumSymbol, declarationMirror) { - String declName = enumSymbol.toString().replaceAll("Symbol(\"", "").replaceAll("\")", ""); + String declName = enumSymbol + .toString() + .replaceAll("Symbol(\"", "") + .replaceAll("\")", ""); if (declarationMirror is MethodMirror) { if (declName == "valueOf") { valueOfMirror = declarationMirror; @@ -45,42 +47,42 @@ main({bool enableLogger : true}) { }); // Nothing to test here... - if (nameOfMirror == null && valueOfMirror == null && toStringMirror == null) { + if (nameOfMirror == null && + valueOfMirror == null && + toStringMirror == null) { continue; } group("${enumClass.toString()}:", () { - // Generate tests for exceptions if (valueOfMirror != null) { group("Exceptions:", () { Object junkValue = _getMethodArgType(valueOfMirror) == String - ? "BADFOOD" - : 0xBADF00D; + ? "BADFOOD" + : 0xBADF00D; - Object formattedJunkValue = junkValue is String - ? "\"BADFOOD\"" - : "0xBADF00D"; + Object formattedJunkValue = + junkValue is String ? "\"BADFOOD\"" : "0xBADF00D"; if (cm.reflectedType == ExchangeType) test("valueOf(${formattedJunkValue}) creates Custom Exchange", () { - ExchangeType customExchange = cm - .invoke(#valueOf, [ junkValue]) - .reflectee; + ExchangeType customExchange = + cm.invoke(#valueOf, [junkValue]).reflectee; expect(customExchange.isCustom, isTrue); }); else test("valueOf(${formattedJunkValue}) throws ArgumentError", () { - expect(() => cm - .invoke(#valueOf, [ junkValue]) - .reflectee, throwsArgumentError); + expect(() => cm.invoke(#valueOf, [junkValue]).reflectee, + throwsArgumentError); }); }); } // Generate tests depending on which methods are available cm.declarations.forEach((Symbol enumSymbol, declarationMirror) { - - String declName = enumSymbol.toString().replaceAll("Symbol(\"", "").replaceAll("\")", ""); + String declName = enumSymbol + .toString() + .replaceAll("Symbol(\"", "") + .replaceAll("\")", ""); // Only process public Enum instances if (declarationMirror is MethodMirror || declarationMirror.isPrivate) { @@ -97,8 +99,10 @@ main({bool enableLogger : true}) { if (valueOfMirror != null) { test("valueOf(${declName}.value) == ${declName}", () { dynamic staticEnumInstance = cm.getField(enumSymbol).reflectee; - dynamic enumValue = cm.getField(enumSymbol).getField(#value).reflectee; - expect(cm.invoke(#valueOf, [ enumValue ]).reflectee, equals(staticEnumInstance)); + dynamic enumValue = + cm.getField(enumSymbol).getField(#value).reflectee; + expect(cm.invoke(#valueOf, [enumValue]).reflectee, + equals(staticEnumInstance)); }); } @@ -106,26 +110,27 @@ main({bool enableLogger : true}) { if (nameOfMirror != null) { test("nameOf(${declName}) == \"${declName}\"", () { dynamic staticEnumInstance = cm.getField(enumSymbol).reflectee; - expect(cm.invoke(#nameOf, [ staticEnumInstance ]).reflectee, equals(declName)); + expect(cm.invoke(#nameOf, [staticEnumInstance]).reflectee, + equals(declName)); }); } // Generate toString tests if (toStringMirror != null) { test("${declName}.toString()", () { - Enum staticEnumInstance = cm.getField(enumSymbol).reflectee; + Enum staticEnumInstance = + cm.getField(enumSymbol).reflectee; Object enumValue = staticEnumInstance.value; Object expectedValue = _getGenericType(cm) == String - ? enumValue - : "${(enumValue as int).toRadixString(10)}"; + ? enumValue + : "${(enumValue as int).toRadixString(10)}"; expect(staticEnumInstance.toString(), equals(expectedValue)); }); } - }); }); }); } -} \ No newline at end of file +} diff --git a/test/lib/exception_handling_test.dart b/test/lib/exception_handling_test.dart index 68f3ed2..611a944 100644 --- a/test/lib/exception_handling_test.dart +++ b/test/lib/exception_handling_test.dart @@ -34,8 +34,7 @@ class ConnectionStartMock extends Mock implements ConnectionStart { ..writeUInt8(versionMinor) ..writeFieldTable(serverProperties) ..writeLongString(mechanisms) - ..writeLongString(locales) - ; + ..writeLongString(locales); } } @@ -55,8 +54,7 @@ class ConnectionTuneMock extends Mock implements ConnectionTune { ..writeUInt16(msgMethodId) ..writeUInt16(channelMax) ..writeUInt32(frameMax) - ..writeUInt16(heartbeat) - ; + ..writeUInt16(heartbeat); } } @@ -70,8 +68,7 @@ class ConnectionOpenOkMock extends Mock implements ConnectionOpenOk { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) - ..writeShortString(reserved_1) - ; + ..writeShortString(reserved_1); } } @@ -81,42 +78,42 @@ class TxSelectOkMock extends Mock implements TxSelectOk { final int msgMethodId = 11; void serialize(TypeEncoder encoder) { - encoder - ..writeUInt16(msgClassId) - ..writeUInt16(msgMethodId) - ; + encoder..writeUInt16(msgClassId)..writeUInt16(msgMethodId); } } -void generateHandshakeMessages(FrameWriter frameWriter, mock.MockServer server) { +void generateHandshakeMessages( + FrameWriter frameWriter, mock.MockServer server) { // Connection start - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection tune - frameWriter.writeMessage(0, new ConnectionTuneMock() - ..channelMax = 0 - ..frameMax = (new TuningSettings()).maxFrameSize - ..heartbeat = 0); + frameWriter.writeMessage( + 0, + ConnectionTuneMock() + ..channelMax = 0 + ..frameMax = (TuningSettings()).maxFrameSize + ..heartbeat = 0); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection open ok - frameWriter.writeMessage(0, new ConnectionOpenOkMock()); + frameWriter.writeMessage(0, ConnectionOpenOkMock()); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); } -main({bool enableLogger : true}) { - Random rnd = new Random(); +main({bool enableLogger = true}) { + Random rnd = Random(); if (enableLogger) { mock.initLogger(); } @@ -129,23 +126,22 @@ main({bool enableLogger : true}) { int port; setUp(() { - tuningSettings = new TuningSettings(); - frameWriter = new FrameWriter(tuningSettings); - server = new mock.MockServer(); + tuningSettings = TuningSettings(); + frameWriter = FrameWriter(tuningSettings); + server = mock.MockServer(); port = 9000 + rnd.nextInt(100); - client = new Client(settings : new ConnectionSettings(port : port)); + client = Client(settings: ConnectionSettings(port: port)); return server.listen('127.0.0.1', port); }); tearDown(() { - return client.close() - .then((_) => server.shutdown()); + return client.close().then((_) => server.shutdown()); }); group("fatal exceptions:", () { test("protocol mismatch", () { - TypeEncoder encoder = new TypeEncoder(); - new ProtocolHeader() + TypeEncoder encoder = TypeEncoder(); + ProtocolHeader() ..protocolVersion = 0 ..majorVersion = 0 ..minorVersion = 8 @@ -156,132 +152,138 @@ main({bool enableLogger : true}) { void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Could not negotiate a valid AMQP protocol version. Server supports AMQP 0.8.0")); + expect( + ex.message, + equalsIgnoringCase( + "Could not negotiate a valid AMQP protocol version. Server supports AMQP 0.8.0")); } - client - .connect() - .then((_) { + client.connect().then((_) { fail("Expected a FatalException to be thrown"); }).catchError(expectAsync2(handleError)); }); test("frame without terminator", () { - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); Uint8List frameData = frameWriter.outputEncoder.writer.joinChunks(); // Set an invalid frame terminator to the mock server response - frameData[ frameData.length - 1 ] = 0xF0; + frameData[frameData.length - 1] = 0xF0; server.replayList.add(frameData); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Frame did not end with the expected frame terminator (0xCE)")); + expect( + ex.message, + equalsIgnoringCase( + "Frame did not end with the expected frame terminator (0xCE)")); } - client - .connect() - .then((_) { + client.connect().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); test("frame on channel > 0 while handshake in progress", () { - frameWriter.writeMessage(1, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 1, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Received message for channel 1 while still handshaking")); + expect( + ex.message, + equalsIgnoringCase( + "Received message for channel 1 while still handshaking")); } - client - .connect() - .then((_) { + client.connect().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); test("unexpected frame during handshake", () { // Connection start - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Connection tune - frameWriter.writeMessage(0, new ConnectionTuneMock() - ..channelMax = 0 - ..frameMax = (new TuningSettings()).maxFrameSize - ..heartbeat = 0); + frameWriter.writeMessage( + 0, + ConnectionTuneMock() + ..channelMax = 0 + ..frameMax = (TuningSettings()).maxFrameSize + ..heartbeat = 0); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); // Unexpected frame - frameWriter.writeMessage(0, new TxSelectOkMock()); + frameWriter.writeMessage(0, TxSelectOkMock()); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); frameWriter.outputEncoder.writer.clear(); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Received unexpected message TxSelectOk during handshake")); + expect( + ex.message, + equalsIgnoringCase( + "Received unexpected message TxSelectOk during handshake")); } - client - .connect() - .then((_) { + client.connect().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); - }); group("connection exceptions:", () { test("illegal frame size", () { - frameWriter.writeMessage(0, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 0, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); Uint8List frameData = frameWriter.outputEncoder.writer.joinChunks(); // Manipulate the frame header to indicate a too long message int len = tuningSettings.maxFrameSize + 1; - frameData[ 3 ] = (len >> 24) & 0xFF; - frameData[ 4 ] = (len >> 16) & 0xFF; - frameData[ 5 ] = (len >> 8) & 0xFF; - frameData[ 6 ] = (len) & 0xFF; + frameData[3] = (len >> 24) & 0xFF; + frameData[4] = (len >> 16) & 0xFF; + frameData[5] = (len >> 8) & 0xFF; + frameData[6] = (len) & 0xFF; server.replayList.add(frameData); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Frame size cannot be larger than ${tuningSettings.maxFrameSize} bytes. Server sent ${tuningSettings.maxFrameSize + 1} bytes")); + expect( + ex.message, + equalsIgnoringCase( + "Frame size cannot be larger than ${tuningSettings.maxFrameSize} bytes. Server sent ${tuningSettings.maxFrameSize + 1} bytes")); } - client - .connect() - .then((_) { + client.connect().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); @@ -290,24 +292,25 @@ main({bool enableLogger : true}) { generateHandshakeMessages(frameWriter, server); // Add a fake connection start message at channel 1 - frameWriter.writeMessage(1, new ConnectionStartMock() - ..versionMajor = 0 - ..versionMinor = 9 - ..serverProperties = { - "product" : "foo" - } - ..mechanisms = "PLAIN" - ..locales = "en"); + frameWriter.writeMessage( + 1, + ConnectionStartMock() + ..versionMajor = 0 + ..versionMinor = 9 + ..serverProperties = {"product": "foo"} + ..mechanisms = "PLAIN" + ..locales = "en"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Received CONNECTION class message on a channel > 0")); + expect( + ex.message, + equalsIgnoringCase( + "Received CONNECTION class message on a channel > 0")); } - client - .channel() - .then((_) { + client.channel().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); @@ -316,17 +319,19 @@ main({bool enableLogger : true}) { generateHandshakeMessages(frameWriter, server); // Add a heartbeat start message at channel 1 - frameWriter.outputEncoder.writer.addLast(new Uint8List.fromList([8, 0, 1, 0, 0, 0, 0, RawFrameParser.FRAME_TERMINATOR])); + frameWriter.outputEncoder.writer.addLast(Uint8List.fromList( + [8, 0, 1, 0, 0, 0, 0, RawFrameParser.FRAME_TERMINATOR])); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.message, equalsIgnoringCase("Received HEARTBEAT message on a channel > 0")); + expect( + ex.message, + equalsIgnoringCase( + "Received HEARTBEAT message on a channel > 0")); } - client - .channel() - .then((_) { + client.channel().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); @@ -335,22 +340,22 @@ main({bool enableLogger : true}) { generateHandshakeMessages(frameWriter, server); // Add a fake connection start message at channel 1 - frameWriter.writeMessage(0, new ConnectionClose() - ..classId = 10 - ..methodId = 40 - ..replyCode = ErrorType.ACCESS_REFUSED.value - ..replyText = "No access" - ); + frameWriter.writeMessage( + 0, + ConnectionClose() + ..classId = 10 + ..methodId = 40 + ..replyCode = ErrorType.ACCESS_REFUSED.value + ..replyText = "No access"); server.replayList.add(frameWriter.outputEncoder.writer.joinChunks()); void handleError(ex, s) { expect(ex, const TypeMatcher()); - expect(ex.toString(), equals("ConnectionException(ACCESS_REFUSED): No access")); + expect(ex.toString(), + equals("ConnectionException(ACCESS_REFUSED): No access")); } - client - .channel() - .then((_) { + client.channel().then((_) { fail("Expected an exception to be thrown"); }).catchError(expectAsync2(handleError)); }); @@ -360,18 +365,20 @@ main({bool enableLogger : true}) { void handleError(ex) { expect(ex, const TypeMatcher()); } - server.shutdown() - .then((_) => server.listen(client.settings.host, client.settings.port)) + + server + .shutdown() + .then((_) => + server.listen(client.settings.host, client.settings.port)) .then((_) { - generateHandshakeMessages(frameWriter, server); - return client - .connect() - .then((_) { - client.errorListener((ex) => handleError(ex)); - return server.shutdown() - .then((_) => new Future.delayed( - new Duration(seconds: 5) + server.responseDelay)) - .then((_) => fail("Expected an exception to be thrown")); + generateHandshakeMessages(frameWriter, server); + return client.connect().then((_) { + client.errorListener((ex) => handleError(ex)); + return server + .shutdown() + .then((_) => + Future.delayed(Duration(seconds: 5) + server.responseDelay)) + .then((_) => fail("Expected an exception to be thrown")); }); }); }); diff --git a/test/lib/exchange_test.dart b/test/lib/exchange_test.dart index d1418a6..f2a589d 100644 --- a/test/lib/exchange_test.dart +++ b/test/lib/exchange_test.dart @@ -11,43 +11,45 @@ import "package:dart_amqp/src/exceptions.dart"; import "mocks/mocks.dart" as mock; // This test expects a local running rabbitmq instance at the default port -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } - group - ("Exchanges:", () { + group("Exchanges:", () { Client client; Client client2; setUp(() { - client = new Client(); - client2 = new Client(); + client = Client(); + client2 = Client(); }); tearDown(() { - return client.close() - .then((_) => client2.close()); + return client.close().then((_) => client2.close()); }); test("check if unknown exchange exists", () { client - .channel() - .then((Channel channel) => channel.exchange("foo123", ExchangeType.DIRECT, passive : true)) - .then((_) => fail("Expected an exception to be thrown")) - .catchError(expectAsync1((e) { + .channel() + .then((Channel channel) => + channel.exchange("foo123", ExchangeType.DIRECT, passive: true)) + .then((_) => fail("Expected an exception to be thrown")) + .catchError(expectAsync1((e) { expect(e, const TypeMatcher()); - expect((e as ExchangeNotFoundException).errorType, equals(ErrorType.NOT_FOUND)); - expect(e.toString(), startsWith("ExchangeNotFoundException: NOT_FOUND")); + expect((e as ExchangeNotFoundException).errorType, + equals(ErrorType.NOT_FOUND)); + expect( + e.toString(), startsWith("ExchangeNotFoundException: NOT_FOUND")); })); }); test("declare exchange", () { client - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then(expectAsync1((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then(expectAsync1((Exchange exchange) { expect(exchange.channel, const TypeMatcher()); expect(exchange.name, equals("ex_test_1")); expect(exchange.type, equals(ExchangeType.DIRECT)); @@ -56,87 +58,97 @@ main({bool enableLogger : true}) { test("declare exchange and bind private queue consumer", () { client - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(["test"])) - .then(expectAsync1((Consumer consumer) { + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange exchange) => + exchange.bindPrivateQueueConsumer(["test"])) + .then(expectAsync1((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); })); - }); test("declare exchange and bind multiple routing keys", () { client - .channel() - .then((Channel channel) => channel.qos(null, 1)) - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(["test", "foo", "bar"])) - .then(expectAsync1((Consumer consumer) { + .channel() + .then((Channel channel) => channel.qos(null, 1)) + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange exchange) => + exchange.bindPrivateQueueConsumer(["test", "foo", "bar"])) + .then(expectAsync1((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); })); - }); test("declare exchange and publish message", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(["test"])) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange exchange) => + exchange.bindPrivateQueueConsumer(["test"])) + .then((Consumer consumer) { // Listen for messages consumer.listen(expectAsync1((AmqpMessage message) { expect(message.payloadAsString, equals("Test message 1234")); expect(message.routingKey, equals("test")); // Check for exception with missing reply-to property - expect(() => message.reply(""), throwsA((e) => e is ArgumentError && e.message == "No reply-to property specified in the incoming message")); + expect( + () => message.reply(""), + throwsA((e) => + e is ArgumentError && + e.message == + "No reply-to property specified in the incoming message")); testCompleter.complete(); })); // Connect second client and publish message to excahnge client2 - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange client2Exchange) => client2Exchange.publish("Test message 1234", "test")); + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange client2Exchange) => + client2Exchange.publish("Test message 1234", "test")); }); return testCompleter.future; - }); test("publish unrouteable message", () { - Completer testCompleter = new Completer(); - client - .channel() - .then((Channel channel) { - channel.basicReturnListener((BasicReturnMessage message){ + Completer testCompleter = Completer(); + client.channel().then((Channel channel) { + channel.basicReturnListener((BasicReturnMessage message) { expect(message.replyCode, equals(312)); expect(message.routingKey, equals("test")); testCompleter.complete(); }); return channel.exchange("ex_test_1", ExchangeType.DIRECT); - }).then((Exchange exchange)=>exchange.publish("Test message 1234", "test", mandatory:true)); + }).then((Exchange exchange) => + exchange.publish("Test message 1234", "test", mandatory: true)); return testCompleter.future; }); test("two client json conversation through an exchange", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer(["test"])) - .then((Consumer consumer) { - + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange exchange) => + exchange.bindPrivateQueueConsumer(["test"])) + .then((Consumer consumer) { // Listen for messages consumer.listen((AmqpMessage message) { expect(message.payloadAsString, equals('{"message":"1234"}')); - expect(message.payloadAsJson, equals({"message":"1234"})); + expect(message.payloadAsJson, equals({"message": "1234"})); expect(message.payload, equals(message.payloadAsString.codeUnits)); expect(message.routingKey, equals("test")); expect(message.properties.corellationId, equals("123")); @@ -148,14 +160,15 @@ main({bool enableLogger : true}) { // Connect second client and publish message to excahnge client2 - .channel() - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange client2Exchange) { + .channel() + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange client2Exchange) { // Allocate private queue for response - client2Exchange.channel.privateQueue() - .then((Queue replyQueue) => replyQueue.consume()) - .then((Consumer replyConsumer) { - + client2Exchange.channel + .privateQueue() + .then((Queue replyQueue) => replyQueue.consume()) + .then((Consumer replyConsumer) { // Bind reply listener replyConsumer.listen((AmqpMessage reply) { expect(reply.properties.corellationId, equals("123")); @@ -166,64 +179,58 @@ main({bool enableLogger : true}) { }); // Send initial message via exchange - client2Exchange.publish( - {"message" : "1234"}, - "test", - properties : new MessageProperties() + client2Exchange.publish({"message": "1234"}, "test", + properties: MessageProperties() ..corellationId = "123" - ..replyTo = replyConsumer.queue.name - ); + ..replyTo = replyConsumer.queue.name); }); }); }); return testCompleter.future; - }); test("declare and delete exchange", () { client - .channel() - .then((Channel channel) => channel.qos(0, 1)) - .then((Channel channel) => channel.exchange("ex_test_1", ExchangeType.DIRECT)) - .then((Exchange exchange) => exchange.delete()) - .then(expectAsync1((Exchange exchange) { - })); - + .channel() + .then((Channel channel) => channel.qos(0, 1)) + .then((Channel channel) => + channel.exchange("ex_test_1", ExchangeType.DIRECT)) + .then((Exchange exchange) => exchange.delete()) + .then(expectAsync1((Exchange exchange) {})); }); test("publish to FANOUT exchange without a routing key", () { client - .channel() - .then((Channel channel) => channel.exchange("ex_test_2", ExchangeType.FANOUT)) - .then((Exchange exchange) => exchange.publish("Hello", "")) - .then(expectAsync1((_) { - })); - + .channel() + .then((Channel channel) => + channel.exchange("ex_test_2", ExchangeType.FANOUT)) + .then((Exchange exchange) => exchange.publish("Hello", "")) + .then(expectAsync1((_) {})); }); test("bind queue to FANOUT exchange without a routing key", () { client - .channel() - .then((Channel channel) => channel.exchange("ex_test_2", ExchangeType.FANOUT)) - .then((Exchange exchange) => exchange.bindPrivateQueueConsumer([])) - .then(expectAsync1((Consumer consumer) { - })); - + .channel() + .then((Channel channel) => + channel.exchange("ex_test_2", ExchangeType.FANOUT)) + .then((Exchange exchange) => exchange.bindPrivateQueueConsumer([])) + .then(expectAsync1((Consumer consumer) {})); }); test("unbind queue from exchange", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("ex_test_2", ExchangeType.FANOUT)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("ex_test_2", ExchangeType.FANOUT)) + .then((Exchange exchange) { exchange.channel - .privateQueue() - .then((Queue privateQueue) => privateQueue.bind(exchange, "")) - .then((Queue boundQueue) => boundQueue.unbind(exchange, "")) - .then((Queue unboundQueue) { + .privateQueue() + .then((Queue privateQueue) => privateQueue.bind(exchange, "")) + .then((Queue boundQueue) => boundQueue.unbind(exchange, "")) + .then((Queue unboundQueue) { testCompleter.complete(); }); }); @@ -233,50 +240,71 @@ main({bool enableLogger : true}) { group("exceptions", () { test("missing exchange name", () { - return client - .channel() - .then((Channel channel) { - expect(() => channel.exchange(null, null), throwsA((ex) => ex is ArgumentError && ex.message == "The name of the exchange cannot be empty")); + return client.channel().then((Channel channel) { + expect( + () => channel.exchange(null, null), + throwsA((ex) => + ex is ArgumentError && + ex.message == "The name of the exchange cannot be empty")); }); }); test("missing exchange type", () { - return client - .channel() - .then((Channel channel) { - expect(() => channel.exchange("foo", null), throwsA((ex) => ex is ArgumentError && ex.message == "The type of the exchange needs to be specified")); + return client.channel().then((Channel channel) { + expect( + () => channel.exchange("foo", null), + throwsA((ex) => + ex is ArgumentError && + ex.message == + "The type of the exchange needs to be specified")); }); }); test("missing routing key for non-fanout exchange publish", () { return client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { - expect(() => exchange.publish("foo", null), throwsA((ex) => ex is ArgumentError && ex.message == "A valid routing key needs to be specified")); + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { + expect( + () => exchange.publish("foo", null), + throwsA((ex) => + ex is ArgumentError && + ex.message == "A valid routing key needs to be specified")); }); }); - test("missing private queue routing key for non-fanout exchange consumer", () { + test("missing private queue routing key for non-fanout exchange consumer", + () { return client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { - expect(() => exchange.bindPrivateQueueConsumer([]), throwsA((ex) => ex is ArgumentError && ex.message == "One or more routing keys needs to be specified for this exchange type")); + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { + expect( + () => exchange.bindPrivateQueueConsumer([]), + throwsA((ex) => + ex is ArgumentError && + ex.message == + "One or more routing keys needs to be specified for this exchange type")); }); }); test("bind to non-FANOUT exchange without specifying routing key", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { - exchange.channel - .privateQueue() - .then((Queue queue) { - expect(() => queue.bind(exchange, ""), throwsA((ex) => ex is ArgumentError && ex.message == "A routing key needs to be specified to bind to this exchange type")); + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { + exchange.channel.privateQueue().then((Queue queue) { + expect( + () => queue.bind(exchange, ""), + throwsA((ex) => + ex is ArgumentError && + ex.message == + "A routing key needs to be specified to bind to this exchange type")); testCompleter.complete(); }); }); @@ -284,18 +312,25 @@ main({bool enableLogger : true}) { return testCompleter.future; }); - test("unbind from non-FANOUT exchange without specifying routing key", () { - Completer testCompleter = new Completer(); + test("unbind from non-FANOUT exchange without specifying routing key", + () { + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { exchange.channel - .privateQueue() - .then((Queue queue) => queue.bind(exchange, "test")) - .then((Queue queue) { - expect(() => queue.unbind(exchange, ""), throwsA((ex) => ex is ArgumentError && ex.message == "A routing key needs to be specified to unbind from this exchange type")); + .privateQueue() + .then((Queue queue) => queue.bind(exchange, "test")) + .then((Queue queue) { + expect( + () => queue.unbind(exchange, ""), + throwsA((ex) => + ex is ArgumentError && + ex.message == + "A routing key needs to be specified to unbind from this exchange type")); testCompleter.complete(); }); }); @@ -304,16 +339,19 @@ main({bool enableLogger : true}) { }); test("bind queue to null exchange", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { - exchange.channel - .privateQueue() - .then((Queue queue) { - expect(() => queue.bind(null, ""), throwsA((ex) => ex is ArgumentError && ex.message == "Exchange cannot be null")); + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { + exchange.channel.privateQueue().then((Queue queue) { + expect( + () => queue.bind(null, ""), + throwsA((ex) => + ex is ArgumentError && + ex.message == "Exchange cannot be null")); testCompleter.complete(); }); }); @@ -322,17 +360,22 @@ main({bool enableLogger : true}) { }); test("unbind queue from null exchange", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.exchange("test", ExchangeType.DIRECT)) - .then((Exchange exchange) { + .channel() + .then((Channel channel) => + channel.exchange("test", ExchangeType.DIRECT)) + .then((Exchange exchange) { exchange.channel - .privateQueue() - .then((Queue queue) => queue.bind(exchange, "test")) - .then((Queue queue) { - expect(() => queue.unbind(null, ""), throwsA((ex) => ex is ArgumentError && ex.message == "Exchange cannot be null")); + .privateQueue() + .then((Queue queue) => queue.bind(exchange, "test")) + .then((Queue queue) { + expect( + () => queue.unbind(null, ""), + throwsA((ex) => + ex is ArgumentError && + ex.message == "Exchange cannot be null")); testCompleter.complete(); }); }); diff --git a/test/lib/mocks/mocks.dart b/test/lib/mocks/mocks.dart index 26528dc..3e8e12a 100644 --- a/test/lib/mocks/mocks.dart +++ b/test/lib/mocks/mocks.dart @@ -6,7 +6,7 @@ import "dart:async"; import "dart:convert"; import "package:logging/logging.dart"; -final Logger mockLogger = new Logger("MockLogger"); +final Logger mockLogger = Logger("MockLogger"); bool initializedLogger = false; void initLogger() { @@ -17,12 +17,12 @@ void initLogger() { hierarchicalLoggingEnabled = true; Logger.root.level = Level.ALL; Logger.root.onRecord.listen((LogRecord rec) { - print("[${rec.level.name}]\t[${rec.time}]\t[${rec.loggerName}]:\t${rec.message}"); + print( + "[${rec.level.name}]\t[${rec.time}]\t[${rec.loggerName}]:\t${rec.message}"); }); } class MockServer { - ServerSocket _server; List clients = []; List replayList = []; @@ -34,14 +34,16 @@ class MockServer { replayList = []; if (_server != null) { - mockLogger.info("Shutting down server [${_server.address}:${_server.port}]"); + mockLogger + .info("Shutting down server [${_server.address}:${_server.port}]"); List cleanupFutures = [] - ..addAll(clients.map((Socket client){ - client.destroy(); - return new Future.value(true); - })) - ..add(_server.close().then((_) => new Future.delayed(new Duration(milliseconds:20), () => true))); + ..addAll(clients.map((Socket client) { + client.destroy(); + return Future.value(true); + })) + ..add(_server.close().then( + (_) => Future.delayed(Duration(milliseconds: 20), () => true))); clients.clear(); _server = null; @@ -49,19 +51,20 @@ class MockServer { return Future.wait(cleanupFutures); } - return new Future.value(); + return Future.value(); } void disconnectClient(int clientIndex) { if (clients.length > clientIndex) { Socket client = clients.removeAt(clientIndex); - mockLogger.info("Disconnecting client [${client.remoteAddress.host}:${client.remotePort}]"); + mockLogger.info( + "Disconnecting client [${client.remoteAddress.host}:${client.remotePort}]"); client.destroy(); } } Future listen(String host, int port) { - Completer completer = new Completer(); + Completer completer = Completer(); mockLogger.info("Binding MockServer to $host:$port"); ServerSocket.bind(host, port).then((ServerSocket server) { @@ -72,24 +75,21 @@ class MockServer { }); return completer.future; - } void _handleConnection(Socket client) { clients.add(client); - mockLogger.info("Client [${client.remoteAddress.host}:${client.remotePort}] connected"); + mockLogger.info( + "Client [${client.remoteAddress.host}:${client.remotePort}] connected"); - client.listen( - (data) => _handleClientData(client, data) - , onError : (err, trace) => _handleClientError(client, err, trace) - ); + client.listen((data) => _handleClientData(client, data), + onError: (err, trace) => _handleClientError(client, err, trace)); } void _handleClientData(Socket client, dynamic data) { if (replayList != null && !replayList.isEmpty) { // Respond with the next payload in replay list - new Future.delayed(responseDelay) - .then((_) { + Future.delayed(responseDelay).then((_) { client ..add(replayList.removeAt(0)) ..flush(); @@ -98,13 +98,13 @@ class MockServer { } void _handleClientError(Socket client, err, trace) { - mockLogger.info("Client [${client.remoteAddress.host}:${client.remotePort}] error ${err.exception.message}"); + mockLogger.info( + "Client [${client.remoteAddress.host}:${client.remotePort}] error ${err.exception.message}"); mockLogger.info("${err.stackTrace}"); } } class _RotEncoder extends Converter { - final bool throwOnConvert; final int _key; @@ -112,10 +112,10 @@ class _RotEncoder extends Converter { Uint8List convert(Map input) { if (throwOnConvert) { - throw new Exception("Something has gone awfully wrong..."); + throw Exception("Something has gone awfully wrong..."); } String serializedMap = json.encode(input); - Uint8List result = new Uint8List(serializedMap.length); + Uint8List result = Uint8List(serializedMap.length); for (int i = 0; i < serializedMap.length; i++) { result[i] = (serializedMap.codeUnitAt(i) + _key) % 256; @@ -126,7 +126,6 @@ class _RotEncoder extends Converter { } class _RotDecoder extends Converter { - final bool throwOnConvert; final int _key; @@ -134,20 +133,19 @@ class _RotDecoder extends Converter { Map convert(Uint8List input) { if (throwOnConvert) { - throw new Exception("Something has gone awfully wrong..."); + throw Exception("Something has gone awfully wrong..."); } - Uint8List result = new Uint8List(input.length); + Uint8List result = Uint8List(input.length); for (int i = 0; i < input.length; i++) { result[i] = (input[i] + _key) % 256; } - return json.decode(new String.fromCharCodes(result)); + return json.decode(String.fromCharCodes(result)); } } class RotCodec extends Codec { - bool throwOnEncode; bool throwOnDecode; @@ -155,9 +153,9 @@ class RotCodec extends Codec { _RotEncoder _encoder; _RotDecoder _decoder; - RotCodec({this.throwOnEncode : false, this.throwOnDecode : false}) { - _encoder = new _RotEncoder(13, throwOnEncode); - _decoder = new _RotDecoder(-13, throwOnDecode); + RotCodec({this.throwOnEncode = false, this.throwOnDecode = false}) { + _encoder = _RotEncoder(13, throwOnEncode); + _decoder = _RotDecoder(-13, throwOnDecode); } Converter get encoder { @@ -167,5 +165,4 @@ class RotCodec extends Codec { Converter get decoder { return _decoder; } - } diff --git a/test/lib/queue_test.dart b/test/lib/queue_test.dart index 00ef5a1..544db92 100644 --- a/test/lib/queue_test.dart +++ b/test/lib/queue_test.dart @@ -12,7 +12,7 @@ import "package:dart_amqp/src/exceptions.dart"; import "mocks/mocks.dart" as mock; // This test expects a local running rabbitmq instance at the default port -main({bool enableLogger : true}) { +main({bool enableLogger = true}) { if (enableLogger) { mock.initLogger(); } @@ -21,7 +21,7 @@ main({bool enableLogger : true}) { Client client; setUp(() { - client = new Client(); + client = Client(); }); tearDown(() { @@ -30,21 +30,22 @@ main({bool enableLogger : true}) { test("check if unknown queue exists", () { client - .channel() - .then((Channel channel) => channel.queue("foo", passive : true)) - .then((_) => fail("Expected an exception to be thrown")) - .catchError(expectAsync1((e) { + .channel() + .then((Channel channel) => channel.queue("foo", passive: true)) + .then((_) => fail("Expected an exception to be thrown")) + .catchError(expectAsync1((e) { expect(e, const TypeMatcher()); - expect((e as QueueNotFoundException).errorType, equals(ErrorType.NOT_FOUND)); + expect((e as QueueNotFoundException).errorType, + equals(ErrorType.NOT_FOUND)); expect(e.toString(), startsWith("QueueNotFoundException: NOT_FOUND")); })); }); test("create private queue", () { client - .channel() - .then((Channel channel) => channel.privateQueue()) - .then(expectAsync1((Queue queue) { + .channel() + .then((Channel channel) => channel.privateQueue()) + .then(expectAsync1((Queue queue) { expect(queue.channel, const TypeMatcher()); expect(queue.name, isNotEmpty); expect(queue.consumerCount, equals(0)); @@ -54,9 +55,9 @@ main({bool enableLogger : true}) { test("create public queue", () { client - .channel() - .then((Channel channel) => channel.queue("test_1")) - .then(expectAsync1((Queue queue) { + .channel() + .then((Channel channel) => channel.queue("test_1")) + .then(expectAsync1((Queue queue) { expect(queue.channel, const TypeMatcher()); expect(queue.name, isNotEmpty); expect(queue.consumerCount, equals(0)); @@ -66,12 +67,13 @@ main({bool enableLogger : true}) { test("Check the existance of a created queue", () { client - .channel() - .then((Channel channel) => channel.privateQueue()) - .then(expectAsync1((Queue privateQueue) { + .channel() + .then((Channel channel) => channel.privateQueue()) + .then(expectAsync1((Queue privateQueue) { // Check existance - privateQueue.channel.queue(privateQueue.name, passive : true) - .then(expectAsync1((Queue queue) { + privateQueue.channel + .queue(privateQueue.name, passive: true) + .then(expectAsync1((Queue queue) { expect(queue.name, equals(privateQueue.name)); })); })); @@ -83,26 +85,22 @@ main({bool enableLogger : true}) { Client client2; setUp(() { - client = new Client(); - client2 = new Client(); + client = Client(); + client2 = Client(); }); tearDown(() { - return Future.wait( - [ - client.close(), - client2.close() - ]); + return Future.wait([client.close(), client2.close()]); }); test("queue message delivery", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_2")) - .then((Queue testQueue) => testQueue.consume()) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("test_2")) + .then((Queue testQueue) => testQueue.consume()) + .then((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); @@ -114,64 +112,66 @@ main({bool enableLogger : true}) { // Using second client publish a message to the queue client2 - .channel() - .then((Channel channel) => channel.queue(consumer.queue.name)) - .then((Queue target) => target.publish("Test payload")); + .channel() + .then((Channel channel) => channel.queue(consumer.queue.name)) + .then((Queue target) => target.publish("Test payload")); }); return testCompleter.future; }); test("queue JSON message delivery (auto-filled content type)", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_2")) - .then((Queue testQueue) => testQueue.consume()) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("test_2")) + .then((Queue testQueue) => testQueue.consume()) + .then((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); consumer.listen(expectAsync1((AmqpMessage message) { - expect(message.payloadAsJson, equals({"message" : "Test payload"})); + expect(message.payloadAsJson, equals({"message": "Test payload"})); expect(message.properties.contentType, equals("application/json")); testCompleter.complete(); })); // Using second client publish a message to the queue client2 - .channel() - .then((Channel channel) => channel.queue(consumer.queue.name)) - .then((Queue target) => target.publish({"message" : "Test payload"})); + .channel() + .then((Channel channel) => channel.queue(consumer.queue.name)) + .then( + (Queue target) => target.publish({"message": "Test payload"})); }); return testCompleter.future; }); - test("queue JSON message delivery (auto-filled content type in existing persistent message property set)", () { - Completer testCompleter = new Completer(); + test( + "queue JSON message delivery (auto-filled content type in existing persistent message property set)", + () { + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_2")) - .then((Queue testQueue) => testQueue.consume()) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("test_2")) + .then((Queue testQueue) => testQueue.consume()) + .then((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); // Use second accuracy - DateTime now = new DateTime.now(); - now = now.subtract(new Duration(milliseconds : now.millisecond, microseconds: now.microsecond)); + DateTime now = DateTime.now(); + now = now.subtract(Duration( + milliseconds: now.millisecond, microseconds: now.microsecond)); consumer.listen(expectAsync1((AmqpMessage message) { - expect(message.payloadAsJson, equals({"message" : "Test payload"})); + expect(message.payloadAsJson, equals({"message": "Test payload"})); expect(message.properties.contentType, equals("application/json")); - expect(message.properties.headers, equals({ - 'X-HEADER' : 'ok' - })); + expect(message.properties.headers, equals({'X-HEADER': 'ok'})); expect(message.properties.priority, equals(1)); expect(message.properties.corellationId, equals("123")); expect(message.properties.replyTo, equals("/dev/null")); @@ -186,37 +186,33 @@ main({bool enableLogger : true}) { // Using second client publish a message with full properties to the queue client2 - .channel() - .then((Channel channel) => channel.queue(consumer.queue.name)) - .then((Queue target) => target.publish( - {"message" : "Test payload"}, - properties : new MessageProperties.persistentMessage() - ..headers = { - 'X-HEADER' : 'ok' - } - ..priority = 1 - ..corellationId = "123" - ..replyTo = "/dev/null" - ..expiration = "60000" // 60 sec - ..messageId = "0xf00" - ..timestamp = now - ..type = "test" - ..userId = "guest" - ..appId = "unit-test" - )); + .channel() + .then((Channel channel) => channel.queue(consumer.queue.name)) + .then((Queue target) => target.publish({"message": "Test payload"}, + properties: MessageProperties.persistentMessage() + ..headers = {'X-HEADER': 'ok'} + ..priority = 1 + ..corellationId = "123" + ..replyTo = "/dev/null" + ..expiration = "60000" // 60 sec + ..messageId = "0xf00" + ..timestamp = now + ..type = "test" + ..userId = "guest" + ..appId = "unit-test")); }); return testCompleter.future; }); test("queue message delivery with ack", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_3")) - .then((Queue testQueue) => testQueue.consume(noAck : false)) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("test_3")) + .then((Queue testQueue) => testQueue.consume(noAck: false)) + .then((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); @@ -229,22 +225,23 @@ main({bool enableLogger : true}) { // Using second client publish a message to the queue (request ack) client2 - .channel() - .then((Channel channel) => channel.queue(consumer.queue.name)) - .then((Queue target) => target.publish("Test payload", mandatory : true)); + .channel() + .then((Channel channel) => channel.queue(consumer.queue.name)) + .then((Queue target) => + target.publish("Test payload", mandatory: true)); }); return testCompleter.future; }); test("reject delivered message", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_3")) - .then((Queue testQueue) => testQueue.consume(noAck : false)) - .then((Consumer consumer) { + .channel() + .then((Channel channel) => channel.queue("test_3")) + .then((Queue testQueue) => testQueue.consume(noAck: false)) + .then((Consumer consumer) { expect(consumer.channel, const TypeMatcher()); expect(consumer.queue, const TypeMatcher()); expect(consumer.tag, isNotEmpty); @@ -257,25 +254,25 @@ main({bool enableLogger : true}) { // Using second client publish a message to the queue (request ack) client2 - .channel() - .then((Channel channel) => channel.queue(consumer.queue.name)) - .then((Queue target) => target.publish("Test payload", mandatory : true)); + .channel() + .then((Channel channel) => channel.queue(consumer.queue.name)) + .then((Queue target) => + target.publish("Test payload", mandatory: true)); }); return testCompleter.future; }); test("queue cancel consumer", () { - Completer testCompleter = new Completer(); + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_3")) - .then((Queue testQueue) => testQueue.consume(noAck : false)) - .then((Consumer consumer) { - + .channel() + .then((Channel channel) => channel.queue("test_3")) + .then((Queue testQueue) => testQueue.consume(noAck: false)) + .then((Consumer consumer) { consumer.listen((AmqpMessage message) { fail("Received unexpected AMQP message"); - }, onDone : () { + }, onDone: () { testCompleter.complete(); }); @@ -288,25 +285,26 @@ main({bool enableLogger : true}) { test("delete queue", () { client - .channel() - .then((Channel channel) => channel.queue("test_3")) - .then((Queue testQueue) => testQueue.delete()) - .then(expectAsync1((Queue queue) { - - })); + .channel() + .then((Channel channel) => channel.queue("test_3")) + .then((Queue testQueue) => testQueue.delete()) + .then(expectAsync1((Queue queue) {})); }); - test("consuming with same consumer tag on same channel should return identical consumer", () { - Completer testCompleter = new Completer(); + test( + "consuming with same consumer tag on same channel should return identical consumer", + () { + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_3")) - .then((Queue testQueue) => testQueue.consume(consumerTag : "test_tag_1")) - .then((Consumer consumer1) { + .channel() + .then((Channel channel) => channel.queue("test_3")) + .then( + (Queue testQueue) => testQueue.consume(consumerTag: "test_tag_1")) + .then((Consumer consumer1) { consumer1.queue - .consume(consumerTag : "test_tag_1") - .then((Consumer consumer2) { + .consume(consumerTag: "test_tag_1") + .then((Consumer consumer2) { expect(true, identical(consumer1, consumer2)); testCompleter.complete(); }); @@ -317,64 +315,66 @@ main({bool enableLogger : true}) { test("purge a queue", () { return client - .channel() - .then((Channel channel) => channel.queue("test_4")) - .then((Queue queue) => queue.purge()); + .channel() + .then((Channel channel) => channel.queue("test_4")) + .then((Queue queue) => queue.purge()); }); group("exceptions:", () { test("unsupported message payload", () { - client - .channel() - .then((Channel channel) => channel.queue("test_99")) - .then((Queue queue) => queue.publish(new StreamController())) - .catchError(expectAsync1((ex) { + .channel() + .then((Channel channel) => channel.queue("test_99")) + .then((Queue queue) => queue.publish(StreamController())) + .catchError(expectAsync1((ex) { expect(ex, const TypeMatcher()); - expect(ex.message, equals("Message payload should be either a Map, an Iterable, a String or an UInt8List instance")); + expect( + ex.message, + equals( + "Message payload should be either a Map, an Iterable, a String or an UInt8List instance")); })); - }); - test("server closes channel after publishing message with invalid properties; next channel operation should fail", () { - + test( + "server closes channel after publishing message with invalid properties; next channel operation should fail", + () { client - .channel() - .then((Channel channel) => channel.queue("test_100")) - .then((Queue queue) { + .channel() + .then((Channel channel) => channel.queue("test_100")) + .then((Queue queue) { queue.publish("invalid properties test", - properties : new MessageProperties() - ..expiration = "undefined" - ); + properties: MessageProperties()..expiration = "undefined"); return queue.channel.queue("other_queue"); - }) - .catchError(expectAsync1((ex) { + }).catchError(expectAsync1((ex) { expect(ex, const TypeMatcher()); - expect(ex.toString(), equals("ChannelException(PRECONDITION_FAILED): PRECONDITION_FAILED - invalid expiration 'undefined': no_integer")); + expect( + ex.toString(), + equals( + "ChannelException(PRECONDITION_FAILED): PRECONDITION_FAILED - invalid expiration 'undefined': no_integer")); })); - }); - test("trying to publish to a channel closed by a prior invalid published message; next publish should fail", () { - Completer testCompleter = new Completer(); + test( + "trying to publish to a channel closed by a prior invalid published message; next publish should fail", + () { + Completer testCompleter = Completer(); client - .channel() - .then((Channel channel) => channel.queue("test_100")) - .then((Queue queue) { + .channel() + .then((Channel channel) => channel.queue("test_100")) + .then((Queue queue) { queue.publish("invalid properties test", - properties : new MessageProperties() - ..expiration = "undefined" - ); + properties: MessageProperties()..expiration = "undefined"); - new Future.delayed(const Duration(seconds: 1)) - .then((_) { + Future.delayed(const Duration(seconds: 1)).then((_) { queue.publish("test"); - }) - .catchError(expectAsync1((ex) { + }).catchError(expectAsync1((ex) { expect(ex, const TypeMatcher()); - expect(ex.toString(), equals("ChannelException(PRECONDITION_FAILED): PRECONDITION_FAILED - invalid expiration 'undefined': no_integer")); + expect( + ex.toString(), + equals( + "ChannelException(PRECONDITION_FAILED): PRECONDITION_FAILED - invalid expiration 'undefined': no_integer")); testCompleter.complete(); })); @@ -382,8 +382,6 @@ main({bool enableLogger : true}) { return testCompleter.future; }); - }); - }); } diff --git a/test/run_all.dart b/test/run_all.dart index dce075c..7bf2868 100644 --- a/test/run_all.dart +++ b/test/run_all.dart @@ -11,7 +11,6 @@ import "lib/exchange_test.dart" as exchanges; import "lib/client_test.dart" as client; void main(List args) { - // Check if we need to disable our loggers bool enableLogger = args.indexOf('--enable-logger') != -1; @@ -20,39 +19,39 @@ void main(List args) { //useCompactVMConfiguration(); // - if (runAll || (new RegExp("enums")).hasMatch(allArgs)) { - enums.main(enableLogger : enableLogger); + if (runAll || (RegExp("enums")).hasMatch(allArgs)) { + enums.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("encoder-decoder")).hasMatch(allArgs)) { - encode_decode.main(enableLogger : enableLogger); + if (runAll || (RegExp("encoder-decoder")).hasMatch(allArgs)) { + encode_decode.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("exception-handling")).hasMatch(allArgs)) { - exceptions.main(enableLogger : enableLogger); + if (runAll || (RegExp("exception-handling")).hasMatch(allArgs)) { + exceptions.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("amqp-decoder")).hasMatch(allArgs)) { - amqp_decoder.main(enableLogger : enableLogger); + if (runAll || (RegExp("amqp-decoder")).hasMatch(allArgs)) { + amqp_decoder.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("authentication")).hasMatch(allArgs)) { - auth.main(enableLogger : enableLogger); + if (runAll || (RegExp("authentication")).hasMatch(allArgs)) { + auth.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("channels")).hasMatch(allArgs)) { - channels.main(enableLogger : enableLogger); + if (runAll || (RegExp("channels")).hasMatch(allArgs)) { + channels.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("queues")).hasMatch(allArgs)) { - queues.main(enableLogger : enableLogger); + if (runAll || (RegExp("queues")).hasMatch(allArgs)) { + queues.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("exchanges")).hasMatch(allArgs)) { - exchanges.main(enableLogger : enableLogger); + if (runAll || (RegExp("exchanges")).hasMatch(allArgs)) { + exchanges.main(enableLogger: enableLogger); } - if (runAll || (new RegExp("client")).hasMatch(allArgs)) { - client.main(enableLogger : enableLogger); + if (runAll || (RegExp("client")).hasMatch(allArgs)) { + client.main(enableLogger: enableLogger); } } diff --git a/tool/generate_bindings.dart b/tool/generate_bindings.dart index 770e135..9137be5 100644 --- a/tool/generate_bindings.dart +++ b/tool/generate_bindings.dart @@ -4,10 +4,9 @@ import "package:xml/xml.dart" as xml; import "package:http/http.dart" as http; import "package:logging/logging.dart"; -final Logger logger = new Logger("tools"); +final Logger logger = Logger("tools"); class AmqpBindingsBuilder { - // The following list of messages will be excluded from // the generated bindings List excludedMessages = const [ @@ -17,12 +16,12 @@ class AmqpBindingsBuilder { "BasicRecoverAsync" ]; - StringBuffer generatedMessageFactoryFile = new StringBuffer(""" + StringBuffer generatedMessageFactoryFile = StringBuffer(""" // The file contains the base class for AMQP method messages // and a factory constructor for unserializing AMQP messages // from incoming frames // -// File was auto-generated by generate_bindings.dart at ${new DateTime.now()} +// File was auto-generated by generate_bindings.dart at ${DateTime.now()} // // Do not modify @@ -45,7 +44,7 @@ abstract class Message { switch( msgClassId ){ """); - StringBuffer generatedMessageFactoryFooter = new StringBuffer(r""" + StringBuffer generatedMessageFactoryFooter = StringBuffer(r""" } // Message decoding failed; unknown message @@ -54,10 +53,10 @@ abstract class Message { } """); - StringBuffer generatedLibraryFile = new StringBuffer(""" + StringBuffer generatedLibraryFile = StringBuffer(""" // The file contains AMQP binding imports // -// File was auto-generated by generate_bindings.dart at ${new DateTime.now()} +// File was auto-generated by generate_bindings.dart at ${DateTime.now()} // // Do not modify @@ -107,44 +106,39 @@ part "protocol/io/amqp_message_decoder.dart"; """); Map _amqpTypeToDartType = { - "bit" : "bool", - "octet" : "int", - "short" : "int", - "long" : "int", - "longlong" : "int", - "shortstr" : "String", - "longstr" : "String", - "timestamp" : "DateTime", - "table" : "Map" - }; - Map _amqpCustomTypeToBasicType = { + "bit": "bool", + "octet": "int", + "short": "int", + "long": "int", + "longlong": "int", + "shortstr": "String", + "longstr": "String", + "timestamp": "DateTime", + "table": "Map" }; + Map _amqpCustomTypeToBasicType = {}; Future _retrieveSchema(String schemaUrl) { logger.info("- Retrieving schema from ${schemaUrl}"); // Check for cached copy - File cachedCopy = new File(schemaUrl.split('/').last); - return cachedCopy.exists() - .then((bool exists) { - return exists - ? cachedCopy.readAsString() - : http.read(schemaUrl); - }) - .then((String data) { + File cachedCopy = File(schemaUrl.split('/').last); + return cachedCopy.exists().then((bool exists) { + return exists ? cachedCopy.readAsString() : http.read(schemaUrl); + }).then((String data) { logger.info("- Parsing schema"); return xml.parse(data); }); } - String _parseMethod(String className, int classId, xml.XmlElement amqpMethod) { + String _parseMethod( + String className, int classId, xml.XmlElement amqpMethod) { // Convert dashed field name to class case String methodName = amqpMethod - .getAttribute("name") - .replaceAllMapped(new RegExp(r"^([a-z])"), (Match m) { + .getAttribute("name") + .replaceAllMapped(RegExp(r"^([a-z])"), (Match m) { return m.group(1).toUpperCase(); - }) - .replaceAllMapped(new RegExp(r"-([a-z])"), (Match m) { + }).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) { return m.group(1).toUpperCase(); }); @@ -153,15 +147,15 @@ part "protocol/io/amqp_message_decoder.dart"; bool hasContent = hasContentAttr != null && hasContentAttr == "1"; // Extract clmethod id - int methodId = int.parse(amqpMethod.getAttribute("index"), radix : 10); + int methodId = int.parse(amqpMethod.getAttribute("index"), radix: 10); bool implementedByClient = amqpMethod - .findAllElements("chassis") - .any((xml.XmlElement elem) => elem.getAttribute("name") == "client"); + .findAllElements("chassis") + .any((xml.XmlElement elem) => elem.getAttribute("name") == "client"); bool implementedByServer = amqpMethod - .findAllElements("chassis") - .any((xml.XmlElement elem) => elem.getAttribute("name") == "server"); + .findAllElements("chassis") + .any((xml.XmlElement elem) => elem.getAttribute("name") == "server"); // Update message factory if (implementedByClient) { @@ -174,7 +168,7 @@ part "protocol/io/amqp_message_decoder.dart"; logger.fine(" Method: ${methodName} (id: ${methodId})"); // Generate class - StringBuffer generatedClass = new StringBuffer(""" + StringBuffer generatedClass = StringBuffer(""" class ${className}${methodName} implements Message { final bool msgHasContent = ${hasContent}; final int msgClassId = ${classId}; @@ -182,25 +176,28 @@ class ${className}${methodName} implements Message { // Message arguments """); - StringBuffer serializerMethod = new StringBuffer(""" + StringBuffer serializerMethod = StringBuffer(""" void serialize( TypeEncoder encoder ) { encoder ..writeUInt16(msgClassId) ..writeUInt16(msgMethodId) """); - StringBuffer ctors = new StringBuffer((implementedByServer || !implementedByClient) ? """ + StringBuffer ctors = + StringBuffer((implementedByServer || !implementedByClient) + ? """ ${className}${methodName}(); -""" : ""); +""" + : ""); if (implementedByClient) { ctors.write(""" ${className}${methodName}.fromStream( TypeDecoder decoder ){ """); } - StringBuffer toStringMethod = new StringBuffer(""" + StringBuffer toStringMethod = StringBuffer(""" String toString(){ return \"\"\" ${className}.${methodName} -${new String.fromCharCodes(new List.filled(className.length + methodName.length + 1, "-".codeUnitAt(0)))} +${String.fromCharCodes(List.filled(className.length + methodName.length + 1, "-".codeUnitAt(0)))} """); bool emittingBits = false; @@ -208,19 +205,18 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le int bitOffset = 0; // Parse fields - amqpMethod - .descendants - .where((xml.XmlNode node) => node is xml.XmlElement && node.name.local == "field") - .forEach((xml.XmlNode node) { + amqpMethod.descendants + .where((xml.XmlNode node) => + node is xml.XmlElement && node.name.local == "field") + .forEach((xml.XmlNode node) { xml.XmlElement amqpMethodField = node as xml.XmlElement; // Convert dashed field name to camelCase String fieldName = amqpMethodField - .getAttribute("name") - .replaceAllMapped(new RegExp(r"-([a-z])"), (Match m) { + .getAttribute("name") + .replaceAllMapped(RegExp(r"-([a-z])"), (Match m) { return m.group(1).toUpperCase(); - }) - .replaceAll("-", "_"); + }).replaceAll("-", "_"); // Retrieve Dart type for field domain String fieldDomain = amqpMethodField.getAttribute("domain"); @@ -228,9 +224,9 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le fieldDomain = amqpMethodField.getAttribute("type"); } String amqpType = _amqpCustomTypeToBasicType.containsKey(fieldDomain) - ? _amqpCustomTypeToBasicType[ fieldDomain ] - : fieldDomain; - String dartType = _amqpTypeToDartType[ amqpType ]; + ? _amqpCustomTypeToBasicType[fieldDomain] + : fieldDomain; + String dartType = _amqpTypeToDartType[amqpType]; logger.fine(" Field: ${fieldName} (=> ${dartType})"); @@ -266,7 +262,8 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le encoderFunc = "writeFieldTable"; break; default: - throw new ArgumentError("Not sure how to encode amqp type ${amqpType} for field ${fieldName} (field domain: ${fieldDomain})"); + throw ArgumentError( + "Not sure how to encode amqp type ${amqpType} for field ${fieldName} (field domain: ${fieldDomain})"); } if (amqpType == "bit") { @@ -291,7 +288,8 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le // Unserialize field value from read _bitmask bitOffset = 0; if (implementedByClient) { - ctors.write(" ${fieldName} = _bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n"); + ctors.write( + " ${fieldName} = _bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n"); } bitOffset++; } else { @@ -299,7 +297,8 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le // Unserialize field value from read _bitmask if (implementedByClient) { - ctors.write(" ${fieldName} = _bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n"); + ctors.write( + " ${fieldName} = _bitmask & 0x${(1 << bitOffset).toRadixString(16)} != 0;\n"); } bitOffset++; } @@ -312,12 +311,14 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le serializerMethod.write(" ..${encoderFunc}(${fieldName})\n"); if (implementedByClient) { - ctors.write(" ${fieldName} = decoder.${encoderFunc.replaceAll("write", "read")}(${amqpType == "table" ? '"${fieldName}"' : ""});\n"); + ctors.write( + " ${fieldName} = decoder.${encoderFunc.replaceAll("write", "read")}(${amqpType == "table" ? '"${fieldName}"' : ""});\n"); } } // Emit to string part - toStringMethod.write("${fieldName} : \${${amqpType == "table" ? "indentingJsonEncoder.convert($fieldName)" : fieldName}}\n"); + toStringMethod.write( + "${fieldName} : \${${amqpType == "table" ? "indentingJsonEncoder.convert($fieldName)" : fieldName}}\n"); }); // If was emitting bits, flush the block @@ -334,31 +335,22 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le } // End casacade - serializerMethod - ..write(" ;\n") - ..write(" }\n"); + serializerMethod..write(" ;\n")..write(" }\n"); - generatedClass - ..write("\n") - ..write(ctors); + generatedClass..write("\n")..write(ctors); if (implementedByServer || !implementedByClient) { - generatedClass - ..write("\n") - ..write(serializerMethod); + generatedClass..write("\n")..write(serializerMethod); } else { // Write an empty serializer stub to avoid warnings - generatedClass - ..write("\n\n") - ..write(""" + generatedClass..write("\n\n")..write(""" void serialize( TypeEncoder encoder ) { } """); } // ..write("\n") // ..write(toStringMethod) - generatedClass - ..write("}\n"); + generatedClass..write("}\n"); return generatedClass.toString(); } @@ -366,16 +358,15 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le void _parseClass(xml.XmlElement amqpClass) { // Convert dashed field name to class case String className = amqpClass - .getAttribute("name") - .replaceAllMapped(new RegExp(r"^([a-z])"), (Match m) { + .getAttribute("name") + .replaceAllMapped(RegExp(r"^([a-z])"), (Match m) { return m.group(1).toUpperCase(); - }) - .replaceAllMapped(new RegExp(r"-([a-z])"), (Match m) { + }).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) { return m.group(1).toUpperCase(); }); // Extract class id - int classId = int.parse(amqpClass.getAttribute("index"), radix : 10); + int classId = int.parse(amqpClass.getAttribute("index"), radix: 10); logger.fine(" Class: ${className} (id: ${classId})"); @@ -386,10 +377,10 @@ ${new String.fromCharCodes(new List.filled(className.length + methodName.le """); // Begin generation of method classes for this message class - StringBuffer generatedMethodsFile = new StringBuffer(""" + StringBuffer generatedMethodsFile = StringBuffer(""" // The file contains all method messages for AMQP class ${className} (id: ${classId}) // -// File was auto-generated by generate_bindings.dart at ${new DateTime.now()} +// File was auto-generated by generate_bindings.dart at ${DateTime.now()} // // Do not modify @@ -397,26 +388,24 @@ part of dart_amqp.protocol; """); // Fetch methods - amqpClass - .descendants - .where((xml.XmlNode node) => node is xml.XmlElement && node.name.local == "method") - .where((xml.XmlNode elemNode) { + amqpClass.descendants + .where((xml.XmlNode node) => + node is xml.XmlElement && node.name.local == "method") + .where((xml.XmlNode elemNode) { xml.XmlElement node = elemNode as xml.XmlElement; // Apply method exclusion list String methodName = node - .getAttribute("name") - .replaceAllMapped(new RegExp(r"^([a-z])"), (Match m) { + .getAttribute("name") + .replaceAllMapped(RegExp(r"^([a-z])"), (Match m) { return m.group(1).toUpperCase(); - }) - .replaceAllMapped(new RegExp(r"-([a-z])"), (Match m) { + }).replaceAllMapped(RegExp(r"-([a-z])"), (Match m) { return m.group(1).toUpperCase(); }); String fullClassName = "${className}${methodName}"; return !excludedMessages.contains(fullClassName); - }) - .forEach((xml.XmlNode elemNode) { + }).forEach((xml.XmlNode elemNode) { xml.XmlElement node = elemNode as xml.XmlElement; generatedMethodsFile @@ -427,7 +416,8 @@ part of dart_amqp.protocol; //logger.fine(generatedFile.toString()); // Write method class file file - File methodFile = new File("../lib/src/protocol/messages/bindings/${className.toLowerCase()}.dart"); + File methodFile = File( + "../lib/src/protocol/messages/bindings/${className.toLowerCase()}.dart"); methodFile.writeAsStringSync(generatedMethodsFile.toString()); // Update message factory @@ -443,50 +433,52 @@ part of dart_amqp.protocol; String type = amqpDomain.getAttribute("type"); // Already there - if (_amqpTypeToDartType.containsKey(name) || _amqpCustomTypeToBasicType.containsKey(name)) { + if (_amqpTypeToDartType.containsKey(name) || + _amqpCustomTypeToBasicType.containsKey(name)) { return; } // We can map the domain type to an existing amqp type if (_amqpTypeToDartType.containsKey(type)) { - _amqpCustomTypeToBasicType[ name ] = type; + _amqpCustomTypeToBasicType[name] = type; return; } - throw new Exception("Could not map domain ${name} of type ${type} to a known Dart type"); + throw Exception( + "Could not map domain ${name} of type ${type} to a known Dart type"); } void _parseSchema(xml.XmlDocument schema) { logger.info("- Processing custom domains"); - schema - .descendants - .where((xml.XmlNode node) => node is xml.XmlElement && node.name.local == "domain") - .forEach(_parseDomain); + schema.descendants + .where((xml.XmlNode node) => + node is xml.XmlElement && node.name.local == "domain") + .forEach(_parseDomain); logger.info("- Processing amqp classes"); - schema - .descendants - .where((xml.XmlNode node) => node is xml.XmlElement && node.name.local == "class") - .forEach((xml.XmlNode elemNode) { + schema.descendants + .where((xml.XmlNode node) => + node is xml.XmlElement && node.name.local == "class") + .forEach((xml.XmlNode elemNode) { xml.XmlElement amqpClassElement = elemNode as xml.XmlElement; String className = amqpClassElement.getAttribute("name").toLowerCase(); - generatedLibraryFile.write("part \"protocol/messages/bindings/${className}.dart\";\n"); + generatedLibraryFile + .write("part \"protocol/messages/bindings/${className}.dart\";\n"); _parseClass(amqpClassElement); }); // Write output files - File libFile = new File("../lib/src/protocol.dart"); + File libFile = File("../lib/src/protocol.dart"); libFile.writeAsStringSync(generatedLibraryFile.toString()); - File messageFile = new File("../lib/src/protocol/messages/message.dart"); + File messageFile = File("../lib/src/protocol/messages/message.dart"); generatedMessageFactoryFile.write(generatedMessageFactoryFooter); messageFile.writeAsStringSync(generatedMessageFactoryFile.toString()); } void build(String schemaUrl) { - _retrieveSchema(schemaUrl) - .then(_parseSchema); + _retrieveSchema(schemaUrl).then(_parseSchema); } } @@ -498,6 +490,6 @@ main() { logger.info("Building amqp bindings"); - new AmqpBindingsBuilder() + AmqpBindingsBuilder() ..build("https://www.rabbitmq.com/resources/specs/amqp0-9-1.xml"); }