diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..430a85e --- /dev/null +++ b/.github/dependabot.yml
@@ -0,0 +1,11 @@ +# Set update schedule for GitHub Actions +# See https://docs.github.com/en/free-pro-team@latest/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot + +version: 2 +updates: + +- package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every weekday + interval: "daily"
diff --git a/.github/workflows/test-package.yml b/.github/workflows/test-package.yml new file mode 100644 index 0000000..e20942d --- /dev/null +++ b/.github/workflows/test-package.yml
@@ -0,0 +1,86 @@ +name: Dart CI + +on: + # Run on PRs and pushes to the default branch. + push: + branches: [ master ] + pull_request: + branches: [ master ] + schedule: + - cron: "0 0 * * 0" + +env: + PUB_ENVIRONMENT: bot.github + +jobs: + # Check code formatting and static analysis on a single OS (linux) + # against Dart dev. + analyze: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sdk: [dev] + steps: + - uses: actions/checkout@v3 + - uses: dart-lang/setup-dart@v1 + with: + sdk: ${{ matrix.sdk }} + - id: install + name: Install dependencies + run: dart pub get + - name: Check formatting + run: dart format --output=none --set-exit-if-changed . + if: always() && steps.install.outcome == 'success' + - name: Analyze code + run: dart analyze --fatal-infos + if: always() && steps.install.outcome == 'success' + + # Run tests on a matrix consisting of two dimensions: + # 1. OS: ubuntu-latest, (macos-latest, windows-latest) + # 2. release channel: dev + test: + needs: analyze + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # Add macos-latest and/or windows-latest if relevant for this package. + os: [ubuntu-latest] + sdk: [dev] + steps: + - uses: actions/checkout@v3 + - uses: dart-lang/setup-dart@v1 + with: + sdk: ${{ matrix.sdk }} + - id: install + name: Install dependencies + run: dart pub get + - name: Run VM tests + run: dart test --platform vm + if: always() && steps.install.outcome == 'success' + + # Run tests on a matrix consisting of two dimensions: + # 1. OS: ubuntu-latest, (macos-latest, windows-latest) + # 2. release channel: 2.8.4 + test-legacy-sdk: + needs: analyze + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # Add macos-latest and/or windows-latest if relevant for this package. + os: [ubuntu-latest] + sdk: [2.8.4] + steps: + - uses: actions/checkout@v3 + - uses: dart-lang/setup-dart@v1 + with: + sdk: ${{ matrix.sdk }} + - id: install + name: Install dependencies + run: pub get + - name: Run VM tests + run: pub run test --platform vm + if: always() && steps.install.outcome == 'success' +
diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 416dd71..0000000 --- a/.travis.yml +++ /dev/null
@@ -1,29 +0,0 @@ -language: dart -sudo: true - -before_script: - # Add an IPv6 config - see the corresponding Travis issue - # https://github.com/travis-ci/travis-ci/issues/8361 - - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then - sudo sh -c 'echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6'; - fi - -dart: - - 2.2.0 - - dev - -dart_task: - - test - -matrix: - include: - - dart: dev - dart_task: dartfmt - -# Only building master means that we don't run two builds for each pull request. -branches: - only: [master] - -cache: - directories: - - $HOME/.pub-cache
diff --git a/LICENSE b/LICENSE index 389ce98..aa86769 100644 --- a/LICENSE +++ b/LICENSE
@@ -1,4 +1,5 @@ -Copyright 2017, the Dart project authors. All rights reserved. +Copyright 2017, the Dart project authors. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -9,7 +10,7 @@ copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
diff --git a/README.md b/README.md index 55ad5fe..5808dd8 100644 --- a/README.md +++ b/README.md
@@ -1,6 +1,6 @@ # http_io -[![Build Status](https://travis-ci.org/dart-lang/http_io.svg?branch=master)](https://travis-ci.org/dart-lang/http_io) +[![Build Status](https://github.com/dart-lang/http_io/workflows/Dart%20CI/badge.svg)](https://github.com/dart-lang/http_io/actions?query=workflow%3A"Dart+CI"+branch%3Amaster) The HTTP APIs in `dart:io` are pure Dart code not relying on native runtime calls. To enable faster development and bug fixes, these APIs are moving out of
diff --git a/analysis_options.yaml b/analysis_options.yaml index a705446..c04c80e 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml
@@ -1,50 +1,37 @@ -analyzer: - errors: - unused_import: error - unused_local_variable: error - dead_code: error - override_on_non_overriding_method: error +include: package:pedantic/analysis_options.1.8.0.yaml + linter: rules: - # Errors - avoid_empty_else + - avoid_init_to_null + - avoid_returning_null + - avoid_unused_constructor_parameters - await_only_futures + - camel_case_types - comment_references - control_flow_in_finally + - directives_ordering + - empty_constructor_bodies - empty_statements - hash_and_equals - iterable_contains_unrelated_type - - no_duplicate_case_values - - test_types_in_equals - - throw_in_finally - - unawaited_futures - - unnecessary_statements - - unrelated_type_equality_checks - - valid_regexps - - # Style - #- annotate_overrides - #- avoid_function_literals_in_foreach_calls - - avoid_init_to_null - #- avoid_return_types_on_setters - - avoid_returning_null - - avoid_unused_constructor_parameters - - camel_case_types - - directives_ordering - #- empty_catches - - empty_constructor_bodies - library_names - library_prefixes - #- non_constant_identifier_names + - no_duplicate_case_values - prefer_conditional_assignment - prefer_final_fields + - prefer_generic_function_type_aliases - prefer_is_empty - prefer_is_not_empty - prefer_typing_uninitialized_variables - recursive_getters - #- slash_for_doc_comments + - test_types_in_equals + - throw_in_finally - type_init_formals + - unawaited_futures - unnecessary_brace_in_string_interps - unnecessary_getters_setters - #- unnecessary_lambdas - unnecessary_null_aware_assignments + - unnecessary_statements + - unrelated_type_equality_checks + - valid_regexps
diff --git a/lib/http_io.dart b/lib/http_io.dart index 5b96f19..bb8dade 100644 --- a/lib/http_io.dart +++ b/lib/http_io.dart
@@ -49,353 +49,315 @@ part 'src/http_impl.dart'; part 'src/http_overrides.dart'; -/** - * A server that delivers content, such as web pages, using the HTTP protocol. - * - * The HttpServer is a [Stream] that provides [HttpRequest] objects. Each - * HttpRequest has an associated [HttpResponse] object. - * The server responds to a request by writing to that HttpResponse object. - * The following example shows how to bind an HttpServer to an IPv6 - * [InternetAddress] on port 80 (the standard port for HTTP servers) - * and how to listen for requests. - * Port 80 is the default HTTP port. However, on most systems accessing - * this requires super-user privileges. For local testing consider - * using a non-reserved port (1024 and above). - * - * import 'dart:io'; - * - * main() { - * HttpServer - * .bind(InternetAddress.anyIPv6, 80) - * .then((server) { - * server.listen((HttpRequest request) { - * request.response.write('Hello, world!'); - * request.response.close(); - * }); - * }); - * } - * - * Incomplete requests, in which all or part of the header is missing, are - * ignored, and no exceptions or HttpRequest objects are generated for them. - * Likewise, when writing to an HttpResponse, any [Socket] exceptions are - * ignored and any future writes are ignored. - * - * The HttpRequest exposes the request headers and provides the request body, - * if it exists, as a Stream of data. If the body is unread, it is drained - * when the server writes to the HttpResponse or closes it. - * - * ## Bind with a secure HTTPS connection - * - * Use [bindSecure] to create an HTTPS server. - * - * The server presents a certificate to the client. The certificate - * chain and the private key are set in the [SecurityContext] - * object that is passed to [bindSecure]. - * - * import 'dart:io'; - * import "dart:isolate"; - * - * main() { - * SecurityContext context = new SecurityContext(); - * var chain = - * Platform.script.resolve('certificates/server_chain.pem') - * .toFilePath(); - * var key = - * Platform.script.resolve('certificates/server_key.pem') - * .toFilePath(); - * context.useCertificateChain(chain); - * context.usePrivateKey(key, password: 'dartdart'); - * - * HttpServer - * .bindSecure(InternetAddress.anyIPv6, - * 443, - * context) - * .then((server) { - * server.listen((HttpRequest request) { - * request.response.write('Hello, world!'); - * request.response.close(); - * }); - * }); - * } - * - * The certificates and keys are PEM files, which can be created and - * managed with the tools in OpenSSL. - * - * ## Connect to a server socket - * - * You can use the [HttpServer.listenOn] constructor to attach an HTTP server to - * a [ServerSocket]. - * - * import 'dart:io'; - * - * main() { - * ServerSocket.bind(InternetAddress.anyIPv6, 80) - * .then((serverSocket) { - * HttpServer httpserver = new HttpServer.listenOn(serverSocket); - * serverSocket.listen((Socket socket) { - * socket.write('Hello, client.'); - * }); - * }); - * } - * - * ## Other resources - * - * * HttpServer is a Stream. Refer to the [Stream] class for information - * about the streaming qualities of an HttpServer. - * Pausing the subscription of the stream, pauses at the OS level. - * - * * The [shelf](https://pub.dartlang.org/packages/shelf) - * package on pub.dartlang.org contains a set of high-level classes that, - * together with this class, makes it easy to provide content through HTTP - * servers. - */ +/// A server that delivers content, such as web pages, using the HTTP protocol. +/// +/// The HttpServer is a [Stream] that provides [HttpRequest] objects. Each +/// HttpRequest has an associated [HttpResponse] object. +/// The server responds to a request by writing to that HttpResponse object. +/// The following example shows how to bind an HttpServer to an IPv6 +/// [InternetAddress] on port 80 (the standard port for HTTP servers) +/// and how to listen for requests. +/// Port 80 is the default HTTP port. However, on most systems accessing +/// this requires super-user privileges. For local testing consider +/// using a non-reserved port (1024 and above). +/// +/// import 'dart:io'; +/// +/// main() { +/// HttpServer +/// .bind(InternetAddress.anyIPv6, 80) +/// .then((server) { +/// server.listen((HttpRequest request) { +/// request.response.write('Hello, world!'); +/// request.response.close(); +/// }); +/// }); +/// } +/// +/// Incomplete requests, in which all or part of the header is missing, are +/// ignored, and no exceptions or HttpRequest objects are generated for them. +/// Likewise, when writing to an HttpResponse, any [Socket] exceptions are +/// ignored and any future writes are ignored. +/// +/// The HttpRequest exposes the request headers and provides the request body, +/// if it exists, as a Stream of data. If the body is unread, it is drained +/// when the server writes to the HttpResponse or closes it. +/// +/// ## Bind with a secure HTTPS connection +/// +/// Use [bindSecure] to create an HTTPS server. +/// +/// The server presents a certificate to the client. The certificate +/// chain and the private key are set in the [SecurityContext] +/// object that is passed to [bindSecure]. +/// +/// import 'dart:io'; +/// import "dart:isolate"; +/// +/// main() { +/// SecurityContext context = new SecurityContext(); +/// var chain = +/// Platform.script.resolve('certificates/server_chain.pem') +/// .toFilePath(); +/// var key = +/// Platform.script.resolve('certificates/server_key.pem') +/// .toFilePath(); +/// context.useCertificateChain(chain); +/// context.usePrivateKey(key, password: 'dartdart'); +/// +/// HttpServer +/// .bindSecure(InternetAddress.anyIPv6, +/// 443, +/// context) +/// .then((server) { +/// server.listen((HttpRequest request) { +/// request.response.write('Hello, world!'); +/// request.response.close(); +/// }); +/// }); +/// } +/// +/// The certificates and keys are PEM files, which can be created and +/// managed with the tools in OpenSSL. +/// +/// ## Connect to a server socket +/// +/// You can use the [HttpServer.listenOn] constructor to attach an HTTP server to +/// a [ServerSocket]. +/// +/// import 'dart:io'; +/// +/// main() { +/// ServerSocket.bind(InternetAddress.anyIPv6, 80) +/// .then((serverSocket) { +/// HttpServer httpserver = new HttpServer.listenOn(serverSocket); +/// serverSocket.listen((Socket socket) { +/// socket.write('Hello, client.'); +/// }); +/// }); +/// } +/// +/// ## Other resources +/// +/// * HttpServer is a Stream. Refer to the [Stream] class for information +/// about the streaming qualities of an HttpServer. +/// Pausing the subscription of the stream, pauses at the OS level. +/// +/// * The [shelf](https://pub.dartlang.org/packages/shelf) +/// package on pub.dartlang.org contains a set of high-level classes that, +/// together with this class, makes it easy to provide content through HTTP +/// servers. abstract class HttpServer implements Stream<HttpRequest> { - /** - * Gets and sets the default value of the `Server` header for all responses - * generated by this [HttpServer]. - * - * If [serverHeader] is `null`, no `Server` header will be added to each - * response. - * - * The default value is `null`. - */ + /// Gets and sets the default value of the `Server` header for all responses + /// generated by this [HttpServer]. + /// + /// If [serverHeader] is `null`, no `Server` header will be added to each + /// response. + /// + /// The default value is `null`. String serverHeader; - /** - * Default set of headers added to all response objects. - * - * By default the following headers are in this set: - * - * Content-Type: text/plain; charset=utf-8 - * X-Frame-Options: SAMEORIGIN - * X-Content-Type-Options: nosniff - * X-XSS-Protection: 1; mode=block - * - * If the `Server` header is added here and the `serverHeader` is set as - * well then the value of `serverHeader` takes precedence. - */ + /// Default set of headers added to all response objects. + /// + /// By default the following headers are in this set: + /// + /// Content-Type: text/plain; charset=utf-8 + /// X-Frame-Options: SAMEORIGIN + /// X-Content-Type-Options: nosniff + /// X-XSS-Protection: 1; mode=block + /// + /// If the `Server` header is added here and the `serverHeader` is set as + /// well then the value of `serverHeader` takes precedence. HttpHeaders get defaultResponseHeaders; - /** - * Whether the [HttpServer] should compress the content, if possible. - * - * The content can only be compressed when the response is using - * chunked Transfer-Encoding and the incoming request has `gzip` - * as an accepted encoding in the Accept-Encoding header. - * - * The default value is `false` (compression disabled). - * To enable, set `autoCompress` to `true`. - */ + /// Whether the [HttpServer] should compress the content, if possible. + /// + /// The content can only be compressed when the response is using + /// chunked Transfer-Encoding and the incoming request has `gzip` + /// as an accepted encoding in the Accept-Encoding header. + /// + /// The default value is `false` (compression disabled). + /// To enable, set `autoCompress` to `true`. bool autoCompress; - /** - * Gets or sets the timeout used for idle keep-alive connections. If no - * further request is seen within [idleTimeout] after the previous request was - * completed, the connection is dropped. - * - * Default is 120 seconds. - * - * Note that it may take up to `2 * idleTimeout` before a idle connection is - * aborted. - * - * To disable, set [idleTimeout] to `null`. - */ + /// Gets or sets the timeout used for idle keep-alive connections. If no + /// further request is seen within [idleTimeout] after the previous request was + /// completed, the connection is dropped. + /// + /// Default is 120 seconds. + /// + /// Note that it may take up to `2 * idleTimeout` before a idle connection is + /// aborted. + /// + /// To disable, set [idleTimeout] to `null`. Duration idleTimeout; - /** - * Starts listening for HTTP requests on the specified [address] and - * [port]. - * - * The [address] can either be a [String] or an - * [InternetAddress]. If [address] is a [String], [bind] will - * perform a [InternetAddress.lookup] and use the first value in the - * list. To listen on the loopback adapter, which will allow only - * incoming connections from the local host, use the value - * [InternetAddress.loopbackIPv4] or - * [InternetAddress.loopbackIPv6]. To allow for incoming - * connection from the network use either one of the values - * [InternetAddress.anyIPv4] or [InternetAddress.anyIPv6] to - * bind to all interfaces or the IP address of a specific interface. - * - * If an IP version 6 (IPv6) address is used, both IP version 6 - * (IPv6) and version 4 (IPv4) connections will be accepted. To - * restrict this to version 6 (IPv6) only, use [v6Only] to set - * version 6 only. However, if the address is - * [InternetAddress.loopbackIPv6], only IP version 6 (IPv6) connections - * will be accepted. - * - * If [port] has the value [:0:] an ephemeral port will be chosen by - * the system. The actual port used can be retrieved using the - * [port] getter. - * - * The optional argument [backlog] can be used to specify the listen - * backlog for the underlying OS listen setup. If [backlog] has the - * value of [:0:] (the default) a reasonable value will be chosen by - * the system. - * - * The optional argument [shared] specifies whether additional HttpServer - * objects can bind to the same combination of `address`, `port` and `v6Only`. - * If `shared` is `true` and more `HttpServer`s from this isolate or other - * isolates are bound to the port, then the incoming connections will be - * distributed among all the bound `HttpServer`s. Connections can be - * distributed over multiple isolates this way. - */ + /// Starts listening for HTTP requests on the specified [address] and + /// [port]. + /// + /// The [address] can either be a [String] or an + /// [InternetAddress]. If [address] is a [String], [bind] will + /// perform a [InternetAddress.lookup] and use the first value in the + /// list. To listen on the loopback adapter, which will allow only + /// incoming connections from the local host, use the value + /// [InternetAddress.loopbackIPv4] or + /// [InternetAddress.loopbackIPv6]. To allow for incoming + /// connection from the network use either one of the values + /// [InternetAddress.anyIPv4] or [InternetAddress.anyIPv6] to + /// bind to all interfaces or the IP address of a specific interface. + /// + /// If an IP version 6 (IPv6) address is used, both IP version 6 + /// (IPv6) and version 4 (IPv4) connections will be accepted. To + /// restrict this to version 6 (IPv6) only, use [v6Only] to set + /// version 6 only. However, if the address is + /// [InternetAddress.loopbackIPv6], only IP version 6 (IPv6) connections + /// will be accepted. + /// + /// If [port] has the value [:0:] an ephemeral port will be chosen by + /// the system. The actual port used can be retrieved using the + /// [port] getter. + /// + /// The optional argument [backlog] can be used to specify the listen + /// backlog for the underlying OS listen setup. If [backlog] has the + /// value of [:0:] (the default) a reasonable value will be chosen by + /// the system. + /// + /// The optional argument [shared] specifies whether additional HttpServer + /// objects can bind to the same combination of `address`, `port` and `v6Only`. + /// If `shared` is `true` and more `HttpServer`s from this isolate or other + /// isolates are bound to the port, then the incoming connections will be + /// distributed among all the bound `HttpServer`s. Connections can be + /// distributed over multiple isolates this way. static Future<HttpServer> bind(address, int port, - {int backlog: 0, bool v6Only: false, bool shared: false}) => + {int backlog = 0, bool v6Only = false, bool shared = false}) => _HttpServer.bind(address, port, backlog, v6Only, shared); - /** - * The [address] can either be a [String] or an - * [InternetAddress]. If [address] is a [String], [bind] will - * perform a [InternetAddress.lookup] and use the first value in the - * list. To listen on the loopback adapter, which will allow only - * incoming connections from the local host, use the value - * [InternetAddress.loopbackIPv4] or - * [InternetAddress.loopbackIPv6]. To allow for incoming - * connection from the network use either one of the values - * [InternetAddress.anyIPv4] or [InternetAddress.anyIPv6] to - * bind to all interfaces or the IP address of a specific interface. - * - * If an IP version 6 (IPv6) address is used, both IP version 6 - * (IPv6) and version 4 (IPv4) connections will be accepted. To - * restrict this to version 6 (IPv6) only, use [v6Only] to set - * version 6 only. - * - * If [port] has the value [:0:] an ephemeral port will be chosen by - * the system. The actual port used can be retrieved using the - * [port] getter. - * - * The optional argument [backlog] can be used to specify the listen - * backlog for the underlying OS listen setup. If [backlog] has the - * value of [:0:] (the default) a reasonable value will be chosen by - * the system. - * - * If [requestClientCertificate] is true, the server will - * request clients to authenticate with a client certificate. - * The server will advertise the names of trusted issuers of client - * certificates, getting them from a [SecurityContext], where they have been - * set using [SecurityContext.setClientAuthorities]. - * - * The optional argument [shared] specifies whether additional HttpServer - * objects can bind to the same combination of `address`, `port` and `v6Only`. - * If `shared` is `true` and more `HttpServer`s from this isolate or other - * isolates are bound to the port, then the incoming connections will be - * distributed among all the bound `HttpServer`s. Connections can be - * distributed over multiple isolates this way. - */ + /// The [address] can either be a [String] or an + /// [InternetAddress]. If [address] is a [String], [bind] will + /// perform a [InternetAddress.lookup] and use the first value in the + /// list. To listen on the loopback adapter, which will allow only + /// incoming connections from the local host, use the value + /// [InternetAddress.loopbackIPv4] or + /// [InternetAddress.loopbackIPv6]. To allow for incoming + /// connection from the network use either one of the values + /// [InternetAddress.anyIPv4] or [InternetAddress.anyIPv6] to + /// bind to all interfaces or the IP address of a specific interface. + /// + /// If an IP version 6 (IPv6) address is used, both IP version 6 + /// (IPv6) and version 4 (IPv4) connections will be accepted. To + /// restrict this to version 6 (IPv6) only, use [v6Only] to set + /// version 6 only. + /// + /// If [port] has the value [:0:] an ephemeral port will be chosen by + /// the system. The actual port used can be retrieved using the + /// [port] getter. + /// + /// The optional argument [backlog] can be used to specify the listen + /// backlog for the underlying OS listen setup. If [backlog] has the + /// value of [:0:] (the default) a reasonable value will be chosen by + /// the system. + /// + /// If [requestClientCertificate] is true, the server will + /// request clients to authenticate with a client certificate. + /// The server will advertise the names of trusted issuers of client + /// certificates, getting them from a [SecurityContext], where they have been + /// set using [SecurityContext.setClientAuthorities]. + /// + /// The optional argument [shared] specifies whether additional HttpServer + /// objects can bind to the same combination of `address`, `port` and `v6Only`. + /// If `shared` is `true` and more `HttpServer`s from this isolate or other + /// isolates are bound to the port, then the incoming connections will be + /// distributed among all the bound `HttpServer`s. Connections can be + /// distributed over multiple isolates this way. static Future<HttpServer> bindSecure( address, int port, SecurityContext context, - {int backlog: 0, - bool v6Only: false, - bool requestClientCertificate: false, - bool shared: false}) => + {int backlog = 0, + bool v6Only = false, + bool requestClientCertificate = false, + bool shared = false}) => _HttpServer.bindSecure(address, port, context, backlog, v6Only, requestClientCertificate, shared); - /** - * Attaches the HTTP server to an existing [ServerSocket]. When the - * [HttpServer] is closed, the [HttpServer] will just detach itself, - * closing current connections but not closing [serverSocket]. - */ + /// Attaches the HTTP server to an existing [ServerSocket]. When the + /// [HttpServer] is closed, the [HttpServer] will just detach itself, + /// closing current connections but not closing [serverSocket]. factory HttpServer.listenOn(ServerSocket serverSocket) => - new _HttpServer.listenOn(serverSocket); + _HttpServer.listenOn(serverSocket); - /** - * Permanently stops this [HttpServer] from listening for new - * connections. This closes the [Stream] of [HttpRequest]s with a - * done event. The returned future completes when the server is - * stopped. For a server started using [bind] or [bindSecure] this - * means that the port listened on no longer in use. - * - * If [force] is `true`, active connections will be closed immediately. - */ - Future close({bool force: false}); + /// Permanently stops this [HttpServer] from listening for new + /// connections. This closes the [Stream] of [HttpRequest]s with a + /// done event. The returned future completes when the server is + /// stopped. For a server started using [bind] or [bindSecure] this + /// means that the port listened on no longer in use. + /// + /// If [force] is `true`, active connections will be closed immediately. + Future close({bool force = false}); - /** - * Returns the port that the server is listening on. This can be - * used to get the actual port used when a value of 0 for [:port:] is - * specified in the [bind] or [bindSecure] call. - */ + /// Returns the port that the server is listening on. This can be + /// used to get the actual port used when a value of 0 for [:port:] is + /// specified in the [bind] or [bindSecure] call. int get port; - /** - * Returns the address that the server is listening on. This can be - * used to get the actual address used, when the address is fetched by - * a lookup from a hostname. - */ + /// Returns the address that the server is listening on. This can be + /// used to get the actual address used, when the address is fetched by + /// a lookup from a hostname. InternetAddress get address; - /** - * Sets the timeout, in seconds, for sessions of this [HttpServer]. - * The default timeout is 20 minutes. - */ + /// Sets the timeout, in seconds, for sessions of this [HttpServer]. + /// The default timeout is 20 minutes. set sessionTimeout(int timeout); - /** - * Returns an [HttpConnectionsInfo] object summarizing the number of - * current connections handled by the server. - */ + /// Returns an [HttpConnectionsInfo] object summarizing the number of + /// current connections handled by the server. HttpConnectionsInfo connectionsInfo(); } -/** - * Summary statistics about an [HttpServer]s current socket connections. - */ +/// Summary statistics about an [HttpServer]s current socket connections. class HttpConnectionsInfo { - /** - * Total number of socket connections. - */ + /// Total number of socket connections. int total = 0; - /** - * Number of active connections where actual request/response - * processing is active. - */ + /// Number of active connections where actual request/response + /// processing is active. int active = 0; - /** - * Number of idle connections held by clients as persistent connections. - */ + /// Number of idle connections held by clients as persistent connections. int idle = 0; - /** - * Number of connections which are preparing to close. Note: These - * connections are also part of the [:active:] count as they might - * still be sending data to the client before finally closing. - */ + /// Number of connections which are preparing to close. Note: These + /// connections are also part of the [:active:] count as they might + /// still be sending data to the client before finally closing. int closing = 0; } -/** - * Headers for HTTP requests and responses. - * - * In some situations, headers are immutable: - * - * * HttpRequest and HttpClientResponse always have immutable headers. - * - * * HttpResponse and HttpClientRequest have immutable headers - * from the moment the body is written to. - * - * In these situations, the mutating methods throw exceptions. - * - * For all operations on HTTP headers the header name is - * case-insensitive. - * - * To set the value of a header use the `set()` method: - * - * request.headers.set(HttpHeaders.CACHE_CONTROL, - * 'max-age=3600, must-revalidate'); - * - * To retrieve the value of a header use the `value()` method: - * - * print(request.headers.value(HttpHeaders.USER_AGENT)); - * - * An HttpHeaders object holds a list of values for each name - * as the standard allows. In most cases a name holds only a single value, - * The most common mode of operation is to use `set()` for setting a value, - * and `value()` for retrieving a value. - */ +/// Headers for HTTP requests and responses. +/// +/// In some situations, headers are immutable: +/// +/// * HttpRequest and HttpClientResponse always have immutable headers. +/// +/// * HttpResponse and HttpClientRequest have immutable headers +/// from the moment the body is written to. +/// +/// In these situations, the mutating methods throw exceptions. +/// +/// For all operations on HTTP headers the header name is +/// case-insensitive. +/// +/// To set the value of a header use the `set()` method: +/// +/// request.headers.set(HttpHeaders.CACHE_CONTROL, +/// 'max-age=3600, must-revalidate'); +/// +/// To retrieve the value of a header use the `value()` method: +/// +/// print(request.headers.value(HttpHeaders.USER_AGENT)); +/// +/// An HttpHeaders object holds a list of values for each name +/// as the standard allows. In most cases a name holds only a single value, +/// The most common mode of operation is to use `set()` for setting a value, +/// and `value()` for retrieving a value. abstract class HttpHeaders { static const ACCEPT = "accept"; static const ACCEPT_CHARSET = "accept-charset"; @@ -449,7 +411,7 @@ static const COOKIE = "cookie"; static const SET_COOKIE = "set-cookie"; - static const GENERAL_HEADERS = const [ + static const GENERAL_HEADERS = [ CACHE_CONTROL, CONNECTION, DATE, @@ -461,7 +423,7 @@ WARNING ]; - static const ENTITY_HEADERS = const [ + static const ENTITY_HEADERS = [ ALLOW, CONTENT_ENCODING, CONTENT_LANGUAGE, @@ -474,7 +436,7 @@ LAST_MODIFIED ]; - static const RESPONSE_HEADERS = const [ + static const RESPONSE_HEADERS = [ ACCEPT_RANGES, AGE, ETAG, @@ -486,7 +448,7 @@ WWW_AUTHENTICATE ]; - static const REQUEST_HEADERS = const [ + static const REQUEST_HEADERS = [ ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, @@ -508,753 +470,605 @@ USER_AGENT ]; - /** - * Gets and sets the date. The value of this property will - * reflect the 'date' header. - */ + /// Gets and sets the date. The value of this property will + /// reflect the 'date' header. DateTime date; - /** - * Gets and sets the expiry date. The value of this property will - * reflect the 'expires' header. - */ + /// Gets and sets the expiry date. The value of this property will + /// reflect the 'expires' header. DateTime expires; - /** - * Gets and sets the "if-modified-since" date. The value of this property will - * reflect the "if-modified-since" header. - */ + /// Gets and sets the "if-modified-since" date. The value of this property will + /// reflect the "if-modified-since" header. DateTime ifModifiedSince; - /** - * Gets and sets the host part of the 'host' header for the - * connection. - */ + /// Gets and sets the host part of the 'host' header for the + /// connection. String host; - /** - * Gets and sets the port part of the 'host' header for the - * connection. - */ + /// Gets and sets the port part of the 'host' header for the + /// connection. int port; - /** - * Gets the protocol version for the connection. - */ + /// Gets the protocol version for the connection. String get protocolVersion; - /** - * Gets and sets the content type. Note that the content type in the - * header will only be updated if this field is set - * directly. Mutating the returned current value will have no - * effect. - */ + /// Gets and sets the content type. Note that the content type in the + /// header will only be updated if this field is set + /// directly. Mutating the returned current value will have no + /// effect. ContentType contentType; - /** - * Gets and sets the content length header value. - */ + /// Gets and sets the content length header value. int contentLength; - /** - * Gets and sets the persistent connection header value. - */ + /// Gets and sets the persistent connection header value. bool persistentConnection; - /** - * Gets and sets the chunked transfer encoding header value. - */ + /// Gets and sets the chunked transfer encoding header value. bool chunkedTransferEncoding; - /** - * Returns the list of values for the header named [name]. If there - * is no header with the provided name, [:null:] will be returned. - */ + /// Returns the list of values for the header named [name]. If there + /// is no header with the provided name, [:null:] will be returned. List<String> operator [](String name); - /** - * Convenience method for the value for a single valued header. If - * there is no header with the provided name, [:null:] will be - * returned. If the header has more than one value an exception is - * thrown. - */ + /// Convenience method for the value for a single valued header. If + /// there is no header with the provided name, [:null:] will be + /// returned. If the header has more than one value an exception is + /// thrown. String value(String name); - /** - * Adds a header value. The header named [name] will have the value - * [value] added to its list of values. Some headers are single - * valued, and for these adding a value will replace the previous - * value. If the value is of type DateTime a HTTP date format will be - * applied. If the value is a [:List:] each element of the list will - * be added separately. For all other types the default [:toString:] - * method will be used. - */ + /// Adds a header value. The header named [name] will have the value + /// [value] added to its list of values. Some headers are single + /// valued, and for these adding a value will replace the previous + /// value. If the value is of type DateTime a HTTP date format will be + /// applied. If the value is a [:List:] each element of the list will + /// be added separately. For all other types the default [:toString:] + /// method will be used. void add(String name, Object value); - /** - * Sets a header. The header named [name] will have all its values - * cleared before the value [value] is added as its value. - */ + /// Sets a header. The header named [name] will have all its values + /// cleared before the value [value] is added as its value. void set(String name, Object value); - /** - * Removes a specific value for a header name. Some headers have - * system supplied values and for these the system supplied values - * will still be added to the collection of values for the header. - */ + /// Removes a specific value for a header name. Some headers have + /// system supplied values and for these the system supplied values + /// will still be added to the collection of values for the header. void remove(String name, Object value); - /** - * Removes all values for the specified header name. Some headers - * have system supplied values and for these the system supplied - * values will still be added to the collection of values for the - * header. - */ + /// Removes all values for the specified header name. Some headers + /// have system supplied values and for these the system supplied + /// values will still be added to the collection of values for the + /// header. void removeAll(String name); - /** - * Enumerates the headers, applying the function [f] to each - * header. The header name passed in [:name:] will be all lower - * case. - */ + /// Enumerates the headers, applying the function [f] to each + /// header. The header name passed in [:name:] will be all lower + /// case. void forEach(void f(String name, List<String> values)); - /** - * Disables folding for the header named [name] when sending the HTTP - * header. By default, multiple header values are folded into a - * single header line by separating the values with commas. The - * 'set-cookie' header has folding disabled by default. - */ + /// Disables folding for the header named [name] when sending the HTTP + /// header. By default, multiple header values are folded into a + /// single header line by separating the values with commas. The + /// 'set-cookie' header has folding disabled by default. void noFolding(String name); - /** - * Remove all headers. Some headers have system supplied values and - * for these the system supplied values will still be added to the - * collection of values for the header. - */ + /// Remove all headers. Some headers have system supplied values and + /// for these the system supplied values will still be added to the + /// collection of values for the header. void clear(); } -/** - * Representation of a header value in the form: - * - * [:value; parameter1=value1; parameter2=value2:] - * - * [HeaderValue] can be used to conveniently build and parse header - * values on this form. - * - * To build an [:accepts:] header with the value - * - * text/plain; q=0.3, text/html - * - * use code like this: - * - * HttpClientRequest request = ...; - * var v = new HeaderValue("text/plain", {"q": "0.3"}); - * request.headers.add(HttpHeaders.ACCEPT, v); - * request.headers.add(HttpHeaders.ACCEPT, "text/html"); - * - * To parse the header values use the [:parse:] static method. - * - * HttpRequest request = ...; - * List<String> values = request.headers[HttpHeaders.ACCEPT]; - * values.forEach((value) { - * HeaderValue v = HeaderValue.parse(value); - * // Use v.value and v.parameters - * }); - * - * An instance of [HeaderValue] is immutable. - */ +/// Representation of a header value in the form: +/// +/// [:value; parameter1=value1; parameter2=value2:] +/// +/// [HeaderValue] can be used to conveniently build and parse header +/// values on this form. +/// +/// To build an [:accepts:] header with the value +/// +/// text/plain; q=0.3, text/html +/// +/// use code like this: +/// +/// HttpClientRequest request = ...; +/// var v = new HeaderValue("text/plain", {"q": "0.3"}); +/// request.headers.add(HttpHeaders.ACCEPT, v); +/// request.headers.add(HttpHeaders.ACCEPT, "text/html"); +/// +/// To parse the header values use the [:parse:] static method. +/// +/// HttpRequest request = ...; +/// List<String> values = request.headers[HttpHeaders.ACCEPT]; +/// values.forEach((value) { +/// HeaderValue v = HeaderValue.parse(value); +/// // Use v.value and v.parameters +/// }); +/// +/// An instance of [HeaderValue] is immutable. abstract class HeaderValue { - /** - * Creates a new header value object setting the value and parameters. - */ + /// Creates a new header value object setting the value and parameters. factory HeaderValue([String value = "", Map<String, String> parameters]) { - return new HeaderValueImpl(value, parameters); + return HeaderValueImpl(value, parameters); } - /** - * Creates a new header value object from parsing a header value - * string with both value and optional parameters. - */ + /// Creates a new header value object from parsing a header value + /// string with both value and optional parameters. static HeaderValue parse(String value, - {String parameterSeparator: ";", + {String parameterSeparator = ";", String valueSeparator, - bool preserveBackslash: false}) { + bool preserveBackslash = false}) { return HeaderValueImpl.parse(value, parameterSeparator: parameterSeparator, valueSeparator: valueSeparator, preserveBackslash: preserveBackslash); } - /** - * Gets the header value. - */ + /// Gets the header value. String get value; - /** - * Gets the map of parameters. - * - * This map cannot be modified. Invoking any operation which would - * modify the map will throw [UnsupportedError]. - */ + /// Gets the map of parameters. + /// + /// This map cannot be modified. Invoking any operation which would + /// modify the map will throw [UnsupportedError]. Map<String, String> get parameters; - /** - * Returns the formatted string representation in the form: - * - * value; parameter1=value1; parameter2=value2 - */ + /// Returns the formatted string representation in the form: + /// + /// value; parameter1=value1; parameter2=value2 String toString(); } -/** - * Representation of a content type. An instance of [ContentType] is - * immutable. - */ +/// Representation of a content type. An instance of [ContentType] is +/// immutable. abstract class ContentType implements HeaderValue { - /** - * Content type for plain text using UTF-8 encoding. - * - * text/plain; charset=utf-8 - */ - static final TEXT = new ContentType("text", "plain", charset: "utf-8"); + /// Content type for plain text using UTF-8 encoding. + /// + /// text/plain; charset=utf-8 + static final TEXT = ContentType("text", "plain", charset: "utf-8"); - /** - * Content type for HTML using UTF-8 encoding. - * - * text/html; charset=utf-8 - */ - static final HTML = new ContentType("text", "html", charset: "utf-8"); + /// Content type for HTML using UTF-8 encoding. + /// + /// text/html; charset=utf-8 + static final HTML = ContentType("text", "html", charset: "utf-8"); - /** - * Content type for JSON using UTF-8 encoding. - * - * application/json; charset=utf-8 - */ - static final JSON = new ContentType("application", "json", charset: "utf-8"); + /// Content type for JSON using UTF-8 encoding. + /// + /// application/json; charset=utf-8 + static final JSON = ContentType("application", "json", charset: "utf-8"); - /** - * Content type for binary data. - * - * application/octet-stream - */ - static final BINARY = new ContentType("application", "octet-stream"); + /// Content type for binary data. + /// + /// application/octet-stream + static final BINARY = ContentType("application", "octet-stream"); - /** - * Creates a new content type object setting the primary type and - * sub type. The charset and additional parameters can also be set - * using [charset] and [parameters]. If charset is passed and - * [parameters] contains charset as well the passed [charset] will - * override the value in parameters. Keys passed in parameters will be - * converted to lower case. The `charset` entry, whether passed as `charset` - * or in `parameters`, will have its value converted to lower-case. - */ + /// Creates a new content type object setting the primary type and + /// sub type. The charset and additional parameters can also be set + /// using [charset] and [parameters]. If charset is passed and + /// [parameters] contains charset as well the passed [charset] will + /// override the value in parameters. Keys passed in parameters will be + /// converted to lower case. The `charset` entry, whether passed as `charset` + /// or in `parameters`, will have its value converted to lower-case. factory ContentType(String primaryType, String subType, {String charset, Map<String, String> parameters}) { - return new ContentTypeImpl(primaryType, subType, charset, parameters); + return ContentTypeImpl(primaryType, subType, charset, parameters); } - /** - * Creates a new content type object from parsing a Content-Type - * header value. As primary type, sub type and parameter names and - * values are not case sensitive all these values will be converted - * to lower case. Parsing this string - * - * text/html; charset=utf-8 - * - * will create a content type object with primary type [:text:], sub - * type [:html:] and parameter [:charset:] with value [:utf-8:]. - */ + /// Creates a new content type object from parsing a Content-Type + /// header value. As primary type, sub type and parameter names and + /// values are not case sensitive all these values will be converted + /// to lower case. Parsing this string + /// + /// text/html; charset=utf-8 + /// + /// will create a content type object with primary type [:text:], sub + /// type [:html:] and parameter [:charset:] with value [:utf-8:]. static ContentType parse(String value) { return ContentTypeImpl.parse(value); } - /** - * Gets the mime-type, without any parameters. - */ + /// Gets the mime-type, without any parameters. String get mimeType; - /** - * Gets the primary type. - */ + /// Gets the primary type. String get primaryType; - /** - * Gets the sub type. - */ + /// Gets the sub type. String get subType; - /** - * Gets the character set. - */ + /// Gets the character set. String get charset; } -/** - * Representation of a cookie. For cookies received by the server as - * Cookie header values only [:name:] and [:value:] fields will be - * set. When building a cookie for the 'set-cookie' header in the server - * and when receiving cookies in the client as 'set-cookie' headers all - * fields can be used. - */ +/// Representation of a cookie. For cookies received by the server as +/// Cookie header values only [:name:] and [:value:] fields will be +/// set. When building a cookie for the 'set-cookie' header in the server +/// and when receiving cookies in the client as 'set-cookie' headers all +/// fields can be used. abstract class Cookie { - /** - * Gets and sets the name. - */ + /// Gets and sets the name. String name; - /** - * Gets and sets the value. - */ + /// Gets and sets the value. String value; - /** - * Gets and sets the expiry date. - */ + /// Gets and sets the expiry date. DateTime expires; - /** - * Gets and sets the max age. A value of [:0:] means delete cookie - * now. - */ + /// Gets and sets the max age. A value of [:0:] means delete cookie + /// now. int maxAge; - /** - * Gets and sets the domain. - */ + /// Gets and sets the domain. String domain; - /** - * Gets and sets the path. - */ + /// Gets and sets the path. String path; - /** - * Gets and sets whether this cookie is secure. - */ + /// Gets and sets whether this cookie is secure. bool secure; - /** - * Gets and sets whether this cookie is HTTP only. - */ + /// Gets and sets whether this cookie is HTTP only. bool httpOnly; - /** - * Creates a new cookie optionally setting the name and value. - * - * By default the value of `httpOnly` will be set to `true`. - */ - factory Cookie([String name, String value]) => new CookieImpl(name, value); + /// Creates a new cookie optionally setting the name and value. + /// + /// By default the value of `httpOnly` will be set to `true`. + factory Cookie([String name, String value]) => CookieImpl(name, value); - /** - * Creates a new cookie by parsing a header value from a 'set-cookie' - * header. - */ + /// Creates a new cookie by parsing a header value from a 'set-cookie' + /// header. factory Cookie.fromSetCookieValue(String value) { - return new CookieImpl.fromSetCookieValue(value); + return CookieImpl.fromSetCookieValue(value); } - /** - * Returns the formatted string representation of the cookie. The - * string representation can be used for for setting the Cookie or - * 'set-cookie' headers - */ + /// Returns the formatted string representation of the cookie. The + /// string representation can be used for for setting the Cookie or + /// 'set-cookie' headers String toString(); } -/** - * A server-side object - * that contains the content of and information about an HTTP request. - * - * __Note__: Check out the - * [http_server](http://pub.dartlang.org/packages/http_server) - * package, which makes working with the low-level - * dart:io HTTP server subsystem easier. - * - * `HttpRequest` objects are generated by an [HttpServer], - * which listens for HTTP requests on a specific host and port. - * For each request received, the HttpServer, which is a [Stream], - * generates an `HttpRequest` object and adds it to the stream. - * - * An `HttpRequest` object delivers the body content of the request - * as a stream of byte lists. - * The object also contains information about the request, - * such as the method, URI, and headers. - * - * In the following code, an HttpServer listens - * for HTTP requests. When the server receives a request, - * it uses the HttpRequest object's `method` property to dispatch requests. - * - * final HOST = InternetAddress.loopbackIPv4; - * final PORT = 80; - * - * HttpServer.bind(HOST, PORT).then((_server) { - * _server.listen((HttpRequest request) { - * switch (request.method) { - * case 'GET': - * handleGetRequest(request); - * break; - * case 'POST': - * ... - * } - * }, - * onError: handleError); // listen() failed. - * }).catchError(handleError); - * - * An HttpRequest object provides access to the associated [HttpResponse] - * object through the response property. - * The server writes its response to the body of the HttpResponse object. - * For example, here's a function that responds to a request: - * - * void handleGetRequest(HttpRequest req) { - * HttpResponse res = req.response; - * res.write('Received request ${req.method}: ${req.uri.path}'); - * res.close(); - * } - */ +/// A server-side object +/// that contains the content of and information about an HTTP request. +/// +/// __Note__: Check out the +/// [http_server](http://pub.dartlang.org/packages/http_server) +/// package, which makes working with the low-level +/// dart:io HTTP server subsystem easier. +/// +/// `HttpRequest` objects are generated by an [HttpServer], +/// which listens for HTTP requests on a specific host and port. +/// For each request received, the HttpServer, which is a [Stream], +/// generates an `HttpRequest` object and adds it to the stream. +/// +/// An `HttpRequest` object delivers the body content of the request +/// as a stream of byte lists. +/// The object also contains information about the request, +/// such as the method, URI, and headers. +/// +/// In the following code, an HttpServer listens +/// for HTTP requests. When the server receives a request, +/// it uses the HttpRequest object's `method` property to dispatch requests. +/// +/// final HOST = InternetAddress.loopbackIPv4; +/// final PORT = 80; +/// +/// HttpServer.bind(HOST, PORT).then((_server) { +/// _server.listen((HttpRequest request) { +/// switch (request.method) { +/// case 'GET': +/// handleGetRequest(request); +/// break; +/// case 'POST': +/// ... +/// } +/// }, +/// onError: handleError); // listen() failed. +/// }).catchError(handleError); +/// +/// An HttpRequest object provides access to the associated [HttpResponse] +/// object through the response property. +/// The server writes its response to the body of the HttpResponse object. +/// For example, here's a function that responds to a request: +/// +/// void handleGetRequest(HttpRequest req) { +/// HttpResponse res = req.response; +/// res.write('Received request ${req.method}: ${req.uri.path}'); +/// res.close(); +/// } abstract class HttpRequest implements Stream<List<int>> { - /** - * The content length of the request body. - * - * If the size of the request body is not known in advance, - * this value is -1. - */ + /// The content length of the request body. + /// + /// If the size of the request body is not known in advance, + /// this value is -1. int get contentLength; - /** - * The method, such as 'GET' or 'POST', for the request. - */ + /// The method, such as 'GET' or 'POST', for the request. String get method; - /** - * The URI for the request. - * - * This provides access to the - * path and query string for the request. - */ + /// The URI for the request. + /// + /// This provides access to the + /// path and query string for the request. Uri get uri; - /** - * The requested URI for the request. - * - * The returned URI is reconstructed by using http-header fields, to access - * otherwise lost information, e.g. host and scheme. - * - * To reconstruct the scheme, first 'X-Forwarded-Proto' is checked, and then - * falling back to server type. - * - * To reconstruct the host, first 'X-Forwarded-Host' is checked, then 'Host' - * and finally calling back to server. - */ + /// The requested URI for the request. + /// + /// The returned URI is reconstructed by using http-header fields, to access + /// otherwise lost information, e.g. host and scheme. + /// + /// To reconstruct the scheme, first 'X-Forwarded-Proto' is checked, and then + /// falling back to server type. + /// + /// To reconstruct the host, first 'X-Forwarded-Host' is checked, then 'Host' + /// and finally calling back to server. Uri get requestedUri; - /** - * The request headers. - * - * The returned [HttpHeaders] are immutable. - */ + /// The request headers. + /// + /// The returned [HttpHeaders] are immutable. HttpHeaders get headers; - /** - * The cookies in the request, from the Cookie headers. - */ + /// The cookies in the request, from the Cookie headers. List<Cookie> get cookies; - /** - * The persistent connection state signaled by the client. - */ + /// The persistent connection state signaled by the client. bool get persistentConnection; - /** - * The client certificate of the client making the request. - * - * This value is null if the connection is not a secure TLS or SSL connection, - * or if the server does not request a client certificate, or if the client - * does not provide one. - */ + /// The client certificate of the client making the request. + /// + /// This value is null if the connection is not a secure TLS or SSL connection, + /// or if the server does not request a client certificate, or if the client + /// does not provide one. X509Certificate get certificate; - /** - * The session for the given request. - * - * If the session is - * being initialized by this call, [:isNew:] is true for the returned - * session. - * See [HttpServer.sessionTimeout] on how to change default timeout. - */ + /// The session for the given request. + /// + /// If the session is + /// being initialized by this call, [:isNew:] is true for the returned + /// session. + /// See [HttpServer.sessionTimeout] on how to change default timeout. HttpSession get session; - /** - * The HTTP protocol version used in the request, - * either "1.0" or "1.1". - */ + /// The HTTP protocol version used in the request, + /// either "1.0" or "1.1". String get protocolVersion; - /** - * Information about the client connection. - * - * Returns [:null:] if the socket is not available. - */ + /// Information about the client connection. + /// + /// Returns [:null:] if the socket is not available. HttpConnectionInfo get connectionInfo; - /** - * The [HttpResponse] object, used for sending back the response to the - * client. - * - * If the [contentLength] of the body isn't 0, and the body isn't being read, - * any write calls on the [HttpResponse] automatically drain the request - * body. - */ + /// The [HttpResponse] object, used for sending back the response to the + /// client. + /// + /// If the [contentLength] of the body isn't 0, and the body isn't being read, + /// any write calls on the [HttpResponse] automatically drain the request + /// body. HttpResponse get response; } -/** - * An HTTP response, which returns the headers and data - * from the server to the client in response to an HTTP request. - * - * Every HttpRequest object provides access to the associated [HttpResponse] - * object through the `response` property. - * The server sends its response to the client by writing to the - * HttpResponse object. - * - * ## Writing the response - * - * This class implements [IOSink]. - * After the header has been set up, the methods - * from IOSink, such as `writeln()`, can be used to write - * the body of the HTTP response. - * Use the `close()` method to close the response and send it to the client. - * - * server.listen((HttpRequest request) { - * request.response.write('Hello, world!'); - * request.response.close(); - * }); - * - * When one of the IOSink methods is used for the - * first time, the request header is sent. Calling any methods that - * change the header after it is sent throws an exception. - * - * ## Setting the headers - * - * The HttpResponse object has a number of properties for setting up - * the HTTP headers of the response. - * When writing string data through the IOSink, the encoding used - * is determined from the "charset" parameter of the - * "Content-Type" header. - * - * HttpResponse response = ... - * response.headers.contentType - * = new ContentType("application", "json", charset: "utf-8"); - * response.write(...); // Strings written will be UTF-8 encoded. - * - * If no charset is provided the default of ISO-8859-1 (Latin 1) will - * be used. - * - * HttpResponse response = ... - * response.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); - * response.write(...); // Strings written will be ISO-8859-1 encoded. - * - * An exception is thrown if you use the `write()` method - * while an unsupported content-type is set. - */ +/// An HTTP response, which returns the headers and data +/// from the server to the client in response to an HTTP request. +/// +/// Every HttpRequest object provides access to the associated [HttpResponse] +/// object through the `response` property. +/// The server sends its response to the client by writing to the +/// HttpResponse object. +/// +/// ## Writing the response +/// +/// This class implements [IOSink]. +/// After the header has been set up, the methods +/// from IOSink, such as `writeln()`, can be used to write +/// the body of the HTTP response. +/// Use the `close()` method to close the response and send it to the client. +/// +/// server.listen((HttpRequest request) { +/// request.response.write('Hello, world!'); +/// request.response.close(); +/// }); +/// +/// When one of the IOSink methods is used for the +/// first time, the request header is sent. Calling any methods that +/// change the header after it is sent throws an exception. +/// +/// ## Setting the headers +/// +/// The HttpResponse object has a number of properties for setting up +/// the HTTP headers of the response. +/// When writing string data through the IOSink, the encoding used +/// is determined from the "charset" parameter of the +/// "Content-Type" header. +/// +/// HttpResponse response = ... +/// response.headers.contentType +/// = new ContentType("application", "json", charset: "utf-8"); +/// response.write(...); // Strings written will be UTF-8 encoded. +/// +/// If no charset is provided the default of ISO-8859-1 (Latin 1) will +/// be used. +/// +/// HttpResponse response = ... +/// response.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); +/// response.write(...); // Strings written will be ISO-8859-1 encoded. +/// +/// An exception is thrown if you use the `write()` method +/// while an unsupported content-type is set. abstract class HttpResponse implements IOSink { // TODO(ajohnsen): Add documentation of how to pipe a file to the response. - /** - * Gets and sets the content length of the response. If the size of - * the response is not known in advance set the content length to - * -1 - which is also the default if not set. - */ + /// Gets and sets the content length of the response. If the size of + /// the response is not known in advance set the content length to + /// -1 - which is also the default if not set. int contentLength; - /** - * Gets and sets the status code. Any integer value is accepted. For - * the official HTTP status codes use the fields from - * [HttpStatus]. If no status code is explicitly set the default - * value [HttpStatus.OK] is used. - * - * The status code must be set before the body is written - * to. Setting the status code after writing to the response body or - * closing the response will throw a `StateError`. - */ + /// Gets and sets the status code. Any integer value is accepted. For + /// the official HTTP status codes use the fields from + /// [HttpStatus]. If no status code is explicitly set the default + /// value [HttpStatus.OK] is used. + /// + /// The status code must be set before the body is written + /// to. Setting the status code after writing to the response body or + /// closing the response will throw a `StateError`. int statusCode; - /** - * Gets and sets the reason phrase. If no reason phrase is explicitly - * set a default reason phrase is provided. - * - * The reason phrase must be set before the body is written - * to. Setting the reason phrase after writing to the response body - * or closing the response will throw a `StateError`. - */ + /// Gets and sets the reason phrase. If no reason phrase is explicitly + /// set a default reason phrase is provided. + /// + /// The reason phrase must be set before the body is written + /// to. Setting the reason phrase after writing to the response body + /// or closing the response will throw a `StateError`. String reasonPhrase; - /** - * Gets and sets the persistent connection state. The initial value - * of this property is the persistent connection state from the - * request. - */ + /// Gets and sets the persistent connection state. The initial value + /// of this property is the persistent connection state from the + /// request. bool persistentConnection; - /** - * Set and get the [deadline] for the response. The deadline is timed from the - * time it's set. Setting a new deadline will override any previous deadline. - * When a deadline is exceeded, the response will be closed and any further - * data ignored. - * - * To disable a deadline, set the [deadline] to `null`. - * - * The [deadline] is `null` by default. - */ + /// Set and get the [deadline] for the response. The deadline is timed from the + /// time it's set. Setting a new deadline will override any previous deadline. + /// When a deadline is exceeded, the response will be closed and any further + /// data ignored. + /// + /// To disable a deadline, set the [deadline] to `null`. + /// + /// The [deadline] is `null` by default. Duration deadline; - /** - * Gets or sets if the [HttpResponse] should buffer output. - * - * Default value is `true`. - * - * __Note__: Disabling buffering of the output can result in very poor - * performance, when writing many small chunks. - */ + /// Gets or sets if the [HttpResponse] should buffer output. + /// + /// Default value is `true`. + /// + /// __Note__: Disabling buffering of the output can result in very poor + /// performance, when writing many small chunks. bool bufferOutput; - /** - * Returns the response headers. - * - * The response headers can be modified until the response body is - * written to or closed. After that they become immutable. - */ + /// Returns the response headers. + /// + /// The response headers can be modified until the response body is + /// written to or closed. After that they become immutable. HttpHeaders get headers; - /** - * Cookies to set in the client (in the 'set-cookie' header). - */ + /// Cookies to set in the client (in the 'set-cookie' header). List<Cookie> get cookies; - /** - * Respond with a redirect to [location]. - * - * The URI in [location] should be absolute, but there are no checks - * to enforce that. - * - * By default the HTTP status code `HttpStatus.MOVED_TEMPORARILY` - * (`302`) is used for the redirect, but an alternative one can be - * specified using the [status] argument. - * - * This method will also call `close`, and the returned future is - * the future returned by `close`. - */ - Future redirect(Uri location, {int status: HttpStatus.MOVED_TEMPORARILY}); + /// Respond with a redirect to [location]. + /// + /// The URI in [location] should be absolute, but there are no checks + /// to enforce that. + /// + /// By default the HTTP status code `HttpStatus.MOVED_TEMPORARILY` + /// (`302`) is used for the redirect, but an alternative one can be + /// specified using the [status] argument. + /// + /// This method will also call `close`, and the returned future is + /// the future returned by `close`. + Future redirect(Uri location, {int status = HttpStatus.MOVED_TEMPORARILY}); - /** - * Detaches the underlying socket from the HTTP server. When the - * socket is detached the HTTP server will no longer perform any - * operations on it. - * - * This is normally used when a HTTP upgrade request is received - * and the communication should continue with a different protocol. - * - * If [writeHeaders] is `true`, the status line and [headers] will be written - * to the socket before it's detached. If `false`, the socket is detached - * immediately, without any data written to the socket. Default is `true`. - */ - Future<Socket> detachSocket({bool writeHeaders: true}); + /// Detaches the underlying socket from the HTTP server. When the + /// socket is detached the HTTP server will no longer perform any + /// operations on it. + /// + /// This is normally used when a HTTP upgrade request is received + /// and the communication should continue with a different protocol. + /// + /// If [writeHeaders] is `true`, the status line and [headers] will be written + /// to the socket before it's detached. If `false`, the socket is detached + /// immediately, without any data written to the socket. Default is `true`. + Future<Socket> detachSocket({bool writeHeaders = true}); - /** - * Gets information about the client connection. Returns [:null:] if the - * socket is not available. - */ + /// Gets information about the client connection. Returns [:null:] if the + /// socket is not available. HttpConnectionInfo get connectionInfo; } -/** - * A client that receives content, such as web pages, from - * a server using the HTTP protocol. - * - * HttpClient contains a number of methods to send an [HttpClientRequest] - * to an Http server and receive an [HttpClientResponse] back. - * For example, you can use the [get], [getUrl], [post], and [postUrl] methods - * for GET and POST requests, respectively. - * - * ## Making a simple GET request: an example - * - * A `getUrl` request is a two-step process, triggered by two [Future]s. - * When the first future completes with a [HttpClientRequest], the underlying - * network connection has been established, but no data has been sent. - * In the callback function for the first future, the HTTP headers and body - * can be set on the request. Either the first write to the request object - * or a call to [close] sends the request to the server. - * - * When the HTTP response is received from the server, - * the second future, which is returned by close, - * completes with an [HttpClientResponse] object. - * This object provides access to the headers and body of the response. - * The body is available as a stream implemented by HttpClientResponse. - * If a body is present, it must be read. Otherwise, it leads to resource - * leaks. Consider using [HttpClientResponse.drain] if the body is unused. - * - * HttpClient client = new HttpClient(); - * client.getUrl(Uri.parse("http://www.example.com/")) - * .then((HttpClientRequest request) { - * // Optionally set up headers... - * // Optionally write to the request object... - * // Then call close. - * ... - * return request.close(); - * }) - * .then((HttpClientResponse response) { - * // Process the response. - * ... - * }); - * - * The future for [HttpClientRequest] is created by methods such as - * [getUrl] and [open]. - * - * ## HTTPS connections - * - * An HttpClient can make HTTPS requests, connecting to a server using - * the TLS (SSL) secure networking protocol. Calling [getUrl] with an - * https: scheme will work automatically, if the server's certificate is - * signed by a root CA (certificate authority) on the default list of - * well-known trusted CAs, compiled by Mozilla. - * - * To add a custom trusted certificate authority, or to send a client - * certificate to servers that request one, pass a [SecurityContext] object - * as the optional `context` argument to the `HttpClient` constructor. - * The desired security options can be set on the [SecurityContext] object. - * - * ## Headers - * - * All HttpClient requests set the following header by default: - * - * Accept-Encoding: gzip - * - * This allows the HTTP server to use gzip compression for the body if - * possible. If this behavior is not desired set the - * `Accept-Encoding` header to something else. - * To turn off gzip compression of the response, clear this header: - * - * request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING) - * - * ## Closing the HttpClient - * - * The HttpClient supports persistent connections and caches network - * connections to reuse them for multiple requests whenever - * possible. This means that network connections can be kept open for - * some time after a request has completed. Use HttpClient.close - * to force the HttpClient object to shut down and to close the idle - * network connections. - * - * ## Turning proxies on and off - * - * By default the HttpClient uses the proxy configuration available - * from the environment, see [findProxyFromEnvironment]. To turn off - * the use of proxies set the [findProxy] property to - * [:null:]. - * - * HttpClient client = new HttpClient(); - * client.findProxy = null; - */ +/// A client that receives content, such as web pages, from +/// a server using the HTTP protocol. +/// +/// HttpClient contains a number of methods to send an [HttpClientRequest] +/// to an Http server and receive an [HttpClientResponse] back. +/// For example, you can use the [get], [getUrl], [post], and [postUrl] methods +/// for GET and POST requests, respectively. +/// +/// ## Making a simple GET request: an example +/// +/// A `getUrl` request is a two-step process, triggered by two [Future]s. +/// When the first future completes with a [HttpClientRequest], the underlying +/// network connection has been established, but no data has been sent. +/// In the callback function for the first future, the HTTP headers and body +/// can be set on the request. Either the first write to the request object +/// or a call to [close] sends the request to the server. +/// +/// When the HTTP response is received from the server, +/// the second future, which is returned by close, +/// completes with an [HttpClientResponse] object. +/// This object provides access to the headers and body of the response. +/// The body is available as a stream implemented by HttpClientResponse. +/// If a body is present, it must be read. Otherwise, it leads to resource +/// leaks. Consider using `HttpClientResponse.drain` if the body is unused. +/// +/// HttpClient client = new HttpClient(); +/// client.getUrl(Uri.parse("http://www.example.com/")) +/// .then((HttpClientRequest request) { +/// // Optionally set up headers... +/// // Optionally write to the request object... +/// // Then call close. +/// ... +/// return request.close(); +/// }) +/// .then((HttpClientResponse response) { +/// // Process the response. +/// ... +/// }); +/// +/// The future for [HttpClientRequest] is created by methods such as +/// [getUrl] and [open]. +/// +/// ## HTTPS connections +/// +/// An HttpClient can make HTTPS requests, connecting to a server using +/// the TLS (SSL) secure networking protocol. Calling [getUrl] with an +/// https: scheme will work automatically, if the server's certificate is +/// signed by a root CA (certificate authority) on the default list of +/// well-known trusted CAs, compiled by Mozilla. +/// +/// To add a custom trusted certificate authority, or to send a client +/// certificate to servers that request one, pass a [SecurityContext] object +/// as the optional `context` argument to the `HttpClient` constructor. +/// The desired security options can be set on the [SecurityContext] object. +/// +/// ## Headers +/// +/// All HttpClient requests set the following header by default: +/// +/// Accept-Encoding: gzip +/// +/// This allows the HTTP server to use gzip compression for the body if +/// possible. If this behavior is not desired set the +/// `Accept-Encoding` header to something else. +/// To turn off gzip compression of the response, clear this header: +/// +/// request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING) +/// +/// ## Closing the HttpClient +/// +/// The HttpClient supports persistent connections and caches network +/// connections to reuse them for multiple requests whenever +/// possible. This means that network connections can be kept open for +/// some time after a request has completed. Use HttpClient.close +/// to force the HttpClient object to shut down and to close the idle +/// network connections. +/// +/// ## Turning proxies on and off +/// +/// By default the HttpClient uses the proxy configuration available +/// from the environment, see [findProxyFromEnvironment]. To turn off +/// the use of proxies set the [findProxy] property to +/// [:null:]. +/// +/// HttpClient client = new HttpClient(); +/// client.findProxy = null; abstract class HttpClient { static const int DEFAULT_HTTP_PORT = 80; static const int DEFAULT_HTTPS_PORT = 443; @@ -1275,44 +1089,40 @@ /// `null`. Duration connectionTimeout; - /** - * Gets and sets the maximum number of live connections, to a single host. - * - * Increasing this number may lower performance and take up unwanted - * system resources. - * - * To disable, set to `null`. - * - * Default is `null`. - */ + /// Gets and sets the maximum number of live connections, to a single host. + /// + /// Increasing this number may lower performance and take up unwanted + /// system resources. + /// + /// To disable, set to `null`. + /// + /// Default is `null`. int maxConnectionsPerHost; - /** - * Gets and sets whether the body of a response will be automatically - * uncompressed. - * - * The body of an HTTP response can be compressed. In most - * situations providing the un-compressed body is most - * convenient. Therefore the default behavior is to un-compress the - * body. However in some situations (e.g. implementing a transparent - * proxy) keeping the uncompressed stream is required. - * - * NOTE: Headers in the response are never modified. This means - * that when automatic un-compression is turned on the value of the - * header `Content-Length` will reflect the length of the original - * compressed body. Likewise the header `Content-Encoding` will also - * have the original value indicating compression. - * - * NOTE: Automatic un-compression is only performed if the - * `Content-Encoding` header value is `gzip`. - * - * This value affects all responses produced by this client after the - * value is changed. - * - * To disable, set to `false`. - * - * Default is `true`. - */ + /// Gets and sets whether the body of a response will be automatically + /// uncompressed. + /// + /// The body of an HTTP response can be compressed. In most + /// situations providing the un-compressed body is most + /// convenient. Therefore the default behavior is to un-compress the + /// body. However in some situations (e.g. implementing a transparent + /// proxy) keeping the uncompressed stream is required. + /// + /// NOTE: Headers in the response are never modified. This means + /// that when automatic un-compression is turned on the value of the + /// header `Content-Length` will reflect the length of the original + /// compressed body. Likewise the header `Content-Encoding` will also + /// have the original value indicating compression. + /// + /// NOTE: Automatic un-compression is only performed if the + /// `Content-Encoding` header value is `gzip`. + /// + /// This value affects all responses produced by this client after the + /// value is changed. + /// + /// To disable, set to `false`. + /// + /// Default is `true`. bool autoUncompress; /// Gets and sets the default value of the `User-Agent` header for all requests @@ -1327,267 +1137,231 @@ factory HttpClient({SecurityContext context}) { HttpOverrides overrides = HttpOverrides.current; if (overrides == null) { - return new _HttpClient(context); + return _HttpClient(context); } return overrides.createHttpClient(context); } - /** - * Opens a HTTP connection. - * - * The HTTP method to use is specified in [method], the server is - * specified using [host] and [port], and the path (including - * a possible query) is specified using [path]. - * The path may also contain a URI fragment, which will be ignored. - * - * The `Host` header for the request will be set to the value - * [host]:[port]. This can be overridden through the - * [HttpClientRequest] interface before the request is sent. NOTE - * if [host] is an IP address this will still be set in the `Host` - * header. - * - * For additional information on the sequence of events during an - * HTTP transaction, and the objects returned by the futures, see - * the overall documentation for the class [HttpClient]. - */ + /// Opens a HTTP connection. + /// + /// The HTTP method to use is specified in [method], the server is + /// specified using [host] and [port], and the path (including + /// a possible query) is specified using [path]. + /// The path may also contain a URI fragment, which will be ignored. + /// + /// The `Host` header for the request will be set to the value + /// [host]:[port]. This can be overridden through the + /// [HttpClientRequest] interface before the request is sent. NOTE + /// if [host] is an IP address this will still be set in the `Host` + /// header. + /// + /// For additional information on the sequence of events during an + /// HTTP transaction, and the objects returned by the futures, see + /// the overall documentation for the class [HttpClient]. Future<HttpClientRequest> open( String method, String host, int port, String path); - /** - * Opens a HTTP connection. - * - * The HTTP method is specified in [method] and the URL to use in - * [url]. - * - * The `Host` header for the request will be set to the value - * [Uri.host]:[Uri.port] from [url]. This can be overridden through the - * [HttpClientRequest] interface before the request is sent. NOTE - * if [Uri.host] is an IP address this will still be set in the `Host` - * header. - * - * For additional information on the sequence of events during an - * HTTP transaction, and the objects returned by the futures, see - * the overall documentation for the class [HttpClient]. - */ + /// Opens a HTTP connection. + /// + /// The HTTP method is specified in [method] and the URL to use in + /// [url]. + /// + /// The `Host` header for the request will be set to the value + /// [Uri.host]:[Uri.port] from [url]. This can be overridden through the + /// [HttpClientRequest] interface before the request is sent. NOTE + /// if [Uri.host] is an IP address this will still be set in the `Host` + /// header. + /// + /// For additional information on the sequence of events during an + /// HTTP transaction, and the objects returned by the futures, see + /// the overall documentation for the class [HttpClient]. Future<HttpClientRequest> openUrl(String method, Uri url); - /** - * Opens a HTTP connection using the GET method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using - * [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the GET method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using + /// [path]. + /// + /// See [open] for details. Future<HttpClientRequest> get(String host, int port, String path); - /** - * Opens a HTTP connection using the GET method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the GET method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> getUrl(Uri url); - /** - * Opens a HTTP connection using the POST method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using - * [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the POST method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using + /// [path]. + /// + /// See [open] for details. Future<HttpClientRequest> post(String host, int port, String path); - /** - * Opens a HTTP connection using the POST method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the POST method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> postUrl(Uri url); - /** - * Opens a HTTP connection using the PUT method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the PUT method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using [path]. + /// + /// See [open] for details. Future<HttpClientRequest> put(String host, int port, String path); - /** - * Opens a HTTP connection using the PUT method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the PUT method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> putUrl(Uri url); - /** - * Opens a HTTP connection using the DELETE method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the DELETE method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using [path]. + /// + /// See [open] for details. Future<HttpClientRequest> delete(String host, int port, String path); - /** - * Opens a HTTP connection using the DELETE method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the DELETE method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> deleteUrl(Uri url); - /** - * Opens a HTTP connection using the PATCH method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the PATCH method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using [path]. + /// + /// See [open] for details. Future<HttpClientRequest> patch(String host, int port, String path); - /** - * Opens a HTTP connection using the PATCH method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the PATCH method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> patchUrl(Uri url); - /** - * Opens a HTTP connection using the HEAD method. - * - * The server is specified using [host] and [port], and the path - * (including a possible query) is specified using [path]. - * - * See [open] for details. - */ + /// Opens a HTTP connection using the HEAD method. + /// + /// The server is specified using [host] and [port], and the path + /// (including a possible query) is specified using [path]. + /// + /// See [open] for details. Future<HttpClientRequest> head(String host, int port, String path); - /** - * Opens a HTTP connection using the HEAD method. - * - * The URL to use is specified in [url]. - * - * See [openUrl] for details. - */ + /// Opens a HTTP connection using the HEAD method. + /// + /// The URL to use is specified in [url]. + /// + /// See [openUrl] for details. Future<HttpClientRequest> headUrl(Uri url); - /** - * Sets the function to be called when a site is requesting - * authentication. The URL requested and the security realm from the - * server are passed in the arguments `url` and `realm`. - * - * The function returns a [Future] which should complete when the - * authentication has been resolved. If credentials cannot be - * provided the [Future] should complete with [:false:]. If - * credentials are available the function should add these using - * [addCredentials] before completing the [Future] with the value - * [:true:]. - * - * If the [Future] completes with true the request will be retried - * using the updated credentials. Otherwise response processing will - * continue normally. - */ + /// Sets the function to be called when a site is requesting + /// authentication. The URL requested and the security realm from the + /// server are passed in the arguments `url` and `realm`. + /// + /// The function returns a [Future] which should complete when the + /// authentication has been resolved. If credentials cannot be + /// provided the [Future] should complete with [:false:]. If + /// credentials are available the function should add these using + /// [addCredentials] before completing the [Future] with the value + /// [:true:]. + /// + /// If the [Future] completes with true the request will be retried + /// using the updated credentials. Otherwise response processing will + /// continue normally. set authenticate(Future<bool> f(Uri url, String scheme, String realm)); - /** - * Add credentials to be used for authorizing HTTP requests. - */ + /// Add credentials to be used for authorizing HTTP requests. void addCredentials(Uri url, String realm, HttpClientCredentials credentials); - /** - * Sets the function used to resolve the proxy server to be used for - * opening a HTTP connection to the specified `url`. If this - * function is not set, direct connections will always be used. - * - * The string returned by [f] must be in the format used by browser - * PAC (proxy auto-config) scripts. That is either - * - * "DIRECT" - * - * for using a direct connection or - * - * "PROXY host:port" - * - * for using the proxy server [:host:] on port [:port:]. - * - * A configuration can contain several configuration elements - * separated by semicolons, e.g. - * - * "PROXY host:port; PROXY host2:port2; DIRECT" - * - * The static function [findProxyFromEnvironment] on this class can - * be used to implement proxy server resolving based on environment - * variables. - */ + /// Sets the function used to resolve the proxy server to be used for + /// opening a HTTP connection to the specified `url`. If this + /// function is not set, direct connections will always be used. + /// + /// The string returned by [f] must be in the format used by browser + /// PAC (proxy auto-config) scripts. That is either + /// + /// "DIRECT" + /// + /// for using a direct connection or + /// + /// "PROXY host:port" + /// + /// for using the proxy server [:host:] on port [:port:]. + /// + /// A configuration can contain several configuration elements + /// separated by semicolons, e.g. + /// + /// "PROXY host:port; PROXY host2:port2; DIRECT" + /// + /// The static function [findProxyFromEnvironment] on this class can + /// be used to implement proxy server resolving based on environment + /// variables. set findProxy(String f(Uri url)); - /** - * Function for resolving the proxy server to be used for a HTTP - * connection from the proxy configuration specified through - * environment variables. - * - * The following environment variables are taken into account: - * - * http_proxy - * https_proxy - * no_proxy - * HTTP_PROXY - * HTTPS_PROXY - * NO_PROXY - * - * [:http_proxy:] and [:HTTP_PROXY:] specify the proxy server to use for - * http:// urls. Use the format [:hostname:port:]. If no port is used a - * default of 1080 will be used. If both are set the lower case one takes - * precedence. - * - * [:https_proxy:] and [:HTTPS_PROXY:] specify the proxy server to use for - * https:// urls. Use the format [:hostname:port:]. If no port is used a - * default of 1080 will be used. If both are set the lower case one takes - * precedence. - * - * [:no_proxy:] and [:NO_PROXY:] specify a comma separated list of - * postfixes of hostnames for which not to use the proxy - * server. E.g. the value "localhost,127.0.0.1" will make requests - * to both "localhost" and "127.0.0.1" not use a proxy. If both are set - * the lower case one takes precedence. - * - * To activate this way of resolving proxies assign this function to - * the [findProxy] property on the [HttpClient]. - * - * HttpClient client = new HttpClient(); - * client.findProxy = HttpClient.findProxyFromEnvironment; - * - * If you don't want to use the system environment you can use a - * different one by wrapping the function. - * - * HttpClient client = new HttpClient(); - * client.findProxy = (url) { - * return HttpClient.findProxyFromEnvironment( - * url, environment: {"http_proxy": ..., "no_proxy": ...}); - * } - * - * If a proxy requires authentication it is possible to configure - * the username and password as well. Use the format - * [:username:password@hostname:port:] to include the username and - * password. Alternatively the API [addProxyCredentials] can be used - * to set credentials for proxies which require authentication. - */ + /// Function for resolving the proxy server to be used for a HTTP + /// connection from the proxy configuration specified through + /// environment variables. + /// + /// The following environment variables are taken into account: + /// + /// http_proxy + /// https_proxy + /// no_proxy + /// HTTP_PROXY + /// HTTPS_PROXY + /// NO_PROXY + /// + /// [:http_proxy:] and [:HTTP_PROXY:] specify the proxy server to use for + /// http:// urls. Use the format [:hostname:port:]. If no port is used a + /// default of 1080 will be used. If both are set the lower case one takes + /// precedence. + /// + /// [:https_proxy:] and [:HTTPS_PROXY:] specify the proxy server to use for + /// https:// urls. Use the format [:hostname:port:]. If no port is used a + /// default of 1080 will be used. If both are set the lower case one takes + /// precedence. + /// + /// [:no_proxy:] and [:NO_PROXY:] specify a comma separated list of + /// postfixes of hostnames for which not to use the proxy + /// server. E.g. the value "localhost,127.0.0.1" will make requests + /// to both "localhost" and "127.0.0.1" not use a proxy. If both are set + /// the lower case one takes precedence. + /// + /// To activate this way of resolving proxies assign this function to + /// the [findProxy] property on the [HttpClient]. + /// + /// HttpClient client = new HttpClient(); + /// client.findProxy = HttpClient.findProxyFromEnvironment; + /// + /// If you don't want to use the system environment you can use a + /// different one by wrapping the function. + /// + /// HttpClient client = new HttpClient(); + /// client.findProxy = (url) { + /// return HttpClient.findProxyFromEnvironment( + /// url, environment: {"http_proxy": ..., "no_proxy": ...}); + /// } + /// + /// If a proxy requires authentication it is possible to configure + /// the username and password as well. Use the format + /// [:username:password@hostname:port:] to include the username and + /// password. Alternatively the API [addProxyCredentials] can be used + /// to set credentials for proxies which require authentication. static String findProxyFromEnvironment(Uri url, {Map<String, String> environment}) { HttpOverrides overrides = HttpOverrides.current; @@ -1597,54 +1371,48 @@ return overrides.findProxyFromEnvironment(url, environment); } - /** - * Sets the function to be called when a proxy is requesting - * authentication. Information on the proxy in use and the security - * realm for the authentication are passed in the arguments `host`, - * `port` and `realm`. - * - * The function returns a [Future] which should complete when the - * authentication has been resolved. If credentials cannot be - * provided the [Future] should complete with [:false:]. If - * credentials are available the function should add these using - * [addProxyCredentials] before completing the [Future] with the value - * [:true:]. - * - * If the [Future] completes with [:true:] the request will be retried - * using the updated credentials. Otherwise response processing will - * continue normally. - */ + /// Sets the function to be called when a proxy is requesting + /// authentication. Information on the proxy in use and the security + /// realm for the authentication are passed in the arguments `host`, + /// `port` and `realm`. + /// + /// The function returns a [Future] which should complete when the + /// authentication has been resolved. If credentials cannot be + /// provided the [Future] should complete with [:false:]. If + /// credentials are available the function should add these using + /// [addProxyCredentials] before completing the [Future] with the value + /// [:true:]. + /// + /// If the [Future] completes with [:true:] the request will be retried + /// using the updated credentials. Otherwise response processing will + /// continue normally. set authenticateProxy( Future<bool> f(String host, int port, String scheme, String realm)); - /** - * Add credentials to be used for authorizing HTTP proxies. - */ + /// Add credentials to be used for authorizing HTTP proxies. void addProxyCredentials( String host, int port, String realm, HttpClientCredentials credentials); - /** - * Sets a callback that will decide whether to accept a secure connection - * with a server certificate that cannot be authenticated by any of our - * trusted root certificates. - * - * When an secure HTTP request if made, using this HttpClient, and the - * server returns a server certificate that cannot be authenticated, the - * callback is called asynchronously with the [X509Certificate] object and - * the server's hostname and port. If the value of [badCertificateCallback] - * is [:null:], the bad certificate is rejected, as if the callback - * returned [:false:] - * - * If the callback returns true, the secure connection is accepted and the - * [:Future<HttpClientRequest>:] that was returned from the call making the - * request completes with a valid HttpRequest object. If the callback returns - * false, the [:Future<HttpClientRequest>:] completes with an exception. - * - * If a bad certificate is received on a connection attempt, the library calls - * the function that was the value of badCertificateCallback at the time - * the request is made, even if the value of badCertificateCallback - * has changed since then. - */ + /// Sets a callback that will decide whether to accept a secure connection + /// with a server certificate that cannot be authenticated by any of our + /// trusted root certificates. + /// + /// When an secure HTTP request if made, using this HttpClient, and the + /// server returns a server certificate that cannot be authenticated, the + /// callback is called asynchronously with the [X509Certificate] object and + /// the server's hostname and port. If the value of [badCertificateCallback] + /// is [:null:], the bad certificate is rejected, as if the callback + /// returned [:false:] + /// + /// If the callback returns true, the secure connection is accepted and the + /// [:Future<HttpClientRequest>:] that was returned from the call making the + /// request completes with a valid HttpRequest object. If the callback returns + /// false, the [:Future<HttpClientRequest>:] completes with an exception. + /// + /// If a bad certificate is received on a connection attempt, the library calls + /// the function that was the value of badCertificateCallback at the time + /// the request is made, even if the value of badCertificateCallback + /// has changed since then. set badCertificateCallback( bool callback(X509Certificate cert, String host, int port)); @@ -1656,84 +1424,72 @@ /// closed connections will receive an error event to indicate that the client /// was shut down. In both cases trying to establish a new connection after /// calling [close] will throw an exception. - void close({bool force: false}); + void close({bool force = false}); } -/** - * HTTP request for a client connection. - * - * To set up a request, set the headers using the headers property - * provided in this class and write the data to the body of the request. - * HttpClientRequest is an [IOSink]. Use the methods from IOSink, - * such as writeCharCode(), to write the body of the HTTP - * request. When one of the IOSink methods is used for the first - * time, the request header is sent. Calling any methods that - * change the header after it is sent throws an exception. - * - * When writing string data through the [IOSink] the - * encoding used is determined from the "charset" parameter of - * the "Content-Type" header. - * - * HttpClientRequest request = ... - * request.headers.contentType - * = new ContentType("application", "json", charset: "utf-8"); - * request.write(...); // Strings written will be UTF-8 encoded. - * - * If no charset is provided the default of ISO-8859-1 (Latin 1) is - * be used. - * - * HttpClientRequest request = ... - * request.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); - * request.write(...); // Strings written will be ISO-8859-1 encoded. - * - * An exception is thrown if you use an unsupported encoding and the - * `write()` method being used takes a string parameter. - */ +/// HTTP request for a client connection. +/// +/// To set up a request, set the headers using the headers property +/// provided in this class and write the data to the body of the request. +/// HttpClientRequest is an [IOSink]. Use the methods from IOSink, +/// such as writeCharCode(), to write the body of the HTTP +/// request. When one of the IOSink methods is used for the first +/// time, the request header is sent. Calling any methods that +/// change the header after it is sent throws an exception. +/// +/// When writing string data through the [IOSink] the +/// encoding used is determined from the "charset" parameter of +/// the "Content-Type" header. +/// +/// HttpClientRequest request = ... +/// request.headers.contentType +/// = new ContentType("application", "json", charset: "utf-8"); +/// request.write(...); // Strings written will be UTF-8 encoded. +/// +/// If no charset is provided the default of ISO-8859-1 (Latin 1) is +/// be used. +/// +/// HttpClientRequest request = ... +/// request.headers.add(HttpHeaders.CONTENT_TYPE, "text/plain"); +/// request.write(...); // Strings written will be ISO-8859-1 encoded. +/// +/// An exception is thrown if you use an unsupported encoding and the +/// `write()` method being used takes a string parameter. abstract class HttpClientRequest implements IOSink { - /** - * Gets and sets the requested persistent connection state. - * - * The default value is [:true:]. - */ + /// Gets and sets the requested persistent connection state. + /// + /// The default value is [:true:]. bool persistentConnection; - /** - * Set this property to [:true:] if this request should - * automatically follow redirects. The default is [:true:]. - * - * Automatic redirect will only happen for "GET" and "HEAD" requests - * and only for the status codes [:HttpStatus.MOVED_PERMANENTLY:] - * (301), [:HttpStatus.FOUND:] (302), - * [:HttpStatus.MOVED_TEMPORARILY:] (302, alias for - * [:HttpStatus.FOUND:]), [:HttpStatus.SEE_OTHER:] (303) and - * [:HttpStatus.TEMPORARY_REDIRECT:] (307). For - * [:HttpStatus.SEE_OTHER:] (303) automatic redirect will also happen - * for "POST" requests with the method changed to "GET" when - * following the redirect. - * - * All headers added to the request will be added to the redirection - * request(s). However, any body send with the request will not be - * part of the redirection request(s). - */ + /// Set this property to [:true:] if this request should + /// automatically follow redirects. The default is [:true:]. + /// + /// Automatic redirect will only happen for "GET" and "HEAD" requests + /// and only for the status codes [:HttpStatus.MOVED_PERMANENTLY:] + /// (301), [:HttpStatus.FOUND:] (302), + /// [:HttpStatus.MOVED_TEMPORARILY:] (302, alias for + /// [:HttpStatus.FOUND:]), [:HttpStatus.SEE_OTHER:] (303) and + /// [:HttpStatus.TEMPORARY_REDIRECT:] (307). For + /// [:HttpStatus.SEE_OTHER:] (303) automatic redirect will also happen + /// for "POST" requests with the method changed to "GET" when + /// following the redirect. + /// + /// All headers added to the request will be added to the redirection + /// request(s). However, any body send with the request will not be + /// part of the redirection request(s). bool followRedirects; - /** - * Set this property to the maximum number of redirects to follow - * when [followRedirects] is `true`. If this number is exceeded - * an error event will be added with a [RedirectException]. - * - * The default value is 5. - */ + /// Set this property to the maximum number of redirects to follow + /// when [followRedirects] is `true`. If this number is exceeded + /// an error event will be added with a [RedirectException]. + /// + /// The default value is 5. int maxRedirects; - /** - * The method of the request. - */ + /// The method of the request. String get method; - /** - * The uri of the request. - */ + /// The uri of the request. Uri get uri; /// Gets and sets the content length of the request. @@ -1742,28 +1498,22 @@ /// -1, which is also the default. int contentLength; - /** - * Gets or sets if the [HttpClientRequest] should buffer output. - * - * Default value is `true`. - * - * __Note__: Disabling buffering of the output can result in very poor - * performance, when writing many small chunks. - */ + /// Gets or sets if the [HttpClientRequest] should buffer output. + /// + /// Default value is `true`. + /// + /// __Note__: Disabling buffering of the output can result in very poor + /// performance, when writing many small chunks. bool bufferOutput; - /** - * Returns the client request headers. - * - * The client request headers can be modified until the client - * request body is written to or closed. After that they become - * immutable. - */ + /// Returns the client request headers. + /// + /// The client request headers can be modified until the client + /// request body is written to or closed. After that they become + /// immutable. HttpHeaders get headers; - /** - * Cookies to present to the server (in the 'cookie' header). - */ + /// Cookies to present to the server (in the 'cookie' header). List<Cookie> get cookies; /// A [HttpClientResponse] future that will complete once the response is @@ -1773,9 +1523,7 @@ /// complete with an error. Future<HttpClientResponse> get done; - /** - * Close the request for input. Returns the value of [done]. - */ + /// Close the request for input. Returns the value of [done]. Future<HttpClientResponse> close(); /// Gets information about the client connection. @@ -1784,187 +1532,145 @@ HttpConnectionInfo get connectionInfo; } -/** - * HTTP response for a client connection. - * - * The body of a [HttpClientResponse] object is a - * [Stream] of data from the server. Listen to the body to handle - * the data and be notified when the entire body is received. - * - * new HttpClient().get('localhost', 80, '/file.txt') - * .then((HttpClientRequest request) => request.close()) - * .then((HttpClientResponse response) { - * response.transform(utf8.decoder).listen((contents) { - * // handle data - * }); - * }); - */ +/// HTTP response for a client connection. +/// +/// The body of a [HttpClientResponse] object is a +/// [Stream] of data from the server. Listen to the body to handle +/// the data and be notified when the entire body is received. +/// +/// new HttpClient().get('localhost', 80, '/file.txt') +/// .then((HttpClientRequest request) => request.close()) +/// .then((HttpClientResponse response) { +/// response.transform(utf8.decoder).listen((contents) { +/// // handle data +/// }); +/// }); abstract class HttpClientResponse implements Stream<List<int>> { - /** - * Returns the status code. - * - * The status code must be set before the body is written - * to. Setting the status code after writing to the body will throw - * a `StateError`. - */ + /// Returns the status code. + /// + /// The status code must be set before the body is written + /// to. Setting the status code after writing to the body will throw + /// a `StateError`. int get statusCode; - /** - * Returns the reason phrase associated with the status code. - * - * The reason phrase must be set before the body is written - * to. Setting the reason phrase after writing to the body will throw - * a `StateError`. - */ + /// Returns the reason phrase associated with the status code. + /// + /// The reason phrase must be set before the body is written + /// to. Setting the reason phrase after writing to the body will throw + /// a `StateError`. String get reasonPhrase; - /** - * Returns the content length of the response body. Returns -1 if the size of - * the response body is not known in advance. - * - * If the content length needs to be set, it must be set before the - * body is written to. Setting the reason phrase after writing to - * the body will throw a `StateError`. - */ + /// Returns the content length of the response body. Returns -1 if the size of + /// the response body is not known in advance. + /// + /// If the content length needs to be set, it must be set before the + /// body is written to. Setting the reason phrase after writing to + /// the body will throw a `StateError`. int get contentLength; - /** - * Gets the persistent connection state returned by the server. - * - * if the persistent connection state needs to be set, it must be - * set before the body is written to. Setting the reason phrase - * after writing to the body will throw a `StateError`. - */ + /// Gets the persistent connection state returned by the server. + /// + /// if the persistent connection state needs to be set, it must be + /// set before the body is written to. Setting the reason phrase + /// after writing to the body will throw a `StateError`. bool get persistentConnection; - /** - * Returns whether the status code is one of the normal redirect - * codes [HttpStatus.MOVED_PERMANENTLY], [HttpStatus.FOUND], - * [HttpStatus.MOVED_TEMPORARILY], [HttpStatus.SEE_OTHER] and - * [HttpStatus.TEMPORARY_REDIRECT]. - */ + /// Returns whether the status code is one of the normal redirect + /// codes [HttpStatus.MOVED_PERMANENTLY], [HttpStatus.FOUND], + /// [HttpStatus.MOVED_TEMPORARILY], [HttpStatus.SEE_OTHER] and + /// [HttpStatus.TEMPORARY_REDIRECT]. bool get isRedirect; - /** - * Returns the series of redirects this connection has been through. The - * list will be empty if no redirects were followed. [redirects] will be - * updated both in the case of an automatic and a manual redirect. - */ + /// Returns the series of redirects this connection has been through. The + /// list will be empty if no redirects were followed. [redirects] will be + /// updated both in the case of an automatic and a manual redirect. List<RedirectInfo> get redirects; - /** - * Redirects this connection to a new URL. The default value for - * [method] is the method for the current request. The default value - * for [url] is the value of the [HttpHeaders.LOCATION] header of - * the current response. All body data must have been read from the - * current response before calling [redirect]. - * - * All headers added to the request will be added to the redirection - * request. However, any body sent with the request will not be - * part of the redirection request. - * - * If [followLoops] is set to [:true:], redirect will follow the redirect, - * even if the URL was already visited. The default value is [:false:]. - * - * The method will ignore [HttpClientRequest.maxRedirects] - * and will always perform the redirect. - */ + /// Redirects this connection to a new URL. The default value for + /// [method] is the method for the current request. The default value + /// for [url] is the value of the [HttpHeaders.LOCATION] header of + /// the current response. All body data must have been read from the + /// current response before calling [redirect]. + /// + /// All headers added to the request will be added to the redirection + /// request. However, any body sent with the request will not be + /// part of the redirection request. + /// + /// If [followLoops] is set to [:true:], redirect will follow the redirect, + /// even if the URL was already visited. The default value is [:false:]. + /// + /// The method will ignore [HttpClientRequest.maxRedirects] + /// and will always perform the redirect. Future<HttpClientResponse> redirect( [String method, Uri url, bool followLoops]); - /** - * Returns the client response headers. - * - * The client response headers are immutable. - */ + /// Returns the client response headers. + /// + /// The client response headers are immutable. HttpHeaders get headers; - /** - * Detach the underlying socket from the HTTP client. When the - * socket is detached the HTTP client will no longer perform any - * operations on it. - * - * This is normally used when a HTTP upgrade is negotiated and the - * communication should continue with a different protocol. - */ + /// Detach the underlying socket from the HTTP client. When the + /// socket is detached the HTTP client will no longer perform any + /// operations on it. + /// + /// This is normally used when a HTTP upgrade is negotiated and the + /// communication should continue with a different protocol. Future<Socket> detachSocket(); - /** - * Cookies set by the server (from the 'set-cookie' header). - */ + /// Cookies set by the server (from the 'set-cookie' header). List<Cookie> get cookies; - /** - * Returns the certificate of the HTTPS server providing the response. - * Returns null if the connection is not a secure TLS or SSL connection. - */ + /// Returns the certificate of the HTTPS server providing the response. + /// Returns null if the connection is not a secure TLS or SSL connection. X509Certificate get certificate; - /** - * Gets information about the client connection. Returns [:null:] if the socket - * is not available. - */ + /// Gets information about the client connection. Returns [:null:] if the socket + /// is not available. HttpConnectionInfo get connectionInfo; } abstract class HttpClientCredentials {} -/** - * Represents credentials for basic authentication. - */ +/// Represents credentials for basic authentication. abstract class HttpClientBasicCredentials extends HttpClientCredentials { factory HttpClientBasicCredentials(String username, String password) => - new _HttpClientBasicCredentials(username, password); + _HttpClientBasicCredentials(username, password); } -/** - * Represents credentials for digest authentication. Digest - * authentication is only supported for servers using the MD5 - * algorithm and quality of protection (qop) of either "none" or - * "auth". - */ +/// Represents credentials for digest authentication. Digest +/// authentication is only supported for servers using the MD5 +/// algorithm and quality of protection (qop) of either "none" or +/// "auth". abstract class HttpClientDigestCredentials extends HttpClientCredentials { factory HttpClientDigestCredentials(String username, String password) => - new _HttpClientDigestCredentials(username, password); + _HttpClientDigestCredentials(username, password); } -/** - * Information about an [HttpRequest], [HttpResponse], [HttpClientRequest], or - * [HttpClientResponse] connection. - */ +/// Information about an [HttpRequest], [HttpResponse], [HttpClientRequest], or +/// [HttpClientResponse] connection. abstract class HttpConnectionInfo { InternetAddress get remoteAddress; int get remotePort; int get localPort; } -/** - * Redirect information. - */ +/// Redirect information. abstract class RedirectInfo { - /** - * Returns the status code used for the redirect. - */ + /// Returns the status code used for the redirect. int get statusCode; - /** - * Returns the method used for the redirect. - */ + /// Returns the method used for the redirect. String get method; - /** - * Returns the location for the redirect. - */ + /// Returns the location for the redirect. Uri get location; } -/** - * When detaching a socket from either the [:HttpServer:] or the - * [:HttpClient:] due to a HTTP connection upgrade there might be - * unparsed data already read from the socket. This unparsed data - * together with the detached socket is returned in an instance of - * this class. - */ +/// When detaching a socket from either the [:HttpServer:] or the +/// [:HttpClient:] due to a HTTP connection upgrade there might be +/// unparsed data already read from the socket. This unparsed data +/// together with the detached socket is returned in an instance of +/// this class. abstract class DetachedSocket { Socket get socket; List<int> get unparsedData;
diff --git a/lib/src/char_code.dart b/lib/src/char_code.dart index b219ae6..75c8800 100644 --- a/lib/src/char_code.dart +++ b/lib/src/char_code.dart
@@ -5,18 +5,18 @@ // Global constants. class Const { // Bytes for "HTTP". - static const HTTP = const [72, 84, 84, 80]; + static const HTTP = [72, 84, 84, 80]; // Bytes for "HTTP/1.". - static const HTTP1DOT = const [72, 84, 84, 80, 47, 49, 46]; + static const HTTP1DOT = [72, 84, 84, 80, 47, 49, 46]; // Bytes for "HTTP/1.0". - static const HTTP10 = const [72, 84, 84, 80, 47, 49, 46, 48]; + static const HTTP10 = [72, 84, 84, 80, 47, 49, 46, 48]; // Bytes for "HTTP/1.1". - static const HTTP11 = const [72, 84, 84, 80, 47, 49, 46, 49]; + static const HTTP11 = [72, 84, 84, 80, 47, 49, 46, 49]; static const bool T = true; static const bool F = false; // Lookup-map for the following characters: '()<>@,;:\\"/[]?={} \t'. - static const SEPARATOR_MAP = const [ + static const SEPARATOR_MAP = [ F, F, F, F, F, F, F, F, F, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, // F, F, F, F, F, F, F, F, T, F, T, F, F, F, F, F, T, T, F, F, T, F, F, T, // F, F, F, F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, F, F, F, F, F, //
diff --git a/lib/src/crypto.dart b/lib/src/crypto.dart index 5b2eab9..3368100 100644 --- a/lib/src/crypto.dart +++ b/lib/src/crypto.dart
@@ -22,7 +22,7 @@ // -1 : '\r' or '\n' // 0 : = (Padding character). // >0 : Base 64 alphabet index of given byte. - static const List<int> _decodeTable = const [ + static const List<int> _decodeTable = [ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -1, -2, -2, // -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, // -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, 62, -2, 63, // @@ -41,10 +41,10 @@ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 ]; - static final Random _rng = new Random.secure(); + static final Random _rng = Random.secure(); static Uint8List getRandomBytes(int count) { - final Uint8List result = new Uint8List(count); + final Uint8List result = Uint8List(count); for (int i = 0; i < count; i++) { result[i] = _rng.nextInt(0xff); } @@ -52,7 +52,7 @@ } static String bytesToHex(List<int> bytes) { - var result = new StringBuffer(); + var result = StringBuffer(); for (var part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); } @@ -75,7 +75,7 @@ if (addLineSeparator) { outputLen += ((outputLen - 1) ~/ LINE_LENGTH) << 1; } - List<int> out = new List<int>(outputLen); + List<int> out = List<int>.filled(outputLen, null); // Encode 24 bit chunks. int j = 0, i = 0, c = 0; @@ -112,14 +112,14 @@ out[j++] = PAD; } - return new String.fromCharCodes(out); + return String.fromCharCodes(out); } static List<int> base64StringToBytes(String input, [bool ignoreInvalidCharacters = true]) { int len = input.length; if (len == 0) { - return new List<int>(0); + return const <int>[]; } // Count '\r', '\n' and illegal characters, For illegal characters, @@ -130,13 +130,13 @@ if (c < 0) { extrasLen++; if (c == -2 && !ignoreInvalidCharacters) { - throw new FormatException('Invalid character: ${input[i]}'); + throw FormatException('Invalid character: ${input[i]}'); } } } if ((len - extrasLen) % 4 != 0) { - throw new FormatException('''Size of Base 64 characters in Input + throw FormatException('''Size of Base 64 characters in Input must be a multiple of 4. Input: $input'''); } @@ -148,7 +148,7 @@ if (currentCodeUnit == PAD) padLength++; } int outputLen = (((len - extrasLen) * 6) >> 3) - padLength; - List<int> out = new List<int>(outputLen); + List<int> out = List<int>.filled(outputLen, null); for (int i = 0, o = 0; o < outputLen;) { // Accumulate 4 valid 6 bit Base 64 characters into an int. @@ -192,15 +192,14 @@ HashBase( this._chunkSizeInWords, this._digestSizeInWords, this._bigEndianWords) : _pendingData = [] { - _currentChunk = new List(_chunkSizeInWords); - _h = new List(_digestSizeInWords); + _currentChunk = List.filled(_chunkSizeInWords, null); + _h = List.filled(_digestSizeInWords, null); } // Update the hasher with more data. add(List<int> data) { if (_digestCalled) { - throw new StateError( - 'Hash update method called after digest was retrieved'); + throw StateError('Hash update method called after digest was retrieved'); } _lengthInBytes += data.length; _pendingData.addAll(data); @@ -270,7 +269,7 @@ // Convert a 32-bit word to four bytes. List<int> _wordToBytes(int word) { - List<int> bytes = new List(_BYTES_PER_WORD); + List<int> bytes = List.filled(_BYTES_PER_WORD, null); bytes[0] = (word >> (_bigEndianWords ? 24 : 0)) & _MASK_8; bytes[1] = (word >> (_bigEndianWords ? 16 : 8)) & _MASK_8; bytes[2] = (word >> (_bigEndianWords ? 8 : 16)) & _MASK_8; @@ -327,10 +326,10 @@ // Returns a new instance of this Hash. MD5 newInstance() { - return new MD5(); + return MD5(); } - static const _k = const [ + static const _k = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, // 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, // 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, // @@ -344,7 +343,7 @@ 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]; - static const _r = const [ + static const _r = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, // 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, // 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, //
diff --git a/lib/src/http_date.dart b/lib/src/http_date.dart index 93c4def..e84216c 100644 --- a/lib/src/http_date.dart +++ b/lib/src/http_date.dart
@@ -4,10 +4,8 @@ import 'http_exception.dart'; -/** - * Utility functions for working with dates with HTTP specific date - * formats. - */ +/// Utility functions for working with dates with HTTP specific date +/// formats. class HttpDate { // From RFC-2616 section "3.3.1 Full Date", // http://tools.ietf.org/html/rfc2616#section-3.3.1 @@ -32,14 +30,12 @@ // | "May" | "Jun" | "Jul" | "Aug" // | "Sep" | "Oct" | "Nov" | "Dec" - /** - * Format a date according to - * [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), - * e.g. `Thu, 1 Jan 1970 00:00:00 GMT`. - */ + /// Format a date according to + /// [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), + /// e.g. `Thu, 1 Jan 1970 00:00:00 GMT`. static String format(DateTime date) { - const List wkday = const ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; - const List month = const [ + const List wkday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + const List month = [ "Jan", "Feb", "Mar", @@ -55,7 +51,7 @@ ]; DateTime d = date.toUtc(); - StringBuffer sb = new StringBuffer() + StringBuffer sb = StringBuffer() ..write(wkday[d.weekday - 1]) ..write(", ") ..write(d.day <= 9 ? "0" : "") @@ -74,24 +70,21 @@ return sb.toString(); } - /** - * Parse a date string in either of the formats - * [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), - * [RFC-850](http://tools.ietf.org/html/rfc850 "RFC-850") or - * ANSI C's asctime() format. These formats are listed here. - * - * Thu, 1 Jan 1970 00:00:00 GMT - * Thursday, 1-Jan-1970 00:00:00 GMT - * Thu Jan 1 00:00:00 1970 - * - * For more information see [RFC-2616 section - * 3.1.1](http://tools.ietf.org/html/rfc2616#section-3.3.1 - * "RFC-2616 section 3.1.1"). - */ + /// Parse a date string in either of the formats + /// [RFC-1123](http://tools.ietf.org/html/rfc1123 "RFC-1123"), + /// [RFC-850](http://tools.ietf.org/html/rfc850 "RFC-850") or + /// ANSI C's asctime() format. These formats are listed here. + /// + /// Thu, 1 Jan 1970 00:00:00 GMT + /// Thursday, 1-Jan-1970 00:00:00 GMT + /// Thu Jan 1 00:00:00 1970 + /// + /// For more information see + /// [RFC-2616 section 3.1.1](https://tools.ietf.org/html/rfc2616#section-3.3.1). static DateTime parse(String date) { final int SP = 32; - const List wkdays = const ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; - const List weekdays = const [ + const List wkdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + const List weekdays = [ "Monday", "Tuesday", "Wednesday", @@ -100,7 +93,7 @@ "Saturday", "Sunday" ]; - const List months = const [ + const List months = [ "Jan", "Feb", "Mar", @@ -125,11 +118,11 @@ void expect(String s) { if (date.length - index < s.length) { - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } String tmp = date.substring(index, index + s.length); if (tmp != s) { - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } index += s.length; } @@ -140,7 +133,7 @@ int pos = date.indexOf(",", index); if (pos == -1) { int pos = date.indexOf(" ", index); - if (pos == -1) throw new HttpException("Invalid HTTP date $date"); + if (pos == -1) throw HttpException("Invalid HTTP date $date"); tmp = date.substring(index, pos); index = pos + 1; weekday = wkdays.indexOf(tmp); @@ -162,17 +155,17 @@ return weekday; } } - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } int expectMonth(String separator) { int pos = date.indexOf(separator, index); - if (pos - index != 3) throw new HttpException("Invalid HTTP date $date"); + if (pos - index != 3) throw HttpException("Invalid HTTP date $date"); tmp = date.substring(index, pos); index = pos + 1; int month = months.indexOf(tmp); if (month != -1) return month; - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } int expectNum(String separator) { @@ -188,13 +181,13 @@ int value = int.parse(tmp); return value; } on FormatException { - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } } void expectEnd() { if (index != date.length) { - throw new HttpException("Invalid HTTP date $date"); + throw HttpException("Invalid HTTP date $date"); } } @@ -224,6 +217,6 @@ expect("GMT"); } expectEnd(); - return new DateTime.utc(year, month + 1, day, hours, minutes, seconds, 0); + return DateTime.utc(year, month + 1, day, hours, minutes, seconds, 0); } }
diff --git a/lib/src/http_exception.dart b/lib/src/http_exception.dart index 49bd25d..d67472e 100644 --- a/lib/src/http_exception.dart +++ b/lib/src/http_exception.dart
@@ -11,7 +11,9 @@ const HttpException(this.message, {this.uri}); String toString() { - var b = new StringBuffer()..write('HttpException: ')..write(message); + var b = StringBuffer() + ..write('HttpException: ') + ..write(message); if (uri != null) { b.write(', uri = $uri'); }
diff --git a/lib/src/http_headers_impl.dart b/lib/src/http_headers_impl.dart index 5dcffce..9f2dff7 100644 --- a/lib/src/http_headers_impl.dart +++ b/lib/src/http_headers_impl.dart
@@ -28,9 +28,9 @@ final int _defaultPortForScheme; HttpHeadersImpl(this.protocolVersion, - {int defaultPortForScheme: HttpClient.DEFAULT_HTTP_PORT, + {int defaultPortForScheme = HttpClient.DEFAULT_HTTP_PORT, HttpHeadersImpl initialHeaders}) - : headers = new HashMap<String, List<String>>(), + : headers = HashMap<String, List<String>>(), _defaultPortForScheme = defaultPortForScheme { if (initialHeaders != null) { initialHeaders.headers.forEach((name, value) => headers[name] = value); @@ -53,7 +53,7 @@ List<String> values = headers[name]; if (values == null) return null; if (values.length > 1) { - throw new HttpException("More than one value for header $name"); + throw HttpException("More than one value for header $name"); } return values[0]; } @@ -112,13 +112,13 @@ } void noFolding(String name) { - _noFoldingHeaders ??= new List<String>(); + _noFoldingHeaders ??= <String>[]; _noFoldingHeaders.add(name); } bool get persistentConnection => _persistentConnection; - void set persistentConnection(bool persistentConnection) { + set persistentConnection(bool persistentConnection) { _checkMutable(); if (persistentConnection == _persistentConnection) return; if (persistentConnection) { @@ -126,7 +126,7 @@ remove(HttpHeaders.CONNECTION, "close"); } else { if (_contentLength == -1) { - throw new HttpException( + throw HttpException( "Trying to set 'Connection: Keep-Alive' on HTTP 1.0 headers with " "no ContentLength"); } @@ -144,12 +144,12 @@ int get contentLength => _contentLength; - void set contentLength(int contentLength) { + set contentLength(int contentLength) { _checkMutable(); if (protocolVersion == "1.0" && persistentConnection && contentLength == -1) { - throw new HttpException( + throw HttpException( "Trying to clear ContentLength on HTTP 1.0 headers with " "'Connection: Keep-Alive' set"); } @@ -168,10 +168,10 @@ bool get chunkedTransferEncoding => _chunkedTransferEncoding; - void set chunkedTransferEncoding(bool chunkedTransferEncoding) { + set chunkedTransferEncoding(bool chunkedTransferEncoding) { _checkMutable(); if (chunkedTransferEncoding && protocolVersion == "1.0") { - throw new HttpException( + throw HttpException( "Trying to set 'Transfer-Encoding: Chunked' on HTTP 1.0 headers"); } if (chunkedTransferEncoding == _chunkedTransferEncoding) return; @@ -191,7 +191,7 @@ String get host => _host; - void set host(String host) { + set host(String host) { _checkMutable(); _host = host; _updateHostHeader(); @@ -199,7 +199,7 @@ int get port => _port; - void set port(int port) { + set port(int port) { _checkMutable(); _port = port; _updateHostHeader(); @@ -217,7 +217,7 @@ return null; } - void set ifModifiedSince(DateTime ifModifiedSince) { + set ifModifiedSince(DateTime ifModifiedSince) { _checkMutable(); // Format "ifModifiedSince" header with date in Greenwich Mean Time (GMT). String formatted = HttpDate.format(ifModifiedSince.toUtc()); @@ -236,7 +236,7 @@ return null; } - void set date(DateTime date) { + set date(DateTime date) { _checkMutable(); // Format "DateTime" header with date in Greenwich Mean Time (GMT). String formatted = HttpDate.format(date.toUtc()); @@ -255,7 +255,7 @@ return null; } - void set expires(DateTime expires) { + set expires(DateTime expires) { _checkMutable(); // Format "Expires" header with date in Greenwich Mean Time (GMT). String formatted = HttpDate.format(expires.toUtc()); @@ -271,7 +271,7 @@ } } - void set contentType(ContentType contentType) { + set contentType(ContentType contentType) { _checkMutable(); _set(HttpHeaders.CONTENT_TYPE, contentType.toString()); } @@ -345,7 +345,7 @@ } else if (value is String) { contentLength = int.parse(value); } else { - throw new HttpException("Unexpected type for header named $name"); + throw HttpException("Unexpected type for header named $name"); } } @@ -363,7 +363,7 @@ } else if (value is String) { _set(HttpHeaders.DATE, value); } else { - throw new HttpException("Unexpected type for header named $name"); + throw HttpException("Unexpected type for header named $name"); } } @@ -373,7 +373,7 @@ } else if (value is String) { _set(HttpHeaders.EXPIRES, value); } else { - throw new HttpException("Unexpected type for header named $name"); + throw HttpException("Unexpected type for header named $name"); } } @@ -383,7 +383,7 @@ } else if (value is String) { _set(HttpHeaders.IF_MODIFIED_SINCE, value); } else { - throw new HttpException("Unexpected type for header named $name"); + throw HttpException("Unexpected type for header named $name"); } } @@ -411,7 +411,7 @@ } _set(HttpHeaders.HOST, value); } else { - throw new HttpException("Unexpected type for header named $name"); + throw HttpException("Unexpected type for header named $name"); } } @@ -432,7 +432,7 @@ void _addValue(String name, Object value) { List<String> values = headers[name]; if (values == null) { - values = new List<String>(); + values = <String>[]; headers[name] = values; } if (value is DateTime) { @@ -446,13 +446,13 @@ void _set(String name, String value) { assert(name == _validateField(name)); - List<String> values = new List<String>(); + List<String> values = <String>[]; headers[name] = values; values.add(value); } _checkMutable() { - if (!mutable) throw new HttpException("HTTP headers are not mutable"); + if (!mutable) throw HttpException("HTTP headers are not mutable"); } _updateHostHeader() { @@ -462,7 +462,7 @@ _foldHeader(String name) { if (name == HttpHeaders.SET_COOKIE || - (_noFoldingHeaders != null && _noFoldingHeaders.indexOf(name) != -1)) { + (_noFoldingHeaders != null && _noFoldingHeaders.contains(name))) { return false; } return true; @@ -501,16 +501,21 @@ } String toString() { - StringBuffer sb = new StringBuffer(); + StringBuffer sb = StringBuffer(); headers.forEach((String name, List<String> values) { - sb..write(name)..write(": "); + sb + ..write(name) + ..write(": "); bool fold = _foldHeader(name); for (int i = 0; i < values.length; i++) { if (i > 0) { if (fold) { sb.write(", "); } else { - sb..write("\n")..write(name)..write(": "); + sb + ..write("\n") + ..write(name) + ..write(": "); } } sb.write(values[i]); @@ -522,7 +527,7 @@ List<Cookie> parseCookies() { // Parse a Cookie header value according to the rules in RFC 6265. - var cookies = new List<Cookie>(); + var cookies = <Cookie>[]; void parseCookieString(String s) { int index = 0; @@ -572,7 +577,7 @@ skipWS(); String value = parseValue(); try { - cookies.add(new CookieImpl(name, value)); + cookies.add(CookieImpl(name, value)); } catch (_) { // Skip it, invalid cookie data. } @@ -595,7 +600,7 @@ static String _validateField(String field) { for (var i = 0; i < field.length; i++) { if (!CharCode.isTokenChar(field.codeUnitAt(i))) { - throw new FormatException( + throw FormatException( "Invalid HTTP header field name: ${jsonEncode(field)}"); } } @@ -606,7 +611,7 @@ if (value is String) { for (var i = 0; i < value.length; i++) { if (!CharCode.isValueChar(value.codeUnitAt(i))) { - throw new FormatException( + throw FormatException( "Invalid HTTP header field value: ${jsonEncode(value)}"); } } @@ -622,16 +627,16 @@ HeaderValueImpl([this._value = "", Map<String, String> parameters]) { if (parameters != null) { - _parameters = new HashMap<String, String>.from(parameters); + _parameters = HashMap<String, String>.from(parameters); } } static HeaderValueImpl parse(String value, - {String parameterSeparator: ";", + {String parameterSeparator = ";", String valueSeparator, - bool preserveBackslash: false}) { + bool preserveBackslash = false}) { // Parse the string. - var result = new HeaderValueImpl(); + var result = HeaderValueImpl(); result._parse(value, parameterSeparator, valueSeparator, preserveBackslash); return result; } @@ -639,22 +644,26 @@ String get value => _value; void _ensureParameters() { - _parameters ??= new HashMap<String, String>(); + _parameters ??= HashMap<String, String>(); } Map<String, String> get parameters { _ensureParameters(); - _unmodifiableParameters ??= new UnmodifiableMapView(_parameters); + _unmodifiableParameters ??= UnmodifiableMapView(_parameters); return _unmodifiableParameters; } String toString() { - StringBuffer sb = new StringBuffer(); + StringBuffer sb = StringBuffer(); sb.write(_value); if (parameters != null && parameters.isNotEmpty) { _parameters.forEach((String name, String value) { - sb..write("; ")..write(name)..write("=")..write(value); + sb + ..write("; ") + ..write(name) + ..write("=") + ..write(value); }); } return sb.toString(); @@ -687,7 +696,7 @@ void expect(String expected) { if (done() || s[index] != expected) { - throw new HttpException("Failed to parse header value"); + throw HttpException("Failed to parse header value"); } index++; } @@ -697,8 +706,8 @@ } void parseParameters() { - var parameters = new HashMap<String, String>(); - _parameters = new UnmodifiableMapView(parameters); + var parameters = HashMap<String, String>(); + _parameters = UnmodifiableMapView(parameters); String parseParameterName() { int start = index; @@ -716,12 +725,12 @@ String parseParameterValue() { if (!done() && s[index] == "\"") { // Parse quoted value. - StringBuffer sb = new StringBuffer(); + StringBuffer sb = StringBuffer(); index++; while (!done()) { if (s[index] == "\\") { if (index + 1 == s.length) { - throw new HttpException("Failed to parse header value"); + throw HttpException("Failed to parse header value"); } if (preserveBackslash && s[index + 1] != "\"") { sb.write(s[index]); @@ -811,7 +820,7 @@ ContentTypeImpl._(); static ContentTypeImpl parse(String value) { - var result = new ContentTypeImpl._(); + var result = ContentTypeImpl._(); result._parse(value, ";", null, false); int index = result._value.indexOf("/"); if (index == -1 || index == (result._value.length - 1)) { @@ -924,7 +933,7 @@ name = parseName(); if (done() || name.isEmpty) { - throw new HttpException("Failed to parse header value [$s]"); + throw HttpException("Failed to parse header value [$s]"); } index++; // Skip the = character. value = parseValue(); @@ -935,19 +944,30 @@ } String toString() { - StringBuffer sb = new StringBuffer(); - sb..write(name)..write("=")..write(value); + StringBuffer sb = StringBuffer(); + sb + ..write(name) + ..write("=") + ..write(value); if (expires != null) { - sb..write("; Expires=")..write(HttpDate.format(expires)); + sb + ..write("; Expires=") + ..write(HttpDate.format(expires)); } if (maxAge != null) { - sb..write("; Max-Age=")..write(maxAge); + sb + ..write("; Max-Age=") + ..write(maxAge); } if (domain != null) { - sb..write("; Domain=")..write(domain); + sb + ..write("; Domain=") + ..write(domain); } if (path != null) { - sb..write("; Path=")..write(path); + sb + ..write("; Path=") + ..write(path); } if (secure) sb.write("; Secure"); if (httpOnly) sb.write("; HttpOnly"); @@ -955,7 +975,7 @@ } void _validate() { - const SEPERATORS = const [ + const SEPERATORS = [ "(", ")", "<", @@ -976,10 +996,8 @@ ]; for (int i = 0; i < name.length; i++) { int codeUnit = name.codeUnits[i]; - if (codeUnit <= 32 || - codeUnit >= 127 || - SEPERATORS.indexOf(name[i]) >= 0) { - throw new FormatException( + if (codeUnit <= 32 || codeUnit >= 127 || SEPERATORS.contains(name[i])) { + throw FormatException( "Invalid character in cookie name, code unit: '$codeUnit'"); } } @@ -990,7 +1008,7 @@ (codeUnit >= 0x2D && codeUnit <= 0x3A) || (codeUnit >= 0x3C && codeUnit <= 0x5B) || (codeUnit >= 0x5D && codeUnit <= 0x7E))) { - throw new FormatException( + throw FormatException( "Invalid character in cookie value, code unit: '$codeUnit'"); } } @@ -999,7 +1017,7 @@ // Parse a cookie date string. DateTime parseCookieDate(String date) { - const List monthsLowerCase = const [ + const List monthsLowerCase = [ "jan", "feb", "mar", @@ -1017,7 +1035,7 @@ int position = 0; void error() { - throw new HttpException("Invalid cookie date $date"); + throw HttpException("Invalid cookie date $date"); } bool isEnd() => position == date.length; @@ -1057,18 +1075,23 @@ int toInt(String s) { int index = 0; -// ignore: empty_statements - for (; index < s.length && isDigit(s[index]); index++); + for (; index < s.length && isDigit(s[index]); index++) {} return int.parse(s.substring(0, index)); } var tokens = <String>[]; while (!isEnd()) { - while (!isEnd() && isDelimiter(date[position])) position++; + while (!isEnd() && isDelimiter(date[position])) { + position++; + } int start = position; - while (!isEnd() && isNonDelimiter(date[position])) position++; + while (!isEnd() && isNonDelimiter(date[position])) { + position++; + } tokens.add(date.substring(start, position).toLowerCase()); - while (!isEnd() && isDelimiter(date[position])) position++; + while (!isEnd() && isDelimiter(date[position])) { + position++; + } } String timeStr; @@ -1103,9 +1126,11 @@ } int year = toInt(yearStr); - if (year >= 70 && year <= 99) + if (year >= 70 && year <= 99) { year += 1900; - else if (year >= 0 && year <= 69) year += 2000; + } else if (year >= 0 && year <= 69) { + year += 2000; + } if (year < 1601) error(); int dayOfMonth = toInt(dayOfMonthStr); @@ -1122,5 +1147,5 @@ if (minute > 59) error(); if (second > 59) error(); - return new DateTime.utc(year, month, dayOfMonth, hour, minute, second, 0); + return DateTime.utc(year, month, dayOfMonth, hour, minute, second, 0); }
diff --git a/lib/src/http_impl.dart b/lib/src/http_impl.dart index d0de8b0..50f9f11 100644 --- a/lib/src/http_impl.dart +++ b/lib/src/http_impl.dart
@@ -8,7 +8,7 @@ // Start with 1024 bytes. static const int _INIT_SIZE = 1024; - static final _emptyList = new Uint8List(0); + static final _emptyList = Uint8List(0); int _length = 0; Uint8List _buffer; @@ -16,7 +16,7 @@ _CopyingBytesBuilder([int initialCapacity = 0]) : _buffer = (initialCapacity <= 0) ? _emptyList - : new Uint8List(_pow2roundup(initialCapacity)); + : Uint8List(_pow2roundup(initialCapacity)); void add(List<int> bytes) { int bytesLength = bytes.length; @@ -56,22 +56,21 @@ } else { newSize = _pow2roundup(newSize); } - var newBuffer = new Uint8List(newSize); + var newBuffer = Uint8List(newSize); newBuffer.setRange(0, _buffer.length, _buffer); _buffer = newBuffer; } Uint8List takeBytes() { if (_length == 0) return _emptyList; - var buffer = new Uint8List.view(_buffer.buffer, 0, _length); + var buffer = Uint8List.view(_buffer.buffer, 0, _length); clear(); return buffer; } Uint8List toBytes() { if (_length == 0) return _emptyList; - return new Uint8List.fromList( - new Uint8List.view(_buffer.buffer, 0, _length)); + return Uint8List.fromList(Uint8List.view(_buffer.buffer, 0, _length)); } int get length => _length; @@ -99,7 +98,7 @@ const int _OUTGOING_BUFFER_SIZE = 8 * 1024; -typedef void _BytesConsumer(List<int> bytes); +typedef _BytesConsumer = void Function(List<int> bytes); abstract class _HttpInboundMessage extends Stream<List<int>> { final HttpIncoming _incoming; @@ -166,7 +165,9 @@ var proto = headers['x-forwarded-proto']; var scheme = proto != null ? proto.first - : _httpConnection._socket is SecureSocket ? "https" : "http"; + : _httpConnection._socket is SecureSocket + ? "https" + : "http"; var hostList = headers['x-forwarded-host']; String host; if (hostList != null) { @@ -234,16 +235,16 @@ X509Certificate get certificate { var socket = _httpRequest._httpClientConnection._socket; if (socket is SecureSocket) return socket.peerCertificate; - throw new UnsupportedError("Socket is not a SecureSocket"); + throw UnsupportedError("Socket is not a SecureSocket"); } List<Cookie> get cookies { if (_cookies != null) return _cookies; - _cookies = new List<Cookie>(); + _cookies = <Cookie>[]; List<String> values = headers[HttpHeaders.SET_COOKIE]; if (values != null) { values.forEach((value) { - _cookies.add(new Cookie.fromSetCookieValue(value)); + _cookies.add(Cookie.fromSetCookieValue(value)); }); } return _cookies; @@ -274,15 +275,15 @@ if (url == null) { String location = headers.value(HttpHeaders.LOCATION); if (location == null) { - throw new StateError("Response has no Location header for redirect"); + throw StateError("Response has no Location header for redirect"); } url = Uri.parse(location); } if (followLoops != true) { for (var redirect in redirects) { if (redirect.location == url) { - return new Future.error( - new RedirectException("Redirect loop detected", redirects)); + return Future.error( + RedirectException("Redirect loop detected", redirects)); } } } @@ -291,7 +292,7 @@ .then((request) { request._responseRedirects ..addAll(this.redirects) - ..add(new _RedirectInfo(statusCode, method, url)); + ..add(_RedirectInfo(statusCode, method, url)); return request.close(); }); } @@ -303,12 +304,12 @@ // Since listening to upgraded data is 'bogus', simply close and // return empty stream subscription. _httpRequest._httpClientConnection.destroy(); - return new Stream<List<int>>.empty().listen(null, onDone: onDone); + return Stream<List<int>>.empty().listen(null, onDone: onDone); } Stream<List<int>> stream = _incoming; if (_httpClient.autoUncompress && headers.value(HttpHeaders.CONTENT_ENCODING) == "gzip") { - stream = stream.transform(gzip.decoder); + stream = gzip.decoder.bind(stream); } return stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); @@ -372,14 +373,14 @@ _AuthenticationScheme scheme, String realm) { if (proxyAuth) { if (_httpClient._authenticateProxy == null) { - return new Future.value(false); + return Future.value(false); } var proxy = _httpRequest._proxy; return _httpClient._authenticateProxy( proxy.host, proxy.port, scheme.toString(), realm); } else { if (_httpClient._authenticate == null) { - return new Future.value(false); + return Future.value(false); } return _httpClient._authenticate( _httpRequest.uri, scheme.toString(), realm); @@ -391,7 +392,7 @@ HeaderValueImpl header = HeaderValueImpl.parse(challenge[0], parameterSeparator: ","); _AuthenticationScheme scheme = - new _AuthenticationScheme.fromString(header.value); + _AuthenticationScheme.fromString(header.value); String realm = header.parameters["realm"]; // See if any matching credentials are available. @@ -452,7 +453,7 @@ class _StreamSinkImpl<T> implements StreamSink<T> { final StreamConsumer<T> _target; - final Completer _doneCompleter = new Completer(); + final Completer _doneCompleter = Completer(); StreamController<T> _controllerInstance; Completer _controllerCompleter; bool _isClosed = false; @@ -485,7 +486,7 @@ Future addStream(Stream<T> stream) { if (_isBound) { - throw new StateError("StreamSink is already bound to a stream"); + throw StateError("StreamSink is already bound to a stream"); } _isBound = true; if (_hasError) return done; @@ -504,9 +505,9 @@ Future flush() { if (_isBound) { - throw new StateError("StreamSink is bound to a stream"); + throw StateError("StreamSink is bound to a stream"); } - if (_controllerInstance == null) return new Future.value(this); + if (_controllerInstance == null) return Future.value(this); // Adding an empty stream-controller will return a future that will complete // when all data is done. _isBound = true; @@ -519,7 +520,7 @@ Future close() { if (_isBound) { - throw new StateError("StreamSink is bound to a stream"); + throw StateError("StreamSink is bound to a stream"); } if (!_isClosed) { _isClosed = true; @@ -553,14 +554,14 @@ StreamController<T> get _controller { if (_isBound) { - throw new StateError("StreamSink is bound to a stream"); + throw StateError("StreamSink is bound to a stream"); } if (_isClosed) { - throw new StateError("StreamSink is closed"); + throw StateError("StreamSink is closed"); } if (_controllerInstance == null) { - _controllerInstance = new StreamController<T>(sync: true); - _controllerCompleter = new Completer(); + _controllerInstance = StreamController<T>(sync: true); + _controllerCompleter = Completer(); _target.addStream(_controller.stream).then((_) { if (_isBound) { // A new stream takes over - forward values to that stream. @@ -596,9 +597,9 @@ Encoding get encoding => _encoding; - void set encoding(Encoding value) { + set encoding(Encoding value) { if (!_encodingMutable) { - throw new StateError("IOSink encoding is not mutable"); + throw StateError("IOSink encoding is not mutable"); } _encoding = value; } @@ -631,7 +632,7 @@ } void writeCharCode(int charCode) { - write(new String.fromCharCode(charCode)); + write(String.fromCharCode(charCode)); } } @@ -650,7 +651,7 @@ _HttpOutboundMessage(Uri uri, String protocolVersion, _HttpOutgoing outgoing, {HttpHeadersImpl initialHeaders}) : _uri = uri, - headers = new HttpHeadersImpl(protocolVersion, + headers = HttpHeadersImpl(protocolVersion, defaultPortForScheme: uri.scheme == 'https' ? HttpClient.DEFAULT_HTTPS_PORT : HttpClient.DEFAULT_HTTP_PORT, @@ -662,18 +663,18 @@ } int get contentLength => headers.contentLength; - void set contentLength(int contentLength) { + set contentLength(int contentLength) { headers.contentLength = contentLength; } bool get persistentConnection => headers.persistentConnection; - void set persistentConnection(bool p) { + set persistentConnection(bool p) { headers.persistentConnection = p; } bool get bufferOutput => _bufferOutput; - void set bufferOutput(bool bufferOutput) { - if (_outgoing.headersWritten) throw new StateError("Header already sent"); + set bufferOutput(bool bufferOutput) { + if (_outgoing.headersWritten) throw StateError("Header already sent"); _bufferOutput = bufferOutput; } @@ -726,31 +727,31 @@ bool get _isConnectionClosed => _httpRequest._httpConnection._isClosing; List<Cookie> get cookies { - _cookies ??= new List<Cookie>(); + _cookies ??= <Cookie>[]; return _cookies; } int get statusCode => _statusCode; - void set statusCode(int statusCode) { - if (_outgoing.headersWritten) throw new StateError("Header already sent"); + set statusCode(int statusCode) { + if (_outgoing.headersWritten) throw StateError("Header already sent"); _statusCode = statusCode; } String get reasonPhrase => _findReasonPhrase(statusCode); - void set reasonPhrase(String reasonPhrase) { - if (_outgoing.headersWritten) throw new StateError("Header already sent"); + set reasonPhrase(String reasonPhrase) { + if (_outgoing.headersWritten) throw StateError("Header already sent"); _reasonPhrase = reasonPhrase; } - Future redirect(Uri location, {int status: HttpStatus.MOVED_TEMPORARILY}) { - if (_outgoing.headersWritten) throw new StateError("Header already sent"); + Future redirect(Uri location, {int status = HttpStatus.MOVED_TEMPORARILY}) { + if (_outgoing.headersWritten) throw StateError("Header already sent"); statusCode = status; headers.set("location", location.toString()); return close(); } - Future<Socket> detachSocket({bool writeHeaders: true}) { - if (_outgoing.headersWritten) throw new StateError("Headers already sent"); + Future<Socket> detachSocket({bool writeHeaders = true}) { + if (_outgoing.headersWritten) throw StateError("Headers already sent"); deadline = null; // Be sure to stop any deadline. var future = _httpRequest._httpConnection.detachSocket(); if (writeHeaders) { @@ -774,18 +775,18 @@ Duration get deadline => _deadline; - void set deadline(Duration d) { + set deadline(Duration d) { if (_deadlineTimer != null) _deadlineTimer.cancel(); _deadline = d; if (_deadline == null) return; - _deadlineTimer = new Timer(_deadline, () { + _deadlineTimer = Timer(_deadline, () { _httpRequest._httpConnection.destroy(); }); } void _writeHeader() { - BytesBuilder buffer = new _CopyingBytesBuilder(_OUTGOING_BUFFER_SIZE); + BytesBuilder buffer = _CopyingBytesBuilder(_OUTGOING_BUFFER_SIZE); // Write status line. if (headers.protocolVersion == "1.1") { @@ -816,7 +817,7 @@ } } if (!found) { - var cookie = new Cookie(DART_SESSION_ID, session.id); + var cookie = Cookie(DART_SESSION_ID, session.id); cookies.add(cookie ..httpOnly = true ..path = "/"); @@ -935,14 +936,14 @@ implements HttpClientRequest { final String method; final Uri uri; - final List<Cookie> cookies = new List<Cookie>(); + final List<Cookie> cookies = <Cookie>[]; // The HttpClient this request belongs to. final _HttpClient _httpClient; final _HttpClientConnection _httpClientConnection; final Completer<HttpClientResponse> _responseCompleter = - new Completer<HttpClientResponse>(); + Completer<HttpClientResponse>(); final _Proxy _proxy; @@ -980,21 +981,21 @@ } int get maxRedirects => _maxRedirects; - void set maxRedirects(int maxRedirects) { - if (_outgoing.headersWritten) throw new StateError("Request already sent"); + set maxRedirects(int maxRedirects) { + if (_outgoing.headersWritten) throw StateError("Request already sent"); _maxRedirects = maxRedirects; } bool get followRedirects => _followRedirects; - void set followRedirects(bool followRedirects) { - if (_outgoing.headersWritten) throw new StateError("Request already sent"); + set followRedirects(bool followRedirects) { + if (_outgoing.headersWritten) throw StateError("Request already sent"); _followRedirects = followRedirects; } HttpConnectionInfo get connectionInfo => _httpClientConnection.connectionInfo; void _onIncoming(HttpIncoming incoming) { - var response = new _HttpClientResponse(incoming, this, _httpClient); + var response = _HttpClientResponse(incoming, this, _httpClient); Future<HttpClientResponse> future; if (followRedirects && response.isRedirect) { if (response.redirects.length < maxRedirects) { @@ -1005,8 +1006,8 @@ } else { // End with exception, too many redirects. future = response.drain().then<HttpClientResponse>((_) { - return new Future<HttpClientResponse>.error(new RedirectException( - "Redirect limit exceeded", response.redirects)); + return Future<HttpClientResponse>.error( + RedirectException("Redirect limit exceeded", response.redirects)); }); } } else if (response._shouldAuthenticateProxy) { @@ -1014,7 +1015,7 @@ } else if (response._shouldAuthenticate) { future = response._authenticate(false); } else { - future = new Future<HttpClientResponse>.value(response); + future = Future<HttpClientResponse>.value(response); } future.then((v) => _responseCompleter.complete(v), onError: _responseCompleter.completeError); @@ -1055,7 +1056,7 @@ } void _writeHeader() { - BytesBuilder buffer = new _CopyingBytesBuilder(_OUTGOING_BUFFER_SIZE); + BytesBuilder buffer = _CopyingBytesBuilder(_OUTGOING_BUFFER_SIZE); // Write the request method. buffer.add(method.codeUnits); @@ -1070,10 +1071,13 @@ // Add the cookies to the headers. if (cookies.isNotEmpty) { - StringBuffer sb = new StringBuffer(); + StringBuffer sb = StringBuffer(); for (int i = 0; i < cookies.length; i++) { if (i > 0) sb.write("; "); - sb..write(cookies[i].name)..write("=")..write(cookies[i].value); + sb + ..write(cookies[i].name) + ..write("=") + ..write(cookies[i].value); } headers.add(HttpHeaders.COOKIE, sb.toString()); } @@ -1101,7 +1105,7 @@ void addSlice(List<int> chunk, int start, int end, bool isLast) { if (chunk is Uint8List) { - _consume(new Uint8List.view(chunk.buffer, start, end - start)); + _consume(Uint8List.view(chunk.buffer, start, end - start)); } else { _consume(chunk.sublist(start, end - start)); } @@ -1119,7 +1123,7 @@ // Most notable is the GZip compression, that uses a double-buffering system, // one before gzip (_gzipBuffer) and one after (_buffer). class _HttpOutgoing implements StreamConsumer<List<int>> { - static const List<int> _footerAndChunk0Length = const [ + static const List<int> _footerAndChunk0Length = [ CharCode.CR, CharCode.LF, 0x30, @@ -1129,7 +1133,7 @@ CharCode.LF ]; - static const List<int> _chunk0Length = const [ + static const List<int> _chunk0Length = [ 0x30, CharCode.CR, CharCode.LF, @@ -1137,7 +1141,7 @@ CharCode.LF ]; - final Completer<Socket> _doneCompleter = new Completer<Socket>(); + final Completer<Socket> _doneCompleter = Completer<Socket>(); final Socket socket; bool ignoreBody = false; @@ -1170,7 +1174,7 @@ // Returns either a future or 'null', if it was able to write headers // immediately. - Future writeHeaders({bool drainRequest: true, bool setOutgoing: true}) { + Future writeHeaders({bool drainRequest = true, bool setOutgoing = true}) { if (headersWritten) return null; headersWritten = true; Future drainFuture; @@ -1220,7 +1224,7 @@ Future addStream(Stream<List<int>> stream) { if (_socketError) { stream.listen(null).cancel(); - return new Future.value(outbound); + return Future.value(outbound); } if (ignoreBody) { stream.drain().catchError((_) {}); @@ -1234,7 +1238,7 @@ // Use new stream so we are able to pause (see below listen). The // alternative is to use stream.extand, but that won't give us a way of // pausing. - var controller = new StreamController<List<int>>( + var controller = StreamController<List<int>>( onPause: () => sub.pause(), onResume: () => sub.resume(), sync: true); void onData(List<int> data) { @@ -1253,11 +1257,11 @@ if (contentLength != null) { _bytesWritten += data.length; if (_bytesWritten > contentLength) { - controller.addError(new HttpException( - "Content size exceeds specified contentLength. " - "$_bytesWritten bytes written while expected " - "$contentLength. " - "[${new String.fromCharCodes(data)}]")); + controller.addError( + HttpException("Content size exceeds specified contentLength. " + "$_bytesWritten bytes written while expected " + "$contentLength. " + "[${String.fromCharCodes(data)}]")); return; } } @@ -1298,8 +1302,8 @@ if (_closeFuture != null) return _closeFuture; // If we earlier saw an error, return immediate. The notification to // _Http*Connection is already done. - if (_socketError) return new Future.value(outbound); - if (outbound._isConnectionClosed) return new Future.value(outbound); + if (_socketError) return Future.value(outbound); + if (outbound._isConnectionClosed) return Future.value(outbound); if (!headersWritten && !ignoreBody) { if (outbound.headers.contentLength == -1) { // If no body was written, ignoreBody is false (it's not a HEAD @@ -1308,24 +1312,24 @@ outbound.headers.chunkedTransferEncoding = false; outbound.headers.contentLength = 0; } else if (outbound.headers.contentLength > 0) { - var error = new HttpException( + var error = HttpException( "No content even though contentLength was specified to be " "greater than 0: ${outbound.headers.contentLength}.", uri: outbound._uri); _doneCompleter.completeError(error); - return _closeFuture = new Future.error(error); + return _closeFuture = Future.error(error); } } // If contentLength was specified, validate it. if (contentLength != null) { if (_bytesWritten < contentLength) { - var error = new HttpException( + var error = HttpException( "Content size below specified contentLength. " " $_bytesWritten bytes written but expected " "$contentLength.", uri: outbound._uri); _doneCompleter.completeError(error); - return _closeFuture = new Future.error(error); + return _closeFuture = Future.error(error); } } @@ -1336,8 +1340,8 @@ if (_gzip) { _gzipAdd = socket.add; if (_gzipBufferLength > 0) { - _gzipSink.add( - new Uint8List.view(_gzipBuffer.buffer, 0, _gzipBufferLength)); + _gzipSink + .add(Uint8List.view(_gzipBuffer.buffer, 0, _gzipBufferLength)); } _gzipBuffer = null; _gzipSink.close(); @@ -1347,7 +1351,7 @@ } // Add any remaining data in the buffer. if (_length > 0) { - socket.add(new Uint8List.view(_buffer.buffer, 0, _length)); + socket.add(Uint8List.view(_buffer.buffer, 0, _length)); } // Clear references, for better GC. _buffer = null; @@ -1382,13 +1386,13 @@ _length = length; } - void set gzip(bool value) { + set gzip(bool value) { _gzip = value; if (_gzip) { - _gzipBuffer = new Uint8List(_OUTGOING_BUFFER_SIZE); + _gzipBuffer = Uint8List(_OUTGOING_BUFFER_SIZE); assert(_gzipSink == null); - _gzipSink = new ZLibEncoder(gzip: true) - .startChunkedConversion(new _HttpGZipSink((data) { + _gzipSink = + ZLibEncoder(gzip: true).startChunkedConversion(_HttpGZipSink((data) { // We are closing down prematurely, due to an error. Discard. if (_gzipAdd == null) return; _addChunk(_chunkHeader(data.length), _gzipAdd); @@ -1408,8 +1412,8 @@ return; } if (chunk.length > _gzipBuffer.length - _gzipBufferLength) { - add(new Uint8List.view(_gzipBuffer.buffer, 0, _gzipBufferLength)); - _gzipBuffer = new Uint8List(_OUTGOING_BUFFER_SIZE); + add(Uint8List.view(_gzipBuffer.buffer, 0, _gzipBufferLength)); + _gzipBuffer = Uint8List(_OUTGOING_BUFFER_SIZE); _gzipBufferLength = 0; } if (chunk.length > _OUTGOING_BUFFER_SIZE) { @@ -1426,7 +1430,7 @@ if (_buffer != null) { // If _buffer is not null, we have not written the header yet. Write // it now. - add(new Uint8List.view(_buffer.buffer, 0, _length)); + add(Uint8List.view(_buffer.buffer, 0, _length)); _buffer = null; _length = 0; } @@ -1434,8 +1438,8 @@ return; } if (chunk.length > _buffer.length - _length) { - add(new Uint8List.view(_buffer.buffer, 0, _length)); - _buffer = new Uint8List(_OUTGOING_BUFFER_SIZE); + add(Uint8List.view(_buffer.buffer, 0, _length)); + _buffer = Uint8List(_OUTGOING_BUFFER_SIZE); _length = 0; } if (chunk.length > _OUTGOING_BUFFER_SIZE) { @@ -1447,7 +1451,7 @@ } List<int> _chunkHeader(int length) { - const hexDigits = const [ + const hexDigits = [ 0x30, 0x31, 0x32, @@ -1476,7 +1480,7 @@ size++; len >>= 4; } - var footerAndHeader = new Uint8List(size + 2); + var footerAndHeader = Uint8List(size + 2); if (_pendingChunkedFooter == 2) { footerAndHeader[0] = CharCode.CR; footerAndHeader[1] = CharCode.LF; @@ -1510,7 +1514,7 @@ _HttpClientConnection(this.key, this._socket, this._httpClient, [this._proxyTunnel = false, this._context]) - : _httpParser = new HttpParser.responseParser() { + : _httpParser = HttpParser.responseParser() { _httpParser.listenToStream(_socket); // Set up handlers on the parser here, so we are sure to get 'onDone' from @@ -1521,7 +1525,7 @@ _subscription.pause(); // We assume the response is not here, until we have send the request. if (_nextResponseCompleter == null) { - throw new HttpException( + throw HttpException( "Unexpected response (unsolicited response without request).", uri: _currentUri); } @@ -1535,7 +1539,7 @@ _subscription.resume(); }).catchError((error, [StackTrace stackTrace]) { _nextResponseCompleter.completeError( - new HttpException(error.message, uri: _currentUri), stackTrace); + HttpException(error.message, uri: _currentUri), stackTrace); _nextResponseCompleter = null; }); } else { @@ -1545,12 +1549,12 @@ }, onError: (error, [StackTrace stackTrace]) { if (_nextResponseCompleter != null) { _nextResponseCompleter.completeError( - new HttpException(error.message, uri: _currentUri), stackTrace); + HttpException(error.message, uri: _currentUri), stackTrace); _nextResponseCompleter = null; } }, onDone: () { if (_nextResponseCompleter != null) { - _nextResponseCompleter.completeError(new HttpException( + _nextResponseCompleter.completeError(HttpException( "Connection closed before response was received", uri: _currentUri)); _nextResponseCompleter = null; @@ -1561,18 +1565,17 @@ _HttpClientRequest send(Uri uri, int port, String method, _Proxy proxy) { if (closed) { - throw new HttpException("Socket closed before request was sent", - uri: uri); + throw HttpException("Socket closed before request was sent", uri: uri); } _currentUri = uri; // Start with pausing the parser. _subscription.pause(); _ProxyCredentials proxyCreds; // Credentials used to authorize proxy. _SiteCredentials creds; // Credentials used to authorize this request. - var outgoing = new _HttpOutgoing(_socket); + var outgoing = _HttpOutgoing(_socket); // Create new request object, wrapping the outgoing connection. var request = - new _HttpClientRequest(outgoing, uri, method, proxy, _httpClient, this); + _HttpClientRequest(outgoing, uri, method, proxy, _httpClient, this); // For the Host header an IPv6 address must be enclosed in []'s. var host = uri.host; if (host.contains(':')) host = "[$host]"; @@ -1612,7 +1615,7 @@ _httpParser.isHead = method == "HEAD"; _streamFuture = outgoing.done.then<Socket>((Socket s) { // Request sent, set up response completer. - _nextResponseCompleter = new Completer<HttpIncoming>(); + _nextResponseCompleter = Completer<HttpIncoming>(); // Listen for response. _nextResponseCompleter.future.then((incoming) { @@ -1664,7 +1667,7 @@ // If we see a state error, we failed to get the 'first' // element. .catchError((error) { - throw new HttpException("Connection closed before data was received", + throw HttpException("Connection closed before data was received", uri: uri); }, test: (error) => error is StateError).catchError( (error, StackTrace stackTrace) { @@ -1683,8 +1686,8 @@ } Future<Socket> detachSocket() { - return _streamFuture.then( - (_) => new _DetachedSocket(_socket, _httpParser.detachIncoming())); + return _streamFuture + .then((_) => _DetachedSocket(_socket, _httpParser.detachIncoming())); } void destroy() { @@ -1704,7 +1707,7 @@ Future<_HttpClientConnection> createProxyTunnel(String host, int port, _Proxy proxy, bool callback(X509Certificate certificate)) { _HttpClientRequest request = - send(new Uri(host: host, port: port), port, "CONNECT", proxy); + send(Uri(host: host, port: port), port, "CONNECT", proxy); if (proxy.isAuthenticated) { // If the proxy configuration contains user information use that // for proxy basic authorization. @@ -1725,7 +1728,7 @@ host: host, context: _context, onBadCertificate: callback); }).then((secureSocket) { String key = _HttpClientConnection.makeKey(true, host, port); - return new _HttpClientConnection( + return _HttpClientConnection( key, secureSocket, request._httpClient, true); }); } @@ -1745,7 +1748,7 @@ void startTimer() { assert(_idleTimer == null); - _idleTimer = new Timer(_httpClient.idleTimeout, () { + _idleTimer = Timer(_httpClient.idleTimeout, () { _idleTimer = null; close(); }); @@ -1766,10 +1769,10 @@ final int port; final bool isSecure; final SecurityContext context; - final Set<_HttpClientConnection> _idle = new HashSet(); - final Set<_HttpClientConnection> _active = new HashSet(); - final Set<ConnectionTask> _socketTasks = new HashSet(); - final Queue _pending = new ListQueue(); + final Set<_HttpClientConnection> _idle = HashSet(); + final Set<_HttpClientConnection> _active = HashSet(); + final Set<ConnectionTask> _socketTasks = HashSet(); + final Queue _pending = ListQueue(); int _connecting = 0; _ConnectionTarget( @@ -1843,11 +1846,11 @@ if (hasIdle) { var connection = takeIdle(); client._connectionsChanged(); - return new Future.value(new _ConnectionInfo(connection, proxy)); + return Future.value(_ConnectionInfo(connection, proxy)); } if (client.maxConnectionsPerHost != null && _active.length + _connecting >= client.maxConnectionsPerHost) { - var completer = new Completer<_ConnectionInfo>(); + var completer = Completer<_ConnectionInfo>(); _pending.add(() { completer.complete(connect(uriHost, uriPort, proxy, client)); }); @@ -1879,7 +1882,7 @@ _connecting--; socket.setOption(SocketOption.tcpNoDelay, true); var connection = - new _HttpClientConnection(key, socket, client, false, context); + _HttpClientConnection(key, socket, client, false, context); if (isSecure && !proxy.isDirect) { connection._dispose = true; return connection @@ -1889,12 +1892,12 @@ ._getConnectionTarget(uriHost, uriPort, true) .addNewActive(tunnel); _socketTasks.remove(task); - return new _ConnectionInfo(tunnel, proxy); + return _ConnectionInfo(tunnel, proxy); }); } else { addNewActive(connection); _socketTasks.remove(task); - return new _ConnectionInfo(connection, proxy); + return _ConnectionInfo(connection, proxy); } }, onError: (error) { _connecting--; @@ -1906,13 +1909,14 @@ } } -typedef bool BadCertificateCallback(X509Certificate cr, String host, int port); +typedef BadCertificateCallback = bool Function( + X509Certificate cr, String host, int port); class _HttpClient implements HttpClient { bool _closing = false; bool _closingForcefully = false; final Map<String, _ConnectionTarget> _connectionTargets = - new HashMap<String, _ConnectionTarget>(); + HashMap<String, _ConnectionTarget>(); final List<_Credentials> _credentials = []; final List<_ProxyCredentials> _proxyCredentials = []; final SecurityContext _context; @@ -1934,7 +1938,7 @@ _HttpClient(this._context); - void set idleTimeout(Duration timeout) { + set idleTimeout(Duration timeout) { _idleTimeout = timeout; for (var c in _connectionTargets.values) { for (var idle in c._idle) { @@ -1970,8 +1974,8 @@ query = path.substring(queryStart + 1, fragmentStart); path = path.substring(0, queryStart); } - Uri uri = new Uri( - scheme: "http", host: host, port: port, path: path, query: query); + Uri uri = + Uri(scheme: "http", host: host, port: port, path: path, query: query); return _openUrl(method, uri); } @@ -2008,7 +2012,7 @@ Future<HttpClientRequest> patchUrl(Uri url) => _openUrl("patch", url); - void close({bool force: false}) { + void close({bool force = false}) { _closing = true; _closingForcefully = force; _closeConnections(_closingForcefully); @@ -2022,7 +2026,7 @@ } void addCredentials(Uri url, String realm, HttpClientCredentials cr) { - _credentials.add(new _SiteCredentials(url, realm, cr)); + _credentials.add(_SiteCredentials(url, realm, cr)); } set authenticateProxy( @@ -2032,7 +2036,7 @@ void addProxyCredentials( String host, int port, String realm, HttpClientCredentials cr) { - _proxyCredentials.add(new _ProxyCredentials(host, port, realm, cr)); + _proxyCredentials.add(_ProxyCredentials(host, port, realm, cr)); } set findProxy(String f(Uri uri)) => _findProxy = f; @@ -2042,14 +2046,13 @@ uri = uri.removeFragment(); if (method == null) { - throw new ArgumentError(method); + throw ArgumentError(method); } if (method != "CONNECT") { if (uri.host.isEmpty) { - throw new ArgumentError("No host specified in URI $uri"); + throw ArgumentError("No host specified in URI $uri"); } else if (uri.scheme != "http" && uri.scheme != "https") { - throw new ArgumentError( - "Unsupported scheme '${uri.scheme}' in URI $uri"); + throw ArgumentError("Unsupported scheme '${uri.scheme}' in URI $uri"); } } @@ -2066,9 +2069,9 @@ // TODO(sgjesse): Keep a map of these as normally only a few // configuration strings will be used. try { - proxyConf = new _ProxyConfiguration(_findProxy(uri)); + proxyConf = _ProxyConfiguration(_findProxy(uri)); } catch (error, stackTrace) { - return new Future.error(error, stackTrace); + return Future.error(error, stackTrace); } } return _getConnection(uri.host, port, proxyConf, isSecure) @@ -2144,7 +2147,7 @@ _ConnectionTarget _getConnectionTarget(String host, int port, bool isSecure) { String key = _HttpClientConnection.makeKey(isSecure, host, port); return _connectionTargets.putIfAbsent(key, () { - return new _ConnectionTarget(key, host, port, isSecure, _context); + return _ConnectionTarget(key, host, port, isSecure, _context); }); } @@ -2154,7 +2157,7 @@ Iterator<_Proxy> proxies = proxyConf.proxies.iterator; Future<_ConnectionInfo> connect(error) { - if (!proxies.moveNext()) return new Future.error(error); + if (!proxies.moveNext()) return Future.error(error); _Proxy proxy = proxies.current; String host = proxy.isDirect ? uriHost : proxy.host; int port = proxy.isDirect ? uriPort : proxy.port; @@ -2168,8 +2171,8 @@ // connection from the pool. For long-running synchronous code the // server might have closed the connection, so this lowers the // probability of getting a connection that was already closed. - return new Future<_ConnectionInfo>( - () => connect(new HttpException("No proxies given"))); + return Future<_ConnectionInfo>( + () => connect(HttpException("No proxies given"))); } _SiteCredentials _findCredentials(Uri url, [_AuthenticationScheme scheme]) { @@ -2249,7 +2252,7 @@ var pos = option.lastIndexOf(":"); if (option.indexOf("]") > pos) option = "$option:1080"; } else { - if (option.indexOf(":") == -1) option = "$option:1080"; + if (!option.contains(":")) option = "$option:1080"; } return "PROXY $option"; } @@ -2300,7 +2303,7 @@ Future _streamFuture; _HttpConnection(this._socket, this._httpServer) - : _httpParser = new HttpParser.requestParser() { + : _httpParser = HttpParser.requestParser() { _httpParser.listenToStream(_socket); _subscription = _httpParser.listen((incoming) { _httpServer._markActive(this); @@ -2312,14 +2315,14 @@ // stream paused until the request has been send. _subscription.pause(); _state = _ACTIVE; - var outgoing = new _HttpOutgoing(_socket); - var response = new _HttpResponse( + var outgoing = _HttpOutgoing(_socket); + var response = _HttpResponse( incoming.uri, incoming.headers.protocolVersion, outgoing, _httpServer.defaultResponseHeaders, _httpServer.serverHeader); - var request = new _HttpRequest(response, incoming, _httpServer, this); + var request = _HttpRequest(response, incoming, _httpServer, this); _streamFuture = outgoing.done.then((_) { response.deadline = null; if (_state == _DETACHED) return; @@ -2374,7 +2377,7 @@ HttpDetachedIncoming detachedIncoming = _httpParser.detachIncoming(); return _streamFuture.then((_) { - return new _DetachedSocket(_socket, detachedIncoming); + return _DetachedSocket(_socket, detachedIncoming); }); } @@ -2401,7 +2404,7 @@ return ServerSocket.bind(address, port, backlog: backlog, v6Only: v6Only, shared: shared) .then<HttpServer>((socket) { - return new _HttpServer._(socket, true); + return _HttpServer._(socket, true); }); } @@ -2419,24 +2422,22 @@ requestClientCertificate: requestClientCertificate, shared: shared) .then<HttpServer>((socket) { - return new _HttpServer._(socket, true); + return _HttpServer._(socket, true); }); } _HttpServer._(this._serverSocket, this._closeServer) { - _controller = - new StreamController<HttpRequest>(sync: true, onCancel: close); + _controller = StreamController<HttpRequest>(sync: true, onCancel: close); idleTimeout = const Duration(seconds: 120); } _HttpServer.listenOn(this._serverSocket) : _closeServer = false { - _controller = - new StreamController<HttpRequest>(sync: true, onCancel: close); + _controller = StreamController<HttpRequest>(sync: true, onCancel: close); idleTimeout = const Duration(seconds: 120); } static HttpHeaders _initDefaultResponseHeaders() { - var defaultResponseHeaders = new HttpHeadersImpl('1.1'); + var defaultResponseHeaders = HttpHeadersImpl('1.1'); defaultResponseHeaders.contentType = ContentType.TEXT; defaultResponseHeaders.set('X-Frame-Options', 'SAMEORIGIN'); defaultResponseHeaders.set('X-Content-Type-Options', 'nosniff'); @@ -2446,14 +2447,14 @@ Duration get idleTimeout => _idleTimeout; - void set idleTimeout(Duration duration) { + set idleTimeout(Duration duration) { if (_idleTimer != null) { _idleTimer.cancel(); _idleTimer = null; } _idleTimeout = duration; if (_idleTimeout != null) { - _idleTimer = new Timer.periodic(_idleTimeout, (_) { + _idleTimer = Timer.periodic(_idleTimeout, (_) { for (var idle in _idleConnections.toList()) { if (idle.isMarkedIdle) { idle.destroy(); @@ -2470,7 +2471,7 @@ _serverSocket.listen((Socket socket) { socket.setOption(SocketOption.tcpNoDelay, true); // Accept the client connection. - _HttpConnection connection = new _HttpConnection(socket, this); + _HttpConnection connection = _HttpConnection(socket, this); _idleConnections.add(connection); }, onError: (error, StackTrace stackTrace) { // Ignore HandshakeExceptions as they are bound to a single request, @@ -2483,13 +2484,13 @@ onError: onError, onDone: onDone, cancelOnError: cancelOnError); } - Future close({bool force: false}) { + Future close({bool force = false}) { closed = true; Future result; if (_serverSocket != null && _closeServer) { result = _serverSocket.close(); } else { - result = new Future.value(); + result = Future.value(); } idleTimeout = null; if (force) { @@ -2516,12 +2517,12 @@ } int get port { - if (closed) throw new HttpException("HttpServer is not bound to a socket"); + if (closed) throw HttpException("HttpServer is not bound to a socket"); return _serverSocket.port; } InternetAddress get address { - if (closed) throw new HttpException("HttpServer is not bound to a socket"); + if (closed) throw HttpException("HttpServer is not bound to a socket"); return _serverSocket.address; } @@ -2555,12 +2556,12 @@ HttpSessionManager get _sessionManager { // Lazy init. - _sessionManagerInstance ??= new HttpSessionManager(); + _sessionManagerInstance ??= HttpSessionManager(); return _sessionManagerInstance; } HttpConnectionsInfo connectionsInfo() { - HttpConnectionsInfo result = new HttpConnectionsInfo(); + HttpConnectionsInfo result = HttpConnectionsInfo(); result.total = _activeConnections.length + _idleConnections.length; _activeConnections.forEach((_HttpConnection conn) { if (conn._isActive) { @@ -2589,9 +2590,9 @@ // Set of currently connected clients. final LinkedList<_HttpConnection> _activeConnections = - new LinkedList<_HttpConnection>(); + LinkedList<_HttpConnection>(); final LinkedList<_HttpConnection> _idleConnections = - new LinkedList<_HttpConnection>(); + LinkedList<_HttpConnection>(); StreamController<HttpRequest> _controller; } @@ -2599,9 +2600,9 @@ static const String PROXY_PREFIX = "PROXY "; static const String DIRECT_PREFIX = "DIRECT"; - _ProxyConfiguration(String configuration) : proxies = new List<_Proxy>() { + _ProxyConfiguration(String configuration) : proxies = <_Proxy>[] { if (configuration == null) { - throw new HttpException("Invalid proxy configuration $configuration"); + throw HttpException("Invalid proxy configuration $configuration"); } List<String> list = configuration.split(";"); list.forEach((String proxy) { @@ -2619,8 +2620,7 @@ proxy = proxy.substring(at + 1).trim(); int colon = userinfo.indexOf(":"); if (colon == -1 || colon == 0 || colon == proxy.length - 1) { - throw new HttpException( - "Invalid proxy configuration $configuration"); + throw HttpException("Invalid proxy configuration $configuration"); } username = userinfo.substring(0, colon).trim(); password = userinfo.substring(colon + 1).trim(); @@ -2628,8 +2628,7 @@ // Look for proxy host and port. int colon = proxy.lastIndexOf(":"); if (colon == -1 || colon == 0 || colon == proxy.length - 1) { - throw new HttpException( - "Invalid proxy configuration $configuration"); + throw HttpException("Invalid proxy configuration $configuration"); } String host = proxy.substring(0, colon).trim(); if (host.startsWith("[") && host.endsWith("]")) { @@ -2640,21 +2639,20 @@ try { port = int.parse(portString); } on FormatException { - throw new HttpException( - "Invalid proxy configuration $configuration, " + throw HttpException("Invalid proxy configuration $configuration, " "invalid port '$portString'"); } - proxies.add(new _Proxy(host, port, username, password)); + proxies.add(_Proxy(host, port, username, password)); } else if (proxy.trim() == DIRECT_PREFIX) { - proxies.add(new _Proxy.direct()); + proxies.add(_Proxy.direct()); } else { - throw new HttpException("Invalid proxy configuration $configuration"); + throw HttpException("Invalid proxy configuration $configuration"); } } }); } - const _ProxyConfiguration.direct() : proxies = const [const _Proxy.direct()]; + const _ProxyConfiguration.direct() : proxies = const [_Proxy.direct()]; final List<_Proxy> proxies; } @@ -2686,23 +2684,24 @@ static _HttpConnectionInfo create(Socket socket) { if (socket == null) return null; try { - _HttpConnectionInfo info = new _HttpConnectionInfo(); - return info + return _HttpConnectionInfo() ..remoteAddress = socket.remoteAddress ..remotePort = socket.remotePort ..localPort = socket.port; - } catch (e) {} + } catch (e) { + // return null on failure + } return null; } } -class _DetachedSocket extends Stream<List<int>> implements Socket { - final Stream<List<int>> _incoming; +class _DetachedSocket extends Stream<Uint8List> implements Socket { + final Stream<Uint8List> _incoming; final Socket _socket; _DetachedSocket(this._socket, this._incoming); - StreamSubscription<List<int>> listen(void onData(List<int> event), + StreamSubscription<Uint8List> listen(void onData(Uint8List event), {Function onError, void onDone(), bool cancelOnError}) { return _incoming.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); @@ -2710,7 +2709,7 @@ Encoding get encoding => _socket.encoding; - void set encoding(Encoding value) { + set encoding(Encoding value) { _socket.encoding = value; } @@ -2738,7 +2737,7 @@ _socket.addError(error, stackTrace); Future addStream(Stream<List<int>> stream) { - return _socket.addStream(stream); + return _socket.addStream(stream.cast<List<int>>()); } void destroy() { @@ -2770,18 +2769,14 @@ void setRawOption(RawSocketOption option) { _socket.setRawOption(option); } - - Map _toJSON(bool ref) { - return (_socket as dynamic)._toJSON(ref); - } } class _AuthenticationScheme { final int _scheme; - static const UNKNOWN = const _AuthenticationScheme(-1); - static const BASIC = const _AuthenticationScheme(0); - static const DIGEST = const _AuthenticationScheme(1); + static const UNKNOWN = _AuthenticationScheme(-1); + static const BASIC = _AuthenticationScheme(0); + static const DIGEST = _AuthenticationScheme(1); const _AuthenticationScheme(this._scheme); @@ -2819,7 +2814,7 @@ // http://tools.ietf.org/html/draft-reschke-basicauth-enc-06. For // now always use UTF-8 encoding. _HttpClientDigestCredentials creds = credentials; - var hasher = new MD5() + var hasher = MD5() ..add(utf8.encode(creds.username)) ..add([CharCode.COLON]) ..add(realm.codeUnits) @@ -2930,7 +2925,7 @@ String authorization(_Credentials credentials, _HttpClientRequest request) { String requestUri = request._requestUri(); - var hasher = new MD5() + var hasher = MD5() ..add(request.method.codeUnits) ..add([CharCode.COLON]) ..add(requestUri.codeUnits); @@ -2939,7 +2934,9 @@ String qop; String cnonce; String nc; - hasher = new MD5()..add(credentials.ha1.codeUnits)..add([CharCode.COLON]); + hasher = MD5() + ..add(credentials.ha1.codeUnits) + ..add([CharCode.COLON]); if (credentials.qop == "auth") { qop = credentials.qop; cnonce = CryptoUtils.bytesToHex(CryptoUtils.getRandomBytes(4)); @@ -2964,7 +2961,7 @@ } var response = CryptoUtils.bytesToHex(hasher.close()); - StringBuffer buffer = new StringBuffer() + StringBuffer buffer = StringBuffer() ..write('Digest ') ..write('username="$username"') ..write(', realm="${credentials.realm}"')
diff --git a/lib/src/http_incoming.dart b/lib/src/http_incoming.dart index 7bc45df..ab0dde0 100644 --- a/lib/src/http_incoming.dart +++ b/lib/src/http_incoming.dart
@@ -9,8 +9,8 @@ class HttpIncoming extends Stream<List<int>> { final int _transferLength; - final _dataCompleter = new Completer<bool>(); - Stream<List<int>> _stream; + final _dataCompleter = Completer<bool>(); + final Stream<List<int>> _stream; bool fullBodyRead = false; @@ -40,7 +40,7 @@ {Function onError, void onDone(), bool cancelOnError}) { hasSubscriber = true; return _stream.handleError((error) { - throw new HttpException(error.message, uri: uri); + throw HttpException(error.message, uri: uri); }).listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); }
diff --git a/lib/src/http_overrides.dart b/lib/src/http_overrides.dart index 5456bb2..bae284a 100644 --- a/lib/src/http_overrides.dart +++ b/lib/src/http_overrides.dart
@@ -4,7 +4,7 @@ part of http_io; -final _httpOverridesToken = new Object(); +final _httpOverridesToken = Object(); const _asyncRunZoned = runZoned; @@ -53,7 +53,7 @@ ZoneSpecification zoneSpecification, Function onError}) { HttpOverrides overrides = - new _HttpOverridesScope(createHttpClient, findProxyFromEnvironment); + _HttpOverridesScope(createHttpClient, findProxyFromEnvironment); return _asyncRunZoned<R>(body, zoneValues: {_httpOverridesToken: overrides}, zoneSpecification: zoneSpecification, @@ -77,7 +77,7 @@ /// When this override is installed, this function overrides the behavior of /// `new HttpClient`. HttpClient createHttpClient(SecurityContext context) { - return new _HttpClient(context); + return _HttpClient(context); } /// Resolves the proxy server to be used for HTTP connections.
diff --git a/lib/src/http_parser.dart b/lib/src/http_parser.dart index 5b228c8..56d711d 100644 --- a/lib/src/http_parser.dart +++ b/lib/src/http_parser.dart
@@ -60,18 +60,16 @@ static const int RESPONSE = 0; } -/** - * The _HttpDetachedStreamSubscription takes a subscription and some extra data, - * and makes it possible to "inject" the data in from of other data events - * from the subscription. - * - * It does so by overriding pause/resume, so that once the - * _HttpDetachedStreamSubscription is resumed, it'll deliver the data before - * resuming the underlaying subscription. - */ -class _HttpDetachedStreamSubscription implements StreamSubscription<List<int>> { - StreamSubscription<List<int>> _subscription; - List<int> _injectData; +/// The _HttpDetachedStreamSubscription takes a subscription and some extra data, +/// and makes it possible to "inject" the data in from of other data events +/// from the subscription. +/// +/// It does so by overriding pause/resume, so that once the +/// _HttpDetachedStreamSubscription is resumed, it'll deliver the data before +/// resuming the underlaying subscription. +class _HttpDetachedStreamSubscription implements StreamSubscription<Uint8List> { + final StreamSubscription<Uint8List> _subscription; + Uint8List _injectData; bool _isCanceled = false; int _pauseCount = 1; Function _userOnData; @@ -91,7 +89,7 @@ return _subscription.cancel(); } - void onData(void handleData(List<int> data)) { + void onData(void handleData(Uint8List data)) { _userOnData = handleData; _subscription.onData(handleData); } @@ -143,13 +141,13 @@ } } -class HttpDetachedIncoming extends Stream<List<int>> { - final StreamSubscription<List<int>> subscription; - final List<int> bufferedData; +class HttpDetachedIncoming extends Stream<Uint8List> { + final StreamSubscription<Uint8List> subscription; + final Uint8List bufferedData; HttpDetachedIncoming(this.subscription, this.bufferedData); - StreamSubscription<List<int>> listen(void onData(List<int> event), + StreamSubscription<Uint8List> listen(void onData(Uint8List event), {Function onError, void onDone(), bool cancelOnError}) { if (subscription != null) { subscription @@ -159,37 +157,34 @@ if (bufferedData == null) { return subscription..resume(); } - return new _HttpDetachedStreamSubscription( - subscription, bufferedData, onData) + return _HttpDetachedStreamSubscription(subscription, bufferedData, onData) ..resume(); } else { // TODO(26379): add test for this branch. - return new Stream<List<int>>.fromIterable([bufferedData]).listen(onData, + return Stream<Uint8List>.fromIterable([bufferedData]).listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } } } -/** - * HTTP parser which parses the data stream given to consume. - * - * If an HTTP parser error occurs, the parser will signal an error to either - * the current _HttpIncoming or the _parser itself. - * - * The connection upgrades (e.g. switching from HTTP/1.1 to the - * WebSocket protocol) is handled in a special way. If connection - * upgrade is specified in the headers, then on the callback to - * [:responseStart:] the [:upgrade:] property on the [:HttpParser:] - * object will be [:true:] indicating that from now on the protocol is - * not HTTP anymore and no more callbacks will happen, that is - * [:dataReceived:] and [:dataEnd:] are not called in this case as - * there is no more HTTP data. After the upgrade the method - * [:readUnparsedData:] can be used to read any remaining bytes in the - * HTTP parser which are part of the protocol the connection is - * upgrading to. These bytes cannot be processed by the HTTP parser - * and should be handled according to whatever protocol is being - * upgraded to. - */ +/// HTTP parser which parses the data stream given to consume. +/// +/// If an HTTP parser error occurs, the parser will signal an error to either +/// the current _HttpIncoming or the _parser itself. +/// +/// The connection upgrades (e.g. switching from HTTP/1.1 to the +/// WebSocket protocol) is handled in a special way. If connection +/// upgrade is specified in the headers, then on the callback to +/// [:responseStart:] the [:upgrade:] property on the [:HttpParser:] +/// object will be [:true:] indicating that from now on the protocol is +/// not HTTP anymore and no more callbacks will happen, that is +/// [:dataReceived:] and [:dataEnd:] are not called in this case as +/// there is no more HTTP data. After the upgrade the method +/// [:readUnparsedData:] can be used to read any remaining bytes in the +/// HTTP parser which are part of the protocol the connection is +/// upgrading to. These bytes cannot be processed by the HTTP parser +/// and should be handled according to whatever protocol is being +/// upgraded to. class HttpParser extends Stream<HttpIncoming> { // State. bool _parserCalled = false; @@ -222,22 +217,22 @@ // The current incoming connection. HttpIncoming _incoming; - StreamSubscription<List<int>> _socketSubscription; + StreamSubscription<Uint8List> _socketSubscription; bool _paused = true; bool _bodyPaused = false; StreamController<HttpIncoming> _controller; - StreamController<List<int>> _bodyController; + StreamController<Uint8List> _bodyController; factory HttpParser.requestParser() { - return new HttpParser._(true); + return HttpParser._(true); } factory HttpParser.responseParser() { - return new HttpParser._(false); + return HttpParser._(false); } HttpParser._(this._requestParser) { - _controller = new StreamController<HttpIncoming>( + _controller = StreamController<HttpIncoming>( sync: true, onListen: () { _paused = false; @@ -264,7 +259,7 @@ onError: onError, onDone: onDone, cancelOnError: cancelOnError); } - void listenToStream(Stream<List<int>> stream) { + void listenToStream(Stream<Uint8List> stream) { // Listen to the stream and handle data accordingly. When a // _HttpIncoming is created, _dataPause, _dataResume, _dataDone is // given to provide a way of controlling the parser. @@ -308,12 +303,11 @@ } _createIncoming(_transferLength); if (_requestParser) { - _incoming.method = new String.fromCharCodes(_method); - _incoming.uri = - Uri.parse(new String.fromCharCodes(_uri_or_reason_phrase)); + _incoming.method = String.fromCharCodes(_method); + _incoming.uri = Uri.parse(String.fromCharCodes(_uri_or_reason_phrase)); } else { _incoming.statusCode = _statusCode; - _incoming.reasonPhrase = new String.fromCharCodes(_uri_or_reason_phrase); + _incoming.reasonPhrase = String.fromCharCodes(_uri_or_reason_phrase); } _method.clear(); _uri_or_reason_phrase.clear(); @@ -361,10 +355,10 @@ assert(!_parserCalled); _parserCalled = true; if (_state == _State.CLOSED) { - throw new HttpException("Data on closed connection"); + throw HttpException("Data on closed connection"); } if (_state == _State.FAILURE) { - throw new HttpException("Data on failed connection"); + throw HttpException("Data on failed connection"); } while (_buffer != null && _index < _buffer.length && @@ -386,11 +380,11 @@ } else { // Start parsing method. if (!CharCode.isTokenChar(byte)) { - throw new HttpException("Invalid request method"); + throw HttpException("Invalid request method"); } _method.add(byte); if (!_requestParser) { - throw new HttpException("Invalid response line"); + throw HttpException("Invalid response line"); } _state = _State.REQUEST_LINE_METHOD; } @@ -407,7 +401,7 @@ // method anymore. _httpVersionIndex++; if (_requestParser) { - throw new HttpException("Invalid request line"); + throw HttpException("Invalid request line"); } _state = _State.RESPONSE_HTTP_VERSION; } else { @@ -421,7 +415,7 @@ _method.add(byte); _httpVersion = _HttpVersion.UNDETERMINED; if (!_requestParser) { - throw new HttpException("Invalid response line"); + throw HttpException("Invalid response line"); } _state = _State.REQUEST_LINE_METHOD; } @@ -450,7 +444,7 @@ // HTTP version parsed. _state = _State.RESPONSE_LINE_STATUS_CODE; } else { - throw new HttpException("Invalid response line"); + throw HttpException("Invalid response line"); } break; @@ -461,7 +455,7 @@ if (Const.SEPARATOR_MAP[byte] || byte == CharCode.CR || byte == CharCode.LF) { - throw new HttpException("Invalid request method"); + throw HttpException("Invalid request method"); } _method.add(byte); } @@ -470,13 +464,13 @@ case _State.REQUEST_LINE_URI: if (byte == CharCode.SP) { if (_uri_or_reason_phrase.isEmpty) { - throw new HttpException("Invalid request URI"); + throw HttpException("Invalid request URI"); } _state = _State.REQUEST_LINE_HTTP_VERSION; _httpVersionIndex = 0; } else { if (byte == CharCode.CR || byte == CharCode.LF) { - throw new HttpException("Invalid request URI"); + throw HttpException("Invalid request URI"); } _uri_or_reason_phrase.add(byte); } @@ -498,7 +492,7 @@ _persistentConnection = false; _httpVersionIndex++; } else { - throw new HttpException("Invalid response line"); + throw HttpException("Invalid response line"); } } else { if (byte == CharCode.CR) { @@ -527,7 +521,7 @@ } else { _statusCodeLength++; if ((byte < 0x30 && 0x39 < byte) || _statusCodeLength > 3) { - throw new HttpException("Invalid response status code"); + throw HttpException("Invalid response status code"); } else { _statusCode = _statusCode * 10 + byte - 0x30; } @@ -539,7 +533,7 @@ _state = _State.RESPONSE_LINE_ENDING; } else { if (byte == CharCode.CR || byte == CharCode.LF) { - throw new HttpException("Invalid response reason phrase"); + throw HttpException("Invalid response reason phrase"); } _uri_or_reason_phrase.add(byte); } @@ -547,11 +541,9 @@ case _State.RESPONSE_LINE_ENDING: _expect(byte, CharCode.LF); - // TODO(kevmoo): file a linter bug on this! - // ignore: unnecessary_statements - _messageType == _MessageType.RESPONSE; + _messageType = _MessageType.RESPONSE; if (_statusCode < 100 || _statusCode > 599) { - throw new HttpException("Invalid response status code"); + throw HttpException("Invalid response status code"); } else { // Check whether this response will never have a body. if (_statusCode <= 199 || @@ -564,7 +556,7 @@ break; case _State.HEADER_START: - _headers = new HttpHeadersImpl(version); + _headers = HttpHeadersImpl(version); if (byte == CharCode.CR) { _state = _State.HEADER_ENDING; } else if (byte == CharCode.LF) { @@ -582,7 +574,7 @@ _state = _State.HEADER_VALUE_START; } else { if (!CharCode.isTokenChar(byte)) { - throw new HttpException("Invalid header field name"); + throw HttpException("Invalid header field name"); } _headerField.add(_toLowerCaseByte(byte)); } @@ -619,8 +611,8 @@ if (byte == CharCode.SP || byte == CharCode.HT) { _state = _State.HEADER_VALUE_START; } else { - String headerField = new String.fromCharCodes(_headerField); - String headerValue = new String.fromCharCodes(_headerValue); + String headerField = String.fromCharCodes(_headerField); + String headerValue = String.fromCharCodes(_headerValue); if (headerField == "transfer-encoding" && _caseInsensitiveCompare("chunked".codeUnits, _headerValue)) { _chunked = true; @@ -725,7 +717,7 @@ // Always present the data as a view. This way we can handle all // cases like this, and the user will not experience different data // typed (which could lead to polymorphic user code). - List<int> data = new Uint8List.view( + Uint8List data = Uint8List.view( _buffer.buffer, _buffer.offsetInBytes + _index, dataAvailable); _bodyController.add(data); if (_remainingContent != -1) { @@ -765,7 +757,7 @@ } } - void _onData(List<int> buffer) { + void _onData(Uint8List buffer) { _socketSubscription.pause(); assert(_buffer == null); _buffer = buffer; @@ -782,8 +774,8 @@ if (_state != _State.UPGRADED && !(_state == _State.START && !_requestParser) && !(_state == _State.BODY && !_chunked && _transferLength == -1)) { - _bodyController.addError( - new HttpException("Connection closed while receiving data")); + _bodyController + .addError(HttpException("Connection closed while receiving data")); } _closeIncoming(true); _controller.close(); @@ -792,8 +784,8 @@ // If the connection is idle the HTTP stream is closed. if (_state == _State.START) { if (!_requestParser) { - _reportError(new HttpException( - "Connection closed before full header was received")); + _reportError( + HttpException("Connection closed before full header was received")); } _controller.close(); return; @@ -808,8 +800,8 @@ _state = _State.FAILURE; // Report the error through the error callback if any. Otherwise // throw the error. - _reportError(new HttpException( - "Connection closed before full header was received")); + _reportError( + HttpException("Connection closed before full header was received")); _controller.close(); return; } @@ -821,7 +813,7 @@ // Report the error through the error callback if any. Otherwise // throw the error. _reportError( - new HttpException("Connection closed before full body was received")); + HttpException("Connection closed before full body was received")); } _controller.close(); } @@ -841,17 +833,17 @@ bool get upgrade => _connectionUpgrade && _state == _State.UPGRADED; bool get persistentConnection => _persistentConnection; - void set isHead(bool value) { + set isHead(bool value) { if (value) _noMessageBody = true; } HttpDetachedIncoming detachIncoming() { // Simulate detached by marking as upgraded. _state = _State.UPGRADED; - return new HttpDetachedIncoming(_socketSubscription, readUnparsedData()); + return HttpDetachedIncoming(_socketSubscription, readUnparsedData()); } - List<int> readUnparsedData() { + Uint8List readUnparsedData() { if (_buffer == null) return null; if (_index == _buffer.length) return null; var result = _buffer.sublist(_index); @@ -889,7 +881,7 @@ } static List<String> _tokenizeFieldValue(String headerValue) { - List<String> tokens = new List<String>(); + List<String> tokens = <String>[]; int start = 0; int index = 0; while (index < headerValue.length) { @@ -925,7 +917,7 @@ void _expect(int val1, int val2) { if (val1 != val2) { - throw new HttpException("Failed to parse HTTP"); + throw HttpException("Failed to parse HTTP"); } } @@ -937,7 +929,7 @@ } else if (0x61 <= byte && byte <= 0x66) { return byte - 0x61 + 10; // a - f } else { - throw new HttpException("Failed to parse HTTP"); + throw HttpException("Failed to parse HTTP"); } } @@ -946,7 +938,7 @@ assert(_bodyController == null); assert(!_bodyPaused); HttpIncoming incoming; - _bodyController = new StreamController<List<int>>( + _bodyController = StreamController<Uint8List>( sync: true, onListen: () { if (incoming != _incoming) return; @@ -975,7 +967,7 @@ _controller.close(); }); incoming = _incoming = - new HttpIncoming(_headers, transferLength, _bodyController.stream); + HttpIncoming(_headers, transferLength, _bodyController.stream); _bodyPaused = true; _pauseStateChanged(); }
diff --git a/lib/src/http_session.dart b/lib/src/http_session.dart index c5b6336..f0a89f8 100644 --- a/lib/src/http_session.dart +++ b/lib/src/http_session.dart
@@ -3,24 +3,16 @@ // BSD-style license that can be found in the LICENSE file. abstract class HttpSession implements Map { - /** - * Gets the id for the current session. - */ + /// Gets the id for the current session. String get id; - /** - * Destroys the session. This will terminate the session and any further - * connections with this id will be given a new id and session. - */ + /// Destroys the session. This will terminate the session and any further + /// connections with this id will be given a new id and session. void destroy(); - /** - * Sets a callback that will be called when the session is timed out. - */ - void set onTimeout(void callback()); + /// Sets a callback that will be called when the session is timed out. + set onTimeout(void callback()); - /** - * Is true if the session has not been sent to the client yet. - */ + /// Is true if the session has not been sent to the client yet. bool get isNew; }
diff --git a/lib/src/http_session_impl.dart b/lib/src/http_session_impl.dart index a89ff0f..8d3f572 100644 --- a/lib/src/http_session_impl.dart +++ b/lib/src/http_session_impl.dart
@@ -19,16 +19,15 @@ bool _isNew = true; DateTime _lastSeen; Function _timeoutCallback; - HttpSessionManager _sessionManager; + final HttpSessionManager _sessionManager; // Pointers in timeout queue. HttpSessionImpl _prev; HttpSessionImpl _next; final String id; - final Map _data = new HashMap(); + final Map _data = HashMap(); - HttpSessionImpl(this._sessionManager, this.id) - : _lastSeen = new DateTime.now(); + HttpSessionImpl(this._sessionManager, this.id) : _lastSeen = DateTime.now(); void destroy() { destroyed = true; @@ -39,7 +38,7 @@ // Mark the session as seen. This will reset the timeout and move the node to // the end of the timeout queue. void markSeen() { - _lastSeen = new DateTime.now(); + _lastSeen = DateTime.now(); _sessionManager._bumpToEnd(this); } @@ -51,7 +50,7 @@ _isNew = false; } - void set onTimeout(void callback()) { + set onTimeout(void callback()) { _timeoutCallback = callback; } @@ -110,7 +109,7 @@ // * In a map, mapping from ID to HttpSession. // * In a linked list, used as a timeout queue. class HttpSessionManager { - Map<String, HttpSessionImpl> _sessions; + final Map<String, HttpSessionImpl> _sessions; int _sessionTimeout = 20 * 60; // 20 mins. HttpSessionImpl _head; HttpSessionImpl _tail; @@ -133,12 +132,12 @@ while (_sessions.containsKey(id)) { id = createSessionId(); } - var session = _sessions[id] = new HttpSessionImpl(this, id); + var session = _sessions[id] = HttpSessionImpl(this, id); _addToTimeoutQueue(session); return session; } - void set sessionTimeout(int timeout) { + set sessionTimeout(int timeout) { _sessionTimeout = timeout; _stopTimer(); _startTimer(); @@ -200,9 +199,9 @@ void _startTimer() { assert(_timer == null); if (_head != null) { - int seconds = new DateTime.now().difference(_head.lastSeen).inSeconds; - _timer = new Timer( - new Duration(seconds: _sessionTimeout - seconds), _timerTimeout); + int seconds = DateTime.now().difference(_head.lastSeen).inSeconds; + _timer = + Timer(Duration(seconds: _sessionTimeout - seconds), _timerTimeout); } }
diff --git a/lib/src/http_status.dart b/lib/src/http_status.dart index 9546a64..4b8e446 100644 --- a/lib/src/http_status.dart +++ b/lib/src/http_status.dart
@@ -2,9 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -/** - * HTTP status codes. - */ +/// HTTP status codes. abstract class HttpStatus { static const int CONTINUE = 100; static const int SWITCHING_PROTOCOLS = 101;
diff --git a/pubspec.yaml b/pubspec.yaml index ce172f1..15d2069 100644 --- a/pubspec.yaml +++ b/pubspec.yaml
@@ -1,12 +1,14 @@ name: http_io -author: "Dart Team <misc@dartlang.org>" -homepage: https://github.com/dart-lang/http_io +repository: https://github.com/dart-lang/http_io description: HTTP Client and Server APIs. +publish_to: none + environment: - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.8.4 <3.0.0" dev_dependencies: - convert: ^2.0.1 - crypto: ^2.0.2+1 + convert: '>=2.1.1 <4.0.0' + crypto: '>=2.1.5 <4.0.0' + pedantic: ^1.0.0 test: ^1.0.0
diff --git a/test/http_100_continue_test.dart b/test/http_100_continue_test.dart index 2a953e5..6c1ab14 100644 --- a/test/http_100_continue_test.dart +++ b/test/http_100_continue_test.dart
@@ -33,7 +33,7 @@ var server = await ServerSocket.bind('127.0.0.1', 0); server.listen(handleSocket); - var client = new HttpClient(); + var client = HttpClient(); var request = await client.getUrl(Uri.parse('http://127.0.0.1:${server.port}/')); var response = await request.close();
diff --git a/test/http_10_test.dart b/test/http_10_test.dart index c2a19ba..677109d 100644 --- a/test/http_10_test.dart +++ b/test/http_10_test.dart
@@ -12,7 +12,7 @@ // server sets a content length but still needs to close the // connection as there is no keep alive. Future<Null> testHttp10NoKeepAlive() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { expect(request.headers.value('content-length'), isNull); @@ -41,7 +41,7 @@ socket.listen(response.addAll, onDone: () { count++; socket.destroy(); - String s = new String.fromCharCodes(response).toLowerCase(); + String s = String.fromCharCodes(response).toLowerCase(); expect(-1, equals(s.indexOf("keep-alive"))); if (count < 10) { makeRequest(); @@ -62,7 +62,7 @@ // content length so it has to close the connection to mark the end of // the response. Future<Null> testHttp10ServerClose() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { expect(request.headers.value('content-length'), isNull); @@ -90,7 +90,7 @@ onDone: () { socket.destroy(); count++; - String s = new String.fromCharCodes(response).toLowerCase(); + String s = String.fromCharCodes(response).toLowerCase(); expect("z", equals(s[s.length - 1])); expect(-1, equals(s.indexOf("content-length:"))); expect(-1, equals(s.indexOf("keep-alive"))); @@ -114,7 +114,7 @@ // server sets a content length so the persistent connection can be // used. Future<Null> testHttp10KeepAlive() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { expect(request.headers.value('content-length'), isNull); @@ -142,7 +142,7 @@ socket.listen((d) { response.addAll(d); if (response[response.length - 1] == "Z".codeUnitAt(0)) { - String s = new String.fromCharCodes(response).toLowerCase(); + String s = String.fromCharCodes(response).toLowerCase(); expect(s.indexOf("\r\nconnection: keep-alive\r\n") > 0, isTrue); expect(s.indexOf("\r\ncontent-length: 1\r\n") > 0, isTrue); count++; @@ -168,7 +168,7 @@ // server does not set a content length so it cannot honor connection // keep alive. Future<Null> testHttp10KeepAliveServerCloses() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { expect(request.headers.value('content-length'), isNull); @@ -193,7 +193,7 @@ socket.listen(response.addAll, onDone: () { socket.destroy(); count++; - String s = new String.fromCharCodes(response).toLowerCase(); + String s = String.fromCharCodes(response).toLowerCase(); expect("z", equals(s[s.length - 1])); expect(-1, equals(s.indexOf("content-length"))); expect(-1, equals(s.indexOf("connection")));
diff --git a/test/http_auth_digest_test.dart b/test/http_auth_digest_test.dart index d2d3bd5..a6152d4 100644 --- a/test/http_auth_digest_test.dart +++ b/test/http_auth_digest_test.dart
@@ -17,13 +17,13 @@ String ha1; static Future<Server> start(String algorithm, String qop, - {int nonceStaleAfter, bool useNextNonce: false}) { - return new Server()._start(algorithm, qop, nonceStaleAfter, useNextNonce); + {int nonceStaleAfter, bool useNextNonce = false}) { + return Server()._start(algorithm, qop, nonceStaleAfter, useNextNonce); } Future<Server> _start(String serverAlgorithm, String serverQop, int nonceStaleAfter, bool useNextNonce) { - Set ncs = new Set(); + Set ncs = Set(); // Calculate ha1. String realm = "test"; String username = "dart"; @@ -33,13 +33,13 @@ var nonce = "12345678"; // No need for random nonce in test. - var completer = new Completer<Server>(); + var completer = Completer<Server>(); HttpServer.bind("127.0.0.1", 0).then((s) { server = s; server.listen((HttpRequest request) { - sendUnauthorizedResponse(HttpResponse response, {stale: false}) { + sendUnauthorizedResponse(HttpResponse response, {stale = false}) { response.statusCode = HttpStatus.UNAUTHORIZED; - StringBuffer authHeader = new StringBuffer(); + StringBuffer authHeader = StringBuffer(); authHeader.write('Digest'); authHeader.write(', realm="$realm"'); authHeader.write(', nonce="$nonce"'); @@ -135,17 +135,17 @@ } Future<Null> testNoCredentials(String algorithm, String qop) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Server.start(algorithm, qop).then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); // Add digest credentials which does not match the path requested. client.addCredentials(Uri.parse("http://127.0.0.1:${server.port}/xxx"), - "test", new HttpClientDigestCredentials("dart", "password")); + "test", HttpClientDigestCredentials("dart", "password")); // Add basic credentials for the path requested. client.addCredentials(Uri.parse("http://127.0.0.1:${server.port}/digest"), - "test", new HttpClientBasicCredentials("dart", "password")); + "test", HttpClientBasicCredentials("dart", "password")); Future makeRequest(Uri url) { return client @@ -172,9 +172,9 @@ } Future<Null> testCredentials(String algorithm, String qop) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Server.start(algorithm, qop).then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); Future makeRequest(Uri url) { return client @@ -188,7 +188,7 @@ } client.addCredentials(Uri.parse("http://127.0.0.1:${server.port}/digest"), - "test", new HttpClientDigestCredentials("dart", "password")); + "test", HttpClientDigestCredentials("dart", "password")); var futures = <Future>[]; for (int i = 0; i < 2; i++) { @@ -207,19 +207,19 @@ } Future<Null> testAuthenticateCallback(String algorithm, String qop) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Server.start(algorithm, qop).then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client.authenticate = (Uri url, String scheme, String realm) { expect("Digest", equals(scheme)); expect("test", equals(realm)); - Completer<bool> completer = new Completer<bool>(); - new Timer(const Duration(milliseconds: 10), () { + Completer<bool> completer = Completer<bool>(); + Timer(const Duration(milliseconds: 10), () { client.addCredentials( Uri.parse("http://127.0.0.1:${server.port}/digest"), "test", - new HttpClientDigestCredentials("dart", "password")); + HttpClientDigestCredentials("dart", "password")); completer.complete(true); }); return completer.future; @@ -251,9 +251,9 @@ } Future<Null> testStaleNonce() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Server.start("MD5", "auth", nonceStaleAfter: 2).then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); Future makeRequest(Uri url) { return client @@ -267,7 +267,7 @@ } Uri uri = Uri.parse("http://127.0.0.1:${server.port}/digest"); - var credentials = new HttpClientDigestCredentials("dart", "password"); + var credentials = HttpClientDigestCredentials("dart", "password"); client.addCredentials(uri, "test", credentials); makeRequest(uri) @@ -286,10 +286,10 @@ } Future<Null> testNextNonce() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Server.start("MD5", "auth", nonceStaleAfter: 2, useNextNonce: true) .then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); Future makeRequest(Uri url) { return client @@ -303,7 +303,7 @@ } Uri uri = Uri.parse("http://127.0.0.1:${server.port}/digest"); - var credentials = new HttpClientDigestCredentials("dart", "password"); + var credentials = HttpClientDigestCredentials("dart", "password"); client.addCredentials(uri, "test", credentials); makeRequest(uri)
diff --git a/test/http_auth_test.dart b/test/http_auth_test.dart index 995ce87..3bcd5a0 100644 --- a/test/http_auth_test.dart +++ b/test/http_auth_test.dart
@@ -13,7 +13,7 @@ bool passwordChanged = false; Future<Server> start() { - var completer = new Completer<Server>(); + var completer = Completer<Server>(); HttpServer.bind("127.0.0.1", 0).then((s) { server = s; server.listen((HttpRequest request) { @@ -67,13 +67,13 @@ } Future<Server> setupServer() { - return new Server().start(); + return Server().start(); } Future<Null> testUrlUserInfo() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://username:password@127.0.0.1:${server.port}/")) @@ -90,9 +90,9 @@ } Future<Null> testBasicNoCredentials() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); Future makeRequest(Uri url) { return client @@ -121,9 +121,9 @@ } Future<Null> testBasicCredentials() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); Future makeRequest(Uri url) { return client @@ -137,7 +137,7 @@ for (int i = 0; i < 5; i++) { client.addCredentials(Uri.parse("http://127.0.0.1:${server.port}/test$i"), - "realm", new HttpClientBasicCredentials("test$i", "test$i")); + "realm", HttpClientBasicCredentials("test$i", "test$i")); } var futures = <Future>[]; @@ -157,9 +157,9 @@ } Future<Null> testBasicAuthenticateCallback() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); bool passwordChanged = false; client.authenticate = (Uri url, String scheme, String realm) { @@ -168,10 +168,10 @@ String username = url.path.substring(1, 6); String password = url.path.substring(1, 6); if (passwordChanged) password = "${password}1"; - Completer<bool> completer = new Completer<bool>(); - new Timer(const Duration(milliseconds: 10), () { + Completer<bool> completer = Completer<bool>(); + Timer(const Duration(milliseconds: 10), () { client.addCredentials( - url, realm, new HttpClientBasicCredentials(username, password)); + url, realm, HttpClientBasicCredentials(username, password)); completer.complete(true); }); return completer.future;
diff --git a/test/http_bind_test.dart b/test/http_bind_test.dart index ce4c773..79a4267 100644 --- a/test/http_bind_test.dart +++ b/test/http_bind_test.dart
@@ -12,7 +12,7 @@ // Sent a single request using a new HttpClient to ensure a new TCP // connection is used. Future singleRequest(host, port, statusCode) async { - var client = new HttpClient(); + var client = HttpClient(); var request = await client.open('GET', host, port, '/'); var response = await request.close(); await response.drain(); @@ -20,8 +20,8 @@ client.close(force: true); } - Completer server1Request = new Completer(); - Completer server2Request = new Completer(); + Completer server1Request = Completer(); + Completer server2Request = Completer(); var server1 = await HttpServer.bind(host, 0, v6Only: v6Only, shared: true); var port = server1.port;
diff --git a/test/http_client_connect_test.dart b/test/http_client_connect_test.dart index cdb481c..ad14857 100644 --- a/test/http_client_connect_test.dart +++ b/test/http_client_connect_test.dart
@@ -9,13 +9,13 @@ import "package:test/test.dart"; Future<Null> testGetEmptyRequest() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.pipe(request.response); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -30,7 +30,7 @@ } Future<Null> testGetDataRequest() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { var data = "lalala".codeUnits; server.listen((request) { @@ -38,7 +38,7 @@ request.pipe(request.response); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -55,8 +55,8 @@ } Future<Null> testGetInvalidHost() { - Completer<Null> completer = new Completer(); - var client = new HttpClient(); + Completer<Null> completer = Completer(); + var client = HttpClient(); client.get("__SOMETHING_INVALID__", 8888, "/").catchError((error) { client.close(); completer.complete(null); @@ -65,16 +65,16 @@ } Future<Null> testGetServerClose() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { server.close(); - new Timer(const Duration(milliseconds: 100), () { + Timer(const Duration(milliseconds: 100), () { request.response.close(); }); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -85,8 +85,8 @@ } Future<Null> testGetServerCloseNoKeepAlive() { - Completer<Null> completer = new Completer(); - var client = new HttpClient(); + Completer<Null> completer = Completer(); + var client = HttpClient(); HttpServer.bind("127.0.0.1", 0).then((server) { int port = server.port; server.first.then((request) => request.response.close()); @@ -104,13 +104,13 @@ } Future<Null> testGetServerForceClose() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { server.close(force: true); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -123,8 +123,8 @@ } Future<Null> testGetDataServerForceClose() { - Completer<Null> testCompleter = new Completer(); - var completer = new Completer(); + Completer<Null> testCompleter = Completer(); + var completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.response.bufferOutput = false; @@ -134,7 +134,7 @@ completer.future.then((_) => server.close(force: true)); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -154,9 +154,10 @@ return testCompleter.future; } -typedef Future<HttpClientRequest> Callback1(String a1, int a2, String a3); +typedef Callback1 = Future<HttpClientRequest> Function( + String a1, int a2, String a3); Future<Null> testOpenEmptyRequest() async { - var client = new HttpClient(); + var client = HttpClient(); var methods = [ [client.get, 'GET'], [client.post, 'POST'], @@ -167,7 +168,7 @@ ]; for (var method in methods) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); await HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { expect(method[1], equals(request.method)); @@ -188,9 +189,9 @@ } } -typedef Future<HttpClientRequest> Callback2(Uri a1); +typedef Callback2 = Future<HttpClientRequest> Function(Uri a1); Future<Null> testOpenUrlEmptyRequest() async { - var client = new HttpClient(); + var client = HttpClient(); var methods = [ [client.getUrl, 'GET'], [client.postUrl, 'POST'], @@ -201,7 +202,7 @@ ]; for (var method in methods) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); await HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { expect(method[1], equals(request.method)); @@ -223,7 +224,7 @@ } Future<Null> testNoBuffer() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { HttpResponse response; server.listen((request) { @@ -232,13 +233,13 @@ response.writeln('init'); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((clientResponse) { - var iterator = new StreamIterator( - clientResponse.transform(utf8.decoder).transform(new LineSplitter())); + var iterator = StreamIterator( + clientResponse.transform(utf8.decoder).transform(LineSplitter())); iterator.moveNext().then((hasValue) { expect(hasValue, isTrue); expect('init', equals(iterator.current)); @@ -270,7 +271,7 @@ } Future<Null> testMaxConnectionsPerHost(int connectionCap, int connections) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { int handled = 0; server.listen((request) { @@ -283,7 +284,7 @@ } }); - var client = new HttpClient(); + var client = HttpClient(); client.maxConnectionsPerHost = connectionCap; for (int i = 0; i < connections; i++) { client
diff --git a/test/http_client_exception_test.dart b/test/http_client_exception_test.dart index aa0b488..5aab7c0 100644 --- a/test/http_client_exception_test.dart +++ b/test/http_client_exception_test.dart
@@ -11,7 +11,7 @@ } void testInvalidUrl() { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); List<List<String>> tests = <List<String>>[ <String>["ftp://www.google.com", "Unsupported scheme"], <String>["httpx://www.google.com", "Unsupported scheme"], @@ -30,7 +30,7 @@ } void testBadHostName() { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); expect(() => client.get("some.bad.host.name.7654321", 0, "/"), throwsA(predicate((e) => e.toString().contains("Failed host lookup")))); }
diff --git a/test/http_client_request_test.dart b/test/http_client_request_test.dart index 5ce5fa4..c67634e 100644 --- a/test/http_client_request_test.dart +++ b/test/http_client_request_test.dart
@@ -9,13 +9,13 @@ import "package:test/test.dart"; Future<Null> testClientRequest(Future handler(request)) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.drain().then((_) => request.response.close()).catchError((_) {}); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) { @@ -45,7 +45,7 @@ Future<Null> testBadResponseAdd() async { await testClientRequest((request) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); request.contentLength = 0; request.add([0]); request.close(); @@ -56,7 +56,7 @@ }); await testClientRequest((request) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); request.contentLength = 5; request.add([0, 0, 0]); request.add([0, 0, 0]); @@ -68,11 +68,11 @@ }); await testClientRequest((request) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); request.contentLength = 0; - request.add(new Uint8List(64 * 1024)); - request.add(new Uint8List(64 * 1024)); - request.add(new Uint8List(64 * 1024)); + request.add(Uint8List(64 * 1024)); + request.add(Uint8List(64 * 1024)); + request.add(Uint8List(64 * 1024)); request.close(); request.done.catchError((error) { completer.complete(null); @@ -83,7 +83,7 @@ Future<Null> testBadResponseClose() async { await testClientRequest((request) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); request.contentLength = 5; request.close(); request.done.catchError((error) { @@ -93,7 +93,7 @@ }); await testClientRequest((request) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); request.contentLength = 5; request.add([0]); request.close();
diff --git a/test/http_client_stays_alive_test.dart b/test/http_client_stays_alive_test.dart index 3e208af..5944f94 100644 --- a/test/http_client_stays_alive_test.dart +++ b/test/http_client_stays_alive_test.dart
@@ -30,7 +30,7 @@ } Future<Null> runServerProcess() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind('127.0.0.1', 0).then((server) { var url = 'http://127.0.0.1:${server.port}/'; @@ -42,10 +42,10 @@ ..close(); }); - var sw = new Stopwatch()..start(); + var sw = Stopwatch()..start(); var script = "${Directory.current.path}/test/http_client_stays_alive_test.dart"; - if (!(new File(script)).existsSync()) { + if (!(File(script)).existsSync()) { // If we can't find the file relative to the cwd, then look relative to // Platform.script. script = Platform.script @@ -81,7 +81,7 @@ // NOTE: We make an HTTP client request and then *forget to close* the HTTP // client instance. The idle timer should fire after SECONDS. - var client = new HttpClient(); + var client = HttpClient(); client.idleTimeout = const Duration(seconds: SECONDS); client
diff --git a/test/http_close_test.dart b/test/http_close_test.dart index 62213be..5caa65d 100644 --- a/test/http_close_test.dart +++ b/test/http_close_test.dart
@@ -10,7 +10,7 @@ import "package:test/test.dart"; Future<Null> testClientAndServerCloseNoListen(int connections) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { int closed = 0; server.listen((request) { @@ -26,7 +26,7 @@ } }); }); - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { client .get("127.0.0.1", server.port, "/") @@ -38,7 +38,7 @@ } Future<Null> testClientCloseServerListen(int connections) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { int closed = 0; void check() { @@ -58,7 +58,7 @@ request.response.done.then((_) => check()); }); }); - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { client .get("127.0.0.1", server.port, "/") @@ -70,9 +70,9 @@ } Future<Null> testClientCloseSendingResponse(int connections) { - Completer<Null> completer = new Completer(); - var buffer = new Uint8List(64 * 1024); - var rand = new Random(); + Completer<Null> completer = Completer(); + var buffer = Uint8List(64 * 1024); + var rand = Random(); for (int i = 0; i < buffer.length; i++) { buffer[i] = rand.nextInt(256); } @@ -91,7 +91,7 @@ } server.listen((request) { - var timer = new Timer.periodic(const Duration(milliseconds: 50), (_) { + var timer = Timer.periodic(const Duration(milliseconds: 50), (_) { request.response.add(buffer); }); request.response.done.catchError((_) {}).whenComplete(() { @@ -99,7 +99,7 @@ timer.cancel(); }); }); - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { client .get("127.0.0.1", server.port, "/") @@ -108,7 +108,7 @@ // Ensure we don't accept the response until we have send the entire // request. var subscription = response.listen((_) {}); - new Timer(const Duration(milliseconds: 20), () { + Timer(const Duration(milliseconds: 20), () { subscription.cancel(); check(); }); @@ -119,7 +119,7 @@ } Future<Null> testClientCloseWhileSendingRequest(int connections) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) async { server.listen((request) { request.listen((_) {}, onError: (e) { @@ -128,7 +128,7 @@ expect(e is HttpException, isTrue); }); }); - var client = new HttpClient(); + var client = HttpClient(); int closed = 0; for (int i = 0; i < connections; i++) { await client.post("127.0.0.1", server.port, "/").then((request) {
diff --git a/test/http_compression_test.dart b/test/http_compression_test.dart index 90114ac..0a3025b 100644 --- a/test/http_compression_test.dart +++ b/test/http_compression_test.dart
@@ -9,15 +9,15 @@ import "package:http_io/http_io.dart"; import "package:test/test.dart"; -Future<Null> testWithData(List<int> data, {bool clientAutoUncompress: true}) { - Completer<Null> completer = new Completer(); +Future<Null> testWithData(List<int> data, {bool clientAutoUncompress = true}) { + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.autoCompress = true; server.listen((request) { request.response.add(data); request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client.autoUncompress = clientAutoUncompress; client.get("127.0.0.1", server.port, "/").then((request) { request.headers.set(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate"); @@ -43,13 +43,13 @@ return completer.future; } -Future<Null> testRawServerCompressData({bool clientAutoUncompress: true}) { +Future<Null> testRawServerCompressData({bool clientAutoUncompress = true}) { return testWithData("My raw server provided data".codeUnits, clientAutoUncompress: clientAutoUncompress); } -Future<Null> testServerCompressLong({bool clientAutoUncompress: true}) { - var longBuffer = new Uint8List(1024 * 1024); +Future<Null> testServerCompressLong({bool clientAutoUncompress = true}) { + var longBuffer = Uint8List(1024 * 1024); for (int i = 0; i < longBuffer.length; i++) { longBuffer[i] = i & 0xFF; } @@ -68,14 +68,14 @@ } Future<Null> acceptEncodingHeaderHelper(String encoding, bool valid) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.autoCompress = true; server.listen((request) { request.response.write("data"); request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client.get("127.0.0.1", server.port, "/").then((request) { request.headers.set(HttpHeaders.ACCEPT_ENCODING, encoding); return request.close(); @@ -122,7 +122,7 @@ } Future<Null> testDisableCompressTest() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { expect(false, equals(server.autoCompress)); server.listen((request) { @@ -131,7 +131,7 @@ request.response.write("data"); request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close())
diff --git a/test/http_connection_close_test.dart b/test/http_connection_close_test.dart index 876566a..be9526f 100644 --- a/test/http_connection_close_test.dart +++ b/test/http_connection_close_test.dart
@@ -9,7 +9,7 @@ import "package:test/test.dart"; Future<Null> testHttp10Close(bool closeRequest) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.response.close(); @@ -29,7 +29,7 @@ } Future<Null> testHttp11Close(bool closeRequest) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.response.close(); @@ -49,19 +49,19 @@ } Future<Null> testStreamResponse() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { - var timer = new Timer.periodic(const Duration(milliseconds: 0), (_) { + var timer = Timer.periodic(const Duration(milliseconds: 0), (_) { request.response - .write('data:${new DateTime.now().millisecondsSinceEpoch}\n\n'); + .write('data:${DateTime.now().millisecondsSinceEpoch}\n\n'); }); request.response.done.whenComplete(() { timer.cancel(); }).catchError((_) {}); }); - var client = new HttpClient(); + var client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}")) .then((request) => request.close())
diff --git a/test/http_connection_header_test.dart b/test/http_connection_header_test.dart index 49e48f2..aebe3cd 100644 --- a/test/http_connection_header_test.dart +++ b/test/http_connection_header_test.dart
@@ -44,7 +44,7 @@ } Future<Null> headerTest(int totalConnections, bool clientPersistentConnection) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { // Check expected request. @@ -64,7 +64,7 @@ }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client .get("127.0.0.1", server.port, "/")
diff --git a/test/http_connection_info_test.dart b/test/http_connection_info_test.dart index 3ce625d..8389edd 100644 --- a/test/http_connection_info_test.dart +++ b/test/http_connection_info_test.dart
@@ -8,7 +8,7 @@ import "package:test/test.dart"; Future<Null> testHttpConnectionInfo() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("0.0.0.0", 0).then((server) { int clientPort; @@ -26,7 +26,7 @@ }); }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client.get("127.0.0.1", server.port, "/").then((request) { expect(request.connectionInfo.remoteAddress is InternetAddress, isTrue); expect(request.connectionInfo.remotePort, equals(server.port));
diff --git a/test/http_content_length_test.dart b/test/http_content_length_test.dart index 80d81f7..01fe62d 100644 --- a/test/http_content_length_test.dart +++ b/test/http_content_length_test.dart
@@ -8,7 +8,7 @@ import "package:test/test.dart"; Future<Null> testNoBody(int totalConnections, bool explicitContentLength) { - var completer = new Completer<Null>(); + var completer = Completer<Null>(); int count = 0; HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { server.listen((HttpRequest request) { @@ -41,7 +41,7 @@ fail(msg); }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client.get("127.0.0.1", server.port, "/").then((request) { if (explicitContentLength) { @@ -61,7 +61,7 @@ } Future<Null> testBody(int totalConnections, bool useHeader) { - var completer = new Completer<Null>(); + var completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { int serverCount = 0; server.listen((HttpRequest request) { @@ -102,7 +102,7 @@ }); int clientCount = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client.get("127.0.0.1", server.port, "/").then((request) { if (useHeader) { @@ -139,7 +139,7 @@ } Future<Null> testBodyChunked(int totalConnections, bool useHeader) { - var completer = new Completer<Null>(); + var completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { server.listen((HttpRequest request) { expect(request.headers.value('content-length'), isNull); @@ -172,7 +172,7 @@ }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client.get("127.0.0.1", server.port, "/").then((request) { if (useHeader) { @@ -213,7 +213,7 @@ } Future<Null> testSetContentLength() { - var completer = new Completer<Null>(); + var completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { var response = request.response; @@ -226,7 +226,7 @@ response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close())
diff --git a/test/http_cookie_date_test.dart b/test/http_cookie_date_test.dart index 0d4b0cc..a46c4b2 100644 --- a/test/http_cookie_date_test.dart +++ b/test/http_cookie_date_test.dart
@@ -9,12 +9,11 @@ import 'package:test/test.dart'; void testParseHttpCookieDate() { - expect(() => parseCookieDate(""), throwsA(new TypeMatcher<HttpException>())); + expect(() => parseCookieDate(""), throwsA(TypeMatcher<HttpException>())); test(int year, int month, int day, int hours, int minutes, int seconds, String formatted) { - DateTime date = - new DateTime.utc(year, month, day, hours, minutes, seconds, 0); + DateTime date = DateTime.utc(year, month, day, hours, minutes, seconds, 0); expect(date, parseCookieDate(formatted)); }
diff --git a/test/http_cookie_test.dart b/test/http_cookie_test.dart index 62db043..b4b3d9c 100644 --- a/test/http_cookie_test.dart +++ b/test/http_cookie_test.dart
@@ -8,7 +8,7 @@ import 'package:test/test.dart'; Future<Null> testCookies() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); var cookies = [ {'abc': 'def'}, {'ABC': 'DEF'}, @@ -25,18 +25,18 @@ expect(cookies[index], cookiesMap); // Return the same cookies to the client. cookiesMap.forEach((k, v) { - request.response.cookies.add(new Cookie(k, v)); + request.response.cookies.add(Cookie(k, v)); }); request.response.close(); }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < cookies.length; i++) { client.get("127.0.0.1", server.port, "/$i").then((request) { // Send the cookies to the server. cookies[i].forEach((k, v) { - request.cookies.add(new Cookie(k, v)); + request.cookies.add(Cookie(k, v)); }); return request.close(); }).then((response) {
diff --git a/test/http_cross_process_test.dart b/test/http_cross_process_test.dart index 56f198f..8e3717a 100644 --- a/test/http_cross_process_test.dart +++ b/test/http_cross_process_test.dart
@@ -39,10 +39,10 @@ }); } -Future<Process> runClientProcess(int port) { +Future<void> runClientProcess(int port) { var script = "${Directory.current.path}/test/http_client_stays_alive_test.dart"; - if (!(new File(script)).existsSync()) { + if (!(File(script)).existsSync()) { // If we can't find the file relative to the cwd, then look relative to // Platform.script. script = Platform.script @@ -70,7 +70,7 @@ } void runClient(int port) { - var client = new HttpClient(); + var client = HttpClient(); client .get('127.0.0.1', port, "/") .then((request) => request.close())
diff --git a/test/http_date_test.dart b/test/http_date_test.dart index 38a848b..c70b3b7 100644 --- a/test/http_date_test.dart +++ b/test/http_date_test.dart
@@ -7,17 +7,17 @@ void testParseHttpDate() { DateTime date; - date = new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); + date = DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); expect(date, HttpDate.parse("Fri, 11 Jun 1999 18:46:53 GMT")); expect(date, HttpDate.parse("Friday, 11-Jun-1999 18:46:53 GMT")); expect(date, HttpDate.parse("Fri Jun 11 18:46:53 1999")); - date = new DateTime.utc(1970, DateTime.january, 1, 0, 0, 0, 0); + date = DateTime.utc(1970, DateTime.january, 1, 0, 0, 0, 0); expect(date, HttpDate.parse("Thu, 1 Jan 1970 00:00:00 GMT")); expect(date, HttpDate.parse("Thursday, 1-Jan-1970 00:00:00 GMT")); expect(date, HttpDate.parse("Thu Jan 1 00:00:00 1970")); - date = new DateTime.utc(2012, DateTime.march, 5, 23, 59, 59, 0); + date = DateTime.utc(2012, DateTime.march, 5, 23, 59, 59, 0); expect(date, HttpDate.parse("Mon, 5 Mar 2012 23:59:59 GMT")); expect(date, HttpDate.parse("Monday, 5-Mar-2012 23:59:59 GMT")); expect(date, HttpDate.parse("Mon Mar 5 23:59:59 2012")); @@ -28,7 +28,7 @@ String expectedFormatted) { DateTime date; String formatted; - date = new DateTime.utc(year, month, day, hours, minutes, seconds, 0); + date = DateTime.utc(year, month, day, hours, minutes, seconds, 0); formatted = HttpDate.format(date); expect(expectedFormatted, formatted); expect(date, HttpDate.parse(formatted)); @@ -43,7 +43,7 @@ void testParseHttpDateFailures() { // The calls below can throw different exceptions based on the iteration of // the loop. This matcher catches all exceptions. - final throws = throwsA(new TypeMatcher<Object>()); + final throws = throwsA(TypeMatcher<Object>()); expect(() { HttpDate.parse(""); }, throws);
diff --git a/test/http_detach_socket_test.dart b/test/http_detach_socket_test.dart index c0b645d..369e822 100644 --- a/test/http_detach_socket_test.dart +++ b/test/http_detach_socket_test.dart
@@ -9,7 +9,7 @@ import 'package:test/test.dart'; Future<Null> testServerDetachSocket() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.defaultResponseHeaders.clear(); server.serverHeader = null; @@ -18,8 +18,8 @@ response.contentLength = 0; response.detachSocket().then((socket) { expect(socket, isNotNull); - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () => expect("Some data", body.toString())); socket.write("Test!"); socket.close(); @@ -32,8 +32,8 @@ socket.write("GET / HTTP/1.1\r\n" "content-length: 0\r\n\r\n" "Some data"); - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () { expect( "HTTP/1.1 200 OK\r\n" @@ -49,15 +49,15 @@ } Future<Null> testServerDetachSocketNoWriteHeaders() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { var response = request.response; response.contentLength = 0; response.detachSocket(writeHeaders: false).then((socket) { expect(socket, isNotNull); - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () => expect("Some data", body.toString())); socket.write("Test!"); socket.close(); @@ -70,8 +70,8 @@ socket.write("GET / HTTP/1.1\r\n" "content-length: 0\r\n\r\n" "Some data"); - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () { expect("Test!", body.toString()); socket.close(); @@ -82,13 +82,13 @@ } Future<Null> testBadServerDetachSocket() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { var response = request.response; response.contentLength = 0; response.close(); - expect(response.detachSocket, throwsA(new TypeMatcher<StateError>())); + expect(response.detachSocket, throwsA(TypeMatcher<StateError>())); server.close(); completer.complete(); }); @@ -105,15 +105,15 @@ } Future<Null> testClientDetachSocket() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); ServerSocket.bind("127.0.0.1", 0).then((server) { server.listen((socket) { int port = server.port; socket.write("HTTP/1.1 200 OK\r\n" "\r\n" "Test!"); - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () { List<String> lines = body.toString().split("\r\n"); expect(6, lines.length); @@ -130,15 +130,15 @@ completer.complete(); }); - var client = new HttpClient(); + var client = HttpClient(); client.userAgent = null; client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { response.detachSocket().then((socket) { - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), + var body = StringBuffer(); + socket.listen((data) => body.write(String.fromCharCodes(data)), onDone: () { expect("Test!", body.toString()); client.close(); @@ -152,20 +152,20 @@ } Future<Null> testUpgradedConnection() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.response.headers.set('connection', 'upgrade'); if (request.headers.value('upgrade') == 'mine') { request.response.detachSocket().then((socket) { - socket.pipe(socket).then((_) {}); + socket.cast<List<int>>().pipe(socket).then((_) {}); }); } else { request.response.close(); } }); - var client = new HttpClient(); + var client = HttpClient(); client.userAgent = null; client.get("127.0.0.1", server.port, "/").then((request) { request.headers.set('upgrade', 'mine');
diff --git a/test/http_head_test.dart b/test/http_head_test.dart index a38ad7c..c74d2e8 100644 --- a/test/http_head_test.dart +++ b/test/http_head_test.dart
@@ -8,7 +8,7 @@ import 'package:test/test.dart'; Future<Null> testHEAD(int totalConnections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) async { server.listen((request) { var response = request.response; @@ -17,15 +17,15 @@ response.close(); } else if (request.uri.path == "/test200") { response.contentLength = 200; - List<int> data = new List<int>.filled(200, 0); + List<int> data = List<int>.filled(200, 0); response.add(data); response.close(); } else if (request.uri.path == "/testChunked100") { - List<int> data = new List<int>.filled(100, 0); + List<int> data = List<int>.filled(100, 0); response.add(data); response.close(); } else if (request.uri.path == "/testChunked200") { - List<int> data = new List<int>.filled(200, 0); + List<int> data = List<int>.filled(200, 0); response.add(data); response.close(); } else { @@ -33,7 +33,7 @@ } }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); int count = 0;
diff --git a/test/http_headers_state_test.dart b/test/http_headers_state_test.dart index dd5f0fb..516620a 100644 --- a/test/http_headers_state_test.dart +++ b/test/http_headers_state_test.dart
@@ -8,13 +8,13 @@ import 'package:test/test.dart'; Future<Null> runTest(int totalConnections, [String body]) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) async { server.listen((HttpRequest request) { HttpResponse response = request.response; // Cannot mutate request headers. expect(() => request.headers.add("X-Request-Header", "value"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); expect("value", request.headers.value("X-Request-Header")); request.listen((_) {}, onDone: () { // Can still mutate response headers as long as no data has been sent. @@ -26,7 +26,7 @@ expect(() => response.reasonPhrase = "OK", throwsStateError); // Cannot mutate response headers when data has been sent. expect(() => response.headers.add("X-Request-Header", "value2"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); } response..close(); // Cannot change state or reason after connection is closed. @@ -34,12 +34,12 @@ expect(() => response.reasonPhrase = "OK", throwsStateError); // Cannot mutate response headers after connection is closed. expect(() => response.headers.add("X-Request-Header", "value3"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); }); }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { await client .get("127.0.0.1", server.port, "/") @@ -53,17 +53,17 @@ request.write(body); // Cannot mutate request headers when data has been sent. expect(() => request.headers.add("X-Request-Header", "value2"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); } request.close(); // Cannot mutate request headers when data has been sent. expect(() => request.headers.add("X-Request-Header", "value3"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); return request.done; }).then((HttpClientResponse response) { // Cannot mutate response headers. expect(() => response.headers.add("X-Response-Header", "value"), - throwsA(new TypeMatcher<HttpException>())); + throwsA(TypeMatcher<HttpException>())); expect("value", response.headers.value("X-Response-Header")); response.listen((_) {}, onDone: () { // Do not close the connections before we have read the
diff --git a/test/http_headers_test.dart b/test/http_headers_test.dart index 08ac899..dd86cf0 100644 --- a/test/http_headers_test.dart +++ b/test/http_headers_test.dart
@@ -7,7 +7,7 @@ import 'package:test/test.dart'; void testMultiValue() { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers[HttpHeaders.PRAGMA], isNull); headers.add(HttpHeaders.PRAGMA, "pragma1"); expect(1, equals(headers[HttpHeaders.PRAGMA].length)); @@ -43,12 +43,12 @@ } void testDate() { - DateTime date1 = new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); + DateTime date1 = DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); String httpDate1 = "Fri, 11 Jun 1999 18:46:53 GMT"; - DateTime date2 = new DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); + DateTime date2 = DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); String httpDate2 = "Wed, 16 Aug 2000 12:34:56 GMT"; - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers.date, isNull); headers.date = date1; expect(date1, headers.date); @@ -69,12 +69,12 @@ } void testExpires() { - DateTime date1 = new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); + DateTime date1 = DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); String httpDate1 = "Fri, 11 Jun 1999 18:46:53 GMT"; - DateTime date2 = new DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); + DateTime date2 = DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); String httpDate2 = "Wed, 16 Aug 2000 12:34:56 GMT"; - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers.expires, isNull); headers.expires = date1; expect(date1, headers.expires); @@ -95,12 +95,12 @@ } void testIfModifiedSince() { - DateTime date1 = new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); + DateTime date1 = DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0); String httpDate1 = "Fri, 11 Jun 1999 18:46:53 GMT"; - DateTime date2 = new DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); + DateTime date2 = DateTime.utc(2000, DateTime.august, 16, 12, 34, 56, 0); String httpDate2 = "Wed, 16 Aug 2000 12:34:56 GMT"; - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers.ifModifiedSince, isNull); headers.ifModifiedSince = date1; expect(date1, headers.ifModifiedSince); @@ -122,7 +122,7 @@ void testHost() { String host = "www.google.com"; - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers.host, isNull); expect(headers.port, isNull); headers.host = host; @@ -132,7 +132,7 @@ headers.port = HttpClient.DEFAULT_HTTP_PORT; expect(host, headers.value(HttpHeaders.HOST)); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.add(HttpHeaders.HOST, host); expect(host, headers.host); expect(HttpClient.DEFAULT_HTTP_PORT, headers.port); @@ -141,13 +141,13 @@ expect(host, headers.host); expect(4567, headers.port); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.add(HttpHeaders.HOST, "$host:xxx"); expect("$host:xxx", headers.value(HttpHeaders.HOST)); expect(host, headers.host); expect(headers.port, isNull); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.add(HttpHeaders.HOST, ":1234"); expect(":1234", headers.value(HttpHeaders.HOST)); expect(headers.host, isNull); @@ -167,41 +167,41 @@ HttpHeadersImpl headers; - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.chunkedTransferEncoding = true; expectChunked(headers); headers.set('transfer-encoding', ['chunked']); expectChunked(headers); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.set('transfer-encoding', ['chunked']); expectChunked(headers); headers.chunkedTransferEncoding = true; expectChunked(headers); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.chunkedTransferEncoding = true; headers.chunkedTransferEncoding = false; expectNonChunked(headers); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.chunkedTransferEncoding = true; headers.remove('transfer-encoding', 'chunked'); expectNonChunked(headers); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.set('transfer-encoding', ['chunked']); headers.chunkedTransferEncoding = false; expectNonChunked(headers); - headers = new HttpHeadersImpl("1.1"); + headers = HttpHeadersImpl("1.1"); headers.set('transfer-encoding', ['chunked']); headers.remove('transfer-encoding', 'chunked'); expectNonChunked(headers); } void testEnumeration() { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(headers[HttpHeaders.PRAGMA], isNull); headers.add("My-Header-1", "value 1"); headers.add("My-Header-2", "value 2"); @@ -213,12 +213,12 @@ totalValues += values.length; if (name == "my-header-1") { myHeader1 = true; - expect(values.indexOf("value 1") != -1, isTrue); - expect(values.indexOf("value 3") != -1, isTrue); + expect(values, contains("value 1")); + expect(values, contains("value 3")); } if (name == "my-header-2") { myHeader2 = true; - expect(values.indexOf("value 2") != -1, isTrue); + expect(values, contains("value 2")); } }); expect(myHeader1, isTrue); @@ -245,7 +245,7 @@ HeaderValue.parse("xxx; aaa=bbb; ccc=\"\\\";\\a\"; ddd=\" \""); check(headerValue, "xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); headerValue = - new HeaderValue("xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); + HeaderValue("xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); check(headerValue, "xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); headerValue = HeaderValue.parse("attachment; filename=genome.jpeg;" @@ -255,7 +255,7 @@ "modification-date": "Wed, 12 February 1997 16:29:51 -0500" }; check(headerValue, "attachment", parameters); - headerValue = new HeaderValue("attachment", parameters); + headerValue = HeaderValue("attachment", parameters); check(headerValue, "attachment", parameters); headerValue = HeaderValue.parse(" attachment ;filename=genome.jpeg ;" "modification-date = \"Wed, 12 February 1997 16:29:51 -0500\""); @@ -281,7 +281,7 @@ } ContentType contentType; - contentType = new ContentType("", ""); + contentType = ContentType("", ""); expect("", contentType.primaryType); expect("", contentType.subType); expect("/", contentType.value); @@ -291,13 +291,13 @@ contentType = ContentType.parse("text/html"); check(contentType, "text", "html"); expect("text/html", contentType.toString()); - contentType = new ContentType("text", "html", charset: "utf-8"); + contentType = ContentType("text", "html", charset: "utf-8"); check(contentType, "text", "html", {"charset": "utf-8"}); expect("text/html; charset=utf-8", contentType.toString()); expect( () => contentType.parameters["xxx"] = "yyy", throwsA(isUnsupportedError)); - contentType = new ContentType("text", "html", + contentType = ContentType("text", "html", parameters: {"CHARSET": "UTF-8", "xxx": "YYY"}); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "YYY"}); String s = contentType.toString(); @@ -309,7 +309,7 @@ expect( () => contentType.parameters["xxx"] = "yyy", throwsA(isUnsupportedError)); - contentType = new ContentType("text", "html", + contentType = ContentType("text", "html", charset: "ISO-8859-1", parameters: {"CHARSET": "UTF-8", "xxx": "yyy"}); check(contentType, "text", "html", {"charset": "iso-8859-1", "xxx": "yyy"}); s = contentType.toString(); @@ -363,7 +363,7 @@ } void testContentTypeCache() { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); headers.set(HttpHeaders.CONTENT_TYPE, "text/html"); expect("text", headers.contentType.primaryType); expect("html", headers.contentType.subType); @@ -387,14 +387,14 @@ void checkCookie(cookie, s) { expect(s, cookie.toString()); - var c = new Cookie.fromSetCookieValue(s); + var c = Cookie.fromSetCookieValue(s); checkCookiesEquals(cookie, c); } Cookie cookie; - cookie = new Cookie(name, value); + cookie = Cookie(name, value); expect("$name=$value; HttpOnly", cookie.toString()); - DateTime date = new DateTime.utc(2014, DateTime.january, 5, 23, 59, 59, 0); + DateTime date = DateTime.utc(2014, DateTime.january, 5, 23, 59, 59, 0); cookie.expires = date; checkCookie( cookie, @@ -482,18 +482,17 @@ } void testInvalidCookie() { - expect(() => new Cookie.fromSetCookieValue(""), throwsA(isException)); - expect(() => new Cookie.fromSetCookieValue("="), throwsA(isException)); - expect(() => new Cookie.fromSetCookieValue("=xxx"), throwsA(isException)); - expect(() => new Cookie.fromSetCookieValue("xxx"), throwsA(isException)); - expect(() => new Cookie.fromSetCookieValue("xxx=yyy; expires=12 jan 2013"), + expect(() => Cookie.fromSetCookieValue(""), throwsA(isException)); + expect(() => Cookie.fromSetCookieValue("="), throwsA(isException)); + expect(() => Cookie.fromSetCookieValue("=xxx"), throwsA(isException)); + expect(() => Cookie.fromSetCookieValue("xxx"), throwsA(isException)); + expect(() => Cookie.fromSetCookieValue("xxx=yyy; expires=12 jan 2013"), throwsA(isException)); - expect( - () => new Cookie.fromSetCookieValue("x x = y y"), throwsA(isException)); - expect(() => new Cookie("[4", "y"), throwsA(isException)); - expect(() => new Cookie("4", "y\""), throwsA(isException)); + expect(() => Cookie.fromSetCookieValue("x x = y y"), throwsA(isException)); + expect(() => Cookie("[4", "y"), throwsA(isException)); + expect(() => Cookie("4", "y\""), throwsA(isException)); - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); headers.set( 'Cookie', 'DARTSESSID=d3d6fdd78d51aaaf2924c32e991f4349; undefined'); expect('DARTSESSID', headers.parseCookies().single.name); @@ -510,7 +509,7 @@ void testInvalidFieldName() { void test(String field) { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(() => headers.add(field, "value"), throwsA(isFormatException)); expect(() => headers.set(field, "value"), throwsA(isFormatException)); expect(() => headers.remove(field, "value"), throwsA(isFormatException)); @@ -524,8 +523,8 @@ } void testInvalidFieldValue() { - void test(value, {bool remove: true}) { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + void test(value, {bool remove = true}) { + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); expect(() => headers.add("field", value), throwsA(isFormatException)); expect(() => headers.set("field", value), throwsA(isFormatException)); if (remove) { @@ -537,11 +536,11 @@ test('\n'); test('test\x00'); // Test we handle other types correctly. - test(new StringBuffer('\x00'), remove: false); + test(StringBuffer('\x00'), remove: false); } void testClear() { - HttpHeadersImpl headers = new HttpHeadersImpl("1.1"); + HttpHeadersImpl headers = HttpHeadersImpl("1.1"); headers.add("a", "b"); headers.contentLength = 7; headers.chunkedTransferEncoding = true;
diff --git a/test/http_ipv6_test.dart b/test/http_ipv6_test.dart index f2135b3..7bf7b5e 100644 --- a/test/http_ipv6_test.dart +++ b/test/http_ipv6_test.dart
@@ -11,7 +11,7 @@ // server sets a content length but still needs to close the // connection as there is no keep alive. Future<Null> testHttpIPv6() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("::", 0).then((server) { server.listen((HttpRequest request) { expect(request.headers["host"][0], equals("[::1]:${server.port}")); @@ -19,7 +19,7 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); var url = Uri.parse('http://[::1]:${server.port}/xxx'); expect(url.host, equals('::1')); client
diff --git a/test/http_keep_alive_test.dart b/test/http_keep_alive_test.dart index 266be96..237f01c 100644 --- a/test/http_keep_alive_test.dart +++ b/test/http_keep_alive_test.dart
@@ -7,7 +7,7 @@ import 'package:http_io/http_io.dart'; import 'package:test/test.dart'; -Future<int> getData(HttpClient client, int port, bool chunked, int length) { +Future<void> getData(HttpClient client, int port, bool chunked, int length) { return client .get("127.0.0.1", port, "/?chunked=$chunked&length=$length") .then((request) => request.close()) @@ -23,7 +23,7 @@ server.listen((request) { bool chunked = request.uri.queryParameters["chunked"] == "true"; int length = int.parse(request.uri.queryParameters["length"]); - var buffer = new List<int>.filled(length, 0); + var buffer = List<int>.filled(length, 0); if (!chunked) request.response.contentLength = length; request.response.add(buffer); request.response.close(); @@ -33,9 +33,9 @@ } Future<Null> testKeepAliveNonChunked() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); startServer().then((server) { - var client = new HttpClient(); + var client = HttpClient(); getData(client, server.port, false, 100) .then((_) => getData(client, server.port, false, 100)) @@ -52,9 +52,9 @@ } Future<Null> testKeepAliveChunked() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); startServer().then((server) { - var client = new HttpClient(); + var client = HttpClient(); getData(client, server.port, true, 100) .then((_) => getData(client, server.port, true, 100)) @@ -71,9 +71,9 @@ } Future<Null> testKeepAliveMixed() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); startServer().then((server) { - var client = new HttpClient(); + var client = HttpClient(); getData(client, server.port, true, 100) .then((_) => getData(client, server.port, false, 100))
diff --git a/test/http_no_reason_phrase_test.dart b/test/http_no_reason_phrase_test.dart index 97c1919..1c0550e 100644 --- a/test/http_no_reason_phrase_test.dart +++ b/test/http_no_reason_phrase_test.dart
@@ -10,8 +10,8 @@ // Test that a response line without any reason phrase is handled. Future<Null> missingReasonPhrase(int statusCode, bool includeSpace) { - final completer = new Completer<Null>(); - var client = new HttpClient(); + final completer = Completer<Null>(); + var client = HttpClient(); ServerSocket.bind("127.0.0.1", 0).then((server) { server.listen((client) { client.listen(null);
diff --git a/test/http_outgoing_size_test.dart b/test/http_outgoing_size_test.dart index 8c16c03..d39c10a 100644 --- a/test/http_outgoing_size_test.dart +++ b/test/http_outgoing_size_test.dart
@@ -9,11 +9,13 @@ import 'package:test/test.dart'; Future<Null> testChunkedBufferSizeMsg() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); // Buffer of same size as our internal buffer, minus 4. Makes us hit the // boundary. - var sendData = new Uint8List(8 * 1024 - 4); - for (int i = 0; i < sendData.length; i++) sendData[i] = i % 256; + var sendData = Uint8List(8 * 1024 - 4); + for (int i = 0; i < sendData.length; i++) { + sendData[i] = i % 256; + } HttpServer.bind('127.0.0.1', 0).then((server) { server.listen((request) { @@ -29,7 +31,7 @@ request.response.add(sendData); request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client.get('127.0.0.1', server.port, '/').then((request) { request.headers.set(HttpHeaders.ACCEPT_ENCODING, ""); return request.close();
diff --git a/test/http_parser_test.dart b/test/http_parser_test.dart index 33b2160..90a1d5b 100644 --- a/test/http_parser_test.dart +++ b/test/http_parser_test.dart
@@ -23,20 +23,20 @@ static void _testParseRequest( String request, String expectedMethod, String expectedUri, - {int expectedTransferLength: 0, - int expectedBytesReceived: 0, + {int expectedTransferLength = 0, + int expectedBytesReceived = 0, Map<String, String> expectedHeaders, - bool chunked: false, - bool upgrade: false, - int unparsedLength: 0, - bool connectionClose: false, - String expectedVersion: "1.1"}) { - StreamController<List<int>> controller; + bool chunked = false, + bool upgrade = false, + int unparsedLength = 0, + bool connectionClose = false, + String expectedVersion = "1.1"}) { + StreamController<Uint8List> controller; void reset() { - HttpParser httpParser = new HttpParser.requestParser(); - controller = new StreamController(sync: true); - var port1 = new ReceivePort(); - var port2 = new ReceivePort(); + HttpParser httpParser = HttpParser.requestParser(); + controller = StreamController(sync: true); + var port1 = ReceivePort(); + var port2 = ReceivePort(); String method; Uri uri; @@ -101,7 +101,7 @@ upgraded = false; } - void testWrite(List<int> requestData, [int chunkSize = -1]) { + void testWrite(Uint8List requestData, [int chunkSize = -1]) { if (chunkSize == -1) chunkSize = requestData.length; reset(); for (int pos = 0; pos < requestData.length; pos += chunkSize) { @@ -113,7 +113,7 @@ // Test parsing the request three times delivering the data in // different chunks. - List<int> requestData = new Uint8List.fromList(request.codeUnits); + Uint8List requestData = Uint8List.fromList(request.codeUnits); testWrite(requestData); testWrite(requestData, 10); testWrite(requestData, 1); @@ -121,14 +121,14 @@ static void _testParseRequestLean( String request, String expectedMethod, String expectedUri, - {int expectedTransferLength: 0, - int expectedBytesReceived: 0, + {int expectedTransferLength = 0, + int expectedBytesReceived = 0, Map<String, String> expectedHeaders, - bool chunked: false, - bool upgrade: false, - int unparsedLength: 0, - bool connectionClose: false, - String expectedVersion: "1.1"}) { + bool chunked = false, + bool upgrade = false, + int unparsedLength = 0, + bool connectionClose = false, + String expectedVersion = "1.1"}) { _testParseRequest(request, expectedMethod, expectedUri, expectedTransferLength: expectedTransferLength, expectedBytesReceived: expectedBytesReceived, @@ -153,12 +153,12 @@ static void _testParseInvalidRequest(String request) { HttpParser httpParser; bool errorCalled; - StreamController<List<int>> controller; + StreamController<Uint8List> controller; void reset() { - httpParser = new HttpParser.requestParser(); - controller = new StreamController(sync: true); - var port = new ReceivePort(); + httpParser = HttpParser.requestParser(); + controller = StreamController(sync: true); + var port = ReceivePort(); httpParser.listenToStream(controller.stream); var subscription = httpParser.listen((incoming) { fail("Expected request"); @@ -173,7 +173,7 @@ errorCalled = false; } - void testWrite(List<int> requestData, [int chunkSize = -1]) { + void testWrite(Uint8List requestData, [int chunkSize = -1]) { if (chunkSize == -1) chunkSize = requestData.length; reset(); for (int pos = 0; @@ -187,7 +187,7 @@ // Test parsing the request three times delivering the data in // different chunks. - List<int> requestData = new Uint8List.fromList(request.codeUnits); + Uint8List requestData = Uint8List.fromList(request.codeUnits); testWrite(requestData); testWrite(requestData, 10); testWrite(requestData, 1); @@ -195,17 +195,17 @@ static void _testParseResponse( String response, int expectedStatusCode, String expectedReasonPhrase, - {int expectedTransferLength: 0, - int expectedBytesReceived: 0, + {int expectedTransferLength = 0, + int expectedBytesReceived = 0, Map<String, String> expectedHeaders, - bool chunked: false, - bool close: false, + bool chunked = false, + bool close = false, String responseToMethod, - bool connectionClose: false, - bool upgrade: false, - int unparsedLength: 0, - String expectedVersion: "1.1"}) { - StreamController<List<int>> controller; + bool connectionClose = false, + bool upgrade = false, + int unparsedLength = 0, + String expectedVersion = "1.1"}) { + StreamController<Uint8List> controller; void reset() { HttpParser httpParser; @@ -216,9 +216,9 @@ String reasonPhrase; HttpHeaders headers; int bytesReceived; - httpParser = new HttpParser.responseParser(); - controller = new StreamController(sync: true); - var port = new ReceivePort(); + httpParser = HttpParser.responseParser(); + controller = StreamController(sync: true); + var port = ReceivePort(); httpParser.listenToStream(controller.stream); int doneCallCount = 0; // Called when done parsing entire message and done parsing body. @@ -275,7 +275,7 @@ bytesReceived = 0; } - void testWrite(List<int> requestData, [int chunkSize = -1]) { + void testWrite(Uint8List requestData, [int chunkSize = -1]) { if (chunkSize == -1) chunkSize = requestData.length; reset(); for (int pos = 0; pos < requestData.length; pos += chunkSize) { @@ -287,21 +287,21 @@ // Test parsing the request three times delivering the data in // different chunks. - List<int> responseData = new Uint8List.fromList(response.codeUnits); + Uint8List responseData = Uint8List.fromList(response.codeUnits); testWrite(responseData); testWrite(responseData, 10); testWrite(responseData, 1); } - static void _testParseInvalidResponse(String response, [bool close = false]) { - void testWrite(List<int> requestData, [int chunkSize = -1]) { - HttpParser httpParser = new HttpParser.responseParser(); - StreamController<List<int>> controller = new StreamController(sync: true); + static void _testParseInvalidResponse(String response) { + void testWrite(Uint8List requestData, [int chunkSize = -1]) { + HttpParser httpParser = HttpParser.responseParser(); + StreamController<Uint8List> controller = StreamController(sync: true); bool errorCalled = false; if (chunkSize == -1) chunkSize = requestData.length; - var port = new ReceivePort(); + var port = ReceivePort(); httpParser.listenToStream(controller.stream); var subscription = httpParser.listen((incoming) { incoming.listen((data) {}, onError: (e) { @@ -330,7 +330,7 @@ // Test parsing the request three times delivering the data in // different chunks. - List<int> responseData = new Uint8List.fromList(response.codeUnits); + Uint8List responseData = Uint8List.fromList(response.codeUnits); testWrite(responseData); testWrite(responseData, 10); testWrite(responseData, 1); @@ -382,7 +382,7 @@ X-Header-B: bbb\r \r """; - headers = new Map(); + headers = Map(); headers["header-a"] = "AAA"; headers["x-header-b"] = "bbb"; _testParseRequestLean(request, "POST", "/test", expectedHeaders: headers); @@ -394,7 +394,7 @@ \r \r """; - headers = new Map(); + headers = Map(); headers["empty-header-1"] = ""; headers["empty-header-2"] = ""; _testParseRequestLean(request, "POST", "/test", expectedHeaders: headers); @@ -405,7 +405,7 @@ X-Header-B:\t \t bbb\r \r """; - headers = new Map(); + headers = Map(); headers["header-a"] = "AAA"; headers["x-header-b"] = "bbb"; _testParseRequestLean(request, "POST", "/test", expectedHeaders: headers); @@ -420,7 +420,7 @@ \r """; - headers = new Map(); + headers = Map(); headers["header-a"] = "AAA"; headers["x-header-b"] = "bbb"; _testParseRequestLean(request, "POST", "/test", expectedHeaders: headers); @@ -512,7 +512,7 @@ Upgrade: irc/1.2\r Connection: Upgrade\r \r\n\x01\x01\x01\x01\x01\x02\x02\x02\x02\xFF"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "irc/1.2"; _testParseRequest(request, "GET", "/irc", expectedHeaders: headers, upgrade: true, unparsedLength: 10); @@ -523,7 +523,7 @@ Upgrade: irc/1.2\r Connection: Upgrade\r \r\n"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "irc/1.2"; _testParseRequest(request, "GET", "/irc", expectedHeaders: headers, upgrade: true); @@ -538,7 +538,7 @@ Origin: http://example.com\r Sec-WebSocket-Version: 13\r \r\n"""; - headers = new Map(); + headers = Map(); headers["host"] = "server.example.com"; headers["upgrade"] = "websocket"; headers["sec-websocket-key"] = "dGhlIHNhbXBsZSBub25jZQ=="; @@ -561,7 +561,7 @@ Origin: http://example.com\r Sec-WebSocket-Version: 13\r \r\n0123456"""; - headers = new Map(); + headers = Map(); headers["host"] = "server.example.com"; headers["upgrade"] = "websocket"; headers["sec-websocket-key"] = "dGhlIHNhbXBsZSBub25jZQ=="; @@ -619,7 +619,7 @@ Content-Length: 20\r Content-Type: text/html\r \r\n"""; - headers = new Map(); + headers = Map(); headers["content-length"] = "20"; headers["content-type"] = "text/html"; _testParseResponse(response, 200, "OK", @@ -678,7 +678,7 @@ Upgrade: irc/1.2\r Connection: Upgrade\r \r\n"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "irc/1.2"; _testParseResponse(response, 101, "Switching Protocols", expectedHeaders: headers, upgrade: true); @@ -689,7 +689,7 @@ Upgrade: irc/1.2\r Connection: Upgrade\r \r\n\x00\x10\x20\x30\x40\x50\x60\x70\x80\x90\xA0\xB0\xC0\xD0\xE0\xF0"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "irc/1.2"; _testParseResponse(response, 101, "Switching Protocols", expectedHeaders: headers, upgrade: true, unparsedLength: 16); @@ -701,7 +701,7 @@ Connection: Upgrade\r Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r \r\n"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "websocket"; headers["sec-websocket-accept"] = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="; _testParseResponse(response, 101, "Switching Protocols", @@ -714,7 +714,7 @@ Connection: Upgrade\r Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r \r\nABCD"""; - headers = new Map(); + headers = Map(); headers["upgrade"] = "websocket"; headers["sec-websocket-accept"] = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="; _testParseResponse(response, 101, "Switching Protocols",
diff --git a/test/http_proxy_advanced_test.dart b/test/http_proxy_advanced_test.dart index 21c90e0..24a2051 100644 --- a/test/http_proxy_advanced_test.dart +++ b/test/http_proxy_advanced_test.dart
@@ -13,18 +13,18 @@ String localFile(path) { final localPath = '${Directory.current.path}/test/$path'; - if (!(new File(localPath).existsSync())) { + if (!(File(localPath).existsSync())) { return Platform.script.resolve(path).toFilePath(); } return localPath; } -final SecurityContext serverContext = new SecurityContext() +final SecurityContext serverContext = SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) ..usePrivateKey(localFile('certificates/server_key.pem'), password: 'dartdart'); -final SecurityContext clientContext = new SecurityContext() +final SecurityContext clientContext = SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); class Server { @@ -60,7 +60,7 @@ } else { expect(request.headers[HttpHeaders.VIA], isNull); } - var body = new StringBuffer(); + var body = StringBuffer(); onRequestComplete() { String path = request.uri.path.substring(1); if (path != "A") { @@ -72,7 +72,7 @@ } request.listen((data) { - body.write(new String.fromCharCodes(data)); + body.write(String.fromCharCodes(data)); }, onDone: onRequestComplete); } @@ -84,8 +84,8 @@ } Future<Server> setupServer(int proxyHops, - {List<String> directRequestPaths: const <String>[], secure: false}) { - Server server = new Server(proxyHops, directRequestPaths, secure); + {List<String> directRequestPaths = const <String>[], secure = false}) { + Server server = Server(proxyHops, directRequestPaths, secure); return server.start(); } @@ -102,11 +102,11 @@ String ha1; String serverAlgorithm = "MD5"; String serverQop = "auth"; - Set ncs = new Set(); + Set ncs = Set(); var nonce = "12345678"; // No need for random nonce in test. - ProxyServer({this.ipV6: false}) : client = new HttpClient(); + ProxyServer({this.ipV6 = false}) : client = HttpClient(); void useBasicAuthentication(String username, String password) { this.username = username; @@ -134,11 +134,11 @@ }); } - digestAuthenticationRequired(request, {stale: false}) { + digestAuthenticationRequired(request, {stale = false}) { request.fold(null, (x, y) {}).then((_) { var response = request.response; response.statusCode = HttpStatus.PROXY_AUTHENTICATION_REQUIRED; - StringBuffer authHeader = new StringBuffer(); + StringBuffer authHeader = StringBuffer(); authHeader.write('Digest'); authHeader.write(', realm="$realm"'); authHeader.write(', nonce="$nonce"'); @@ -153,7 +153,7 @@ } Future<ProxyServer> start() { - var x = new Completer<ProxyServer>(); + var x = Completer<ProxyServer>(); var host = ipV6 ? "::1" : "localhost"; HttpServer.bind(host, 0).then((s) { server = s; @@ -237,8 +237,8 @@ Socket.connect(tmp[0], int.parse(tmp[1])).then((socket) { request.response.reasonPhrase = "Connection established"; request.response.detachSocket().then((detached) { - socket.pipe(detached); - detached.pipe(socket); + socket.cast<List<int>>().pipe(detached); + detached.cast<List<int>>().pipe(socket); }); }); } else { @@ -278,19 +278,19 @@ int get port => server.port; } -Future<ProxyServer> setupProxyServer({ipV6: false}) { - ProxyServer proxyServer = new ProxyServer(ipV6: ipV6); +Future<ProxyServer> setupProxyServer({ipV6 = false}) { + ProxyServer proxyServer = ProxyServer(ipV6: ipV6); return proxyServer.start(); } int testProxyIPV6DoneCount = 0; Future<Null> testProxyIPV6() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupProxyServer(ipV6: true).then((proxyServer) { setupServer(1, directRequestPaths: ["/4"]).then((server) { setupServer(1, directRequestPaths: ["/4"], secure: true) .then((secureServer) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); List<String> proxy = ["PROXY [::1]:${proxyServer.port}"]; client.findProxy = (Uri uri) { @@ -338,11 +338,11 @@ int testProxyFromEnviromentDoneCount = 0; Future<Null> testProxyFromEnviroment() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupProxyServer().then((proxyServer) { setupServer(1).then((server) { setupServer(1, secure: true).then((secureServer) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); client.findProxy = (Uri uri) { return HttpClient.findProxyFromEnvironment(uri, environment: { @@ -392,15 +392,15 @@ int testProxyAuthenticateCount = 0; Future testProxyAuthenticate(bool useDigestAuthentication) { testProxyAuthenticateCount = 0; - var completer = new Completer(); + var completer = Completer(); setupProxyServer().then((proxyServer) { setupServer(1).then((server) { setupServer(1, secure: true).then((secureServer) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); - Completer step1 = new Completer(); - Completer step2 = new Completer(); + Completer step1 = Completer(); + Completer step2 = Completer(); if (useDigestAuthentication) { proxyServer.useDigestAuthentication("dart", "password"); @@ -447,7 +447,7 @@ client.findProxy = (Uri uri) => "PROXY localhost:${proxyServer.port}"; client.addProxyCredentials("localhost", proxyServer.port, "test", - new HttpClientDigestCredentials("dart", "password")); + HttpClientDigestCredentials("dart", "password")); } else { client.findProxy = (Uri uri) { return "PROXY dart:password@localhost:${proxyServer.port}"; @@ -493,8 +493,8 @@ client.authenticateProxy = (host, port, scheme, realm) { client.addProxyCredentials("localhost", proxyServer.port, "realm", - new HttpClientBasicCredentials("dart", "password")); - return new Future.value(true); + HttpClientBasicCredentials("dart", "password")); + return Future.value(true); }; for (int i = 0; i < loopCount; i++) { @@ -540,9 +540,9 @@ int testRealProxyDoneCount = 0; void testRealProxy() { setupServer(1).then((server) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); client.addProxyCredentials("localhost", 8080, "test", - new HttpClientBasicCredentials("dart", "password")); + HttpClientBasicCredentials("dart", "password")); List<String> proxy = [ "PROXY localhost:8080", @@ -581,7 +581,7 @@ int testRealProxyAuthDoneCount = 0; void testRealProxyAuth() { setupServer(1).then((server) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); List<String> proxy = [ "PROXY dart:password@localhost:8080",
diff --git a/test/http_proxy_test.dart b/test/http_proxy_test.dart index ab759ea..edceedf 100644 --- a/test/http_proxy_test.dart +++ b/test/http_proxy_test.dart
@@ -13,18 +13,18 @@ String localFile(path) { final localPath = "${Directory.current.path}/test/$path"; - if (!(new File(localPath).existsSync())) { + if (!(File(localPath).existsSync())) { return Platform.script.resolve(path).toFilePath(); } return localPath; } -final SecurityContext serverContext = new SecurityContext() +final SecurityContext serverContext = SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) ..usePrivateKey(localFile('certificates/server_key.pem'), password: 'dartdart'); -final SecurityContext clientContext = new SecurityContext() +final SecurityContext clientContext = SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); class Server { @@ -61,7 +61,7 @@ } else { expect(request.headers[HttpHeaders.VIA], isNull); } - var body = new StringBuffer(); + var body = StringBuffer(); onRequestComplete() { String path = request.uri.path.substring(1); if (path != "A") { @@ -73,7 +73,7 @@ } request.listen((data) { - body.write(new String.fromCharCodes(data)); + body.write(String.fromCharCodes(data)); }, onDone: onRequestComplete); } @@ -85,8 +85,8 @@ } Future<Server> setupServer(int proxyHops, - {List<String> directRequestPaths: const <String>[], secure: false}) { - Server server = new Server(proxyHops, directRequestPaths, secure); + {List<String> directRequestPaths = const <String>[], secure = false}) { + Server server = Server(proxyHops, directRequestPaths, secure); return server.start(); } @@ -103,11 +103,11 @@ String ha1; String serverAlgorithm = "MD5"; String serverQop = "auth"; - Set ncs = new Set(); + Set ncs = Set(); var nonce = "12345678"; // No need for random nonce in test. - ProxyServer({this.ipV6: false}) : client = new HttpClient(); + ProxyServer({this.ipV6 = false}) : client = HttpClient(); void useBasicAuthentication(String username, String password) { this.username = username; @@ -125,11 +125,11 @@ }); } - digestAuthenticationRequired(request, {stale: false}) { + digestAuthenticationRequired(request, {stale = false}) { request.fold(null, (x, y) {}).then((_) { var response = request.response; response.statusCode = HttpStatus.PROXY_AUTHENTICATION_REQUIRED; - StringBuffer authHeader = new StringBuffer(); + StringBuffer authHeader = StringBuffer(); authHeader.write('Digest'); authHeader.write(', realm="$realm"'); authHeader.write(', nonce="$nonce"'); @@ -144,7 +144,7 @@ } Future<ProxyServer> start() { - var x = new Completer<ProxyServer>(); + var x = Completer<ProxyServer>(); var host = ipV6 ? "::1" : "localhost"; HttpServer.bind(host, 0).then((s) { server = s; @@ -228,8 +228,8 @@ Socket.connect(tmp[0], int.parse(tmp[1])).then((socket) { request.response.reasonPhrase = "Connection established"; request.response.detachSocket().then((detached) { - socket.pipe(detached); - detached.pipe(socket); + socket.cast<List<int>>().pipe(detached); + detached.cast<List<int>>().pipe(socket); }); }); } else { @@ -269,13 +269,13 @@ int get port => server.port; } -Future<ProxyServer> setupProxyServer({ipV6: false}) { - ProxyServer proxyServer = new ProxyServer(ipV6: ipV6); +Future<ProxyServer> setupProxyServer({ipV6 = false}) { + ProxyServer proxyServer = ProxyServer(ipV6: ipV6); return proxyServer.start(); } testInvalidProxy() { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); client.findProxy = (Uri uri) => ""; client @@ -300,9 +300,9 @@ int testDirectDoneCount = 0; Future<Null> testDirectProxy() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer(0).then((server) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); List<String> proxy = [ "DIRECT", " DIRECT ", @@ -344,12 +344,12 @@ int testProxyDoneCount = 0; Future<Null> testProxy() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupProxyServer().then((proxyServer) { setupServer(1, directRequestPaths: ["/4"]).then((server) { setupServer(1, directRequestPaths: ["/4"], secure: true) .then((secureServer) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); List<String> proxy; if (Platform.operatingSystem == "windows") { @@ -418,7 +418,7 @@ int testProxyChainDoneCount = 0; Future<Null> testProxyChain() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); // Setup two proxy servers having the first using the second as its proxy. setupProxyServer().then((proxyServer1) { setupProxyServer().then((proxyServer2) { @@ -426,7 +426,7 @@ (_) => "PROXY localhost:${proxyServer2.port}"; setupServer(2, directRequestPaths: ["/4"]).then((server) { - HttpClient client = new HttpClient(context: clientContext); + HttpClient client = HttpClient(context: clientContext); List<String> proxy; if (Platform.operatingSystem == "windows") {
diff --git a/test/http_read_test.dart b/test/http_read_test.dart index 59c4b6d..e347e3b 100644 --- a/test/http_read_test.dart +++ b/test/http_read_test.dart
@@ -10,7 +10,7 @@ class IsolatedHttpServer { IsolatedHttpServer() - : _statusPort = new ReceivePort(), + : _statusPort = ReceivePort(), _serverPort = null; void setServerStartedHandler(void startedCallback(int port)) { @@ -18,7 +18,7 @@ } void start([bool chunkedEncoding = false]) { - ReceivePort receivePort = new ReceivePort(); + ReceivePort receivePort = ReceivePort(); Isolate.spawn(startIsolatedHttpServer, receivePort.sendPort); receivePort.first.then((port) { _serverPort = port; @@ -26,13 +26,13 @@ if (chunkedEncoding) { // Send chunked encoding message to the server. port.send([ - new IsolatedHttpServerCommand.chunkedEncoding(), + IsolatedHttpServerCommand.chunkedEncoding(), _statusPort.sendPort ]); } // Send server start message to the server. - var command = new IsolatedHttpServerCommand.start(); + var command = IsolatedHttpServerCommand.start(); port.send([command, _statusPort.sendPort]); }); @@ -46,12 +46,11 @@ void shutdown() { // Send server stop message to the server. - _serverPort - .send([new IsolatedHttpServerCommand.stop(), _statusPort.sendPort]); + _serverPort.send([IsolatedHttpServerCommand.stop(), _statusPort.sendPort]); _statusPort.close(); } - ReceivePort _statusPort; // Port for receiving messages from the server. + final ReceivePort _statusPort; // Port for receiving messages from the server. SendPort _serverPort; // Port for sending messages to the server. void Function(int) _startedCallback; } @@ -69,7 +68,7 @@ bool get isStop => _command == STOP; bool get isChunkedEncoding => _command == CHUNKED_ENCODING; - int _command; + final int _command; } class IsolatedHttpServerStatus { @@ -77,23 +76,27 @@ static const STOPPED = 1; static const ERROR = 2; - IsolatedHttpServerStatus.started(this._port) : _state = STARTED; - IsolatedHttpServerStatus.stopped() : _state = STOPPED; - IsolatedHttpServerStatus.error() : _state = ERROR; + IsolatedHttpServerStatus.started(this.port) : _state = STARTED; + + IsolatedHttpServerStatus.stopped() + : port = null, + _state = STOPPED; + + IsolatedHttpServerStatus.error() + : port = null, + _state = ERROR; bool get isStarted => _state == STARTED; bool get isStopped => _state == STOPPED; bool get isError => _state == ERROR; - int get port => _port; - - int _state; - int _port; + final int _state; + final int port; } void startIsolatedHttpServer(Object replyToObj) { SendPort replyTo = replyToObj; - var server = new TestServer(); + var server = TestServer(); server.init(); replyTo.send(server.dispatchSendPort); } @@ -120,9 +123,9 @@ void init() { // Setup request handlers. - _requestHandlers = new Map(); + _requestHandlers = Map(); _requestHandlers["/echo"] = _echoHandler; - _dispatchPort = new ReceivePort(); + _dispatchPort = ReceivePort(); _dispatchPort.listen(dispatch); } @@ -136,15 +139,15 @@ HttpServer.bind("127.0.0.1", 0).then((server) { _server = server; _server.listen(_requestReceivedHandler); - replyTo.send(new IsolatedHttpServerStatus.started(_server.port)); + replyTo.send(IsolatedHttpServerStatus.started(_server.port)); }); } catch (e) { - replyTo.send(new IsolatedHttpServerStatus.error()); + replyTo.send(IsolatedHttpServerStatus.error()); } } else if (command.isStop) { _server.close(); _dispatchPort.close(); - replyTo.send(new IsolatedHttpServerStatus.stopped()); + replyTo.send(IsolatedHttpServerStatus.stopped()); } } @@ -163,15 +166,15 @@ } Future<Null> testRead(bool chunkedEncoding) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; final int kMessageCount = 10; - IsolatedHttpServer server = new IsolatedHttpServer(); + IsolatedHttpServer server = IsolatedHttpServer(); void runTest(int port) { int count = 0; - HttpClient httpClient = new HttpClient(); + HttpClient httpClient = HttpClient(); void sendRequest() { httpClient.post("127.0.0.1", port, "/echo").then((request) { if (chunkedEncoding) { @@ -184,9 +187,9 @@ return request.close(); }).then((response) { expect(HttpStatus.OK, equals(response.statusCode)); - List<int> body = new List<int>(); + List<int> body = <int>[]; response.listen(body.addAll, onDone: () { - expect(data, equals(new String.fromCharCodes(body))); + expect(data, equals(String.fromCharCodes(body))); count++; if (count < kMessageCount) { sendRequest();
diff --git a/test/http_redirect_test.dart b/test/http_redirect_test.dart index f1e9f15..420688e 100644 --- a/test/http_redirect_test.dart +++ b/test/http_redirect_test.dart
@@ -9,7 +9,7 @@ Future<HttpServer> setupServer() { return HttpServer.bind("127.0.0.1", 0).then((server) { - var handlers = new Map<String, Function>(); + var handlers = Map<String, Function>(); addRequestHandler( String path, void handler(HttpRequest request, HttpResponse response)) { handlers[path] = handler; @@ -191,9 +191,9 @@ } Future<Null> testManualRedirect() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); int redirectCount = 0; handleResponse(HttpClientResponse response) { @@ -223,9 +223,9 @@ } Future<Null> testManualRedirectWithHeaders() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); int redirectCount = 0; @@ -256,10 +256,10 @@ } Future<Null> testAutoRedirect() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/redirect")) @@ -278,9 +278,9 @@ } Future<Null> testAutoRedirectWithHeaders() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/src")) @@ -300,9 +300,9 @@ } Future<Null> testAutoRedirect301POST() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .postUrl(Uri.parse("http://127.0.0.1:${server.port}/301src")) @@ -322,9 +322,9 @@ } Future<Null> testAutoRedirect303POST() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .postUrl(Uri.parse("http://127.0.0.1:${server.port}/303src")) @@ -344,9 +344,9 @@ } Future<Null> testAutoRedirectLimit() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/1")) .then((HttpClientRequest request) => request.close()) @@ -361,9 +361,9 @@ } Future<Null> testRedirectLoop() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/A")) .then((HttpClientRequest request) => request.close()) @@ -378,9 +378,9 @@ } Future<Null> testRedirectClosingConnection() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/closing")) .then((request) => request.close()) @@ -398,9 +398,9 @@ Future<Null> testRedirectRelativeUrl() async { Future<Null> testPath(String path) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}$path")) .then((request) => request.close()) @@ -426,9 +426,9 @@ } Future<Null> testRedirectRelativeToAbsolute() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); setupServer().then((server) { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); handleResponse(HttpClientResponse response) { response.listen((_) => fail("Response data not expected"), onDone: () {
diff --git a/test/http_request_pipeling_test.dart b/test/http_request_pipeling_test.dart index 6aa4131..49b67a0 100644 --- a/test/http_request_pipeling_test.dart +++ b/test/http_request_pipeling_test.dart
@@ -9,7 +9,7 @@ import 'package:test/test.dart'; Future<Null> requestPipeling() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); final int REQUEST_COUNT = 100; int count = 0; HttpServer.bind("127.0.0.1", 0).then((server) {
diff --git a/test/http_requested_uri_test.dart b/test/http_requested_uri_test.dart index ad2faaf..67abd55 100644 --- a/test/http_requested_uri_test.dart +++ b/test/http_requested_uri_test.dart
@@ -11,14 +11,14 @@ const expectedPath = '/path?a=b'; Future<Null> runTest(String expected, Map headers) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("localhost", 0).then((server) { expected = expected.replaceAll('%PORT', server.port.toString()); server.listen((request) { expect("$expected$expectedPath", equals(request.requestedUri.toString())); request.response.close(); }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .get("localhost", server.port, sendPath) .then((request) {
diff --git a/test/http_response_deadline_test.dart b/test/http_response_deadline_test.dart index c6b69c9..517423b 100644 --- a/test/http_response_deadline_test.dart +++ b/test/http_response_deadline_test.dart
@@ -9,7 +9,7 @@ import 'package:test/test.dart'; Future<Null> testSimpleDeadline(int connections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind('localhost', 0).then((server) { server.listen((request) { request.response.deadline = const Duration(seconds: 1000); @@ -18,7 +18,7 @@ }); var futures = <Future>[]; - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { futures.add(client .get('localhost', server.port, '/') @@ -34,7 +34,7 @@ } Future<Null> testExceedDeadline(int connections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind('localhost', 0).then((server) { server.listen((request) { request.response.deadline = const Duration(milliseconds: 100); @@ -43,7 +43,7 @@ }); var futures = <Future>[]; - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { futures.add(client .get('localhost', server.port, '/') @@ -64,14 +64,14 @@ } Future<Null> testDeadlineAndDetach(int connections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind('localhost', 0).then((server) { server.listen((request) { request.response.deadline = const Duration(milliseconds: 0); request.response.contentLength = 5; request.response.persistentConnection = false; request.response.detachSocket().then((socket) { - new Timer(const Duration(milliseconds: 100), () { + Timer(const Duration(milliseconds: 100), () { socket.write('stuff'); socket.close(); socket.listen(null); @@ -80,17 +80,16 @@ }); var futures = <Future>[]; - var client = new HttpClient(); + var client = HttpClient(); for (int i = 0; i < connections; i++) { futures.add(client .get('localhost', server.port, '/') .then((request) => request.close()) .then((response) { return response - .fold(new BytesBuilder(), (b, d) => b..add(d)) + .fold(BytesBuilder(), (b, d) => b..add(d)) .then((builder) { - expect( - 'stuff', equals(new String.fromCharCodes(builder.takeBytes()))); + expect('stuff', equals(String.fromCharCodes(builder.takeBytes()))); }); })); }
diff --git a/test/http_reuse_server_port_test.dart b/test/http_reuse_server_port_test.dart index 3ee4ea9..a27d215 100644 --- a/test/http_reuse_server_port_test.dart +++ b/test/http_reuse_server_port_test.dart
@@ -8,7 +8,7 @@ import 'package:test/test.dart'; Future<int> runServer(int port, int connections, bool clean) { - Completer<int> completer = new Completer<int>(); + Completer<int> completer = Completer<int>(); HttpServer.bind("127.0.0.1", port).then((server) { int i = 0; server.listen((request) { @@ -20,8 +20,8 @@ } }); - Future.wait(new List.generate(connections, (_) { - var client = new HttpClient(); + Future.wait(List.generate(connections, (_) { + var client = HttpClient(); return client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -40,10 +40,10 @@ } Future<Null> testReusePort() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); runServer(0, 10, true).then((int port) { // Stress test the port reusing it 10 times. - Future.forEach(new List(10), (_) { + Future.forEach(Iterable.generate(10), (_) { return runServer(port, 10, true); }).then((_) { completer.complete(); @@ -53,10 +53,10 @@ } Future<Null> testUncleanReusePort() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); runServer(0, 10, false).then((int port) { // Stress test the port reusing it 10 times. - Future.forEach(new List(10), (_) { + Future.forEach(Iterable.generate(10), (_) { return runServer(port, 10, false); }).then((_) { completer.complete();
diff --git a/test/http_server_close_response_after_error_client.dart b/test/http_server_close_response_after_error_client.dart index dd11b24..aa86b1f 100644 --- a/test/http_server_close_response_after_error_client.dart +++ b/test/http_server_close_response_after_error_client.dart
@@ -20,5 +20,7 @@ }); } - for (int i = 0; i < 4; i++) run(); + for (int i = 0; i < 4; i++) { + run(); + } }
diff --git a/test/http_server_close_response_after_error_test.dart b/test/http_server_close_response_after_error_test.dart index 16c04f9..22c1332 100644 --- a/test/http_server_close_response_after_error_test.dart +++ b/test/http_server_close_response_after_error_test.dart
@@ -11,7 +11,7 @@ const CLIENT_SCRIPT = "http_server_close_response_after_error_client.dart"; Future<Null> serverCloseResponseAfterError() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.listen(null, onError: (e) {}, onDone: () { @@ -19,7 +19,7 @@ }); }); var name = '${Directory.current.path}/test/$CLIENT_SCRIPT'; - if (!new File(name).existsSync()) { + if (!File(name).existsSync()) { name = Platform.script.resolve(CLIENT_SCRIPT).toString(); } Process.run(Platform.executable, [name, server.port.toString()])
diff --git a/test/http_server_early_client_close2_test.dart b/test/http_server_early_client_close2_test.dart index 353b42f..2a81214 100644 --- a/test/http_server_early_client_close2_test.dart +++ b/test/http_server_early_client_close2_test.dart
@@ -9,15 +9,15 @@ import 'package:test/test.dart'; Future<Null> httpServerEarlyClientClose2() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { String name = '${Directory.current.path}/test/http_server_early_client_close2_test.dart'; - if (!new File(name).existsSync()) { + if (!File(name).existsSync()) { name = Platform.script.toFilePath(); } - new File(name) + File(name) .openRead() .cast<List<int>>() .pipe(request.response)
diff --git a/test/http_server_early_client_close_test.dart b/test/http_server_early_client_close_test.dart index 9cad8b7..c533684 100644 --- a/test/http_server_early_client_close_test.dart +++ b/test/http_server_early_client_close_test.dart
@@ -26,12 +26,12 @@ Future execute() { return HttpServer.bind("127.0.0.1", 0).then((server) { - Completer c = new Completer(); + Completer c = Completer(); bool calledOnRequest = false; bool calledOnError = false; - ReceivePort port = new ReceivePort(); - var requestCompleter = new Completer(); + ReceivePort port = ReceivePort(); + var requestCompleter = Completer(); server.listen((request) { expect(expectRequest, isTrue); expect(calledOnError, isFalse); @@ -70,9 +70,9 @@ } Future<Null> testEarlyClose1() async { - List<EarlyCloseTest> tests = new List<EarlyCloseTest>(); + List<EarlyCloseTest> tests = <EarlyCloseTest>[]; void add(Object data, [String exception, bool expectRequest = false]) { - tests.add(new EarlyCloseTest(data, exception, expectRequest)); + tests.add(EarlyCloseTest(data, exception, expectRequest)); } // The empty packet is valid. @@ -94,15 +94,15 @@ } Future<Null> testEarlyClose2() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { String name = "${Directory.current.path}/test/http_server_early_client_close_test.dart"; - if (!new File(name).existsSync()) { + if (!File(name).existsSync()) { name = Platform.script.toFilePath(); } - new File(name) + File(name) .openRead() .cast<List<int>>() .pipe(request.response) @@ -135,7 +135,7 @@ } Future<Null> testEarlyClose3() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { StreamSubscription subscription;
diff --git a/test/http_server_idle_timeout_test.dart b/test/http_server_idle_timeout_test.dart index 2f03bb9..1774282 100644 --- a/test/http_server_idle_timeout_test.dart +++ b/test/http_server_idle_timeout_test.dart
@@ -9,7 +9,7 @@ import 'package:test/test.dart'; Future<Null> testTimeoutAfterRequest() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.idleTimeout = null; @@ -32,7 +32,7 @@ } Future<Null> testTimeoutBeforeRequest() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.idleTimeout = const Duration(milliseconds: 100);
diff --git a/test/http_server_response_test.dart b/test/http_server_response_test.dart index 243ed8a..d5676a7 100644 --- a/test/http_server_response_test.dart +++ b/test/http_server_response_test.dart
@@ -21,7 +21,7 @@ handler(server, request); }); - var client = new HttpClient(); + var client = HttpClient(); // We only close the client on either // - Bad response headers // - Response done (with optional errors in between). @@ -51,8 +51,8 @@ } Future<List> testResponseDone() { - final completers = new List<Future<Null>>(); - final completer = new Completer<Null>(); + final completers = <Future<Null>>[]; + final completer = Completer<Null>(); testServerRequest((server, request) { request.response.close(); request.response.done.then((response) { @@ -63,9 +63,9 @@ }); completers.add(completer.future); - final completer2 = new Completer<Null>(); + final completer2 = Completer<Null>(); testServerRequest((server, request) { - new File("__nonexistent_file_") + File("__nonexistent_file_") .openRead() .cast<List<int>>() .pipe(request.response) @@ -76,7 +76,7 @@ }); completers.add(completer2.future); - final completer3 = new Completer<Null>(); + final completer3 = Completer<Null>(); testServerRequest((server, request) { request.response.done.then((_) { server.close(); @@ -93,8 +93,8 @@ Future<List> testResponseAddStream() { File file = scriptSource; int bytes = file.lengthSync(); - final completers = new List<Future<Null>>(); - final completer = new Completer<Null>(); + final completers = <Future<Null>>[]; + final completer = Completer<Null>(); testServerRequest((server, request) { request.response.addStream(file.openRead()).then((response) { response.close(); @@ -106,7 +106,7 @@ }, bytes: bytes); completers.add(completer.future); - final completer2 = new Completer<Null>(); + final completer2 = Completer<Null>(); testServerRequest((server, request) { request.response.addStream(file.openRead()).then((response) { request.response.addStream(file.openRead()).then((response) { @@ -120,9 +120,9 @@ }, bytes: bytes * 2); completers.add(completer2.future); - final completer3 = new Completer<Null>(); + final completer3 = Completer<Null>(); testServerRequest((server, request) { - var controller = new StreamController<List<int>>(sync: true); + var controller = StreamController<List<int>>(sync: true); request.response.addStream(controller.stream).then((response) { response.close(); response.done.then((_) { @@ -134,10 +134,10 @@ }, bytes: 0); completers.add(completer3.future); - final completer4 = new Completer<Null>(); + final completer4 = Completer<Null>(); testServerRequest((server, request) { request.response - .addStream(new File("__nonexistent_file_").openRead()) + .addStream(File("__nonexistent_file_").openRead()) .catchError((e) { server.close(); completer4.complete(); @@ -145,9 +145,9 @@ }); completers.add(completer4.future); - final completer5 = new Completer<Null>(); + final completer5 = Completer<Null>(); testServerRequest((server, request) { - new File("__nonexistent_file_") + File("__nonexistent_file_") .openRead() .cast<List<int>>() .pipe(request.response) @@ -161,7 +161,7 @@ } Future<Null> testResponseAddStreamClosed() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); File file = scriptSource; testServerRequest((server, request) { request.response @@ -197,9 +197,9 @@ Future<List> testResponseAddClosed() { File file = scriptSource; - final completers = new List<Future<Null>>(); + final completers = <Future<Null>>[]; - final completer = new Completer<Null>(); + final completer = Completer<Null>(); testServerRequest((server, request) { request.response.add(file.readAsBytesSync()); request.response.close(); @@ -210,7 +210,7 @@ }, closeClient: true); completers.add(completer.future); - final completer2 = new Completer<Null>(); + final completer2 = Completer<Null>(); testServerRequest((server, request) { for (int i = 0; i < 1000; i++) { request.response.add(file.readAsBytesSync()); @@ -223,7 +223,7 @@ }, closeClient: true); completers.add(completer2.future); - final completer3 = new Completer<Null>(); + final completer3 = Completer<Null>(); testServerRequest((server, request) { int count = 0; write() { @@ -249,8 +249,8 @@ } Future<List> testBadResponseAdd() { - final completers = new List<Future<Null>>(); - final completer = new Completer<Null>(); + final completers = <Future<Null>>[]; + final completer = Completer<Null>(); testServerRequest((server, request) { request.response.contentLength = 0; request.response.add([0]); @@ -262,7 +262,7 @@ }); completers.add(completer.future); - final completer2 = new Completer<Null>(); + final completer2 = Completer<Null>(); testServerRequest((server, request) { request.response.contentLength = 5; request.response.add([0, 0, 0]); @@ -275,12 +275,12 @@ }); completers.add(completer2.future); - final completer3 = new Completer<Null>(); + final completer3 = Completer<Null>(); testServerRequest((server, request) { request.response.contentLength = 0; - request.response.add(new Uint8List(64 * 1024)); - request.response.add(new Uint8List(64 * 1024)); - request.response.add(new Uint8List(64 * 1024)); + request.response.add(Uint8List(64 * 1024)); + request.response.add(Uint8List(64 * 1024)); + request.response.add(Uint8List(64 * 1024)); request.response.close(); request.response.done.catchError((error) { server.close(); @@ -292,8 +292,8 @@ } Future<List> testBadResponseClose() { - final completers = new List<Future<Null>>(); - final completer = new Completer<Null>(); + final completers = <Future<Null>>[]; + final completer = Completer<Null>(); testServerRequest((server, request) { request.response.contentLength = 5; request.response.close(); @@ -304,7 +304,7 @@ }); completers.add(completer.future); - final completer2 = new Completer<Null>(); + final completer2 = Completer<Null>(); testServerRequest((server, request) { request.response.contentLength = 5; request.response.add([0]); @@ -319,7 +319,7 @@ } Future<Null> testIgnoreRequestData() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { // Ignore request data. @@ -327,10 +327,10 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client.get("127.0.0.1", server.port, "/").then((request) { request.contentLength = 1024 * 1024; - request.add(new Uint8List(1024 * 1024)); + request.add(Uint8List(1024 * 1024)); return request.close(); }).then((response) { response.fold(0, (s, b) => s + b.length).then((bytes) { @@ -344,7 +344,7 @@ } Future<Null> testWriteCharCode() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); testServerRequest((server, request) { // Test that default is latin-1 (only 2 bytes). request.response.writeCharCode(0xFF); @@ -359,11 +359,11 @@ void main() { scriptSource = - new File('${Directory.current.path}/test/http_server_response_test.dart'); + File('${Directory.current.path}/test/http_server_response_test.dart'); if (!scriptSource.existsSync()) { // If we can't find the file relative to the cwd, then look relative // to Platform.script. - scriptSource = new File( + scriptSource = File( Platform.script.resolve('http_server_response_test.dart').toFilePath()); } test('responseDone', () => testResponseDone());
diff --git a/test/http_server_test.dart b/test/http_server_test.dart index fd8fa28..6a88ff3 100644 --- a/test/http_server_test.dart +++ b/test/http_server_test.dart
@@ -35,7 +35,7 @@ doTest(bool clearHeaders, Map<String, dynamic> defaultHeaders, Function checker) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { if (clearHeaders) server.defaultResponseHeaders.clear(); if (defaultHeaders != null) { @@ -47,7 +47,7 @@ request.response.close(); }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -68,7 +68,7 @@ Future<Null> testDefaultResponseHeadersContentType() { doTest(bool clearHeaders, String requestBody, List<int> responseBody) { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { if (clearHeaders) server.defaultResponseHeaders.clear(); server.listen((request) { @@ -76,7 +76,7 @@ request.response.close(); }); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -98,14 +98,14 @@ } Future<Null> testListenOn() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); ServerSocket socket; HttpServer server; void doTest(void onDone()) { expect(socket.port, equals(server.port)); - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); client.get("127.0.0.1", socket.port, "/").then((request) { return request.close(); }).then((response) { @@ -123,7 +123,7 @@ // Test two connection after each other. ServerSocket.bind("127.0.0.1", 0).then((s) { socket = s; - server = new HttpServer.listenOn(socket); + server = HttpServer.listenOn(socket); expect(server.address.address, equals('127.0.0.1')); expect(server.address.host, equals('127.0.0.1')); server.listen((HttpRequest request) { @@ -144,7 +144,7 @@ } Future<Null> testHttpServerZone() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Zone parent = Zone.current; runZoned(() { expect(parent, isNot(equals(Zone.current))); @@ -155,7 +155,7 @@ request.response.close(); server.close(); }); - new HttpClient() + HttpClient() .get("127.0.0.1", server.port, '/') .then((request) => request.close()) .then((response) => response.drain()) @@ -166,9 +166,9 @@ } Future<Null> testHttpServerZoneError() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); Zone parent = Zone.current; - runZoned(() { + runZonedGuarded(() { expect(parent, isNot(equals(Zone.current))); HttpServer.bind("127.0.0.1", 0).then((server) { expect(parent, isNot(equals(Zone.current))); @@ -187,30 +187,30 @@ socket.listen(null); }); }); - }, onError: (e) { + }, (e, s) { completer.complete(null); }); return completer.future; } Future<Null> testHttpServerClientClose() { - Completer<Null> completer = new Completer(); + Completer<Null> completer = Completer(); HttpServer.bind("127.0.0.1", 0).then((server) { - runZoned(() { + runZonedGuarded(() { server.listen((request) { request.response.bufferOutput = false; - request.response.add(new Uint8List(64 * 1024)); - new Timer(const Duration(milliseconds: 100), () { + request.response.add(Uint8List(64 * 1024)); + Timer(const Duration(milliseconds: 100), () { request.response.close().then((_) { server.close(); completer.complete(null); }); }); }); - }, onError: (e, s) { + }, (e, s) { fail("Unexpected error: $e(${e.hashCode})\n$s"); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close())
diff --git a/test/http_session_test.dart b/test/http_session_test.dart index a713139..5d23b05 100644 --- a/test/http_session_test.dart +++ b/test/http_session_test.dart
@@ -26,7 +26,7 @@ [String session]) { return client.get("127.0.0.1", port, "/").then((request) { if (session != null) { - request.cookies.add(new Cookie(SESSION_ID, session)); + request.cookies.add(Cookie(SESSION_ID, session)); } return request.close(); }).then((response) { @@ -35,10 +35,10 @@ } Future<Null> testSessions(int sessionCount) { - final completer = new Completer<Null>(); - var client = new HttpClient(); + final completer = Completer<Null>(); + var client = HttpClient(); HttpServer.bind("127.0.0.1", 0).then((server) { - var sessions = new Set(); + var sessions = Set(); server.listen((request) { sessions.add(request.session.id); request.response.close(); @@ -58,7 +58,7 @@ } Future.wait(futures).then((clientSessions) { expect(sessions.length, equals(sessionCount)); - expect(new Set.from(clientSessions), equals(sessions)); + expect(Set.from(clientSessions), equals(sessions)); server.close(); client.close(); completer.complete(); @@ -68,13 +68,13 @@ } Future<Null> testTimeout(int sessionCount) { - final completer = new Completer<Null>(); - var client = new HttpClient(); + final completer = Completer<Null>(); + var client = HttpClient(); HttpServer.bind("127.0.0.1", 0).then((server) { server.sessionTimeout = 1; var timeouts = <Future>[]; server.listen((request) { - var c = new Completer(); + var c = Completer(); timeouts.add(c.future); request.session.onTimeout = () { c.complete(null); @@ -108,7 +108,7 @@ } Future<Null> testSessionsData() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { bool firstHit = false; bool secondHit = false; @@ -129,7 +129,7 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -138,7 +138,7 @@ var id = getSessionId(response.cookies); expect(id, isNotNull); client.get("127.0.0.1", server.port, "/").then((request) { - request.cookies.add(new Cookie(SESSION_ID, id)); + request.cookies.add(Cookie(SESSION_ID, id)); return request.close(); }).then((response) { response.listen((_) {}, onDone: () { @@ -157,7 +157,7 @@ } Future<Null> testSessionsDestroy() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { bool firstHit = false; server.listen((request) { @@ -174,7 +174,7 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -183,7 +183,7 @@ var id = getSessionId(response.cookies); expect(id, isNotNull); client.get("127.0.0.1", server.port, "/").then((request) { - request.cookies.add(new Cookie(SESSION_ID, id)); + request.cookies.add(Cookie(SESSION_ID, id)); return request.close(); }).then((response) { response.listen((_) {}, onDone: () {
diff --git a/test/http_shutdown_test.dart b/test/http_shutdown_test.dart index a07502e..a06123b 100644 --- a/test/http_shutdown_test.dart +++ b/test/http_shutdown_test.dart
@@ -9,7 +9,7 @@ import "package:test/test.dart"; Future<Null> test1(int totalConnections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); // Server which just closes immediately. HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { @@ -17,7 +17,7 @@ }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client .get("127.0.0.1", server.port, "/") @@ -38,7 +38,7 @@ } Future<Null> test2(int totalConnections, int outputStreamWrites) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); // Server which responds without waiting for request body. HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { @@ -47,7 +47,7 @@ }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client .get("127.0.0.1", server.port, "/") @@ -81,7 +81,7 @@ } Future<Null> test3(int totalConnections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); // Server which responds when request body has been received. HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { @@ -92,7 +92,7 @@ }); int count = 0; - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < totalConnections; i++) { client .get("127.0.0.1", server.port, "/") @@ -116,11 +116,11 @@ } Future<Null> test4() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((var request) { request.listen((_) {}, onDone: () { - new Timer.periodic(new Duration(milliseconds: 100), (timer) { + Timer.periodic(Duration(milliseconds: 100), (timer) { if (server.connectionsInfo().total == 0) { server.close(); timer.cancel(); @@ -131,7 +131,7 @@ }); }); - var client = new HttpClient(); + var client = HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) @@ -145,7 +145,7 @@ } Future<Null> test5(int totalConnections) { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { request.listen((_) {}, onDone: () { @@ -157,7 +157,7 @@ // Create a number of client requests and keep then active. Then // close the client and wait for the server to lose all active // connections. - var client = new HttpClient(); + var client = HttpClient(); client.maxConnectionsPerHost = totalConnections; for (int i = 0; i < totalConnections; i++) { client @@ -175,7 +175,7 @@ test: (e) => e is HttpException || e is SocketException); } bool clientClosed = false; - new Timer.periodic(new Duration(milliseconds: 100), (timer) { + Timer.periodic(Duration(milliseconds: 100), (timer) { if (!clientClosed) { if (server.connectionsInfo().total == totalConnections) { clientClosed = true;
diff --git a/test/https_unauthorized_client.dart b/test/https_unauthorized_client.dart index 4ab4434..d53c2e2 100644 --- a/test/https_unauthorized_client.dart +++ b/test/https_unauthorized_client.dart
@@ -17,14 +17,14 @@ void expect(condition, message) { if (!condition) { - throw new ExpectException(message); + throw ExpectException(message); } } const HOST_NAME = "localhost"; Future<Null> runClients(int port) async { - HttpClient client = new HttpClient(); + HttpClient client = HttpClient(); for (int i = 0; i < 20; ++i) { await client.getUrl(Uri.parse('https://$HOST_NAME:$port/')).then( (HttpClientRequest request) {
diff --git a/test/https_unauthorized_test.dart b/test/https_unauthorized_test.dart index dacaf10..79cb3bf 100644 --- a/test/https_unauthorized_test.dart +++ b/test/https_unauthorized_test.dart
@@ -24,7 +24,7 @@ String localFile(path) { var script = "${Directory.current.path}/test/$path"; - if (!(new File(script)).existsSync()) { + if (!(File(script)).existsSync()) { // If we can't find the file relative to the cwd, then look relative to // Platform.script. script = Platform.script.resolve(path).toFilePath(); @@ -32,12 +32,12 @@ return script; } -SecurityContext untrustedServerContext = new SecurityContext() +SecurityContext untrustedServerContext = SecurityContext() ..useCertificateChain(localFile('certificates/untrusted_server_chain.pem')) ..usePrivateKey(localFile('certificates/untrusted_server_key.pem'), password: 'dartdart'); -SecurityContext clientContext = new SecurityContext() +SecurityContext clientContext = SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); Future<HttpServer> runServer() { @@ -55,7 +55,7 @@ } Future<Null> runTest() { - final completer = new Completer<Null>(); + final completer = Completer<Null>(); var clientScript = localFile('https_unauthorized_client.dart'); Future clientProcess(int port) { return Process.run(Platform.executable, [clientScript, port.toString()])
diff --git a/test/session_test.dart b/test/session_test.dart index f5a96d4..aab5b89 100644 --- a/test/session_test.dart +++ b/test/session_test.dart
@@ -27,17 +27,17 @@ var request = await client.get("127.0.0.1", port, "/"); if (session != null) { - request.cookies.add(new Cookie(_sessionId, session)); + request.cookies.add(Cookie(_sessionId, session)); } var response = await request.close(); return response.fold(_getSessionId(response.cookies), (v, _) => v); } Future _testSessions(int sessionCount) async { - var client = new HttpClient(); + var client = HttpClient(); var server = await HttpServer.bind("127.0.0.1", 0); - var sessions = new Set(); + var sessions = Set(); server.listen((request) { sessions.add(request.session.id); request.response.close(); @@ -63,12 +63,12 @@ } Future _testTimeout(int sessionCount) async { - var client = new HttpClient(); + var client = HttpClient(); var server = await HttpServer.bind("127.0.0.1", 0); server.sessionTimeout = 1; var timeouts = <Future>[]; server.listen((request) { - var c = new Completer(); + var c = Completer(); timeouts.add(c.future); request.session.onTimeout = () { c.complete(null); @@ -117,7 +117,7 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); var request = await client.get("127.0.0.1", server.port, "/"); var response = await request.close(); @@ -128,7 +128,7 @@ expect(id, isNotNull); request = await client.get("127.0.0.1", server.port, "/"); - request.cookies.add(new Cookie(_sessionId, id)); + request.cookies.add(Cookie(_sessionId, id)); response = await request.close(); @@ -158,7 +158,7 @@ request.response.close(); }); - var client = new HttpClient(); + var client = HttpClient(); var request = await client.get("127.0.0.1", server.port, "/"); var response = await request.close(); @@ -170,7 +170,7 @@ request = await client.get("127.0.0.1", server.port, "/"); - request.cookies.add(new Cookie(_sessionId, id)); + request.cookies.add(Cookie(_sessionId, id)); response = await request.close(); await response.drain();