diff --git a/bin/web_server.dart b/bin/web_server.dart index 6b1fca3..594ac83 100644 --- a/bin/web_server.dart +++ b/bin/web_server.dart @@ -1,5 +1,6 @@ import "dart:io"; import "dart:async"; +import "package:dart2_constant/io.dart" as io; import "package:web_server/web_server.dart" as webServer; /** @@ -11,7 +12,7 @@ Future main(final List args) async { "h": "help" }; final Map cmdLineArgsMap = _parseCmdLineArgs(args, SHORTHAND_TO_FULL_CMD_LINE_ARG_KEYS); - InternetAddress hostAddr = InternetAddress.ANY_IP_V4; + InternetAddress hostAddr = io.InternetAddress.anyIPv4; int portNumber = 8080; // Default value. if (cmdLineArgsMap.containsKey('help')) { @@ -48,15 +49,15 @@ Future main(final List args) async { // Handle errors localWebServer.httpServerHandler - ..onErrorDocument(HttpStatus.NOT_FOUND, (final HttpRequest httpRequest) { + ..onErrorDocument(io.HttpStatus.notFound, (final HttpRequest httpRequest) { // Use the helper method from this WebServer package webServer.HttpServerRequestHandler.sendPageNotFoundResponse(httpRequest, - '

${HttpStatus.NOT_FOUND} - Page not found

'); + '

${io.HttpStatus.notFound} - Page not found

'); }) - ..onErrorDocument(HttpStatus.INTERNAL_SERVER_ERROR, (final HttpRequest httpRequest) { + ..onErrorDocument(io.HttpStatus.internalServerError, (final HttpRequest httpRequest) { // Use the helper method from this WebServer package webServer.HttpServerRequestHandler.sendInternalServerErrorResponse(httpRequest, - '

${HttpStatus.INTERNAL_SERVER_ERROR} - Internal Server Error

'); + '

${io.HttpStatus.internalServerError} - Internal Server Error

'); }); } diff --git a/example/virtual_directory.dart b/example/virtual_directory.dart index c50bf78..04a1699 100644 --- a/example/virtual_directory.dart +++ b/example/virtual_directory.dart @@ -1,10 +1,11 @@ import "dart:io"; import "dart:async"; +import "package:dart2_constant/io.dart" as io; import "package:web_server/web_server.dart" as webServer; Future main() async { // Initialize the WebServer - final webServer.WebServer localWebServer = new webServer.WebServer(InternetAddress.ANY_IP_V4, 8080, + final webServer.WebServer localWebServer = new webServer.WebServer(io.InternetAddress.anyIPv4, 8080, hasHttpServer: true); // Log out some of the connection information. diff --git a/example/web_server_misc.dart b/example/web_server_misc.dart index 62bab38..41461e3 100644 --- a/example/web_server_misc.dart +++ b/example/web_server_misc.dart @@ -1,9 +1,10 @@ import "dart:io"; +import "package:dart2_constant/io.dart" as io; import "package:web_server/web_server.dart"; void main() { // Initialize and bind the HTTP and WebSocket WebServer - final WebServer localWebServer = new WebServer(InternetAddress.ANY_IP_V4, 8080, + final WebServer localWebServer = new WebServer(io.InternetAddress.anyIPv4, 8080, hasHttpServer: true, hasWebSocketServer: true); // Log out some of the connection information @@ -41,15 +42,15 @@ void main() { // Respond to the Url request httpRequest.response - ..headers.contentType = ContentType.JSON // Set the 'content-type' header as JSON + ..headers.contentType = io.ContentType.json // Set the 'content-type' header as JSON ..write(apiResponse.toJsonEncoded()) // Export as a JSON encoded string ..close(); }) // Add a custom function for handling the request in case of the error code supplied as the parameter. - ..onErrorDocument(HttpStatus.NOT_FOUND, (final HttpRequest httpRequest) { + ..onErrorDocument(io.HttpStatus.notFound, (final HttpRequest httpRequest) { httpRequest.response - ..statusCode = HttpStatus.NOT_FOUND + ..statusCode = io.HttpStatus.notFound ..headers.contentType = new ContentType('text', 'html', charset: 'utf-8') ..write('

404 Error accessing: ${httpRequest.requestedUri.path}

') ..close(); @@ -57,7 +58,7 @@ void main() { // Attach WebSocket command listeners and base events localWebServer.webSocketServerHandler - ..on[0].listen((final WebSocketRequestPayload requestPayload) { /*...*/ }) + ..on[0].listen((final dynamic requestPayload) { /*...*/ }) ..onConnectionOpen.listen((final WebSocketConnectionData connectionData) { /*...*/ }) ..onConnectionError.listen((final WebSocket webSocket) { /*...*/ }) ..onConnectionClose.listen((final WebSocket webSocket) { /*...*/ }); diff --git a/lib/src/web_server/api_response.dart b/lib/src/web_server/api_response.dart index c125198..5bc31b3 100644 --- a/lib/src/web_server/api_response.dart +++ b/lib/src/web_server/api_response.dart @@ -78,7 +78,7 @@ class ApiResponse { * Calls [toJson], then processes it through [JSON.encode()] before returning. */ String toJsonEncoded() { - return JSON.encode(this.toJson()); + return convert.json.encode(this.toJson()); } } @@ -112,6 +112,6 @@ class ApiErrorResponse { } String toJsonEncoded() { - return JSON.encode(this.toJson()); + return convert.json.encode(this.toJson()); } } \ No newline at end of file diff --git a/lib/src/web_server/http_server_request_handler.dart b/lib/src/web_server/http_server_request_handler.dart index 62e905d..e82209e 100644 --- a/lib/src/web_server/http_server_request_handler.dart +++ b/lib/src/web_server/http_server_request_handler.dart @@ -173,7 +173,7 @@ class HttpServerRequestHandler { } else { // Respond with 404 error because nothing was matched. if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.log('No registered url match found.'); - this._callListenerForErrorDocument(HttpStatus.NOT_FOUND, httpRequest); + this._callListenerForErrorDocument(io.HttpStatus.notFound, httpRequest); } } } @@ -242,12 +242,12 @@ class HttpServerRequestHandler { _AuthCheckResults _checkAuthFromRequest(final HttpRequest httpRequest, final _PathDataWithAuth acceptedCredentialsPathData) { // If no auth header supplied - if (httpRequest.headers.value(HttpHeaders.AUTHORIZATION) == null) { + if (httpRequest.headers.value(io.HttpHeaders.authorizationHeader) == null) { return const _AuthCheckResults(false); } const int MAX_ALLOWED_CHARACTER_RANGE = 256; - final String authHeaderStr = httpRequest.headers.value(HttpHeaders.AUTHORIZATION); // Get the provided auth info + final String authHeaderStr = httpRequest.headers.value(io.HttpHeaders.authorizationHeader); // Get the provided auth info final int trimRange = (authHeaderStr.length <= MAX_ALLOWED_CHARACTER_RANGE) ? authHeaderStr.length : MAX_ALLOWED_CHARACTER_RANGE; // Determine subStr amt final String clientProvidedAuthInfo = authHeaderStr.substring(0, trimRange).replaceFirst(new RegExp('^Basic '), ''); // Remove the prefixed "Basic " from auth header @@ -261,8 +261,8 @@ class HttpServerRequestHandler { /// Helper for sending an HTTP 401 Auth required response static void sendRequiredBasicAuthResponse(final HttpRequest httpRequest, final String errMessage) { httpRequest.response - ..statusCode = HttpStatus.UNAUTHORIZED - ..headers.add(HttpHeaders.WWW_AUTHENTICATE, 'Basic realm="Enter credentials"') + ..statusCode = io.HttpStatus.unauthorized + ..headers.add(io.HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Enter credentials"') ..write(errMessage) ..close(); } @@ -270,7 +270,7 @@ class HttpServerRequestHandler { /// Helper for sending a HTTP 404 response with an optional custom HTML error message. static void sendPageNotFoundResponse(final HttpRequest httpRequest, [final String responseVal = '404 - Page not found']) { httpRequest.response - ..statusCode = HttpStatus.NOT_FOUND + ..statusCode = io.HttpStatus.notFound ..headers.contentType = new ContentType('text', 'html', charset: 'utf-8') ..write(responseVal) ..close(); @@ -279,7 +279,7 @@ class HttpServerRequestHandler { /// Helper for sending an HTTP 500 response with an optional custom HTML error message. static void sendInternalServerErrorResponse(final HttpRequest httpRequest, [final String responseVal = '500 - Internal Server Error']) { httpRequest.response - ..statusCode = HttpStatus.INTERNAL_SERVER_ERROR + ..statusCode = io.HttpStatus.internalServerError ..headers.contentType = new ContentType('text', 'html', charset: 'utf-8') ..write(responseVal) ..close(); @@ -320,26 +320,28 @@ class HttpServerRequestHandler { this._possibleFiles[urlData.path] = urlData.id; - this._functionStore[urlData.id].listen((final HttpRequest httpRequest) async { - String _localFileContents; + this._functionStore[urlData.id].listen((final dynamic httpRequest) async { + if (httpRequest is HttpRequest) { + String _localFileContents; - if (enableCaching == true) { // Use a cached file, or initialize the cached file, if enabled - if (_fileContents == null) { // If a version has not been cached before - _fileContents = await file.readAsString(); - } + if (enableCaching == true) { // Use a cached file, or initialize the cached file, if enabled + if (_fileContents == null) { // If a version has not been cached before + _fileContents = await file.readAsString(); + } - _localFileContents = _fileContents; - } else if (enableCaching == false) { // Read freshly, if caching is not enabled - _localFileContents = await file.readAsString(); - } + _localFileContents = _fileContents; + } else if (enableCaching == false) { // Read freshly, if caching is not enabled + _localFileContents = await file.readAsString(); + } - if (_contentType != null) { - httpRequest.response.headers.contentType = _contentType; - } + if (_contentType != null) { + httpRequest.response.headers.contentType = _contentType; + } - httpRequest.response + httpRequest.response ..write(_localFileContents) ..close(); + } }); } else { if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.error('The file at path ($pathToFile) was not found in the filesystem; unable to serve it.'); @@ -440,7 +442,7 @@ class HttpServerRequestHandler { final FileStat fileStat = await entity.stat(); // Don't process if this is not a file. - if (fileStat.type != FileSystemEntityType.FILE) { + if (fileStat.type != io.FileSystemEntityType.file) { return; } @@ -558,7 +560,7 @@ class HttpServerRequestHandler { } else { // File not found if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.error('_HttpServerRequestHandler::_serveStandardFile(String, HttpRequest) - File not found at path: ($pathToFile)'); - this._callListenerForErrorDocument(HttpStatus.NOT_FOUND, httpRequest); + this._callListenerForErrorDocument(io.HttpStatus.notFound, httpRequest); } } catch(err, stackTrace) { ServerLogger.error(err); diff --git a/lib/src/web_server/web_socket_server_request_handler.dart b/lib/src/web_server/web_socket_server_request_handler.dart index a0443d9..f042bf6 100644 --- a/lib/src/web_server/web_socket_server_request_handler.dart +++ b/lib/src/web_server/web_socket_server_request_handler.dart @@ -37,12 +37,14 @@ class _WebSocketServerRequestHandler { webSocket.map((final dynamic message) { if ((message is String) == false) { - return JSON.decode(this.customDecodeMessage(message, httpRequest, webSocket)); + return convert.json.decode(this.customDecodeMessage(message, httpRequest, webSocket)); } - return JSON.decode(message); - }).listen((final Map json) { - this.onMessage(json, httpRequest, webSocket); + return convert.json.decode(message); + }).listen((final dynamic json) { + if (json is Map) { + this.onMessage(json, httpRequest, webSocket); + } }, onError: (final dynamic err) { ServerLogger.error(err); diff --git a/lib/web_server.dart b/lib/web_server.dart index eb38295..cf8ce59 100644 --- a/lib/web_server.dart +++ b/lib/web_server.dart @@ -6,9 +6,10 @@ library WebServer; import "dart:io"; import "dart:async"; -import "dart:convert" show JSON, UTF8, LineSplitter; import "dart:typed_data"; import "package:cache/cache.dart"; +import 'package:dart2_constant/convert.dart' as convert; +import 'package:dart2_constant/io.dart' as io; import "package:event_listener/event_listener.dart"; import "package:path/path.dart" as path; import "package:server_logger/server_logger.dart" as ServerLogger; @@ -91,7 +92,7 @@ class WebServer { (this.allowedMethods != null && this.allowedMethods.contains(httpRequest.method) == false)) { httpRequest.response - ..statusCode = HttpStatus.FORBIDDEN + ..statusCode = io.HttpStatus.forbidden ..close(); return; } @@ -107,7 +108,7 @@ class WebServer { this.httpServerHandler._onHttpRequest(httpRequest); } else { httpRequest.response - ..statusCode = HttpStatus.FORBIDDEN + ..statusCode = io.HttpStatus.forbidden ..close(); } } diff --git a/lib/web_socket_connection_manager.dart b/lib/web_socket_connection_manager.dart index 9f23247..fd7ccb7 100644 --- a/lib/web_socket_connection_manager.dart +++ b/lib/web_socket_connection_manager.dart @@ -5,7 +5,7 @@ library WebSocketConnectionManager; import "dart:io"; -import "dart:convert" show JSON; +import "package:dart2_constant/convert.dart" as convert; import "package:server_logger/server_logger.dart" as ServerLogger; part 'src/web_socket_connection_manager/web_socket_object_store.dart'; @@ -19,7 +19,7 @@ abstract class WebSocketConnectionManager { ServerLogger.log('Broadcasting message to (${WebSocketConnectionManager.objectStore.length}) clients: \n$message'); WebSocketConnectionManager.objectStore.values.forEach((final WebSocketConnection webSocketConnection) { - webSocketConnection.webSocket.add(JSON.encode(message)); + webSocketConnection.webSocket.add(convert.json.encode(message)); }); } } \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index 2ce8e74..3923fa3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,10 +1,10 @@ name: web_server -version: 2.0.0+3 +version: 2.0.1 author: Brandon White description: An efficient server library for quickly creating a WebServer and handling HTTP requests, WebSocket connections, and API requests. homepage: https://github.com/bwhite000/web-server environment: - sdk: '>=1.9.0 <2.0.0' + sdk: '>=1.9.0 <3.0.0' documentation: http://jennex.it/github/bwhite000/web-server/docs/ dependencies: cache: @@ -16,5 +16,9 @@ dependencies: server_logger: git: https://github.com/bwhite000/server-logger.git version: '>=0.1.0 <2.0.0' + dart2_constant: + git: + url: https://github.com/Stargator/dart2_constant.git + ref: 1.0.3+dart2 executables: web_server: \ No newline at end of file