├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── NOTICE ├── README.md ├── package.json ├── plugin.xml ├── src └── android │ ├── com │ └── knowledgecode │ │ └── cordova │ │ └── websocket │ │ ├── ConnectionTask.java │ │ ├── DestroyTask.java │ │ ├── DisconnectionTask.java │ │ ├── ResetTask.java │ │ ├── SendingTask.java │ │ ├── TaskBean.java │ │ ├── TaskRunner.java │ │ ├── WebSocket.java │ │ └── WebSocketGenerator.java │ └── org │ └── eclipse │ └── jetty │ ├── http │ ├── HttpException.java │ ├── HttpHeaderValues.java │ ├── HttpHeaders.java │ ├── HttpMethods.java │ ├── HttpParser.java │ ├── HttpVersions.java │ └── Parser.java │ ├── io │ ├── AbstractBuffer.java │ ├── AbstractBuffers.java │ ├── AbstractConnection.java │ ├── AsyncEndPoint.java │ ├── Buffer.java │ ├── BufferCache.java │ ├── BufferUtil.java │ ├── Buffers.java │ ├── ByteArrayBuffer.java │ ├── ConnectedEndPoint.java │ ├── Connection.java │ ├── EndPoint.java │ ├── EofException.java │ ├── SimpleBuffers.java │ ├── ThreadLocalBuffers.java │ ├── View.java │ └── nio │ │ ├── AsyncConnection.java │ │ ├── ChannelEndPoint.java │ │ ├── DirectNIOBuffer.java │ │ ├── IndirectNIOBuffer.java │ │ ├── NIOBuffer.java │ │ ├── SelectChannelEndPoint.java │ │ ├── SelectorManager.java │ │ └── SslConnection.java │ ├── util │ ├── BlockingArrayQueue.java │ ├── ConcurrentHashSet.java │ ├── IO.java │ ├── QuotedStringTokenizer.java │ ├── StringMap.java │ ├── TypeUtil.java │ ├── component │ │ ├── AbstractLifeCycle.java │ │ ├── AggregateLifeCycle.java │ │ ├── Dumpable.java │ │ └── LifeCycle.java │ ├── log │ │ ├── AndroidLog.java │ │ ├── Log.java │ │ └── Logger.java │ ├── resource │ │ ├── Resource.java │ │ └── URLResource.java │ ├── security │ │ ├── CertificateUtils.java │ │ ├── CertificateValidator.java │ │ └── Password.java │ ├── ssl │ │ ├── AliasedX509ExtendedKeyManager.java │ │ └── SslContextFactory.java │ └── thread │ │ ├── QueuedThreadPool.java │ │ ├── ThreadPool.java │ │ └── Timeout.java │ └── websocket │ ├── Extension.java │ ├── MaskGen.java │ ├── PerMessageDeflateExtension.java │ ├── RandomMaskGen.java │ ├── WebSocket.java │ ├── WebSocketBuffer.java │ ├── WebSocketBuffers.java │ ├── WebSocketClient.java │ ├── WebSocketClientFactory.java │ ├── WebSocketConnection.java │ ├── WebSocketConnectionRFC6455.java │ ├── WebSocketGenerator.java │ ├── WebSocketGeneratorRFC6455.java │ ├── WebSocketParser.java │ └── WebSocketParserRFC6455.java └── www └── websocket.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change Log 2 | #### 0.12.2 3 | * support for cookies that include "=" character in the value (thanks to @evgk) 4 | 5 | #### 0.12.1 6 | * added readyState attribute values to WebSocket constructor (thanks to @llevkin) 7 | 8 | #### 0.12.0 9 | * changed minimum version of `cordova-android` that is required (3.6.0 or later) 10 | * fixed a bug that could not get cookies that have secure attribute when using wss protocol 11 | * fixed a bug that crashed when closing an app with leaving a connection open 12 | * prevented that corrupt option strings are injected 13 | * improved speed of receiving large binary 14 | * logging support 15 | * removed unused code 16 | * refactor 17 | 18 | #### 0.11.1 19 | * fixed a bug that was not be done unescape when sending a message (thanks to @shilder) 20 | * fixed a bug that became unable to send a message when was created an instance many times 21 | * temporarily disabled `AndroidLogger` 22 | 23 | #### 0.11.0 24 | * permessage-deflate support 25 | * removed unused code (further shrank about 20%) 26 | * performance improvement (further about 15% to 25% faster than previous versions) 27 | 28 | #### 0.10.0 29 | * permessage-deflate support (experimental) 30 | * fixed a multiple subprotocol bug 31 | * improved finalization 32 | * removed unused code (shrank about 20%) 33 | 34 | #### 0.9.2 35 | * fixed a bug that was lacked of trailing zeros (0x00) when receiving binary (thanks to @lemoncola) 36 | 37 | #### 0.9.1 38 | * updated only documents 39 | 40 | #### 0.9.0 41 | * integrated with jetty-8.1.17.v20150415 42 | * performance improvement (about 10% to 25% faster than previous versions) 43 | * added `agent` option 44 | * changed default value of `origin` option 45 | * restored `maxTextMessageSize`/`maxBinaryMessageSize` options 46 | * Crosswalk support 47 | * Android 2.2 (Froyo) support end 48 | * refactor 49 | 50 | #### 0.8.3 51 | * fixed that difference between packages and directories structure (thanks to @digigm) 52 | 53 | #### 0.8.2 54 | * fixed a constructor error on 4.4 and later (thanks to @digigm) 55 | 56 | #### 0.8.1 57 | * fixed a frame aggregation error (thanks to @Atsyn) 58 | * fixed a binary transmission for the case of using the plugin on 4.4 and later 59 | 60 | #### 0.8.0 61 | * performance improvement (about 5% to 15% faster than previous versions) 62 | * deployed source of Jetty directly (instead the jar file) 63 | * abolished `maxTextMessageSize`/`maxBinaryMessageSize` options 64 | * added `override` option 65 | * refactor 66 | 67 | #### 0.7.0 68 | * solved a problem of SSL on 4.0 and 2.3 (thanks to @agalazis and koush/AndroidAsync) 69 | 70 | #### 0.6.3 71 | * fixed a bug of a receiving binary size 72 | 73 | #### 0.6.2a 74 | * limit installation target to Android (thanks to @peli44) 75 | 76 | #### 0.6.2 77 | * updated Jetty WebSocket library 78 | 79 | #### 0.6.1 80 | * added escaping of special characters (thanks to @odbol) 81 | 82 | #### 0.6.0 83 | * cookie support (thanks to @ericfong) 84 | * removed a second argument from the send() method 85 | 86 | #### 0.5.2 87 | * clobbered buggy websockets on 4.3 or lower (thanks to @rpastorvargas and @punj) 88 | * bug fix 89 | 90 | #### 0.5.1 91 | * bug fix 92 | 93 | #### 0.5.0 94 | * change the way to set plugin options 95 | * multiple subprotocol support 96 | * readyState property support (thanks to @jrpereirajr) 97 | 98 | #### 0.4.0 99 | * Cordova/Phonegap 3 support 100 | * binary support 101 | * event listener support 102 | * more compliant with the WebSocket API requirements 103 | * license change from MIT to Apache v2.0 104 | 105 | #### 0.3.2 106 | * bug fix 107 | 108 | #### 0.3.1 109 | * bug fix 110 | 111 | #### 0.3.0 112 | * `origin` support (thanks to @rgillan) 113 | 114 | #### 0.2.0 115 | * comply with the WebSocket API requirements 116 | 117 | #### 0.1.0 118 | * first release 119 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | ============================================================== 2 | Jetty Web Container 3 | Copyright 1995-2015 Mort Bay Consulting Pty Ltd. 4 | ============================================================== 5 | 6 | The Jetty Web Container is Copyright Mort Bay Consulting Pty Ltd 7 | unless otherwise noted. 8 | 9 | Jetty is dual licensed under both 10 | 11 | * The Apache 2.0 License 12 | http://www.apache.org/licenses/LICENSE-2.0.html 13 | 14 | and 15 | 16 | * The Eclipse Public 1.0 License 17 | http://www.eclipse.org/legal/epl-v10.html 18 | 19 | Jetty may be distributed under either license. 20 | 21 | The javax.servlet package used was sourced from the Apache 22 | Software Foundation and is distributed under the apache 2.0 23 | license. 24 | 25 | The UnixCrypt.java code implements the one way cryptography used by 26 | Unix systems for simple password protection. Copyright 1996 Aki Yoshida, 27 | modified April 2001 by Iris Van den Broeke, Daniel Deville. 28 | Permission to use, copy, modify and distribute UnixCrypt 29 | for non-commercial or commercial purposes and without fee is 30 | granted provided that the copyright notice appears in all copies. 31 | 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cordova-plugin-websocket [![GitHub version](https://badge.fury.io/gh/knowledgecode%2FWebSocket-for-Android.svg)](http://badge.fury.io/gh/knowledgecode%2FWebSocket-for-Android) 2 | This is a Cordova plugin, which is being developed based on [Jetty 8](https://github.com/eclipse/jetty.project/tree/jetty-8), makes WebSocket (RFC6455) available on Android. 3 | 4 | ## Requirements 5 | - Android 2.3 or later (recommended 4.1 or later) 6 | - `cordova-android@3.6.0` or later, or compatible framework 7 | - `cordova-plugin-whitelist` or `cordova-plugin-legacy-whitelist` if using `cordova-android@4.0.0` and later 8 | 9 | The plugin for Cordova 2.x can be found [here](https://github.com/knowledgecode/WebSocket-for-Android/tree/2.x). However it is no longer maintained. 10 | 11 | ## Supported Features 12 | | version | WS protocol | WSS protocol | text message | binary message | 13 | |:---------------:|:-----------:|:------------:|:------------:|:--------------:| 14 | | 2.3.x (API 10) | ✓ | ✓ | ✓ | | 15 | | 4.0.x (API 14) | ✓ | ✓ | ✓ | ✓ | 16 | | 4.0.x (API 15) | ✓ | ✓ | ✓ | ✓ | 17 | | 4.1.x (API 16) | ✓ | ✓ | ✓ | ✓ | 18 | | 4.2.x (API 17) | ✓ | ✓ | ✓ | ✓ | 19 | | 4.3.x (API 18) | ✓ | ✓ | ✓ | ✓ | 20 | | 4.4.x and later | - | - | - | - | 21 | 22 | #### Notes 23 | - Since Android 4.4.x (KitKat) and later support WebSocket, this plugin is **NOT** used on there by default. 24 | - WSS protocol is only supported TLS. SSL is not supported. 25 | - Android 3.x (Honeycomb) are not supported (might work but is not tested). 26 | - In `cordova-android@4.0.0` and later, this plugin can be used together with [Crosswalk](https://crosswalk-project.org/). In this case also it is not used on there by default since that supports WebSocket. 27 | - In order to support Android 5.x (Lollipop) and later, would be better to build with `cordova-android@3.7.1` or later. 28 | 29 | ## Installation 30 | Use Cordova Command-Line Interface (CLI). At first check your CLI version: 31 | ```sh 32 | $ cordova --version 33 | 5.0.0 34 | ``` 35 | If using 5.0.0 and later, you can install it via npm: 36 | ```sh 37 | $ cordova plugin add cordova-plugin-websocket 38 | ``` 39 | If using other old versions, you can install it via GitHub: 40 | ```sh 41 | $ cordova plugin add https://github.com/knowledgecode/WebSocket-for-Android.git 42 | ``` 43 | 44 | #### Setting a Content-Security-Policy (CSP) 45 | `cordova-android@4.0.0` and later support SCP. In order to permit WebSocket access using `cordova-plugin-whitelist`, append `connect-src` directive in `index.html`: 46 | ```html 47 | connect-src ws://example.com wss://example.com 48 | ``` 49 | For example: 50 | ```html 51 | 52 | 53 | ``` 54 | 55 | ## Upgrading from previous versions 56 | Remove and then reinstall: 57 | ```sh 58 | $ cordova plugin rm cordova-plugin-websocket 59 | $ cordova plugin add cordova-plugin-websocket 60 | ``` 61 | 62 | #### Caveats 63 | - When install this plugin, it adds `INTERNET` permission to `platforms/android/AndroidManifest.xml`. If remove this plugin, the permission is also removed at the same time even if it is required for other plugins. 64 | - It has not supported `cordova-android@3.5.x` and earlier since v0.12.0. Please make sure Android platform version is more than that: 65 | ```sh 66 | $ cordova platform 67 | Installed platforms: android 4.1.1 68 | ``` 69 | 70 | ## Usage 71 | ### *WebSocket(url[, protocols])* 72 | The WebSocket(url, protocols) constructor takes one or two arguments. The first argument, url, specifies the URL to which to connect. The second, protocols, is either a string or an array of strings. 73 | A simple code is as follows: 74 | ```javascript 75 | document.addEventListener('deviceready', function () { 76 | var ws = new WebSocket('ws://echo.websocket.org'); 77 | 78 | ws.onopen = function () { 79 | console.log('open'); 80 | this.send('hello'); // transmit "hello" after connecting 81 | }; 82 | 83 | ws.onmessage = function (event) { 84 | console.log(event.data); // will be "hello" 85 | this.close(); 86 | }; 87 | 88 | ws.onerror = function () { 89 | console.log('error occurred!'); 90 | }; 91 | 92 | ws.onclose = function (event) { 93 | console.log('close code=' + event.code); 94 | }; 95 | }, false); 96 | ``` 97 | #### Options 98 | This plugin has the following options. All these parameters are optional. Of course these don't affect built-in WebSocket. 99 | 100 | | key | type | default value | supported version | 101 | |:---------------------|:--------|:--------------------|:-------------------------| 102 | | origin | string | file:// (usually) | >=v0.3.0 | 103 | | maxConnectTime | number | 75000 | >=v0.4.0 | 104 | | maxTextMessageSize | number | -1 | >=v0.4.0 (except v0.8.x) | 105 | | maxBinaryMessageSize | number | -1 | >=v0.4.0 (except v0.8.x) | 106 | | override | boolean | false | >=v0.8.0 | 107 | | agent | string | (depends on device) | >=v0.9.0 | 108 | | perMessageDeflate | boolean | true | >=v0.10.0 | 109 | 110 | `origin` is a value to set a request header field. Default value is usually `file://`. This is the same value as when using built-in WebSocket. 111 | 112 | `maxConnectTime` is time to wait for connection. A unit is millisecond. 113 | 114 | `maxTextMessageSize` and `maxBinaryMessageSize` are receivable maximum size from a server. Default value is -1 (unlimited. depends on heap size of devices). A unit is byte. 115 | 116 | `override` is a flag to force WebView to use this plugin even if it supports WebSocket. However in most cases it will be slower than built-in WebSocket. 117 | 118 | `agent` is user-agent to set a request header field. Default value depends on devices. This is the same value as when using built-in WebSocket. 119 | 120 | `perMessageDeflate` is a flag whether to use permessage-deflate extension. Default value is true. Sends data with compression if a server also supports permessage-deflate. However if mainly sending compressed binary like JPEG images, recommended to set to false. 121 | 122 | If change these parameters, need to do before creating a instance: 123 | ```javascript 124 | WebSocket.pluginOptions = { 125 | origin: 'http://example.com', 126 | maxConnectTime: 5000, 127 | override: true 128 | }; 129 | 130 | var ws = new WebSocket('ws://echo.websocket.org'); 131 | ``` 132 | ### *send(data)* 133 | Transmits data to the server over the WebSocket connection. The data takes a string, a blob, or an arraybuffer. 134 | 135 | #### Notes 136 | An upper limit of the message size depends on heap size of devices. It would be better to consider a way to split the message if it is quite large. 137 | ### *close([code[, reason]])* 138 | Closes the WebSocket connection or connection attempt, if any. 139 | 140 | ### For debug 141 | This plugin has been available logging for debug since v0.12.0. The logging level can be adjusted with `config.xml` that is in your project directory: 142 | ```xml 143 | 144 | 145 | 146 | ``` 147 | If don't specify this parameter, default level is `DEBUG`. So at first you may be surprised to see many debug logs on logcat. To stop logs except errors, change the level to `ERROR`. 148 | 149 | ## Change Log 150 | See [CHANGELOG.md](https://github.com/knowledgecode/WebSocket-for-Android/blob/master/CHANGELOG.md). 151 | 152 | ## License 153 | This plugin is available under the terms of the Apache License Version 2.0. 154 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cordova-plugin-websocket", 3 | "version": "0.12.2", 4 | "description": "Cordova WebSocket Plugin for Android", 5 | "cordova": { 6 | "id": "cordova-plugin-websocket", 7 | "platforms": [ 8 | "android" 9 | ] 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/knowledgecode/WebSocket-for-Android.git" 14 | }, 15 | "keywords": [ 16 | "cordova", 17 | "phonegap", 18 | "websocket", 19 | "android", 20 | "ecosystem:cordova", 21 | "cordova-android" 22 | ], 23 | "engines": [ 24 | { 25 | "name": "cordova", 26 | "version": ">=3.0.0" 27 | } 28 | ], 29 | "author": "KNOWLEDGECODE", 30 | "license": "Apache 2.0", 31 | "bugs": { 32 | "url": "https://github.com/knowledgecode/WebSocket-for-Android/issues" 33 | }, 34 | "homepage": "https://github.com/knowledgecode/WebSocket-for-Android#readme" 35 | } 36 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/ConnectionTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import java.net.URI; 22 | import java.util.Map; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import org.apache.cordova.CallbackContext; 26 | import org.apache.cordova.PluginResult; 27 | import org.apache.cordova.PluginResult.Status; 28 | import org.eclipse.jetty.websocket.PerMessageDeflateExtension; 29 | import org.eclipse.jetty.websocket.WebSocket.Connection; 30 | import org.eclipse.jetty.websocket.WebSocketClient; 31 | import org.eclipse.jetty.websocket.WebSocketClientFactory; 32 | import org.json.JSONArray; 33 | import org.json.JSONObject; 34 | 35 | import com.knowledgecode.cordova.websocket.TaskRunner.Task; 36 | import com.knowledgecode.cordova.websocket.WebSocketGenerator.OnCloseListener; 37 | import com.knowledgecode.cordova.websocket.WebSocketGenerator.OnOpenListener; 38 | 39 | import android.util.SparseArray; 40 | import android.webkit.CookieManager; 41 | 42 | /** 43 | * Connect to server. 44 | */ 45 | class ConnectionTask implements Task { 46 | 47 | private static final long MAX_CONNECT_TIME = 75000; 48 | private static final int MAX_TEXT_MESSAGE_SIZE = -1; 49 | private static final int MAX_BINARY_MESSAGE_SIZE = -1; 50 | private static final String WSS = "wss"; 51 | 52 | private final WebSocketClientFactory _factory; 53 | private final SparseArray _map; 54 | 55 | /** 56 | * Constructor 57 | * 58 | * @param factory 59 | * @param map 60 | */ 61 | public ConnectionTask(WebSocketClientFactory factory, SparseArray map) { 62 | _factory = factory; 63 | _map = map; 64 | 65 | if (!_factory.isRunning()) { 66 | try { 67 | _factory.start(); 68 | } catch (Exception e) { 69 | } 70 | } 71 | } 72 | 73 | /** 74 | * Set cookies, if any. 75 | * 76 | * @param cookies 77 | * @param host 78 | * @param secure 79 | */ 80 | private static void setCookie(Map cookies, String host, String path, boolean secure) { 81 | String url = String.format("%s://%s%s", secure ? "https" : "http", host, path); 82 | String cookie = CookieManager.getInstance().getCookie(url); 83 | 84 | if (cookie != null) { 85 | for (String c : cookie.split(";")) { 86 | int position = c.indexOf("="); 87 | 88 | if (position > 0) { 89 | String key = c.substring(0, position).trim(); 90 | String value = c.substring(position + 1).trim(); 91 | cookies.put(key, value); 92 | } 93 | } 94 | } 95 | } 96 | 97 | @Override 98 | public void execute(String rawArgs, CallbackContext ctx) { 99 | try { 100 | WebSocketClient client = _factory.newWebSocketClient(); 101 | 102 | JSONArray args = new JSONArray(rawArgs); 103 | int id = args.getInt(0); 104 | URI uri = new URI(args.getString(1)); 105 | String protocol = args.getString(2); 106 | JSONObject options = args.getJSONObject(5); 107 | String origin = options.optString("origin", args.getString(3)); 108 | String agent = options.optString("agent", args.getString(4)); 109 | boolean deflate = options.optBoolean("perMessageDeflate", true); 110 | long maxConnectTime = options.optLong("maxConnectTime", MAX_CONNECT_TIME); 111 | 112 | client.setMaxTextMessageSize(options.optInt("maxTextMessageSize", MAX_TEXT_MESSAGE_SIZE)); 113 | client.setMaxBinaryMessageSize(options.optInt("maxBinaryMessageSize", MAX_BINARY_MESSAGE_SIZE)); 114 | if (protocol.length() > 0) { 115 | client.setProtocol(protocol); 116 | } 117 | if (origin.length() > 0) { 118 | client.setOrigin(origin); 119 | } 120 | if (agent.length() > 0) { 121 | client.setAgent(agent); 122 | } 123 | if (deflate) { 124 | client.getExtensions().add(new PerMessageDeflateExtension()); 125 | } 126 | 127 | setCookie(client.getCookies(), uri.getHost(), uri.getPath(), WSS.equals(uri.getScheme())); 128 | 129 | WebSocketGenerator gen = new WebSocketGenerator(id, ctx); 130 | 131 | gen.setOnOpenListener(new OnOpenListener() { 132 | @Override 133 | public void onOpen(int id, Connection conn) { 134 | _map.put(id, conn); 135 | } 136 | }); 137 | gen.setOnCloseListener(new OnCloseListener() { 138 | @Override 139 | public void onClose(int id) { 140 | if (_map.indexOfKey(id) >= 0) { 141 | _map.remove(id); 142 | } 143 | } 144 | }); 145 | client.open(uri, gen, maxConnectTime, TimeUnit.MILLISECONDS); 146 | } catch (Exception e) { 147 | if (!ctx.isFinished()) { 148 | PluginResult result = new PluginResult(Status.ERROR); 149 | result.setKeepCallback(true); 150 | ctx.sendPluginResult(result); 151 | } 152 | } 153 | } 154 | } 155 | 156 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/DestroyTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import org.apache.cordova.CallbackContext; 22 | import org.eclipse.jetty.websocket.WebSocket.Connection; 23 | import org.eclipse.jetty.websocket.WebSocketClientFactory; 24 | 25 | import com.knowledgecode.cordova.websocket.TaskRunner.Task; 26 | 27 | import android.util.SparseArray; 28 | 29 | /** 30 | * Stop WebSocket client. 31 | */ 32 | class DestroyTask implements Task { 33 | 34 | private final WebSocketClientFactory _factory; 35 | private final SparseArray _map; 36 | 37 | /** 38 | * Constructor 39 | * 40 | * @param factory 41 | * @param map 42 | */ 43 | public DestroyTask(WebSocketClientFactory factory, SparseArray map) { 44 | _factory = factory; 45 | _map = map; 46 | } 47 | 48 | @Override 49 | public void execute(String rawArgs, CallbackContext ctx) { 50 | for (int i = 0; i < _map.size(); i++) { 51 | int key = _map.keyAt(i); 52 | 53 | if (_map.get(key).isOpen()) { 54 | _map.get(key).close(true); 55 | } 56 | } 57 | _map.clear(); 58 | 59 | if (_factory.isRunning()) { 60 | try { 61 | _factory.stop(); 62 | } catch (Exception e) { 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/DisconnectionTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import org.apache.cordova.CallbackContext; 22 | import org.apache.cordova.PluginResult; 23 | import org.apache.cordova.PluginResult.Status; 24 | import org.eclipse.jetty.websocket.WebSocket.Connection; 25 | import org.json.JSONArray; 26 | 27 | import com.knowledgecode.cordova.websocket.TaskRunner.Task; 28 | 29 | import android.util.SparseArray; 30 | 31 | /** 32 | * Close a connection. 33 | */ 34 | class DisconnectionTask implements Task { 35 | 36 | private final SparseArray _map; 37 | 38 | /** 39 | * Constructor 40 | * 41 | * @param map 42 | */ 43 | public DisconnectionTask(SparseArray map) { 44 | _map = map; 45 | } 46 | 47 | @Override 48 | public void execute(String rawArgs, CallbackContext ctx) { 49 | try { 50 | JSONArray args = new JSONArray(rawArgs); 51 | int id = Integer.parseInt(args.getString(0), 16); 52 | int code = args.getInt(1); 53 | String reason = args.getString(2); 54 | Connection conn = _map.get(id); 55 | 56 | if (conn != null) { 57 | if (code > 0) { 58 | conn.close(code, reason); 59 | } else { 60 | conn.close(); 61 | } 62 | } 63 | } catch (Exception e) { 64 | if (!ctx.isFinished()) { 65 | PluginResult result = new PluginResult(Status.ERROR); 66 | result.setKeepCallback(true); 67 | ctx.sendPluginResult(result); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/ResetTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import org.apache.cordova.CallbackContext; 22 | import org.eclipse.jetty.websocket.WebSocket.Connection; 23 | 24 | import com.knowledgecode.cordova.websocket.TaskRunner.Task; 25 | 26 | import android.util.SparseArray; 27 | 28 | /** 29 | * Close all connections. 30 | */ 31 | class ResetTask implements Task { 32 | 33 | private final SparseArray _map; 34 | 35 | /** 36 | * Constructor 37 | * 38 | * @param map 39 | */ 40 | public ResetTask(SparseArray map) { 41 | _map = map; 42 | } 43 | 44 | @Override 45 | public void execute(String rawArgs, CallbackContext ctx) { 46 | for (int i = 0; i < _map.size(); i++) { 47 | int key = _map.keyAt(i); 48 | 49 | if (_map.get(key).isOpen()) { 50 | _map.get(key).close(true); 51 | } 52 | } 53 | _map.clear(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/SendingTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import org.apache.cordova.CallbackContext; 22 | import org.apache.cordova.PluginResult; 23 | import org.apache.cordova.PluginResult.Status; 24 | import org.eclipse.jetty.websocket.WebSocket.Connection; 25 | import org.json.JSONArray; 26 | 27 | import com.knowledgecode.cordova.websocket.TaskRunner.Task; 28 | 29 | import android.util.Base64; 30 | import android.util.SparseArray; 31 | 32 | /** 33 | * Send text/binary data. 34 | */ 35 | class SendingTask implements Task { 36 | 37 | private final SparseArray _map; 38 | 39 | /** 40 | * Constructor 41 | * 42 | * @param map 43 | */ 44 | public SendingTask(SparseArray map) { 45 | _map = map; 46 | } 47 | 48 | @Override 49 | public void execute(String rawArgs, CallbackContext ctx) { 50 | try { 51 | String args = new JSONArray(rawArgs).getString(0); 52 | Connection conn = _map.get(Integer.parseInt(args.substring(0, 8), 16)); 53 | 54 | if (conn != null) { 55 | if (args.charAt(8) == '1') { 56 | byte[] binary = Base64.decode(args.substring(args.indexOf(',') + 1), Base64.NO_WRAP); 57 | conn.sendMessage(binary, 0, binary.length); 58 | } else { 59 | conn.sendMessage(args.substring(9)); 60 | } 61 | } else { 62 | } 63 | } catch (Exception e) { 64 | if (!ctx.isFinished()) { 65 | PluginResult result = new PluginResult(Status.ERROR); 66 | result.setKeepCallback(true); 67 | ctx.sendPluginResult(result); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/TaskBean.java: -------------------------------------------------------------------------------- 1 | package com.knowledgecode.cordova.websocket; 2 | 3 | import org.apache.cordova.CallbackContext; 4 | 5 | class TaskBean { 6 | private final String _action; 7 | private final String _rawArgs; 8 | private final CallbackContext _ctx; 9 | 10 | public TaskBean(final String action) { 11 | _action = action; 12 | _rawArgs = "[]"; 13 | _ctx = null; 14 | } 15 | 16 | public TaskBean(final String action, final String rawArgs, final CallbackContext ctx) { 17 | _action = action; 18 | _rawArgs = rawArgs; 19 | _ctx = ctx; 20 | } 21 | 22 | public String getAction() { 23 | return _action; 24 | } 25 | 26 | public String getRawArgs() { 27 | return _rawArgs; 28 | } 29 | 30 | public CallbackContext getCtx() { 31 | return _ctx; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/TaskRunner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | import java.util.concurrent.BlockingQueue; 24 | import java.util.concurrent.LinkedBlockingQueue; 25 | 26 | import org.apache.cordova.CallbackContext; 27 | 28 | class TaskRunner implements Runnable { 29 | 30 | interface Task { 31 | public void execute(String rawArgs, CallbackContext ctx); 32 | } 33 | 34 | private BlockingQueue _queue; 35 | private Map _map; 36 | 37 | public TaskRunner() { 38 | _queue = new LinkedBlockingQueue(); 39 | _map = new HashMap(); 40 | } 41 | 42 | public void setTask(String action, Task task) { 43 | _map.put(action, task); 44 | } 45 | 46 | public boolean addTaskQueue(TaskBean bean) { 47 | try { 48 | _queue.put(bean); 49 | } catch (InterruptedException e) { 50 | return false; 51 | } 52 | return true; 53 | } 54 | 55 | @Override 56 | public void run() { 57 | while (true) { 58 | TaskBean task; 59 | 60 | try { 61 | task = _queue.take(); 62 | } catch (InterruptedException e) { 63 | break; 64 | } 65 | String action = task.getAction(); 66 | 67 | _map.get(action).execute(task.getRawArgs(), task.getCtx()); 68 | if (WebSocket.DESTROY_TASK.equals(action)) { 69 | break; 70 | } 71 | } 72 | _queue.clear(); 73 | _map.clear(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/WebSocket.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import java.util.concurrent.ExecutorService; 22 | import java.util.concurrent.Executors; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import org.apache.cordova.CordovaPreferences; 26 | import org.apache.cordova.CordovaWebView; 27 | import org.apache.cordova.CallbackContext; 28 | import org.apache.cordova.CordovaInterface; 29 | import org.apache.cordova.CordovaPlugin; 30 | import org.eclipse.jetty.util.log.Log; 31 | import org.eclipse.jetty.websocket.WebSocket.Connection; 32 | import org.eclipse.jetty.websocket.WebSocketClientFactory; 33 | 34 | import android.util.SparseArray; 35 | 36 | /** 37 | * Cordova WebSocket Plugin for Android 38 | * This plugin is using Jetty under the terms of the Apache License v2.0. 39 | * 40 | * @author KNOWLEDGECODE 41 | * @version 0.12.2 42 | */ 43 | public class WebSocket extends CordovaPlugin { 44 | 45 | static final String CREATE_TASK = "create"; 46 | static final String SEND_TASK = "send"; 47 | static final String CLOSE_TASK = "close"; 48 | static final String RESET_TASK = "reset"; 49 | static final String DESTROY_TASK = "destroy"; 50 | 51 | private WebSocketClientFactory _factory; 52 | private SparseArray _conn; 53 | private ExecutorService _executor; 54 | private TaskRunner _runner; 55 | 56 | @Override 57 | public void initialize(CordovaInterface cordova, final CordovaWebView webView) { 58 | super.initialize(cordova, webView); 59 | _factory = new WebSocketClientFactory(); 60 | _conn = new SparseArray(); 61 | _executor = Executors.newSingleThreadExecutor(); 62 | _runner = new TaskRunner(); 63 | _runner.setTask(CREATE_TASK, new ConnectionTask(_factory, _conn)); 64 | _runner.setTask(SEND_TASK, new SendingTask(_conn)); 65 | _runner.setTask(CLOSE_TASK, new DisconnectionTask(_conn)); 66 | _runner.setTask(RESET_TASK, new ResetTask(_conn)); 67 | _runner.setTask(DESTROY_TASK, new DestroyTask(_factory, _conn)); 68 | _executor.execute(_runner); 69 | Log.setLogLevel(getLogLevel(this.preferences)); 70 | } 71 | 72 | @Override 73 | public boolean execute(String action, String rawArgs, CallbackContext ctx) { 74 | return _runner.addTaskQueue(new TaskBean(action, rawArgs, ctx)); 75 | }; 76 | 77 | @Override 78 | public void onReset() { 79 | _runner.addTaskQueue(new TaskBean(RESET_TASK)); 80 | super.onReset(); 81 | } 82 | 83 | @Override 84 | public void onDestroy() { 85 | _runner.addTaskQueue(new TaskBean(DESTROY_TASK)); 86 | _executor.shutdown(); 87 | try { 88 | _executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); 89 | } catch (InterruptedException e) { 90 | } 91 | super.onDestroy(); 92 | } 93 | 94 | private static int getLogLevel(CordovaPreferences preferences) { 95 | String logLevel = preferences.getString("LogLevel", "ERROR"); 96 | 97 | if ("VERBOSE".equals(logLevel)) { 98 | return android.util.Log.VERBOSE; 99 | } else if ("DEBUG".equals(logLevel)) { 100 | return android.util.Log.DEBUG; 101 | } else if ("INFO".equals(logLevel)) { 102 | return android.util.Log.INFO; 103 | } else if ("WARN".equals(logLevel)) { 104 | return android.util.Log.WARN; 105 | } else { 106 | return android.util.Log.ERROR; 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/android/com/knowledgecode/cordova/websocket/WebSocketGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package com.knowledgecode.cordova.websocket; 20 | 21 | import java.nio.charset.Charset; 22 | 23 | import org.apache.cordova.CallbackContext; 24 | import org.apache.cordova.PluginResult; 25 | import org.apache.cordova.PluginResult.Status; 26 | 27 | import android.text.TextUtils; 28 | 29 | class WebSocketGenerator implements 30 | org.eclipse.jetty.websocket.WebSocket.OnTextMessage, 31 | org.eclipse.jetty.websocket.WebSocket.OnBinaryMessage { 32 | 33 | interface OnOpenListener { 34 | public void onOpen(int id, Connection conn); 35 | } 36 | 37 | interface OnCloseListener { 38 | public void onClose(int id); 39 | } 40 | 41 | private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); 42 | 43 | private final int _id; 44 | private final CallbackContext _ctx; 45 | private OnOpenListener _openListener; 46 | private OnCloseListener _closeListener; 47 | 48 | /** 49 | * Constructor 50 | * 51 | * @param id 52 | * @param ctx 53 | */ 54 | public WebSocketGenerator(int id, CallbackContext ctx) { 55 | _id = id; 56 | _ctx = ctx; 57 | _openListener = new OnOpenListener() { 58 | @Override 59 | public void onOpen(int id, Connection conn) { 60 | // NOP 61 | } 62 | }; 63 | _closeListener = new OnCloseListener() { 64 | @Override 65 | public void onClose(int id) { 66 | // NOP 67 | } 68 | }; 69 | } 70 | 71 | /** 72 | * Set OnOpen listener. 73 | * 74 | * @param l 75 | */ 76 | public void setOnOpenListener(OnOpenListener l) { 77 | _openListener = l; 78 | } 79 | 80 | /** 81 | * Set OnClose listener. 82 | * 83 | * @param l 84 | */ 85 | public void setOnCloseListener(OnCloseListener l) { 86 | _closeListener = l; 87 | } 88 | 89 | @Override 90 | public void onOpen(Connection conn) { 91 | _openListener.onOpen(_id, conn); 92 | 93 | String protocol = conn.getProtocol(); 94 | String extensions = conn.getExtensions(); 95 | protocol = protocol == null ? "" : protocol; 96 | extensions = extensions == null ? "" : extensions; 97 | sendCallback(String.format("O[\"%s\",\"%s\"]", protocol, extensions), true); 98 | } 99 | 100 | @Override 101 | public void onMessage(String data) { 102 | sendCallback("T" + data, true); 103 | } 104 | 105 | @Override 106 | public void onMessage(byte[] data, int offset, int length) { 107 | sendCallback((String) TextUtils.concat( 108 | "B", String.format("%08x", length), new String(data, offset, length, ISO_8859_1)), true); 109 | } 110 | 111 | @Override 112 | public void onClose(int code, String reason) { 113 | _closeListener.onClose(_id); 114 | 115 | String wasClean = code == 1000 ? "1" : "0"; 116 | reason = reason == null ? "" : reason; 117 | sendCallback(String.format("C%s%4d%s", wasClean, code, reason), false); 118 | } 119 | 120 | /** 121 | * Send plugin result. 122 | * 123 | * @param callbackString 124 | * @param keepCallback 125 | */ 126 | private void sendCallback(String callbackString, boolean keepCallback) { 127 | if (!_ctx.isFinished()) { 128 | PluginResult result = new PluginResult(Status.OK, callbackString); 129 | result.setKeepCallback(keepCallback); 130 | _ctx.sendPluginResult(result); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/http/HttpException.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.http; 20 | 21 | import java.io.IOException; 22 | 23 | @SuppressWarnings("serial") 24 | public class HttpException extends IOException 25 | { 26 | int _status; 27 | String _reason; 28 | 29 | /* ------------------------------------------------------------ */ 30 | public HttpException(int status) 31 | { 32 | _status=status; 33 | _reason=null; 34 | } 35 | 36 | /* ------------------------------------------------------------ */ 37 | public HttpException(int status,String reason) 38 | { 39 | _status=status; 40 | _reason=reason; 41 | } 42 | 43 | /* ------------------------------------------------------------ */ 44 | @Override 45 | public String toString() 46 | { 47 | return ("HttpException("+_status+","+_reason+","+super.getCause()+")"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/http/HttpHeaderValues.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.http; 20 | 21 | import org.eclipse.jetty.io.Buffer; 22 | import org.eclipse.jetty.io.BufferCache; 23 | import org.eclipse.jetty.io.ByteArrayBuffer; 24 | 25 | /** 26 | * Cached HTTP Header values. 27 | * This class caches the conversion of common HTTP Header values to and from {@link ByteArrayBuffer} instances. 28 | * The resource "/org/eclipse/jetty/useragents" is checked for a list of common user agents, so that repeated 29 | * creation of strings for these agents can be avoided. 30 | * 31 | * 32 | */ 33 | public class HttpHeaderValues extends BufferCache 34 | { 35 | public final static String 36 | CLOSE="close", 37 | CHUNKED="chunked", 38 | GZIP="gzip", 39 | IDENTITY="identity", 40 | KEEP_ALIVE="keep-alive", 41 | CONTINUE="100-continue", 42 | PROCESSING="102-processing", 43 | TE="TE", 44 | BYTES="bytes", 45 | NO_CACHE="no-cache", 46 | UPGRADE="Upgrade"; 47 | 48 | public final static int 49 | CLOSE_ORDINAL=1, 50 | CHUNKED_ORDINAL=2, 51 | GZIP_ORDINAL=3, 52 | IDENTITY_ORDINAL=4, 53 | KEEP_ALIVE_ORDINAL=5, 54 | CONTINUE_ORDINAL=6, 55 | PROCESSING_ORDINAL=7, 56 | TE_ORDINAL=8, 57 | BYTES_ORDINAL=9, 58 | NO_CACHE_ORDINAL=10, 59 | UPGRADE_ORDINAL=11; 60 | 61 | public final static HttpHeaderValues CACHE= new HttpHeaderValues(); 62 | 63 | public final static Buffer 64 | CLOSE_BUFFER=CACHE.add(CLOSE,CLOSE_ORDINAL), 65 | CHUNKED_BUFFER=CACHE.add(CHUNKED,CHUNKED_ORDINAL), 66 | GZIP_BUFFER=CACHE.add(GZIP,GZIP_ORDINAL), 67 | IDENTITY_BUFFER=CACHE.add(IDENTITY,IDENTITY_ORDINAL), 68 | KEEP_ALIVE_BUFFER=CACHE.add(KEEP_ALIVE,KEEP_ALIVE_ORDINAL), 69 | CONTINUE_BUFFER=CACHE.add(CONTINUE, CONTINUE_ORDINAL), 70 | PROCESSING_BUFFER=CACHE.add(PROCESSING, PROCESSING_ORDINAL), 71 | TE_BUFFER=CACHE.add(TE,TE_ORDINAL), 72 | BYTES_BUFFER=CACHE.add(BYTES,BYTES_ORDINAL), 73 | NO_CACHE_BUFFER=CACHE.add(NO_CACHE,NO_CACHE_ORDINAL), 74 | UPGRADE_BUFFER=CACHE.add(UPGRADE,UPGRADE_ORDINAL); 75 | } 76 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/http/HttpMethods.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.http; 20 | 21 | import org.eclipse.jetty.io.Buffer; 22 | import org.eclipse.jetty.io.BufferCache; 23 | 24 | /* ------------------------------------------------------------------------------- */ 25 | /** 26 | * 27 | * 28 | */ 29 | public class HttpMethods 30 | { 31 | public final static String GET= "GET", 32 | POST= "POST", 33 | HEAD= "HEAD", 34 | PUT= "PUT", 35 | OPTIONS= "OPTIONS", 36 | DELETE= "DELETE", 37 | TRACE= "TRACE", 38 | CONNECT= "CONNECT", 39 | MOVE= "MOVE"; 40 | 41 | public final static int GET_ORDINAL= 1, 42 | POST_ORDINAL= 2, 43 | HEAD_ORDINAL= 3, 44 | PUT_ORDINAL= 4, 45 | OPTIONS_ORDINAL= 5, 46 | DELETE_ORDINAL= 6, 47 | TRACE_ORDINAL= 7, 48 | CONNECT_ORDINAL= 8, 49 | MOVE_ORDINAL= 9; 50 | 51 | public final static BufferCache CACHE= new BufferCache(); 52 | 53 | public final static Buffer 54 | GET_BUFFER= CACHE.add(GET, GET_ORDINAL), 55 | POST_BUFFER= CACHE.add(POST, POST_ORDINAL), 56 | HEAD_BUFFER= CACHE.add(HEAD, HEAD_ORDINAL), 57 | PUT_BUFFER= CACHE.add(PUT, PUT_ORDINAL), 58 | OPTIONS_BUFFER= CACHE.add(OPTIONS, OPTIONS_ORDINAL), 59 | DELETE_BUFFER= CACHE.add(DELETE, DELETE_ORDINAL), 60 | TRACE_BUFFER= CACHE.add(TRACE, TRACE_ORDINAL), 61 | CONNECT_BUFFER= CACHE.add(CONNECT, CONNECT_ORDINAL), 62 | MOVE_BUFFER= CACHE.add(MOVE, MOVE_ORDINAL); 63 | } 64 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/http/HttpVersions.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.http; 20 | 21 | import org.eclipse.jetty.io.Buffer; 22 | import org.eclipse.jetty.io.BufferCache; 23 | 24 | /* ------------------------------------------------------------------------------- */ 25 | /** 26 | * 27 | * 28 | */ 29 | public class HttpVersions 30 | { 31 | public final static String 32 | HTTP_0_9 = "", 33 | HTTP_1_0 = "HTTP/1.0", 34 | HTTP_1_1 = "HTTP/1.1"; 35 | 36 | public final static int 37 | HTTP_0_9_ORDINAL=9, 38 | HTTP_1_0_ORDINAL=10, 39 | HTTP_1_1_ORDINAL=11; 40 | 41 | public final static BufferCache CACHE = new BufferCache(); 42 | 43 | public final static Buffer 44 | HTTP_0_9_BUFFER=CACHE.add(HTTP_0_9,HTTP_0_9_ORDINAL), 45 | HTTP_1_0_BUFFER=CACHE.add(HTTP_1_0,HTTP_1_0_ORDINAL), 46 | HTTP_1_1_BUFFER=CACHE.add(HTTP_1_1,HTTP_1_1_ORDINAL); 47 | } 48 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/http/Parser.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.http; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * Abstract interface for a connection Parser for use by Jetty. 25 | */ 26 | public interface Parser 27 | { 28 | boolean isComplete(); 29 | 30 | /** 31 | * @return True if progress made 32 | * @throws IOException 33 | */ 34 | boolean parseAvailable() throws IOException; 35 | 36 | boolean isIdle(); 37 | } 38 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/AbstractBuffers.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import org.eclipse.jetty.io.nio.DirectNIOBuffer; 22 | import org.eclipse.jetty.io.nio.IndirectNIOBuffer; 23 | 24 | public abstract class AbstractBuffers implements Buffers 25 | { 26 | protected final Buffers.Type _headerType; 27 | protected final int _headerSize; 28 | protected final Buffers.Type _bufferType; 29 | protected final int _bufferSize; 30 | protected final Buffers.Type _otherType; 31 | 32 | /* ------------------------------------------------------------ */ 33 | public AbstractBuffers(Buffers.Type headerType, int headerSize, Buffers.Type bufferType, int bufferSize, Buffers.Type otherType) 34 | { 35 | _headerType=headerType; 36 | _headerSize=headerSize; 37 | _bufferType=bufferType; 38 | _bufferSize=bufferSize; 39 | _otherType=otherType; 40 | } 41 | 42 | /* ------------------------------------------------------------ */ 43 | /** 44 | * @return Returns the buffer size in bytes. 45 | */ 46 | public int getBufferSize() 47 | { 48 | return _bufferSize; 49 | } 50 | 51 | /* ------------------------------------------------------------ */ 52 | /** 53 | * @return Returns the header size in bytes. 54 | */ 55 | public int getHeaderSize() 56 | { 57 | return _headerSize; 58 | } 59 | 60 | 61 | /* ------------------------------------------------------------ */ 62 | /** 63 | * Create a new header Buffer 64 | * @return new Buffer 65 | */ 66 | final protected Buffer newHeader() 67 | { 68 | switch(_headerType) 69 | { 70 | case BYTE_ARRAY: 71 | return new ByteArrayBuffer(_headerSize); 72 | case DIRECT: 73 | return new DirectNIOBuffer(_headerSize); 74 | case INDIRECT: 75 | return new IndirectNIOBuffer(_headerSize); 76 | } 77 | throw new IllegalStateException(); 78 | } 79 | 80 | /* ------------------------------------------------------------ */ 81 | /** 82 | * Create a new content Buffer 83 | * @return new Buffer 84 | */ 85 | final protected Buffer newBuffer() 86 | { 87 | switch(_bufferType) 88 | { 89 | case BYTE_ARRAY: 90 | return new ByteArrayBuffer(_bufferSize); 91 | case DIRECT: 92 | return new DirectNIOBuffer(_bufferSize); 93 | case INDIRECT: 94 | return new IndirectNIOBuffer(_bufferSize); 95 | } 96 | throw new IllegalStateException(); 97 | } 98 | 99 | /* ------------------------------------------------------------ */ 100 | /** 101 | * @param buffer 102 | * @return True if the buffer is the correct type to be a Header buffer 103 | */ 104 | public final boolean isHeader(Buffer buffer) 105 | { 106 | if (buffer.capacity()==_headerSize) 107 | { 108 | switch(_headerType) 109 | { 110 | case BYTE_ARRAY: 111 | return buffer instanceof ByteArrayBuffer && !(buffer instanceof IndirectNIOBuffer); 112 | case DIRECT: 113 | return buffer instanceof DirectNIOBuffer; 114 | case INDIRECT: 115 | return buffer instanceof IndirectNIOBuffer; 116 | } 117 | } 118 | return false; 119 | } 120 | 121 | /* ------------------------------------------------------------ */ 122 | /** 123 | * @param buffer 124 | * @return True if the buffer is the correct type to be a Header buffer 125 | */ 126 | public final boolean isBuffer(Buffer buffer) 127 | { 128 | if (buffer.capacity()==_bufferSize) 129 | { 130 | switch(_bufferType) 131 | { 132 | case BYTE_ARRAY: 133 | return buffer instanceof ByteArrayBuffer && !(buffer instanceof IndirectNIOBuffer); 134 | case DIRECT: 135 | return buffer instanceof DirectNIOBuffer; 136 | case INDIRECT: 137 | return buffer instanceof IndirectNIOBuffer; 138 | } 139 | } 140 | return false; 141 | } 142 | 143 | /* ------------------------------------------------------------ */ 144 | public String toString() 145 | { 146 | return String.format("%s [%d,%d]", getClass().getSimpleName(), _headerSize, _bufferSize); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/AbstractConnection.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.io.IOException; 22 | 23 | import org.eclipse.jetty.util.log.Log; 24 | import org.eclipse.jetty.util.log.Logger; 25 | 26 | 27 | public abstract class AbstractConnection implements Connection 28 | { 29 | private static final Logger LOG = Log.getLogger(AbstractConnection.class); 30 | 31 | protected final EndPoint _endp; 32 | 33 | public AbstractConnection(EndPoint endp,long timestamp) 34 | { 35 | _endp=(EndPoint)endp; 36 | } 37 | 38 | public void onIdleExpired(long idleForMs) 39 | { 40 | try 41 | { 42 | LOG.debug("onIdleExpired {}ms {} {}",idleForMs,this,_endp); 43 | if (_endp.isInputShutdown() || _endp.isOutputShutdown()) 44 | _endp.close(); 45 | else 46 | _endp.shutdownOutput(); 47 | } 48 | catch(IOException e) 49 | { 50 | LOG.ignore(e); 51 | 52 | try 53 | { 54 | _endp.close(); 55 | } 56 | catch(IOException e2) 57 | { 58 | LOG.ignore(e2); 59 | } 60 | } 61 | } 62 | 63 | public String toString() 64 | { 65 | return String.format("%s@%x", getClass().getSimpleName(), hashCode()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/AsyncEndPoint.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | public interface AsyncEndPoint extends ConnectedEndPoint 22 | { 23 | /* ------------------------------------------------------------ */ 24 | /** 25 | * Dispatch the endpoint if it is not already dispatched 26 | * 27 | */ 28 | public void dispatch(); 29 | 30 | /* ------------------------------------------------------------ */ 31 | /** Schedule a write dispatch. 32 | * Set the endpoint to not be writable and schedule a dispatch when 33 | * it becomes writable. 34 | */ 35 | public void scheduleWrite(); 36 | 37 | /* ------------------------------------------------------------ */ 38 | /** 39 | * @return True if IO has been successfully performed since the last call to {@link #hasProgressed()} 40 | */ 41 | public boolean hasProgressed(); 42 | } 43 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/BufferCache.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.util.ArrayList; 22 | import java.util.HashMap; 23 | import java.util.Map.Entry; 24 | 25 | import org.eclipse.jetty.util.StringMap; 26 | 27 | /* ------------------------------------------------------------------------------- */ 28 | /** 29 | * Stores a collection of {@link Buffer} objects. 30 | * Buffers are stored in an ordered collection and can retreived by index or value 31 | * 32 | */ 33 | public class BufferCache 34 | { 35 | private final HashMap _bufferMap=new HashMap(); 36 | private final StringMap _stringMap=new StringMap(StringMap.CASE_INSENSTIVE); 37 | private final ArrayList _index= new ArrayList(); 38 | 39 | /* ------------------------------------------------------------------------------- */ 40 | /** Add a buffer to the cache at the specified index. 41 | * @param value The content of the buffer. 42 | */ 43 | public CachedBuffer add(String value, int ordinal) 44 | { 45 | CachedBuffer buffer= new CachedBuffer(value, ordinal); 46 | _bufferMap.put(buffer, buffer); 47 | _stringMap.put(value, buffer); 48 | while ((ordinal - _index.size()) >= 0) 49 | _index.add(null); 50 | if (_index.get(ordinal)==null) 51 | _index.add(ordinal, buffer); 52 | return buffer; 53 | } 54 | 55 | public CachedBuffer get(Buffer buffer) 56 | { 57 | return (CachedBuffer)_bufferMap.get(buffer); 58 | } 59 | 60 | public Buffer lookup(Buffer buffer) 61 | { 62 | if (buffer instanceof CachedBuffer) 63 | return buffer; 64 | 65 | Buffer b= get(buffer); 66 | if (b == null) 67 | { 68 | if (buffer instanceof Buffer.CaseInsensitve) 69 | return buffer; 70 | return new ByteArrayBuffer.CaseInsensitive(buffer.asArray(),0,buffer.length(),Buffer.IMMUTABLE); 71 | } 72 | 73 | return b; 74 | } 75 | 76 | public CachedBuffer getBest(byte[] value, int offset, int maxLength) 77 | { 78 | Entry entry = _stringMap.getBestEntry(value, offset, maxLength); 79 | if (entry!=null) 80 | return (CachedBuffer)entry.getValue(); 81 | return null; 82 | } 83 | 84 | public int getOrdinal(String value) 85 | { 86 | CachedBuffer buffer = (CachedBuffer)_stringMap.get(value); 87 | return buffer==null?-1:buffer.getOrdinal(); 88 | } 89 | 90 | public int getOrdinal(Buffer buffer) 91 | { 92 | if (buffer instanceof CachedBuffer) 93 | return ((CachedBuffer)buffer).getOrdinal(); 94 | buffer=lookup(buffer); 95 | if (buffer!=null && buffer instanceof CachedBuffer) 96 | return ((CachedBuffer)buffer).getOrdinal(); 97 | return -1; 98 | } 99 | 100 | public static class CachedBuffer extends ByteArrayBuffer.CaseInsensitive 101 | { 102 | private final int _ordinal; 103 | 104 | public CachedBuffer(String value, int ordinal) 105 | { 106 | super(value); 107 | _ordinal= ordinal; 108 | } 109 | 110 | public int getOrdinal() 111 | { 112 | return _ordinal; 113 | } 114 | } 115 | 116 | @Override 117 | public String toString() 118 | { 119 | return "CACHE["+ 120 | "bufferMap="+_bufferMap+ 121 | ",stringMap="+_stringMap+ 122 | ",index="+_index+ 123 | "]"; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/BufferUtil.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | /* ------------------------------------------------------------------------------- */ 22 | /** Buffer utility methods. 23 | * 24 | * 25 | */ 26 | public class BufferUtil 27 | { 28 | static final byte SPACE= 0x20; 29 | static final byte MINUS= '-'; 30 | 31 | /** 32 | * Convert buffer to an long. 33 | * Parses up to the first non-numeric character. If no number is found an 34 | * IllegalArgumentException is thrown 35 | * @param buffer A buffer containing an integer. The position is not changed. 36 | * @return an int 37 | */ 38 | public static long toLong(Buffer buffer) 39 | { 40 | long val= 0; 41 | boolean started= false; 42 | boolean minus= false; 43 | for (int i= buffer.getIndex(); i < buffer.putIndex(); i++) 44 | { 45 | byte b= buffer.peek(i); 46 | if (b <= SPACE) 47 | { 48 | if (started) 49 | break; 50 | } 51 | else if (b >= '0' && b <= '9') 52 | { 53 | val= val * 10L + (b - '0'); 54 | started= true; 55 | } 56 | else if (b == MINUS && !started) 57 | { 58 | minus= true; 59 | } 60 | else 61 | break; 62 | } 63 | 64 | if (started) 65 | return minus ? (-val) : val; 66 | throw new NumberFormatException(buffer.toString()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/Buffers.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | 22 | /* ------------------------------------------------------------ */ 23 | /** BufferSource. 24 | * Represents a pool or other source of buffers and abstracts the creation 25 | * of specific types of buffers (eg NIO). The concept of big and little buffers 26 | * is supported, but these terms have no absolute meaning and must be determined by context. 27 | * 28 | */ 29 | public interface Buffers 30 | { 31 | enum Type { BYTE_ARRAY, DIRECT, INDIRECT } ; 32 | 33 | Buffer getHeader(); 34 | Buffer getBuffer(); 35 | 36 | void returnBuffer(Buffer buffer); 37 | } 38 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/ByteArrayBuffer.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.nio.charset.Charset; 22 | 23 | /* ------------------------------------------------------------------------------- */ 24 | /** 25 | * 26 | */ 27 | public class ByteArrayBuffer extends AbstractBuffer 28 | { 29 | static final Charset __ISO_8859_1 = Charset.forName("ISO-8859-1"); 30 | final protected byte[] _bytes; 31 | 32 | protected ByteArrayBuffer(int size, int access, boolean isVolatile) 33 | { 34 | this(new byte[size],0,0,access, isVolatile); 35 | } 36 | 37 | public ByteArrayBuffer(byte[] bytes, int index, int length, int access) 38 | { 39 | super(READWRITE, NON_VOLATILE); 40 | _bytes = bytes; 41 | setPutIndex(index + length); 42 | setGetIndex(index); 43 | _access = access; 44 | } 45 | 46 | public ByteArrayBuffer(byte[] bytes, int index, int length, int access, boolean isVolatile) 47 | { 48 | super(READWRITE, isVolatile); 49 | _bytes = bytes; 50 | setPutIndex(index + length); 51 | setGetIndex(index); 52 | _access = access; 53 | } 54 | 55 | public ByteArrayBuffer(int size) 56 | { 57 | this(new byte[size], 0, 0, READWRITE); 58 | setPutIndex(0); 59 | } 60 | 61 | public ByteArrayBuffer(String value) 62 | { 63 | super(READWRITE,NON_VOLATILE); 64 | _bytes = value.getBytes(__ISO_8859_1); 65 | setGetIndex(0); 66 | setPutIndex(_bytes.length); 67 | _access=IMMUTABLE; 68 | _string = value; 69 | } 70 | 71 | public ByteArrayBuffer(String value,boolean immutable) 72 | { 73 | super(READWRITE,NON_VOLATILE); 74 | _bytes = value.getBytes(__ISO_8859_1); 75 | setGetIndex(0); 76 | setPutIndex(_bytes.length); 77 | if (immutable) 78 | { 79 | _access=IMMUTABLE; 80 | _string = value; 81 | } 82 | } 83 | 84 | public byte[] array() 85 | { 86 | return _bytes; 87 | } 88 | 89 | public int capacity() 90 | { 91 | return _bytes.length; 92 | } 93 | 94 | @Override 95 | public void compact() 96 | { 97 | if (isReadOnly()) 98 | throw new IllegalStateException(__READONLY); 99 | int s = markIndex() >= 0 ? markIndex() : getIndex(); 100 | if (s > 0) 101 | { 102 | int length = putIndex() - s; 103 | if (length > 0) 104 | { 105 | System.arraycopy(_bytes, s,_bytes, 0, length); 106 | } 107 | if (markIndex() > 0) setMarkIndex(markIndex() - s); 108 | setGetIndex(getIndex() - s); 109 | setPutIndex(putIndex() - s); 110 | } 111 | } 112 | 113 | @Override 114 | public boolean equals(Object obj) 115 | { 116 | if (obj==this) 117 | return true; 118 | 119 | if (obj == null || !(obj instanceof Buffer)) 120 | return false; 121 | 122 | if (obj instanceof Buffer.CaseInsensitve) 123 | return equalsIgnoreCase((Buffer)obj); 124 | 125 | 126 | Buffer b = (Buffer) obj; 127 | 128 | // reject different lengths 129 | if (b.length() != length()) 130 | return false; 131 | 132 | // reject AbstractBuffer with different hash value 133 | if (_hash != 0 && obj instanceof AbstractBuffer) 134 | { 135 | AbstractBuffer ab = (AbstractBuffer) obj; 136 | if (ab._hash != 0 && _hash != ab._hash) 137 | return false; 138 | } 139 | 140 | // Nothing for it but to do the hard grind. 141 | int get=getIndex(); 142 | int bi=b.putIndex(); 143 | for (int i = putIndex(); i-->get;) 144 | { 145 | byte b1 = _bytes[i]; 146 | byte b2 = b.peek(--bi); 147 | if (b1 != b2) return false; 148 | } 149 | return true; 150 | } 151 | 152 | @Override 153 | public boolean equalsIgnoreCase(Buffer b) 154 | { 155 | if (b==this) 156 | return true; 157 | 158 | // reject different lengths 159 | if (b==null || b.length() != length()) 160 | return false; 161 | 162 | // reject AbstractBuffer with different hash value 163 | if (_hash != 0 && b instanceof AbstractBuffer) 164 | { 165 | AbstractBuffer ab = (AbstractBuffer) b; 166 | if (ab._hash != 0 && _hash != ab._hash) return false; 167 | } 168 | 169 | // Nothing for it but to do the hard grind. 170 | int get=getIndex(); 171 | int bi=b.putIndex(); 172 | byte[] barray=b.array(); 173 | if (barray==null) 174 | { 175 | for (int i = putIndex(); i-->get;) 176 | { 177 | byte b1 = _bytes[i]; 178 | byte b2 = b.peek(--bi); 179 | if (b1 != b2) 180 | { 181 | if ('a' <= b1 && b1 <= 'z') b1 = (byte) (b1 - 'a' + 'A'); 182 | if ('a' <= b2 && b2 <= 'z') b2 = (byte) (b2 - 'a' + 'A'); 183 | if (b1 != b2) return false; 184 | } 185 | } 186 | } 187 | else 188 | { 189 | for (int i = putIndex(); i-->get;) 190 | { 191 | byte b1 = _bytes[i]; 192 | byte b2 = barray[--bi]; 193 | if (b1 != b2) 194 | { 195 | if ('a' <= b1 && b1 <= 'z') b1 = (byte) (b1 - 'a' + 'A'); 196 | if ('a' <= b2 && b2 <= 'z') b2 = (byte) (b2 - 'a' + 'A'); 197 | if (b1 != b2) return false; 198 | } 199 | } 200 | } 201 | return true; 202 | } 203 | 204 | @Override 205 | public byte get() 206 | { 207 | return _bytes[_get++]; 208 | } 209 | 210 | @Override 211 | public int hashCode() 212 | { 213 | if (_hash == 0 || _hashGet!=_get || _hashPut!=_put) 214 | { 215 | int get=getIndex(); 216 | for (int i = putIndex(); i-- >get;) 217 | { 218 | byte b = _bytes[i]; 219 | if ('a' <= b && b <= 'z') 220 | b = (byte) (b - 'a' + 'A'); 221 | _hash = 31 * _hash + b; 222 | } 223 | if (_hash == 0) 224 | _hash = -1; 225 | _hashGet=_get; 226 | _hashPut=_put; 227 | } 228 | return _hash; 229 | } 230 | 231 | public byte peek(int index) 232 | { 233 | return _bytes[index]; 234 | } 235 | 236 | public int peek(int index, byte[] b, int offset, int length) 237 | { 238 | int l = length; 239 | if (index + l > capacity()) 240 | { 241 | l = capacity() - index; 242 | if (l==0) 243 | return -1; 244 | } 245 | 246 | if (l < 0) 247 | return -1; 248 | 249 | System.arraycopy(_bytes, index, b, offset, l); 250 | return l; 251 | } 252 | 253 | public void poke(int index, byte b) 254 | { 255 | _bytes[index] = b; 256 | } 257 | 258 | @Override 259 | public int poke(int index, Buffer src) 260 | { 261 | _hash=0; 262 | 263 | int length=src.length(); 264 | if (index + length > capacity()) 265 | { 266 | length=capacity()-index; 267 | } 268 | 269 | byte[] src_array = src.array(); 270 | if (src_array != null) 271 | System.arraycopy(src_array, src.getIndex(), _bytes, index, length); 272 | else 273 | { 274 | int s=src.getIndex(); 275 | for (int i=0;i capacity()) 288 | { 289 | length=capacity()-index; 290 | } 291 | 292 | System.arraycopy(b, offset, _bytes, index, length); 293 | 294 | return length; 295 | } 296 | 297 | /* ------------------------------------------------------------ */ 298 | @Override 299 | public int space() 300 | { 301 | return _bytes.length - _put; 302 | } 303 | 304 | /* ------------------------------------------------------------ */ 305 | /* ------------------------------------------------------------ */ 306 | /* ------------------------------------------------------------ */ 307 | public static class CaseInsensitive extends ByteArrayBuffer implements Buffer.CaseInsensitve 308 | { 309 | public CaseInsensitive(String s) 310 | { 311 | super(s); 312 | } 313 | 314 | public CaseInsensitive(byte[] b, int o, int l, int rw) 315 | { 316 | super(b,o,l,rw); 317 | } 318 | 319 | @Override 320 | public boolean equals(Object obj) 321 | { 322 | return obj instanceof Buffer && equalsIgnoreCase((Buffer)obj); 323 | } 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/ConnectedEndPoint.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | public interface ConnectedEndPoint extends EndPoint 22 | { 23 | Connection getConnection(); 24 | void setConnection(Connection connection); 25 | } 26 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/Connection.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.io.IOException; 22 | 23 | /* ------------------------------------------------------------ */ 24 | /** Abstract Connection used by Jetty Connectors. 25 | *

26 | * Jetty will call the handle method of a connection when there is work 27 | * to be done on the connection. For blocking connections, this is soon 28 | * as the connection is open and handle will keep being called until the 29 | * connection is closed. For non-blocking connections, handle will only 30 | * be called if there are bytes to be read or the connection becomes writable 31 | * after being write blocked. 32 | * 33 | * @see org.eclipse.jetty.io.nio.SelectorManager 34 | */ 35 | public interface Connection 36 | { 37 | /* ------------------------------------------------------------ */ 38 | /** 39 | * Handle the connection. 40 | * @return The Connection to use for the next handling of the connection. 41 | * This allows protocol upgrades and support for CONNECT. 42 | * @throws IOException if the handling of I/O operations fail 43 | */ 44 | Connection handle() throws IOException; 45 | 46 | /** 47 | *

The semantic of this method is to return true to indicate interest in further reads, 48 | * or false otherwise, but it is misnamed and should be really called isReadInterested().

49 | * 50 | * @return true to indicate interest in further reads, false otherwise 51 | */ 52 | // TODO: rename to isReadInterested() in the next release 53 | boolean isSuspended(); 54 | 55 | /** 56 | * Called after the connection is closed 57 | */ 58 | void onClose(); 59 | 60 | /** 61 | * Called when the connection idle timeout expires 62 | * @param idleForMs how long the connection has been idle 63 | * @see #isIdle() 64 | */ 65 | void onIdleExpired(long idleForMs); 66 | } 67 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/EndPoint.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * 25 | * A transport EndPoint 26 | */ 27 | public interface EndPoint 28 | { 29 | /** 30 | * Shutdown any backing output stream associated with the endpoint 31 | */ 32 | void shutdownOutput() throws IOException; 33 | 34 | boolean isOutputShutdown(); 35 | 36 | /** 37 | * Shutdown any backing input stream associated with the endpoint 38 | */ 39 | void shutdownInput() throws IOException; 40 | 41 | boolean isInputShutdown(); 42 | 43 | /** 44 | * Close any backing stream associated with the endpoint 45 | */ 46 | void close() throws IOException; 47 | 48 | /** 49 | * Fill the buffer from the current putIndex to it's capacity from whatever 50 | * byte source is backing the buffer. The putIndex is increased if bytes filled. 51 | * The buffer may chose to do a compact before filling. 52 | * @return an int value indicating the number of bytes 53 | * filled or -1 if EOF is reached. 54 | * @throws EofException If input is shutdown or the endpoint is closed. 55 | */ 56 | int fill(Buffer buffer) throws IOException; 57 | 58 | /** 59 | * Flush the buffer from the current getIndex to it's putIndex using whatever byte 60 | * sink is backing the buffer. The getIndex is updated with the number of bytes flushed. 61 | * Any mark set is cleared. 62 | * If the entire contents of the buffer are flushed, then an implicit empty() is done. 63 | * 64 | * @param buffer The buffer to flush. This buffers getIndex is updated. 65 | * @return the number of bytes written 66 | * @throws EofException If the endpoint is closed or output is shutdown. 67 | */ 68 | int flush(Buffer buffer) throws IOException; 69 | 70 | /* ------------------------------------------------------------ */ 71 | /** 72 | * @return The local IP address to which this EndPoint is bound, or null 73 | * if this EndPoint does not represent a network connection. 74 | */ 75 | public String getLocalAddr(); 76 | 77 | /* ------------------------------------------------------------ */ 78 | /** 79 | * @return The local port number on which this EndPoint is listening, or 0 80 | * if this EndPoint does not represent a network connection. 81 | */ 82 | public int getLocalPort(); 83 | 84 | /* ------------------------------------------------------------ */ 85 | /** 86 | * @return The remote IP address to which this EndPoint is connected, or null 87 | * if this EndPoint does not represent a network connection. 88 | */ 89 | public String getRemoteAddr(); 90 | 91 | /* ------------------------------------------------------------ */ 92 | /** 93 | * @return The remote port number to which this EndPoint is connected, or 0 94 | * if this EndPoint does not represent a network connection. 95 | */ 96 | public int getRemotePort(); 97 | 98 | /* ------------------------------------------------------------ */ 99 | public boolean isBlocking(); 100 | 101 | /* ------------------------------------------------------------ */ 102 | public boolean blockWritable(long millisecs) throws IOException; 103 | 104 | /* ------------------------------------------------------------ */ 105 | public boolean isOpen(); 106 | 107 | /* ------------------------------------------------------------ */ 108 | /** Flush any buffered output. 109 | * May fail to write all data if endpoint is non-blocking 110 | * @throws EofException If the endpoint is closed or output is shutdown. 111 | */ 112 | public void flush() throws IOException; 113 | 114 | /* ------------------------------------------------------------ */ 115 | /** Get the max idle time in ms. 116 | *

The max idle time is the time the endpoint can be idle before 117 | * extraordinary handling takes place. This loosely corresponds to 118 | * the {@link java.net.Socket#getSoTimeout()} for blocking connections, 119 | * but {@link AsyncEndPoint} implementations must use other mechanisms 120 | * to implement the max idle time. 121 | * @return the max idle time in ms or if ms <= 0 implies an infinite timeout 122 | */ 123 | public int getMaxIdleTime(); 124 | 125 | /* ------------------------------------------------------------ */ 126 | /** Set the max idle time. 127 | * @param timeMs the max idle time in MS. Timeout <= 0 implies an infinite timeout 128 | * @throws IOException if the timeout cannot be set. 129 | */ 130 | public void setMaxIdleTime(int timeMs) throws IOException; 131 | } 132 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/EofException.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | import java.io.EOFException; 22 | 23 | 24 | /* ------------------------------------------------------------ */ 25 | /** A Jetty specialization of EOFException. 26 | *

This is thrown by Jetty to distinguish between EOF received from 27 | * the connection, vs and EOF thrown by some application talking to some other file/socket etc. 28 | * The only difference in handling is that Jetty EOFs are logged less verbosely. 29 | */ 30 | @SuppressWarnings("serial") 31 | public class EofException extends EOFException 32 | { 33 | public EofException() 34 | { 35 | } 36 | 37 | public EofException(String reason) 38 | { 39 | super(reason); 40 | } 41 | 42 | public EofException(Throwable th) 43 | { 44 | if (th!=null) 45 | initCause(th); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/SimpleBuffers.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | /* ------------------------------------------------------------ */ 22 | /** SimpleBuffers. 23 | * Simple implementation of Buffers holder. 24 | * 25 | * 26 | */ 27 | public class SimpleBuffers implements Buffers 28 | { 29 | final Buffer _header; 30 | final Buffer _buffer; 31 | boolean _headerOut; 32 | boolean _bufferOut; 33 | 34 | /* ------------------------------------------------------------ */ 35 | /** 36 | * 37 | */ 38 | public SimpleBuffers(Buffer header, Buffer buffer) 39 | { 40 | _header=header; 41 | _buffer=buffer; 42 | } 43 | 44 | /* ------------------------------------------------------------ */ 45 | public Buffer getBuffer() 46 | { 47 | synchronized(this) 48 | { 49 | if (_buffer!=null && !_bufferOut) 50 | { 51 | _bufferOut=true; 52 | return _buffer; 53 | } 54 | 55 | if (_buffer!=null && _header!=null && _header.capacity()==_buffer.capacity() && !_headerOut) 56 | { 57 | _headerOut=true; 58 | return _header; 59 | } 60 | 61 | if (_buffer!=null) 62 | return new ByteArrayBuffer(_buffer.capacity()); 63 | return new ByteArrayBuffer(4096); 64 | } 65 | } 66 | 67 | /* ------------------------------------------------------------ */ 68 | public Buffer getHeader() 69 | { 70 | synchronized(this) 71 | { 72 | if (_header!=null && !_headerOut) 73 | { 74 | _headerOut=true; 75 | return _header; 76 | } 77 | 78 | if (_buffer!=null && _header!=null && _header.capacity()==_buffer.capacity() && !_bufferOut) 79 | { 80 | _bufferOut=true; 81 | return _buffer; 82 | } 83 | 84 | if (_header!=null) 85 | return new ByteArrayBuffer(_header.capacity()); 86 | return new ByteArrayBuffer(4096); 87 | } 88 | } 89 | 90 | /* ------------------------------------------------------------ */ 91 | public void returnBuffer(Buffer buffer) 92 | { 93 | synchronized(this) 94 | { 95 | buffer.clear(); 96 | if (buffer==_header) 97 | _headerOut=false; 98 | if (buffer==_buffer) 99 | _bufferOut=false; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/ThreadLocalBuffers.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | 22 | 23 | /* ------------------------------------------------------------ */ 24 | /** Abstract Buffer pool. 25 | * simple unbounded pool of buffers for header, request and response sizes. 26 | * 27 | */ 28 | public class ThreadLocalBuffers extends AbstractBuffers 29 | { 30 | /* ------------------------------------------------------------ */ 31 | private final ThreadLocal _buffers=new ThreadLocal() 32 | { 33 | @Override 34 | protected ThreadBuffers initialValue() 35 | { 36 | return new ThreadBuffers(); 37 | } 38 | }; 39 | 40 | /* ------------------------------------------------------------ */ 41 | public ThreadLocalBuffers(Buffers.Type headerType, int headerSize, Buffers.Type bufferType, int bufferSize, Buffers.Type otherType) 42 | { 43 | super(headerType,headerSize,bufferType,bufferSize,otherType); 44 | } 45 | 46 | /* ------------------------------------------------------------ */ 47 | public Buffer getBuffer() 48 | { 49 | ThreadBuffers buffers = _buffers.get(); 50 | if (buffers._buffer!=null) 51 | { 52 | Buffer b=buffers._buffer; 53 | buffers._buffer=null; 54 | return b; 55 | } 56 | 57 | if (buffers._other!=null && isBuffer(buffers._other)) 58 | { 59 | Buffer b=buffers._other; 60 | buffers._other=null; 61 | return b; 62 | } 63 | 64 | return newBuffer(); 65 | } 66 | 67 | /* ------------------------------------------------------------ */ 68 | public Buffer getHeader() 69 | { 70 | ThreadBuffers buffers = _buffers.get(); 71 | if (buffers._header!=null) 72 | { 73 | Buffer b=buffers._header; 74 | buffers._header=null; 75 | return b; 76 | } 77 | 78 | if (buffers._other!=null && isHeader(buffers._other)) 79 | { 80 | Buffer b=buffers._other; 81 | buffers._other=null; 82 | return b; 83 | } 84 | 85 | return newHeader(); 86 | } 87 | 88 | /* ------------------------------------------------------------ */ 89 | public void returnBuffer(Buffer buffer) 90 | { 91 | buffer.clear(); 92 | if (buffer.isVolatile() || buffer.isImmutable()) 93 | return; 94 | 95 | ThreadBuffers buffers = _buffers.get(); 96 | 97 | if (buffers._header==null && isHeader(buffer)) 98 | buffers._header=buffer; 99 | else if (buffers._buffer==null && isBuffer(buffer)) 100 | buffers._buffer=buffer; 101 | else 102 | buffers._other=buffer; 103 | } 104 | 105 | /* ------------------------------------------------------------ */ 106 | @Override 107 | public String toString() 108 | { 109 | return "{{"+getHeaderSize()+","+getBufferSize()+"}}"; 110 | } 111 | 112 | /* ------------------------------------------------------------ */ 113 | /* ------------------------------------------------------------ */ 114 | protected static class ThreadBuffers 115 | { 116 | Buffer _buffer; 117 | Buffer _header; 118 | Buffer _other; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/View.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io; 20 | 21 | /** 22 | * A View on another buffer. Allows operations that do not change the _content or 23 | * indexes of the backing buffer. 24 | * 25 | * 26 | * 27 | */ 28 | public class View extends AbstractBuffer 29 | { 30 | Buffer _buffer; 31 | 32 | /** 33 | * @param buffer The Buffer on which we are presenting a View. 34 | * @param mark The initial value of the {@link Buffer#markIndex mark index} 35 | * @param get The initial value of the {@link Buffer#getIndex get index} 36 | * @param put The initial value of the {@link Buffer#putIndex put index} 37 | * @param access The access level - one of the constants from {@link Buffer}. 38 | */ 39 | public View(Buffer buffer, int mark, int get, int put,int access) 40 | { 41 | super(READWRITE,!buffer.isImmutable()); 42 | _buffer=buffer.buffer(); 43 | setPutIndex(put); 44 | setGetIndex(get); 45 | setMarkIndex(mark); 46 | _access=access; 47 | } 48 | 49 | public View(Buffer buffer) 50 | { 51 | super(READWRITE,!buffer.isImmutable()); 52 | _buffer=buffer.buffer(); 53 | setPutIndex(buffer.putIndex()); 54 | setGetIndex(buffer.getIndex()); 55 | setMarkIndex(buffer.markIndex()); 56 | _access=buffer.isReadOnly()?READONLY:READWRITE; 57 | } 58 | 59 | public View() 60 | { 61 | super(READWRITE,true); 62 | } 63 | 64 | /** 65 | * Update view to buffer 66 | */ 67 | public void update(Buffer buffer) 68 | { 69 | _access=READWRITE; 70 | _buffer=buffer.buffer(); 71 | setGetIndex(0); 72 | setPutIndex(buffer.putIndex()); 73 | setGetIndex(buffer.getIndex()); 74 | setMarkIndex(buffer.markIndex()); 75 | _access=buffer.isReadOnly()?READONLY:READWRITE; 76 | } 77 | 78 | public void update(int get, int put) 79 | { 80 | int a=_access; 81 | _access=READWRITE; 82 | setGetIndex(0); 83 | setPutIndex(put); 84 | setGetIndex(get); 85 | setMarkIndex(-1); 86 | _access=a; 87 | } 88 | 89 | /** 90 | * @return The {@link Buffer#array()} from the underlying buffer. 91 | */ 92 | public byte[] array() 93 | { 94 | return _buffer.array(); 95 | } 96 | 97 | /** 98 | * @return The {@link Buffer#buffer()} from the underlying buffer. 99 | */ 100 | @Override 101 | public Buffer buffer() 102 | { 103 | return _buffer.buffer(); 104 | } 105 | 106 | /** 107 | * @return The {@link Buffer#capacity} of the underlying buffer. 108 | */ 109 | public int capacity() 110 | { 111 | return _buffer.capacity(); 112 | } 113 | 114 | /** 115 | * 116 | */ 117 | @Override 118 | public void clear() 119 | { 120 | setMarkIndex(-1); 121 | setGetIndex(0); 122 | setPutIndex(_buffer.getIndex()); 123 | setGetIndex(_buffer.getIndex()); 124 | } 125 | 126 | /** 127 | * 128 | */ 129 | @Override 130 | public void compact() 131 | { 132 | // TODO 133 | } 134 | 135 | /* 136 | * (non-Javadoc) 137 | * 138 | * @see java.lang.Object#equals(java.lang.Object) 139 | */ 140 | @Override 141 | public boolean equals(Object obj) 142 | { 143 | return this==obj ||((obj instanceof Buffer)&& obj.equals(this)) || super.equals(obj); 144 | } 145 | 146 | /** 147 | * @return Whether the underlying buffer is {@link Buffer#isReadOnly read only} 148 | */ 149 | @Override 150 | public boolean isReadOnly() 151 | { 152 | return _buffer.isReadOnly(); 153 | } 154 | 155 | /** 156 | * @return Whether the underlying buffer is {@link Buffer#isVolatile volatile} 157 | */ 158 | @Override 159 | public boolean isVolatile() 160 | { 161 | return true; 162 | } 163 | 164 | /** 165 | * @return The result of calling {@link Buffer#peek(int)} on the underlying buffer 166 | */ 167 | public byte peek(int index) 168 | { 169 | return _buffer.peek(index); 170 | } 171 | 172 | /** 173 | * @return The result of calling {@link Buffer#peek(int, byte[], int, int)} on the underlying buffer 174 | */ 175 | public int peek(int index, byte[] b, int offset, int length) 176 | { 177 | return _buffer.peek(index,b,offset,length); 178 | } 179 | 180 | /** 181 | * @param index 182 | * @param src 183 | */ 184 | @Override 185 | public int poke(int index, Buffer src) 186 | { 187 | return _buffer.poke(index,src); 188 | } 189 | 190 | /** 191 | * @param index 192 | * @param b 193 | */ 194 | public void poke(int index, byte b) 195 | { 196 | _buffer.poke(index,b); 197 | } 198 | 199 | /** 200 | * @param index 201 | * @param b 202 | * @param offset 203 | * @param length 204 | */ 205 | @Override 206 | public int poke(int index, byte[] b, int offset, int length) 207 | { 208 | return _buffer.poke(index,b,offset,length); 209 | } 210 | 211 | @Override 212 | public String toString() 213 | { 214 | if (_buffer==null) 215 | return "INVALID"; 216 | return super.toString(); 217 | } 218 | 219 | public static class CaseInsensitive extends View implements Buffer.CaseInsensitve 220 | { 221 | public CaseInsensitive() 222 | { 223 | super(); 224 | } 225 | 226 | @Override 227 | public boolean equals(Object obj) 228 | { 229 | return this==obj ||((obj instanceof Buffer)&&((Buffer)obj).equalsIgnoreCase(this)) || super.equals(obj); 230 | } 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/nio/AsyncConnection.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io.nio; 20 | 21 | import java.io.IOException; 22 | 23 | import org.eclipse.jetty.io.Connection; 24 | 25 | public interface AsyncConnection extends Connection 26 | { 27 | void onInputShutdown() throws IOException; 28 | } 29 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/nio/DirectNIOBuffer.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io.nio; 20 | 21 | import java.io.File; 22 | import java.io.FileInputStream; 23 | import java.io.IOException; 24 | import java.nio.ByteBuffer; 25 | import java.nio.channels.FileChannel; 26 | 27 | import org.eclipse.jetty.io.AbstractBuffer; 28 | import org.eclipse.jetty.io.Buffer; 29 | import org.eclipse.jetty.util.IO; 30 | import org.eclipse.jetty.util.log.Log; 31 | import org.eclipse.jetty.util.log.Logger; 32 | 33 | /* ------------------------------------------------------------------------------- */ 34 | /** 35 | * 36 | * 37 | */ 38 | public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer 39 | { 40 | private static final Logger LOG = Log.getLogger(DirectNIOBuffer.class); 41 | 42 | protected final ByteBuffer _buf; 43 | 44 | public DirectNIOBuffer(int size) 45 | { 46 | super(READWRITE,NON_VOLATILE); 47 | _buf = ByteBuffer.allocateDirect(size); 48 | _buf.position(0); 49 | _buf.limit(_buf.capacity()); 50 | } 51 | 52 | public DirectNIOBuffer(ByteBuffer buffer,boolean immutable) 53 | { 54 | super(immutable?IMMUTABLE:READWRITE,NON_VOLATILE); 55 | if (!buffer.isDirect()) 56 | throw new IllegalArgumentException(); 57 | _buf = buffer; 58 | setGetIndex(buffer.position()); 59 | setPutIndex(buffer.limit()); 60 | } 61 | 62 | /** 63 | * @param file 64 | */ 65 | public DirectNIOBuffer(File file) throws IOException 66 | { 67 | super(READONLY,NON_VOLATILE); 68 | FileInputStream fis = null; 69 | FileChannel fc = null; 70 | try 71 | { 72 | fis = new FileInputStream(file); 73 | fc = fis.getChannel(); 74 | _buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); 75 | setGetIndex(0); 76 | setPutIndex((int)file.length()); 77 | _access=IMMUTABLE; 78 | } 79 | finally 80 | { 81 | if (fc != null) try {fc.close();} catch (IOException e){LOG.ignore(e);} 82 | IO.close(fis); 83 | } 84 | } 85 | 86 | /* ------------------------------------------------------------ */ 87 | public boolean isDirect() 88 | { 89 | return true; 90 | } 91 | 92 | /* ------------------------------------------------------------ */ 93 | public byte[] array() 94 | { 95 | return null; 96 | } 97 | 98 | /* ------------------------------------------------------------ */ 99 | public int capacity() 100 | { 101 | return _buf.capacity(); 102 | } 103 | 104 | /* ------------------------------------------------------------ */ 105 | public byte peek(int position) 106 | { 107 | return _buf.get(position); 108 | } 109 | 110 | public int peek(int index, byte[] b, int offset, int length) 111 | { 112 | int l = length; 113 | if (index+l > capacity()) 114 | { 115 | l=capacity()-index; 116 | if (l==0) 117 | return -1; 118 | } 119 | 120 | if (l < 0) 121 | return -1; 122 | try 123 | { 124 | _buf.position(index); 125 | _buf.get(b,offset,l); 126 | } 127 | finally 128 | { 129 | _buf.position(0); 130 | } 131 | 132 | return l; 133 | } 134 | 135 | public void poke(int index, byte b) 136 | { 137 | if (isReadOnly()) throw new IllegalStateException(__READONLY); 138 | if (index < 0) throw new IllegalArgumentException("index<0: " + index + "<0"); 139 | if (index > capacity()) 140 | throw new IllegalArgumentException("index>capacity(): " + index + ">" + capacity()); 141 | _buf.put(index,b); 142 | } 143 | 144 | @Override 145 | public int poke(int index, Buffer src) 146 | { 147 | if (isReadOnly()) throw new IllegalStateException(__READONLY); 148 | 149 | byte[] array=src.array(); 150 | if (array!=null) 151 | { 152 | return poke(index,array,src.getIndex(),src.length()); 153 | } 154 | else 155 | { 156 | Buffer src_buf=src.buffer(); 157 | if (src_buf instanceof DirectNIOBuffer) 158 | { 159 | ByteBuffer src_bytebuf = ((DirectNIOBuffer)src_buf)._buf; 160 | if (src_bytebuf==_buf) 161 | src_bytebuf=_buf.duplicate(); 162 | try 163 | { 164 | _buf.position(index); 165 | int space = _buf.remaining(); 166 | 167 | int length=src.length(); 168 | if (length>space) 169 | length=space; 170 | 171 | src_bytebuf.position(src.getIndex()); 172 | src_bytebuf.limit(src.getIndex()+length); 173 | 174 | _buf.put(src_bytebuf); 175 | return length; 176 | } 177 | finally 178 | { 179 | _buf.position(0); 180 | src_bytebuf.limit(src_bytebuf.capacity()); 181 | src_bytebuf.position(0); 182 | } 183 | } 184 | else 185 | return super.poke(index,src); 186 | } 187 | } 188 | 189 | @Override 190 | public int poke(int index, byte[] b, int offset, int length) 191 | { 192 | if (isReadOnly()) throw new IllegalStateException(__READONLY); 193 | 194 | if (index < 0) throw new IllegalArgumentException("index<0: " + index + "<0"); 195 | 196 | if (index + length > capacity()) 197 | { 198 | length=capacity()-index; 199 | if (length<0) 200 | throw new IllegalArgumentException("index>capacity(): " + index + ">" + capacity()); 201 | } 202 | 203 | try 204 | { 205 | _buf.position(index); 206 | 207 | int space=_buf.remaining(); 208 | 209 | if (length>space) 210 | length=space; 211 | if (length>0) 212 | _buf.put(b,offset,length); 213 | return length; 214 | } 215 | finally 216 | { 217 | _buf.position(0); 218 | } 219 | } 220 | 221 | /* ------------------------------------------------------------ */ 222 | public ByteBuffer getByteBuffer() 223 | { 224 | return _buf; 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/nio/IndirectNIOBuffer.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io.nio; 20 | 21 | import java.nio.ByteBuffer; 22 | 23 | import org.eclipse.jetty.io.ByteArrayBuffer; 24 | 25 | public class IndirectNIOBuffer extends ByteArrayBuffer implements NIOBuffer 26 | { 27 | protected final ByteBuffer _buf; 28 | 29 | /* ------------------------------------------------------------ */ 30 | public IndirectNIOBuffer(int size) 31 | { 32 | super(size,READWRITE,NON_VOLATILE); 33 | _buf = ByteBuffer.wrap(_bytes); 34 | _buf.position(0); 35 | _buf.limit(_buf.capacity()); 36 | } 37 | 38 | /* ------------------------------------------------------------ */ 39 | public ByteBuffer getByteBuffer() 40 | { 41 | return _buf; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/io/nio/NIOBuffer.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.io.nio; 20 | 21 | import java.nio.ByteBuffer; 22 | 23 | import org.eclipse.jetty.io.Buffer; 24 | 25 | /* ------------------------------------------------------------------------------- */ 26 | /** 27 | * 28 | * 29 | */ 30 | public interface NIOBuffer extends Buffer 31 | { 32 | /* ------------------------------------------------------------ */ 33 | public ByteBuffer getByteBuffer(); 34 | } 35 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/ConcurrentHashSet.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util; 20 | 21 | import java.util.AbstractSet; 22 | import java.util.Collection; 23 | import java.util.Iterator; 24 | import java.util.Map; 25 | import java.util.Set; 26 | import java.util.concurrent.ConcurrentHashMap; 27 | 28 | public class ConcurrentHashSet extends AbstractSet implements Set 29 | { 30 | private final Map _map = new ConcurrentHashMap(); 31 | private transient Set _keys = _map.keySet(); 32 | 33 | public ConcurrentHashSet() 34 | { 35 | } 36 | 37 | @Override 38 | public boolean add(E e) 39 | { 40 | return _map.put(e,Boolean.TRUE) == null; 41 | } 42 | 43 | @Override 44 | public void clear() 45 | { 46 | _map.clear(); 47 | } 48 | 49 | @Override 50 | public boolean contains(Object o) 51 | { 52 | return _map.containsKey(o); 53 | } 54 | 55 | @Override 56 | public boolean containsAll(Collection c) 57 | { 58 | return _keys.containsAll(c); 59 | } 60 | 61 | @Override 62 | public boolean equals(Object o) 63 | { 64 | return o == this || _keys.equals(o); 65 | } 66 | 67 | @Override 68 | public int hashCode() 69 | { 70 | return _keys.hashCode(); 71 | } 72 | 73 | @Override 74 | public boolean isEmpty() 75 | { 76 | return _map.isEmpty(); 77 | } 78 | 79 | @Override 80 | public Iterator iterator() 81 | { 82 | return _keys.iterator(); 83 | } 84 | 85 | @Override 86 | public boolean remove(Object o) 87 | { 88 | return _map.remove(o) != null; 89 | } 90 | 91 | @Override 92 | public boolean removeAll(Collection c) 93 | { 94 | return _keys.removeAll(c); 95 | } 96 | 97 | @Override 98 | public boolean retainAll(Collection c) 99 | { 100 | return _keys.retainAll(c); 101 | } 102 | 103 | @Override 104 | public int size() 105 | { 106 | return _map.size(); 107 | } 108 | 109 | @Override 110 | public Object[] toArray() 111 | { 112 | return _keys.toArray(); 113 | } 114 | 115 | @Override 116 | public T[] toArray(T[] a) 117 | { 118 | return _keys.toArray(a); 119 | } 120 | 121 | @Override 122 | public String toString() 123 | { 124 | return _keys.toString(); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/IO.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util; 20 | import java.io.Closeable; 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.io.OutputStream; 24 | 25 | import org.eclipse.jetty.util.log.Log; 26 | import org.eclipse.jetty.util.log.Logger; 27 | 28 | /* ======================================================================== */ 29 | /** IO Utilities. 30 | * Provides stream handling utilities in 31 | * singleton Threadpool implementation accessed by static members. 32 | */ 33 | public class IO 34 | { 35 | private static final Logger LOG = Log.getLogger(IO.class); 36 | 37 | /* ------------------------------------------------------------------- */ 38 | public static int bufferSize = 64*1024; 39 | 40 | /* ------------------------------------------------------------------- */ 41 | /** Copy Stream in to Stream out until EOF or exception. 42 | */ 43 | public static void copy(InputStream in, OutputStream out) 44 | throws IOException 45 | { 46 | copy(in,out,-1); 47 | } 48 | 49 | /* ------------------------------------------------------------------- */ 50 | /** Copy Stream in to Stream for byteCount bytes or until EOF or exception. 51 | */ 52 | public static void copy(InputStream in, 53 | OutputStream out, 54 | long byteCount) 55 | throws IOException 56 | { 57 | byte buffer[] = new byte[bufferSize]; 58 | int len=bufferSize; 59 | 60 | if (byteCount>=0) 61 | { 62 | while (byteCount>0) 63 | { 64 | int max = byteCount=0) 59 | { 60 | StringBuffer b=new StringBuffer(s.length()+8); 61 | quote(b,s); 62 | return b.toString(); 63 | } 64 | } 65 | 66 | return s; 67 | } 68 | 69 | private static final char[] escapes = new char[32]; 70 | static 71 | { 72 | Arrays.fill(escapes, (char)0xFFFF); 73 | escapes['\b'] = 'b'; 74 | escapes['\t'] = 't'; 75 | escapes['\n'] = 'n'; 76 | escapes['\f'] = 'f'; 77 | escapes['\r'] = 'r'; 78 | } 79 | 80 | /* ------------------------------------------------------------ */ 81 | /** Quote a string into an Appendable. 82 | * The characters ", \, \n, \r, \t, \f and \b are escaped 83 | * @param buffer The Appendable 84 | * @param input The String to quote. 85 | */ 86 | public static void quote(Appendable buffer, String input) 87 | { 88 | try 89 | { 90 | buffer.append('"'); 91 | for (int i = 0; i < input.length(); ++i) 92 | { 93 | char c = input.charAt(i); 94 | if (c >= 32) 95 | { 96 | if (c == '"' || c == '\\') 97 | buffer.append('\\'); 98 | buffer.append(c); 99 | } 100 | else 101 | { 102 | char escape = escapes[c]; 103 | if (escape == 0xFFFF) 104 | { 105 | // Unicode escape 106 | buffer.append('\\').append('u').append('0').append('0'); 107 | if (c < 0x10) 108 | buffer.append('0'); 109 | buffer.append(Integer.toString(c, 16)); 110 | } 111 | else 112 | { 113 | buffer.append('\\').append(escape); 114 | } 115 | } 116 | } 117 | buffer.append('"'); 118 | } 119 | catch (IOException x) 120 | { 121 | throw new RuntimeException(x); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/TypeUtil.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util; 20 | 21 | import java.io.IOException; 22 | 23 | /* ------------------------------------------------------------ */ 24 | /** 25 | * TYPE Utilities. 26 | * Provides various static utiltiy methods for manipulating types and their 27 | * string representations. 28 | * 29 | * @since Jetty 4.1 30 | */ 31 | public class TypeUtil 32 | { 33 | /* ------------------------------------------------------------ */ 34 | public static void toHex(byte b,Appendable buf) 35 | { 36 | try 37 | { 38 | int d=0xf&((0xF0&b)>>4); 39 | buf.append((char)((d>9?('A'-10):'0')+d)); 40 | d=0xf&b; 41 | buf.append((char)((d>9?('A'-10):'0')+d)); 42 | } 43 | catch(IOException e) 44 | { 45 | throw new RuntimeException(e); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/component/AbstractLifeCycle.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.component; 20 | 21 | import java.util.concurrent.CopyOnWriteArrayList; 22 | 23 | import org.eclipse.jetty.util.log.Log; 24 | import org.eclipse.jetty.util.log.Logger; 25 | 26 | /** 27 | * Basic implementation of the life cycle interface for components. 28 | * 29 | * 30 | */ 31 | public abstract class AbstractLifeCycle implements LifeCycle 32 | { 33 | private static final Logger LOG = Log.getLogger(AbstractLifeCycle.class); 34 | public static final String STOPPED="STOPPED"; 35 | public static final String FAILED="FAILED"; 36 | public static final String STARTING="STARTING"; 37 | public static final String STARTED="STARTED"; 38 | public static final String STOPPING="STOPPING"; 39 | public static final String RUNNING="RUNNING"; 40 | 41 | private final Object _lock = new Object(); 42 | private final int __FAILED = -1, __STOPPED = 0, __STARTING = 1, __STARTED = 2, __STOPPING = 3; 43 | private volatile int _state = __STOPPED; 44 | 45 | protected final CopyOnWriteArrayList _listeners=new CopyOnWriteArrayList(); 46 | 47 | protected void doStart() throws Exception 48 | { 49 | } 50 | 51 | protected void doStop() throws Exception 52 | { 53 | } 54 | 55 | public final void start() throws Exception 56 | { 57 | synchronized (_lock) 58 | { 59 | try 60 | { 61 | if (_state == __STARTED || _state == __STARTING) 62 | return; 63 | setStarting(); 64 | doStart(); 65 | setStarted(); 66 | } 67 | catch (Exception e) 68 | { 69 | setFailed(e); 70 | throw e; 71 | } 72 | catch (Error e) 73 | { 74 | setFailed(e); 75 | throw e; 76 | } 77 | } 78 | } 79 | 80 | public final void stop() throws Exception 81 | { 82 | synchronized (_lock) 83 | { 84 | try 85 | { 86 | if (_state == __STOPPING || _state == __STOPPED) 87 | return; 88 | setStopping(); 89 | doStop(); 90 | setStopped(); 91 | } 92 | catch (Exception e) 93 | { 94 | setFailed(e); 95 | throw e; 96 | } 97 | catch (Error e) 98 | { 99 | setFailed(e); 100 | throw e; 101 | } 102 | } 103 | } 104 | 105 | public boolean isRunning() 106 | { 107 | final int state = _state; 108 | 109 | return state == __STARTED || state == __STARTING; 110 | } 111 | 112 | public boolean isStarted() 113 | { 114 | return _state == __STARTED; 115 | } 116 | 117 | public boolean isStarting() 118 | { 119 | return _state == __STARTING; 120 | } 121 | 122 | public boolean isStopping() 123 | { 124 | return _state == __STOPPING; 125 | } 126 | 127 | public boolean isStopped() 128 | { 129 | return _state == __STOPPED; 130 | } 131 | 132 | public String getState() 133 | { 134 | switch(_state) 135 | { 136 | case __FAILED: return FAILED; 137 | case __STARTING: return STARTING; 138 | case __STARTED: return STARTED; 139 | case __STOPPING: return STOPPING; 140 | case __STOPPED: return STOPPED; 141 | } 142 | return null; 143 | } 144 | 145 | public static String getState(LifeCycle lc) 146 | { 147 | if (lc.isStarting()) return STARTING; 148 | if (lc.isStarted()) return STARTED; 149 | if (lc.isStopping()) return STOPPING; 150 | if (lc.isStopped()) return STOPPED; 151 | return FAILED; 152 | } 153 | 154 | private void setStarted() 155 | { 156 | _state = __STARTED; 157 | LOG.debug(STARTED+" {}",this); 158 | for (Listener listener : _listeners) 159 | listener.lifeCycleStarted(this); 160 | } 161 | 162 | private void setStarting() 163 | { 164 | LOG.debug("starting {}",this); 165 | _state = __STARTING; 166 | for (Listener listener : _listeners) 167 | listener.lifeCycleStarting(this); 168 | } 169 | 170 | private void setStopping() 171 | { 172 | LOG.debug("stopping {}",this); 173 | _state = __STOPPING; 174 | for (Listener listener : _listeners) 175 | listener.lifeCycleStopping(this); 176 | } 177 | 178 | private void setStopped() 179 | { 180 | _state = __STOPPED; 181 | LOG.debug("{} {}",STOPPED,this); 182 | for (Listener listener : _listeners) 183 | listener.lifeCycleStopped(this); 184 | } 185 | 186 | private void setFailed(Throwable th) 187 | { 188 | _state = __FAILED; 189 | LOG.warn(FAILED+" " + this+": "+th,th); 190 | for (Listener listener : _listeners) 191 | listener.lifeCycleFailure(this,th); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/component/AggregateLifeCycle.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.component; 20 | 21 | import java.io.IOException; 22 | import java.util.ArrayList; 23 | import java.util.Collection; 24 | import java.util.Collections; 25 | import java.util.List; 26 | import java.util.concurrent.CopyOnWriteArrayList; 27 | 28 | /** 29 | * An AggregateLifeCycle is an {@link LifeCycle} implementation for a collection of contained beans. 30 | *

31 | * Beans can be added the AggregateLifeCycle either as managed beans or as unmanaged beans. A managed bean is started, stopped and destroyed with the aggregate. 32 | * An unmanaged bean is associated with the aggregate for the purposes of {@link #dump()}, but it's lifecycle must be managed externally. 33 | *

34 | * When a bean is added, if it is a {@link LifeCycle} and it is already started, then it is assumed to be an unmanaged bean. 35 | * Otherwise the methods {@link #addBean(Object, boolean)}, {@link #manage(Object)} and {@link #unmanage(Object)} can be used to 36 | * explicitly control the life cycle relationship. 37 | *

38 | * If adding a bean that is shared between multiple {@link AggregateLifeCycle} instances, then it should be started before being added, so it is unmanaged, or 39 | * the API must be used to explicitly set it as unmanaged. 40 | *

41 | */ 42 | public class AggregateLifeCycle extends AbstractLifeCycle implements Dumpable 43 | { 44 | private final List _beans=new CopyOnWriteArrayList(); 45 | private boolean _started=false; 46 | 47 | private class Bean 48 | { 49 | Bean(Object b) 50 | { 51 | _bean=b; 52 | } 53 | final Object _bean; 54 | volatile boolean _managed=true; 55 | 56 | public String toString() 57 | { 58 | return "{"+_bean+","+_managed+"}"; 59 | } 60 | } 61 | 62 | /* ------------------------------------------------------------ */ 63 | /** 64 | * Start the managed lifecycle beans in the order they were added. 65 | * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() 66 | */ 67 | @Override 68 | protected void doStart() throws Exception 69 | { 70 | for (Bean b:_beans) 71 | { 72 | if (b._managed && b._bean instanceof LifeCycle) 73 | { 74 | LifeCycle l=(LifeCycle)b._bean; 75 | if (!l.isRunning()) 76 | l.start(); 77 | } 78 | } 79 | // indicate that we are started, so that addBean will start other beans added. 80 | _started=true; 81 | super.doStart(); 82 | } 83 | 84 | /* ------------------------------------------------------------ */ 85 | /** 86 | * Stop the joined lifecycle beans in the reverse order they were added. 87 | * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() 88 | */ 89 | @Override 90 | protected void doStop() throws Exception 91 | { 92 | _started=false; 93 | super.doStop(); 94 | List reverse = new ArrayList(_beans); 95 | Collections.reverse(reverse); 96 | for (Bean b:reverse) 97 | { 98 | if (b._managed && b._bean instanceof LifeCycle) 99 | { 100 | LifeCycle l=(LifeCycle)b._bean; 101 | if (l.isRunning()) 102 | l.stop(); 103 | } 104 | } 105 | } 106 | 107 | /* ------------------------------------------------------------ */ 108 | /** Is the bean contained in the aggregate. 109 | * @param bean 110 | * @return True if the aggregate contains the bean 111 | */ 112 | public boolean contains(Object bean) 113 | { 114 | for (Bean b:_beans) 115 | if (b._bean==bean) 116 | return true; 117 | return false; 118 | } 119 | 120 | /* ------------------------------------------------------------ */ 121 | /** 122 | * Add an associated bean. 123 | * If the bean is a {@link LifeCycle}, then it will be managed if it is not 124 | * already started and umanaged if it is already started. The {@link #addBean(Object, boolean)} 125 | * method should be used if this is not correct, or the {@link #manage(Object)} and {@link #unmanage(Object)} 126 | * methods may be used after an add to change the status. 127 | * @param o the bean object to add 128 | * @return true if the bean was added or false if it has already been added. 129 | */ 130 | public boolean addBean(Object o) 131 | { 132 | // beans are joined unless they are started lifecycles 133 | return addBean(o,!((o instanceof LifeCycle)&&((LifeCycle)o).isStarted())); 134 | } 135 | 136 | /* ------------------------------------------------------------ */ 137 | /** Add an associated lifecycle. 138 | * @param o The lifecycle to add 139 | * @param managed True if the LifeCycle is to be joined, otherwise it will be disjoint. 140 | * @return true if bean was added, false if already present. 141 | */ 142 | public boolean addBean(Object o, boolean managed) 143 | { 144 | if (contains(o)) 145 | return false; 146 | 147 | Bean b = new Bean(o); 148 | b._managed=managed; 149 | _beans.add(b); 150 | 151 | if (o instanceof LifeCycle) 152 | { 153 | LifeCycle l=(LifeCycle)o; 154 | 155 | // Start the bean if we are started 156 | if (managed && _started) 157 | { 158 | try 159 | { 160 | l.start(); 161 | } 162 | catch(Exception e) 163 | { 164 | throw new RuntimeException (e); 165 | } 166 | } 167 | } 168 | return true; 169 | } 170 | 171 | /* ------------------------------------------------------------ */ 172 | protected void dumpThis(Appendable out) throws IOException 173 | { 174 | out.append(String.valueOf(this)).append(" - ").append(getState()).append("\n"); 175 | } 176 | 177 | /* ------------------------------------------------------------ */ 178 | public static void dumpObject(Appendable out,Object o) throws IOException 179 | { 180 | try 181 | { 182 | if (o instanceof LifeCycle) 183 | out.append(String.valueOf(o)).append(" - ").append((AbstractLifeCycle.getState((LifeCycle)o))).append("\n"); 184 | else 185 | out.append(String.valueOf(o)).append("\n"); 186 | } 187 | catch(Throwable th) 188 | { 189 | out.append(" => ").append(th.toString()).append('\n'); 190 | } 191 | } 192 | 193 | /* ------------------------------------------------------------ */ 194 | public void dump(Appendable out,String indent) throws IOException 195 | { 196 | dumpThis(out); 197 | int size=_beans.size(); 198 | if (size==0) 199 | return; 200 | int i=0; 201 | for (Bean b : _beans) 202 | { 203 | i++; 204 | 205 | out.append(indent).append(" +- "); 206 | if (b._managed) 207 | { 208 | if (b._bean instanceof Dumpable) 209 | ((Dumpable)b._bean).dump(out,indent+(i==size?" ":" | ")); 210 | else 211 | dumpObject(out,b._bean); 212 | } 213 | else 214 | dumpObject(out,b._bean); 215 | } 216 | 217 | if (i!=size) 218 | out.append(indent).append(" |\n"); 219 | } 220 | 221 | /* ------------------------------------------------------------ */ 222 | public static void dump(Appendable out,String indent,Collection... collections) throws IOException 223 | { 224 | if (collections.length==0) 225 | return; 226 | int size=0; 227 | for (Collection c : collections) 228 | size+=c.size(); 229 | if (size==0) 230 | return; 231 | 232 | int i=0; 233 | for (Collection c : collections) 234 | { 235 | for (Object o : c) 236 | { 237 | i++; 238 | out.append(indent).append(" +- "); 239 | 240 | if (o instanceof Dumpable) 241 | ((Dumpable)o).dump(out,indent+(i==size?" ":" | ")); 242 | else 243 | dumpObject(out,o); 244 | } 245 | 246 | if (i!=size) 247 | out.append(indent).append(" |\n"); 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/component/Dumpable.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.component; 20 | 21 | import java.io.IOException; 22 | 23 | public interface Dumpable 24 | { 25 | void dump(Appendable out,String indent) throws IOException; 26 | } 27 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/component/LifeCycle.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.component; 20 | 21 | import java.util.EventListener; 22 | 23 | /* ------------------------------------------------------------ */ 24 | /** 25 | * The lifecycle interface for generic components. 26 | *
27 | * Classes implementing this interface have a defined life cycle 28 | * defined by the methods of this interface. 29 | * 30 | * 31 | */ 32 | public interface LifeCycle 33 | { 34 | /* ------------------------------------------------------------ */ 35 | /** 36 | * Starts the component. 37 | * @throws Exception If the component fails to start 38 | * @see #isStarted() 39 | * @see #stop() 40 | * @see #isFailed() 41 | */ 42 | public void start() 43 | throws Exception; 44 | 45 | /* ------------------------------------------------------------ */ 46 | /** 47 | * Stops the component. 48 | * The component may wait for current activities to complete 49 | * normally, but it can be interrupted. 50 | * @exception Exception If the component fails to stop 51 | * @see #isStopped() 52 | * @see #start() 53 | * @see #isFailed() 54 | */ 55 | public void stop() 56 | throws Exception; 57 | 58 | /* ------------------------------------------------------------ */ 59 | /** 60 | * @return true if the component is starting or has been started. 61 | */ 62 | public boolean isRunning(); 63 | 64 | /* ------------------------------------------------------------ */ 65 | /** 66 | * @return true if the component has been started. 67 | * @see #start() 68 | * @see #isStarting() 69 | */ 70 | public boolean isStarted(); 71 | 72 | /* ------------------------------------------------------------ */ 73 | /** 74 | * @return true if the component is starting. 75 | * @see #isStarted() 76 | */ 77 | public boolean isStarting(); 78 | 79 | /* ------------------------------------------------------------ */ 80 | /** 81 | * @return true if the component is stopping. 82 | * @see #isStopped() 83 | */ 84 | public boolean isStopping(); 85 | 86 | /* ------------------------------------------------------------ */ 87 | /** 88 | * @return true if the component has been stopped. 89 | * @see #stop() 90 | * @see #isStopping() 91 | */ 92 | public boolean isStopped(); 93 | 94 | 95 | /* ------------------------------------------------------------ */ 96 | /** Listener. 97 | * A listener for Lifecycle events. 98 | */ 99 | public interface Listener extends EventListener 100 | { 101 | public void lifeCycleStarting(LifeCycle event); 102 | public void lifeCycleStarted(LifeCycle event); 103 | public void lifeCycleFailure(LifeCycle event,Throwable cause); 104 | public void lifeCycleStopping(LifeCycle event); 105 | public void lifeCycleStopped(LifeCycle event); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/log/AndroidLog.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.eclipse.jetty.util.log; 20 | 21 | /** 22 | * A logger implementation for Android 23 | * 24 | * Copyright (c) 2015 KNOWLEDGECODE 25 | */ 26 | final class AndroidLog implements Logger { 27 | 28 | private String _tag; 29 | 30 | AndroidLog(String tag) { 31 | _tag = tag.substring(tag.length() > 23 ? tag.length() - 23 : 0); 32 | } 33 | 34 | private static String format(String msg, Object... args) { 35 | return String.format(msg.replaceAll("\\{\\}", "%s"), args); 36 | } 37 | 38 | @Override 39 | public String getName() { 40 | return AndroidLog.class.getName(); 41 | } 42 | 43 | @Override 44 | public void warn(String msg, Object... args) { 45 | if (Log.logLevel <= android.util.Log.WARN) { 46 | android.util.Log.w(_tag, format(msg, args)); 47 | } 48 | } 49 | 50 | @Override 51 | public void warn(Throwable thrown) { 52 | if (Log.logLevel <= android.util.Log.WARN) { 53 | android.util.Log.w(_tag, thrown); 54 | } 55 | } 56 | 57 | @Override 58 | public void warn(String msg, Throwable thrown) { 59 | if (Log.logLevel <= android.util.Log.WARN) { 60 | android.util.Log.w(_tag, msg, thrown); 61 | } 62 | } 63 | 64 | @Override 65 | public void info(String msg, Object... args) { 66 | if (Log.logLevel <= android.util.Log.INFO) { 67 | android.util.Log.i(_tag, format(msg, args)); 68 | } 69 | } 70 | 71 | @Override 72 | public void info(Throwable thrown) { 73 | if (Log.logLevel <= android.util.Log.INFO) { 74 | android.util.Log.i(_tag, "", thrown); 75 | } 76 | } 77 | 78 | @Override 79 | public void info(String msg, Throwable thrown) { 80 | if (Log.logLevel <= android.util.Log.INFO) { 81 | android.util.Log.i(_tag, msg, thrown); 82 | } 83 | } 84 | 85 | @Override 86 | public boolean isDebugEnabled() { 87 | return android.util.Log.isLoggable(_tag, android.util.Log.DEBUG); 88 | } 89 | 90 | @Override 91 | public void setDebugEnabled(boolean enabled) { 92 | throw new UnsupportedOperationException(); 93 | } 94 | 95 | @Override 96 | public void debug(String msg, Object... args) { 97 | if (Log.logLevel <= android.util.Log.DEBUG) { 98 | android.util.Log.d(_tag, format(msg, args)); 99 | } 100 | } 101 | 102 | @Override 103 | public void debug(Throwable thrown) { 104 | if (Log.logLevel <= android.util.Log.DEBUG) { 105 | android.util.Log.d(_tag, "", thrown); 106 | } 107 | } 108 | 109 | @Override 110 | public void debug(String msg, Throwable thrown) { 111 | if (Log.logLevel <= android.util.Log.DEBUG) { 112 | android.util.Log.d(_tag, msg, thrown); 113 | } 114 | } 115 | 116 | @Override 117 | public Logger getLogger(String tag) { 118 | throw new UnsupportedOperationException(); 119 | } 120 | 121 | @Override 122 | public void ignore(Throwable ignored) { 123 | // ignore 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/log/Log.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.log; 20 | 21 | /** 22 | * Logging. 23 | * 24 | * Modified by KNOWLEDGECODE 25 | */ 26 | public class Log 27 | { 28 | public static final String EXCEPTION = "EXCEPTION "; 29 | 30 | static int logLevel = android.util.Log.ERROR; 31 | 32 | /** 33 | * Obtain a named Logger based on the fully qualified class name. 34 | * 35 | * @param clazz 36 | * the class to base the Logger name off of 37 | * @return the Logger with the given name 38 | */ 39 | public static Logger getLogger(Class clazz) 40 | { 41 | return getLogger(clazz.getName()); 42 | } 43 | 44 | /** 45 | * Obtain a named Logger or the default Logger if null is passed. 46 | * @param name the Logger name 47 | * @return the Logger with the given name 48 | */ 49 | public static Logger getLogger(String name) 50 | { 51 | return new AndroidLog(name == null ? "" : name); 52 | } 53 | 54 | /** 55 | * Change log level. 56 | * @param level 57 | */ 58 | public static void setLogLevel(int level) 59 | { 60 | logLevel = level; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/log/Logger.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.log; 20 | 21 | /** 22 | * A simple logging facade that is intended simply to capture the style of logging as used by Jetty. 23 | */ 24 | public interface Logger 25 | { 26 | /** 27 | * @return the name of this logger 28 | */ 29 | public String getName(); 30 | 31 | /** 32 | * Formats and logs at warn level. 33 | * @param msg the formatting string 34 | * @param args the optional arguments 35 | */ 36 | public void warn(String msg, Object... args); 37 | 38 | /** 39 | * Logs the given Throwable information at warn level 40 | * @param thrown the Throwable to log 41 | */ 42 | public void warn(Throwable thrown); 43 | 44 | /** 45 | * Logs the given message at warn level, with Throwable information. 46 | * @param msg the message to log 47 | * @param thrown the Throwable to log 48 | */ 49 | public void warn(String msg, Throwable thrown); 50 | 51 | /** 52 | * Formats and logs at info level. 53 | * @param msg the formatting string 54 | * @param args the optional arguments 55 | */ 56 | public void info(String msg, Object... args); 57 | 58 | /** 59 | * Logs the given Throwable information at info level 60 | * @param thrown the Throwable to log 61 | */ 62 | public void info(Throwable thrown); 63 | 64 | /** 65 | * Logs the given message at info level, with Throwable information. 66 | * @param msg the message to log 67 | * @param thrown the Throwable to log 68 | */ 69 | public void info(String msg, Throwable thrown); 70 | 71 | /** 72 | * @return whether the debug level is enabled 73 | */ 74 | public boolean isDebugEnabled(); 75 | 76 | /** 77 | * Mutator used to turn debug on programmatically. 78 | * @param enabled whether to enable the debug level 79 | */ 80 | public void setDebugEnabled(boolean enabled); 81 | 82 | /** 83 | * Formats and logs at debug level. 84 | * @param msg the formatting string 85 | * @param args the optional arguments 86 | */ 87 | public void debug(String msg, Object... args); 88 | 89 | /** 90 | * Logs the given Throwable information at debug level 91 | * @param thrown the Throwable to log 92 | */ 93 | public void debug(Throwable thrown); 94 | 95 | /** 96 | * Logs the given message at debug level, with Throwable information. 97 | * @param msg the message to log 98 | * @param thrown the Throwable to log 99 | */ 100 | public void debug(String msg, Throwable thrown); 101 | 102 | /** 103 | * @param name the name of the logger 104 | * @return a logger with the given name 105 | */ 106 | public Logger getLogger(String name); 107 | 108 | /** 109 | * Ignore an exception. 110 | *

This should be used rather than an empty catch block. 111 | */ 112 | public void ignore(Throwable ignored); 113 | } 114 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/resource/Resource.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.resource; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.net.MalformedURLException; 24 | import java.net.URL; 25 | 26 | import org.eclipse.jetty.util.log.Log; 27 | import org.eclipse.jetty.util.log.Logger; 28 | 29 | /* ------------------------------------------------------------ */ 30 | /**g 31 | * Abstract resource class. 32 | */ 33 | public abstract class Resource 34 | { 35 | private static final Logger LOG = Log.getLogger(Resource.class); 36 | public static boolean __defaultUseCaches = true; 37 | volatile Object _associate; 38 | 39 | /* ------------------------------------------------------------ */ 40 | /** Construct a resource from a url. 41 | * @param url A URL. 42 | * @return A Resource object. 43 | * @throws IOException Problem accessing URL 44 | */ 45 | public static Resource newResource(URL url) 46 | throws IOException 47 | { 48 | return newResource(url, __defaultUseCaches); 49 | } 50 | 51 | /* ------------------------------------------------------------ */ 52 | /** 53 | * Construct a resource from a url. 54 | * @param url the url for which to make the resource 55 | * @param useCaches true enables URLConnection caching if applicable to the type of resource 56 | * @return 57 | */ 58 | static Resource newResource(URL url, boolean useCaches) 59 | { 60 | if (url==null) 61 | return null; 62 | 63 | return new URLResource(url,null,useCaches); 64 | } 65 | 66 | /* ------------------------------------------------------------ */ 67 | /** Construct a resource from a string. 68 | * @param resource A URL or filename. 69 | * @return A Resource object. 70 | */ 71 | public static Resource newResource(String resource) 72 | throws MalformedURLException, IOException 73 | { 74 | return newResource(resource, __defaultUseCaches); 75 | } 76 | 77 | /* ------------------------------------------------------------ */ 78 | /** Construct a resource from a string. 79 | * @param resource A URL or filename. 80 | * @param useCaches controls URLConnection caching 81 | * @return A Resource object. 82 | */ 83 | public static Resource newResource (String resource, boolean useCaches) 84 | throws MalformedURLException, IOException 85 | { 86 | URL url=null; 87 | try 88 | { 89 | // Try to format as a URL? 90 | url = new URL(resource); 91 | } 92 | catch(MalformedURLException e) 93 | { 94 | LOG.warn("Bad Resource: "+resource); 95 | throw e; 96 | } 97 | 98 | return newResource(url); 99 | } 100 | 101 | /* ------------------------------------------------------------ */ 102 | @Override 103 | protected void finalize() 104 | { 105 | release(); 106 | } 107 | 108 | /* ------------------------------------------------------------ */ 109 | /** Release any temporary resources held by the resource. 110 | */ 111 | public abstract void release(); 112 | 113 | /* ------------------------------------------------------------ */ 114 | /** 115 | * Returns an input stream to the resource 116 | */ 117 | public abstract InputStream getInputStream() 118 | throws java.io.IOException; 119 | } 120 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/resource/URLResource.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.resource; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.net.URL; 24 | import java.net.URLConnection; 25 | 26 | import org.eclipse.jetty.util.log.Log; 27 | import org.eclipse.jetty.util.log.Logger; 28 | 29 | /* ------------------------------------------------------------ */ 30 | /** Abstract resource class. 31 | */ 32 | public class URLResource extends Resource 33 | { 34 | private static final Logger LOG = Log.getLogger(URLResource.class); 35 | protected URL _url; 36 | protected String _urlString; 37 | 38 | protected URLConnection _connection; 39 | protected InputStream _in=null; 40 | transient boolean _useCaches = Resource.__defaultUseCaches; 41 | 42 | /* ------------------------------------------------------------ */ 43 | protected URLResource(URL url, URLConnection connection) 44 | { 45 | _url = url; 46 | _urlString=_url.toString(); 47 | _connection=connection; 48 | } 49 | 50 | /* ------------------------------------------------------------ */ 51 | protected URLResource (URL url, URLConnection connection, boolean useCaches) 52 | { 53 | this (url, connection); 54 | _useCaches = useCaches; 55 | } 56 | 57 | /* ------------------------------------------------------------ */ 58 | protected synchronized boolean checkConnection() 59 | { 60 | if (_connection==null) 61 | { 62 | try{ 63 | _connection=_url.openConnection(); 64 | _connection.setUseCaches(_useCaches); 65 | } 66 | catch(IOException e) 67 | { 68 | LOG.ignore(e); 69 | } 70 | } 71 | return _connection!=null; 72 | } 73 | 74 | /* ------------------------------------------------------------ */ 75 | /** Release any resources held by the resource. 76 | */ 77 | @Override 78 | public synchronized void release() 79 | { 80 | if (_in!=null) 81 | { 82 | try{_in.close();}catch(IOException e){LOG.ignore(e);} 83 | _in=null; 84 | } 85 | 86 | if (_connection!=null) 87 | _connection=null; 88 | } 89 | 90 | /* ------------------------------------------------------------ */ 91 | /** 92 | * Returns an input stream to the resource 93 | */ 94 | @Override 95 | public synchronized InputStream getInputStream() 96 | throws java.io.IOException 97 | { 98 | if (!checkConnection()) 99 | throw new IOException( "Invalid resource"); 100 | 101 | try 102 | { 103 | if( _in != null) 104 | { 105 | InputStream in = _in; 106 | _in=null; 107 | return in; 108 | } 109 | return _connection.getInputStream(); 110 | } 111 | finally 112 | { 113 | _connection=null; 114 | } 115 | } 116 | 117 | /* ------------------------------------------------------------ */ 118 | @Override 119 | public String toString() 120 | { 121 | return _urlString; 122 | } 123 | 124 | /* ------------------------------------------------------------ */ 125 | @Override 126 | public boolean equals( Object o) 127 | { 128 | return o instanceof URLResource && _urlString.equals(((URLResource)o)._urlString); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/security/CertificateUtils.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.security; 20 | 21 | import java.io.InputStream; 22 | import java.security.KeyStore; 23 | import java.security.cert.CRL; 24 | import java.security.cert.CertificateFactory; 25 | import java.util.Collection; 26 | 27 | import org.eclipse.jetty.util.resource.Resource; 28 | 29 | public class CertificateUtils 30 | { 31 | /* ------------------------------------------------------------ */ 32 | public static KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception 33 | { 34 | KeyStore keystore = null; 35 | 36 | if (storeStream != null || storePath != null) 37 | { 38 | InputStream inStream = storeStream; 39 | try 40 | { 41 | if (inStream == null) 42 | { 43 | inStream = Resource.newResource(storePath).getInputStream(); 44 | } 45 | 46 | if (storeProvider != null) 47 | { 48 | keystore = KeyStore.getInstance(storeType, storeProvider); 49 | } 50 | else 51 | { 52 | keystore = KeyStore.getInstance(storeType); 53 | } 54 | 55 | keystore.load(inStream, storePassword == null ? null : storePassword.toCharArray()); 56 | } 57 | finally 58 | { 59 | if (inStream != null) 60 | { 61 | inStream.close(); 62 | } 63 | } 64 | } 65 | 66 | return keystore; 67 | } 68 | 69 | /* ------------------------------------------------------------ */ 70 | public static Collection loadCRL(String crlPath) throws Exception 71 | { 72 | Collection crlList = null; 73 | 74 | if (crlPath != null) 75 | { 76 | InputStream in = null; 77 | try 78 | { 79 | in = Resource.newResource(crlPath).getInputStream(); 80 | crlList = CertificateFactory.getInstance("X.509").generateCRLs(in); 81 | } 82 | finally 83 | { 84 | if (in != null) 85 | { 86 | in.close(); 87 | } 88 | } 89 | } 90 | 91 | return crlList; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/security/CertificateValidator.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.security; 20 | 21 | import java.security.GeneralSecurityException; 22 | import java.security.InvalidParameterException; 23 | import java.security.KeyStore; 24 | import java.security.KeyStoreException; 25 | import java.security.Security; 26 | import java.security.cert.CRL; 27 | import java.security.cert.CertPathBuilder; 28 | import java.security.cert.CertPathBuilderResult; 29 | import java.security.cert.CertPathValidator; 30 | import java.security.cert.CertStore; 31 | import java.security.cert.Certificate; 32 | import java.security.cert.CertificateException; 33 | import java.security.cert.CollectionCertStoreParameters; 34 | import java.security.cert.PKIXBuilderParameters; 35 | import java.security.cert.X509CertSelector; 36 | import java.security.cert.X509Certificate; 37 | import java.util.ArrayList; 38 | import java.util.Collection; 39 | import java.util.concurrent.atomic.AtomicLong; 40 | 41 | import org.eclipse.jetty.util.log.Log; 42 | import org.eclipse.jetty.util.log.Logger; 43 | 44 | /** 45 | * Convenience class to handle validation of certificates, aliases and keystores 46 | * 47 | * Allows specifying Certificate Revocation List (CRL), as well as enabling 48 | * CRL Distribution Points Protocol (CRLDP) certificate extension support, 49 | * and also enabling On-Line Certificate Status Protocol (OCSP) support. 50 | * 51 | * IMPORTANT: at least one of the above mechanisms *MUST* be configured and 52 | * operational, otherwise certificate validation *WILL FAIL* unconditionally. 53 | */ 54 | public class CertificateValidator 55 | { 56 | private static final Logger LOG = Log.getLogger(CertificateValidator.class); 57 | private static AtomicLong __aliasCount = new AtomicLong(); 58 | 59 | private KeyStore _trustStore; 60 | private Collection _crls; 61 | 62 | /** Maximum certification path length (n - number of intermediate certs, -1 for unlimited) */ 63 | private int _maxCertPathLength = -1; 64 | /** CRL Distribution Points (CRLDP) support */ 65 | private boolean _enableCRLDP = false; 66 | /** On-Line Certificate Status Protocol (OCSP) support */ 67 | private boolean _enableOCSP = false; 68 | 69 | /** 70 | * creates an instance of the certificate validator 71 | * 72 | * @param trustStore 73 | * @param crls 74 | */ 75 | public CertificateValidator(KeyStore trustStore, Collection crls) 76 | { 77 | if (trustStore == null) 78 | { 79 | throw new InvalidParameterException("TrustStore must be specified for CertificateValidator."); 80 | } 81 | 82 | _trustStore = trustStore; 83 | _crls = crls; 84 | } 85 | 86 | /** 87 | * validates a specific certificate inside of the keystore being passed in 88 | * 89 | * @param keyStore 90 | * @param cert 91 | * @throws CertificateException 92 | */ 93 | public void validate(KeyStore keyStore, Certificate cert) throws CertificateException 94 | { 95 | Certificate[] certChain = null; 96 | 97 | if (cert != null && cert instanceof X509Certificate) 98 | { 99 | ((X509Certificate)cert).checkValidity(); 100 | 101 | String certAlias = null; 102 | try 103 | { 104 | if (keyStore == null) 105 | { 106 | throw new InvalidParameterException("Keystore cannot be null"); 107 | } 108 | 109 | certAlias = keyStore.getCertificateAlias((X509Certificate)cert); 110 | if (certAlias == null) 111 | { 112 | certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet()); 113 | keyStore.setCertificateEntry(certAlias, cert); 114 | } 115 | 116 | certChain = keyStore.getCertificateChain(certAlias); 117 | if (certChain == null || certChain.length == 0) 118 | { 119 | throw new IllegalStateException("Unable to retrieve certificate chain"); 120 | } 121 | } 122 | catch (KeyStoreException kse) 123 | { 124 | LOG.debug(kse); 125 | throw new CertificateException("Unable to validate certificate" + 126 | (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse); 127 | } 128 | 129 | validate(certChain); 130 | } 131 | } 132 | 133 | public void validate(Certificate[] certChain) throws CertificateException 134 | { 135 | try 136 | { 137 | ArrayList certList = new ArrayList(); 138 | for (Certificate item : certChain) 139 | { 140 | if (item == null) 141 | continue; 142 | 143 | if (!(item instanceof X509Certificate)) 144 | { 145 | throw new IllegalStateException("Invalid certificate type in chain"); 146 | } 147 | 148 | certList.add((X509Certificate)item); 149 | } 150 | 151 | if (certList.isEmpty()) 152 | { 153 | throw new IllegalStateException("Invalid certificate chain"); 154 | 155 | } 156 | 157 | X509CertSelector certSelect = new X509CertSelector(); 158 | certSelect.setCertificate(certList.get(0)); 159 | 160 | // Configure certification path builder parameters 161 | PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect); 162 | pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList))); 163 | 164 | // Set maximum certification path length 165 | pbParams.setMaxPathLength(_maxCertPathLength); 166 | 167 | // Enable revocation checking 168 | pbParams.setRevocationEnabled(true); 169 | 170 | // Set static Certificate Revocation List 171 | if (_crls != null && !_crls.isEmpty()) 172 | { 173 | pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls))); 174 | } 175 | 176 | // Enable On-Line Certificate Status Protocol (OCSP) support 177 | if (_enableOCSP) 178 | { 179 | Security.setProperty("ocsp.enable","true"); 180 | } 181 | // Enable Certificate Revocation List Distribution Points (CRLDP) support 182 | if (_enableCRLDP) 183 | { 184 | System.setProperty("com.sun.security.enableCRLDP","true"); 185 | } 186 | 187 | // Build certification path 188 | CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); 189 | 190 | // Validate certification path 191 | CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams); 192 | } 193 | catch (GeneralSecurityException gse) 194 | { 195 | LOG.debug(gse); 196 | throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse); 197 | } 198 | } 199 | 200 | /* ------------------------------------------------------------ */ 201 | /** 202 | * @param maxCertPathLength 203 | * maximum number of intermediate certificates in 204 | * the certification path (-1 for unlimited) 205 | */ 206 | public void setMaxCertPathLength(int maxCertPathLength) 207 | { 208 | _maxCertPathLength = maxCertPathLength; 209 | } 210 | 211 | /* ------------------------------------------------------------ */ 212 | /** Enables CRL Distribution Points Support 213 | * @param enableCRLDP true - turn on, false - turns off 214 | */ 215 | public void setEnableCRLDP(boolean enableCRLDP) 216 | { 217 | _enableCRLDP = enableCRLDP; 218 | } 219 | 220 | /* ------------------------------------------------------------ */ 221 | /** Enables On-Line Certificate Status Protocol support 222 | * @param enableOCSP true - turn on, false - turn off 223 | */ 224 | public void setEnableOCSP(boolean enableOCSP) 225 | { 226 | _enableOCSP = enableOCSP; 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/security/Password.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.security; 20 | 21 | /* ------------------------------------------------------------ */ 22 | /** 23 | * Password utility class. 24 | * 25 | * This utility class gets a password or pass phrase either by: 26 | * 27 | *

28 |  *  + Password is set as a system property.
29 |  *  + The password is prompted for and read from standard input
30 |  *  + A program is run to get the password.
31 |  * 
32 | * 33 | * Passwords that begin with OBF: are de obfuscated. Passwords can be obfuscated 34 | * by run org.eclipse.util.Password as a main class. Obfuscated password are 35 | * required if a system needs to recover the full password (eg. so that it may 36 | * be passed to another system). They are not secure, but prevent casual 37 | * observation. 38 | *

39 | * Passwords that begin with CRYPT: are oneway encrypted with UnixCrypt. The 40 | * real password cannot be retrieved, but comparisons can be made to other 41 | * passwords. A Crypt can be generated by running org.eclipse.util.UnixCrypt as 42 | * a main class, passing password and then the username. Checksum passwords are 43 | * a secure(ish) way to store passwords that only need to be checked rather than 44 | * recovered. Note that it is not strong security - specially if simple 45 | * passwords are used. 46 | * 47 | * 48 | */ 49 | public class Password 50 | { 51 | private String _pw; 52 | 53 | /* ------------------------------------------------------------ */ 54 | @Override 55 | public String toString() 56 | { 57 | return _pw; 58 | } 59 | 60 | /* ------------------------------------------------------------ */ 61 | @Override 62 | public boolean equals(Object o) 63 | { 64 | if (this == o) 65 | return true; 66 | 67 | if (null == o) 68 | return false; 69 | 70 | if (o instanceof Password) 71 | { 72 | Password p = (Password) o; 73 | //noinspection StringEquality 74 | return p._pw == _pw || (null != _pw && _pw.equals(p._pw)); 75 | } 76 | 77 | if (o instanceof String) 78 | return o.equals(_pw); 79 | 80 | return false; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/ssl/AliasedX509ExtendedKeyManager.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.ssl; 20 | 21 | import java.net.Socket; 22 | import java.security.Principal; 23 | import java.security.PrivateKey; 24 | import java.security.cert.X509Certificate; 25 | 26 | import javax.net.ssl.X509ExtendedKeyManager; 27 | import javax.net.ssl.X509KeyManager; 28 | 29 | 30 | /* ------------------------------------------------------------ */ 31 | /** 32 | * KeyManager to select a key with desired alias 33 | * while delegating processing to specified KeyManager 34 | * Can be used both with server and client sockets 35 | */ 36 | public class AliasedX509ExtendedKeyManager extends X509ExtendedKeyManager 37 | { 38 | private String _keyAlias; 39 | private X509KeyManager _keyManager; 40 | 41 | /* ------------------------------------------------------------ */ 42 | /** 43 | * Construct KeyManager instance 44 | * @param keyAlias Alias of the key to be selected 45 | * @param keyManager Instance of KeyManager to be wrapped 46 | * @throws Exception 47 | */ 48 | public AliasedX509ExtendedKeyManager(String keyAlias, X509KeyManager keyManager) throws Exception 49 | { 50 | _keyAlias = keyAlias; 51 | _keyManager = keyManager; 52 | } 53 | 54 | /* ------------------------------------------------------------ */ 55 | /** 56 | * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], java.security.Principal[], java.net.Socket) 57 | */ 58 | public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) 59 | { 60 | return _keyAlias == null ? _keyManager.chooseClientAlias(keyType, issuers, socket) : _keyAlias; 61 | } 62 | 63 | /* ------------------------------------------------------------ */ 64 | /** 65 | * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, java.security.Principal[], java.net.Socket) 66 | */ 67 | public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) 68 | { 69 | return _keyAlias == null ? _keyManager.chooseServerAlias(keyType, issuers, socket) : _keyAlias; 70 | } 71 | 72 | /* ------------------------------------------------------------ */ 73 | /** 74 | * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, java.security.Principal[]) 75 | */ 76 | public String[] getClientAliases(String keyType, Principal[] issuers) 77 | { 78 | return _keyManager.getClientAliases(keyType, issuers); 79 | } 80 | 81 | /* ------------------------------------------------------------ */ 82 | /** 83 | * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, java.security.Principal[]) 84 | */ 85 | public String[] getServerAliases(String keyType, Principal[] issuers) 86 | { 87 | return _keyManager.getServerAliases(keyType, issuers); 88 | } 89 | 90 | /* ------------------------------------------------------------ */ 91 | /** 92 | * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String) 93 | */ 94 | public X509Certificate[] getCertificateChain(String alias) 95 | { 96 | return _keyManager.getCertificateChain(alias); 97 | } 98 | 99 | /* ------------------------------------------------------------ */ 100 | /** 101 | * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String) 102 | */ 103 | public PrivateKey getPrivateKey(String alias) 104 | { 105 | return _keyManager.getPrivateKey(alias); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/thread/ThreadPool.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.thread; 20 | 21 | /* ------------------------------------------------------------ */ 22 | /** ThreadPool. 23 | * 24 | * 25 | */ 26 | public interface ThreadPool 27 | { 28 | /* ------------------------------------------------------------ */ 29 | public abstract boolean dispatch(Runnable job); 30 | 31 | /* ------------------------------------------------------------ */ 32 | /** 33 | * @return The total number of threads currently in the pool 34 | */ 35 | public int getThreads(); 36 | 37 | /* ------------------------------------------------------------ */ 38 | /** 39 | * @return The number of idle threads in the pool 40 | */ 41 | public int getIdleThreads(); 42 | } 43 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/util/thread/Timeout.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.util.thread; 20 | 21 | 22 | /* ------------------------------------------------------------ */ 23 | /** Timeout queue. 24 | * This class implements a timeout queue for timers that are at least as likely to be cancelled as they are to expire. 25 | * Unlike the util timeout class, the duration of the timeouts is shared by all scheduled tasks and if the duration 26 | * is changed, this affects all scheduled tasks. 27 | *

28 | * The nested class Task should be extended by users of this class to obtain call back notification of 29 | * expires. 30 | */ 31 | public class Timeout 32 | { 33 | private Object _lock; 34 | private long _duration; 35 | private volatile long _now=System.currentTimeMillis(); 36 | private Task _head=new Task(); 37 | 38 | /* ------------------------------------------------------------ */ 39 | public Timeout(Object lock) 40 | { 41 | _lock=lock; 42 | _head._timeout=this; 43 | } 44 | 45 | /* ------------------------------------------------------------ */ 46 | /** 47 | * @param duration The duration to set. 48 | */ 49 | public void setDuration(long duration) 50 | { 51 | _duration = duration; 52 | } 53 | 54 | /* ------------------------------------------------------------ */ 55 | public long getNow() 56 | { 57 | return _now; 58 | } 59 | 60 | /* ------------------------------------------------------------ */ 61 | public void setNow(long now) 62 | { 63 | _now=now; 64 | } 65 | 66 | /* ------------------------------------------------------------ */ 67 | /** Get an expired tasks. 68 | * This is called instead of {@link #tick()} to obtain the next 69 | * expired Task, but without calling it's {@link Task#expire()} or 70 | * {@link Task#expired()} methods. 71 | * 72 | * @return the next expired task or null. 73 | */ 74 | public Task expired() 75 | { 76 | synchronized (_lock) 77 | { 78 | long _expiry = _now-_duration; 79 | 80 | if (_head._next!=_head) 81 | { 82 | Task task = _head._next; 83 | if (task._timestamp>_expiry) 84 | return null; 85 | 86 | task.unlink(); 87 | task._expired=true; 88 | return task; 89 | } 90 | return null; 91 | } 92 | } 93 | 94 | /* ------------------------------------------------------------ */ 95 | public void cancelAll() 96 | { 97 | synchronized (_lock) 98 | { 99 | _head._next=_head._prev=_head; 100 | } 101 | } 102 | 103 | /* ------------------------------------------------------------ */ 104 | public long getTimeToNext() 105 | { 106 | synchronized (_lock) 107 | { 108 | if (_head._next==_head) 109 | return -1; 110 | long to_next = _duration+_head._next._timestamp-_now; 111 | return to_next<0?0:to_next; 112 | } 113 | } 114 | 115 | /* ------------------------------------------------------------ */ 116 | @Override 117 | public String toString() 118 | { 119 | StringBuffer buf = new StringBuffer(); 120 | buf.append(super.toString()); 121 | 122 | Task task = _head._next; 123 | while (task!=_head) 124 | { 125 | buf.append("-->"); 126 | buf.append(task); 127 | task=task._next; 128 | } 129 | 130 | return buf.toString(); 131 | } 132 | 133 | /* ------------------------------------------------------------ */ 134 | /* ------------------------------------------------------------ */ 135 | /* ------------------------------------------------------------ */ 136 | /* ------------------------------------------------------------ */ 137 | /** Task. 138 | * The base class for scheduled timeouts. This class should be 139 | * extended to implement the expire() method, which is called if the 140 | * timeout expires. 141 | * 142 | * 143 | * 144 | */ 145 | public static class Task 146 | { 147 | Task _next; 148 | Task _prev; 149 | Timeout _timeout; 150 | long _delay; 151 | long _timestamp=0; 152 | boolean _expired=false; 153 | 154 | /* ------------------------------------------------------------ */ 155 | protected Task() 156 | { 157 | _next=_prev=this; 158 | } 159 | 160 | /* ------------------------------------------------------------ */ 161 | private void unlink() 162 | { 163 | _next._prev=_prev; 164 | _prev._next=_next; 165 | _next=_prev=this; 166 | _expired=false; 167 | } 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/Extension.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import java.util.Map; 22 | 23 | public interface Extension extends WebSocketParser.FrameHandler, WebSocketGenerator 24 | { 25 | public String getName(); 26 | public String getParameterizedName(); 27 | public boolean init(Map parameters); 28 | public void bind(WebSocket.FrameConnection connection, WebSocketParser.FrameHandler inbound, WebSocketGenerator outbound); 29 | } 30 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/MaskGen.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | public interface MaskGen 22 | { 23 | void genMask(byte[] mask); 24 | } 25 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/RandomMaskGen.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import java.util.Random; 22 | 23 | 24 | public class RandomMaskGen implements MaskGen 25 | { 26 | private final Random _random; 27 | 28 | public RandomMaskGen() 29 | { 30 | this(new Random()); 31 | } 32 | 33 | public RandomMaskGen(Random random) 34 | { 35 | _random=random; 36 | } 37 | 38 | public void genMask(byte[] mask) 39 | { 40 | // The assumption is that this code is always called 41 | // with an external lock held to prevent concurrent access 42 | // Otherwise we need to synchronize on the _random. 43 | _random.nextBytes(mask); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocket.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * WebSocket Interface. 25 | *

26 | * This interface provides the signature for a server-side end point of a websocket connection. 27 | * The Interface has several nested interfaces, for each type of message that may be received. 28 | */ 29 | public interface WebSocket 30 | { 31 | /** 32 | * Called when a new websocket connection is accepted. 33 | * @param connection The Connection object to use to send messages. 34 | */ 35 | void onOpen(Connection connection); 36 | 37 | /** 38 | * Called when an established websocket connection closes 39 | * @param closeCode 40 | * @param message 41 | */ 42 | void onClose(int closeCode, String message); 43 | 44 | /** 45 | * A nested WebSocket interface for receiving text messages 46 | */ 47 | interface OnTextMessage extends WebSocket 48 | { 49 | /** 50 | * Called with a complete text message when all fragments have been received. 51 | * The maximum size of text message that may be aggregated from multiple frames is set with {@link Connection#setMaxTextMessageSize(int)}. 52 | * @param data The message 53 | */ 54 | void onMessage(String data); 55 | } 56 | 57 | /** 58 | * A nested WebSocket interface for receiving binary messages 59 | */ 60 | interface OnBinaryMessage extends WebSocket 61 | { 62 | /** 63 | * Called with a complete binary message when all fragments have been received. 64 | * The maximum size of binary message that may be aggregated from multiple frames is set with {@link Connection#setMaxBinaryMessageSize(int)}. 65 | * @param data 66 | * @param offset 67 | * @param length 68 | */ 69 | void onMessage(byte[] data, int offset, int length); 70 | } 71 | 72 | /** 73 | * A nested WebSocket interface for receiving control messages 74 | */ 75 | interface OnControl extends WebSocket 76 | { 77 | /** 78 | * Called when a control message has been received. 79 | * @param controlCode 80 | * @param data 81 | * @param offset 82 | * @param length 83 | * @return true if this call has completely handled the control message and no further processing is needed. 84 | */ 85 | boolean onControl(byte controlCode,byte[] data, int offset, int length); 86 | } 87 | 88 | /** 89 | * A nested WebSocket interface for receiving any websocket frame 90 | */ 91 | interface OnFrame extends WebSocket 92 | { 93 | /** 94 | * Called when any websocket frame is received. 95 | * @param flags 96 | * @param opcode 97 | * @param data 98 | * @param offset 99 | * @param length 100 | * @return true if this call has completely handled the frame and no further processing is needed (including aggregation and/or message delivery) 101 | */ 102 | boolean onFrame(byte flags,byte opcode,byte[] data, int offset, int length); 103 | 104 | void onHandshake(FrameConnection connection); 105 | } 106 | 107 | /** 108 | * A Connection interface is passed to a WebSocket instance via the {@link WebSocket#onOpen(Connection)} to 109 | * give the application access to the specifics of the current connection. This includes methods 110 | * for sending frames and messages as well as methods for interpreting the flags and opcodes of the connection. 111 | * 112 | * modified by KNOWLEDGECODE 113 | */ 114 | public interface Connection 115 | { 116 | String getProtocol(); 117 | String getExtensions(); 118 | void sendMessage(String data) throws IOException; 119 | void sendMessage(byte[] data, int offset, int length) throws IOException; 120 | 121 | /** 122 | * Close the connection with normal close code. 123 | */ 124 | void close(); 125 | 126 | /** 127 | * Close the connection with normal close code. 128 | * @param silent Whether telling the app this thing or not 129 | */ 130 | void close(boolean silent); 131 | 132 | /** Close the connection with specific closeCode and message. 133 | * @param closeCode The close code to send, or -1 for no close code 134 | * @param message The message to send or null for no message 135 | */ 136 | void close(int closeCode,String message); 137 | 138 | boolean isOpen(); 139 | 140 | /** 141 | * @param ms The time in ms that the connection can be idle before closing 142 | */ 143 | void setMaxIdleTime(int ms); 144 | 145 | /** 146 | * @param size size<0 No aggregation of frames to messages, >=0 max size of text frame aggregation buffer in characters 147 | */ 148 | void setMaxTextMessageSize(int size); 149 | 150 | /** 151 | * @param size size<0 no aggregation of binary frames, >=0 size of binary frame aggregation buffer 152 | */ 153 | void setMaxBinaryMessageSize(int size); 154 | 155 | /** 156 | * @return The time in ms that the connection can be idle before closing 157 | */ 158 | int getMaxIdleTime(); 159 | 160 | /** 161 | * Size in characters of the maximum text message to be received 162 | * @return size <0 No aggregation of frames to messages, >=0 max size of text frame aggregation buffer in characters 163 | */ 164 | int getMaxTextMessageSize(); 165 | 166 | /** 167 | * Size in bytes of the maximum binary message to be received 168 | * @return size <0 no aggregation of binary frames, >=0 size of binary frame aggregation buffer 169 | */ 170 | int getMaxBinaryMessageSize(); 171 | } 172 | 173 | /** 174 | * Frame Level Connection 175 | *

The Connection interface at the level of sending/receiving frames rather than messages. 176 | * Also contains methods to decode/generate flags and opcodes without using constants, so that 177 | * code can be written to work with multiple drafts of the protocol. 178 | * 179 | */ 180 | public interface FrameConnection extends Connection 181 | { 182 | /** 183 | * @return The opcode of a binary message 184 | */ 185 | byte binaryOpcode(); 186 | 187 | /** 188 | * @return The opcode of a text message 189 | */ 190 | byte textOpcode(); 191 | 192 | /** 193 | * @return The opcode of a continuation frame 194 | */ 195 | byte continuationOpcode(); 196 | 197 | /** 198 | * @return Mask for the FIN bit. 199 | */ 200 | byte finMask(); 201 | 202 | /** Set if frames larger than the frame buffer are handled with local fragmentations 203 | * @param allowFragmentation 204 | */ 205 | void setAllowFrameFragmentation(boolean allowFragmentation); 206 | 207 | /** 208 | * @param flags The flags bytes of a frame 209 | * @return True of the flags indicate a final frame. 210 | */ 211 | boolean isMessageComplete(byte flags); 212 | 213 | /** 214 | * @param opcode 215 | * @return True if the opcode is for a control frame 216 | */ 217 | boolean isControl(byte opcode); 218 | 219 | /** 220 | * @param opcode 221 | * @return True if the opcode is for a text frame 222 | */ 223 | boolean isText(byte opcode); 224 | 225 | /** 226 | * @param opcode 227 | * @return True if the opcode is for a binary frame 228 | */ 229 | boolean isBinary(byte opcode); 230 | 231 | /** 232 | * @param opcode 233 | * @return True if the opcode is for a continuation frame 234 | */ 235 | boolean isContinuation(byte opcode); 236 | 237 | /** 238 | * @param opcode 239 | * @return True if the opcode is a close control 240 | */ 241 | boolean isClose(byte opcode); 242 | 243 | /** 244 | * @param opcode 245 | * @return True if the opcode is a ping control 246 | */ 247 | boolean isPing(byte opcode); 248 | 249 | /** 250 | * @param opcode 251 | * @return True if the opcode is a pong control 252 | */ 253 | boolean isPong(byte opcode); 254 | 255 | /** 256 | * @return True if frames larger than the frame buffer are fragmented. 257 | */ 258 | boolean isAllowFrameFragmentation(); 259 | 260 | /** Send a control frame 261 | * @param control 262 | * @param data 263 | * @param offset 264 | * @param length 265 | * @throws IOException 266 | */ 267 | void sendControl(byte control,byte[] data, int offset, int length) throws IOException; 268 | 269 | /** Send an arbitrary frame 270 | * @param flags 271 | * @param opcode 272 | * @param data 273 | * @param offset 274 | * @param length 275 | * @throws IOException 276 | */ 277 | void sendFrame(byte flags,byte opcode,byte[] data, int offset, int length) throws IOException; 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocketBuffer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.eclipse.jetty.websocket; 20 | 21 | import java.nio.charset.Charset; 22 | import java.util.Arrays; 23 | 24 | import org.eclipse.jetty.io.Buffer; 25 | 26 | /** 27 | * WebSocketBuffer 28 | * 29 | * Copyright (c) 2015 KNOWLEDGECODE 30 | */ 31 | class WebSocketBuffer implements Buffer { 32 | 33 | private byte[] _buffer; 34 | private int _index; 35 | private int _capacity; 36 | 37 | public WebSocketBuffer(final int capacity) { 38 | _buffer = new byte[capacity]; 39 | _capacity = capacity; 40 | } 41 | 42 | public WebSocketBuffer append(final byte[] array, final int offset, final int length) { 43 | if ((_index += length) > _capacity) { 44 | _buffer = Arrays.copyOf(_buffer, (_capacity = Math.max(_capacity << 1, _index))); 45 | } 46 | System.arraycopy(array, offset, _buffer, _index - length, length); 47 | return this; 48 | } 49 | 50 | @Override 51 | public byte[] array() { 52 | return _buffer; 53 | } 54 | 55 | @Override 56 | public byte[] asArray() { 57 | return Arrays.copyOf(_buffer, _index); 58 | } 59 | 60 | @Override 61 | public Buffer buffer() { 62 | return null; 63 | } 64 | 65 | @Override 66 | public Buffer asMutableBuffer() { 67 | return null; 68 | } 69 | 70 | @Override 71 | public int capacity() { 72 | return _capacity; 73 | } 74 | 75 | @Override 76 | public int space() { 77 | return _capacity - _index; 78 | } 79 | 80 | @Override 81 | public void clear() { 82 | _index = 0; 83 | } 84 | 85 | @Override 86 | public void compact() { 87 | } 88 | 89 | @Override 90 | public byte get() { 91 | return 0; 92 | } 93 | 94 | @Override 95 | public int get(byte[] b, int offset, int length) { 96 | return 0; 97 | } 98 | 99 | @Override 100 | public Buffer get(int length) { 101 | return null; 102 | } 103 | 104 | @Override 105 | public int getIndex() { 106 | return 0; 107 | } 108 | 109 | @Override 110 | public boolean hasContent() { 111 | return false; 112 | } 113 | 114 | @Override 115 | public boolean equalsIgnoreCase(Buffer buffer) { 116 | return false; 117 | } 118 | 119 | @Override 120 | public boolean isImmutable() { 121 | return false; 122 | } 123 | 124 | @Override 125 | public boolean isReadOnly() { 126 | return false; 127 | } 128 | 129 | @Override 130 | public boolean isVolatile() { 131 | return false; 132 | } 133 | 134 | @Override 135 | public int length() { 136 | return _index; 137 | } 138 | 139 | @Override 140 | public void mark() { 141 | } 142 | 143 | @Override 144 | public int markIndex() { 145 | return 0; 146 | } 147 | 148 | @Override 149 | public byte peek() { 150 | return 0; 151 | } 152 | 153 | @Override 154 | public byte peek(int index) { 155 | return 0; 156 | } 157 | 158 | @Override 159 | public int peek(int index, byte[] b, int offset, int length) { 160 | return 0; 161 | } 162 | 163 | @Override 164 | public int poke(int index, Buffer src) { 165 | return 0; 166 | } 167 | 168 | @Override 169 | public void poke(int index, byte b) { 170 | } 171 | 172 | @Override 173 | public int poke(int index, byte[] b, int offset, int length) { 174 | return 0; 175 | } 176 | 177 | @Override 178 | public int put(Buffer src) { 179 | return 0; 180 | } 181 | 182 | @Override 183 | public void put(byte b) { 184 | } 185 | 186 | @Override 187 | public int put(byte[] b, int offset, int length) { 188 | return 0; 189 | } 190 | 191 | @Override 192 | public int put(byte[] b) { 193 | return 0; 194 | } 195 | 196 | @Override 197 | public int putIndex() { 198 | return 0; 199 | } 200 | 201 | @Override 202 | public void setGetIndex(int newStart) { 203 | } 204 | 205 | @Override 206 | public void setMarkIndex(int newMark) { 207 | } 208 | 209 | @Override 210 | public void setPutIndex(int newLimit) { 211 | } 212 | 213 | @Override 214 | public int skip(int n) { 215 | return n; 216 | } 217 | 218 | @Override 219 | public Buffer sliceFromMark() { 220 | return null; 221 | } 222 | 223 | @Override 224 | public Buffer sliceFromMark(int length) { 225 | return null; 226 | } 227 | 228 | @Override 229 | public String toDetailString() { 230 | return null; 231 | } 232 | 233 | @Override 234 | public String toString(Charset charset) { 235 | return new String(_buffer, 0, _index, charset); 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocketBuffers.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import org.eclipse.jetty.io.Buffer; 22 | import org.eclipse.jetty.io.Buffers; 23 | import org.eclipse.jetty.io.Buffers.Type; 24 | import org.eclipse.jetty.io.ThreadLocalBuffers; 25 | 26 | /* ------------------------------------------------------------ */ 27 | /** The WebSocket Buffer Pool. 28 | * 29 | * The normal buffers are byte array buffers so that user processes 30 | * can access directly. However the generator uses direct buffers 31 | * for the final output stage as they are filled in bulk and are more 32 | * efficient to flush. 33 | */ 34 | public class WebSocketBuffers 35 | { 36 | final private Buffers _buffers; 37 | 38 | public WebSocketBuffers(final int bufferSize) 39 | { 40 | _buffers = new ThreadLocalBuffers(Type.DIRECT, bufferSize, Type.INDIRECT, bufferSize, Type.INDIRECT); 41 | } 42 | 43 | public Buffer getBuffer() 44 | { 45 | return _buffers.getBuffer(); 46 | } 47 | 48 | public Buffer getDirectBuffer() 49 | { 50 | return _buffers.getHeader(); 51 | } 52 | 53 | public void returnBuffer(Buffer buffer) 54 | { 55 | _buffers.returnBuffer(buffer); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocketConnection.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | 22 | import java.util.List; 23 | 24 | import org.eclipse.jetty.io.Buffer; 25 | import org.eclipse.jetty.io.nio.AsyncConnection; 26 | 27 | public interface WebSocketConnection extends AsyncConnection 28 | { 29 | void fillBuffersFrom(Buffer buffer); 30 | 31 | List getExtensions(); 32 | 33 | WebSocket.Connection getConnection(); 34 | 35 | void shutdown(); 36 | } 37 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocketGenerator.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import java.io.IOException; 22 | 23 | 24 | 25 | /* ------------------------------------------------------------ */ 26 | /** WebSocketGenerator. 27 | */ 28 | public interface WebSocketGenerator 29 | { 30 | int flush() throws IOException; 31 | boolean isBufferEmpty(); 32 | void addFrame(byte flags,byte opcode, byte[] content, int offset, int length) throws IOException; 33 | } 34 | -------------------------------------------------------------------------------- /src/android/org/eclipse/jetty/websocket/WebSocketParser.java: -------------------------------------------------------------------------------- 1 | // 2 | // ======================================================================== 3 | // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. 4 | // ------------------------------------------------------------------------ 5 | // All rights reserved. This program and the accompanying materials 6 | // are made available under the terms of the Eclipse Public License v1.0 7 | // and Apache License v2.0 which accompanies this distribution. 8 | // 9 | // The Eclipse Public License is available at 10 | // http://www.eclipse.org/legal/epl-v10.html 11 | // 12 | // The Apache License v2.0 is available at 13 | // http://www.opensource.org/licenses/apache2.0.php 14 | // 15 | // You may elect to redistribute this code under either of these licenses. 16 | // ======================================================================== 17 | // 18 | 19 | package org.eclipse.jetty.websocket; 20 | 21 | import org.eclipse.jetty.io.Buffer; 22 | 23 | /* ------------------------------------------------------------ */ 24 | /** 25 | * Parser the WebSocket protocol. 26 | * 27 | * modified by KNOWLEDGECODE 28 | */ 29 | public interface WebSocketParser 30 | { 31 | /* ------------------------------------------------------------ */ 32 | /* ------------------------------------------------------------ */ 33 | /* ------------------------------------------------------------ */ 34 | public interface FrameHandler 35 | { 36 | void onFrame(byte flags, byte opcode, byte[] array, int offset, int length); 37 | void close(int code,String message); 38 | } 39 | 40 | Buffer getBuffer(); 41 | 42 | /** 43 | * @return an indication of progress, normally bytes filled plus events parsed, or -1 for EOF 44 | */ 45 | int parseNext(); 46 | 47 | boolean isBufferEmpty(); 48 | 49 | void fill(Buffer buffer); 50 | } 51 | --------------------------------------------------------------------------------