├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.ja.md ├── README.md ├── pom.xml └── src ├── main └── java │ └── net │ └── unit8 │ └── wscl │ ├── BinaryFrameOutputStream.java │ ├── ClassLoaderEndpoint.java │ ├── ClassLoaderHolder.java │ ├── ClassProvider.java │ ├── ThinClientLauncher.java │ ├── WebSocketClassLoader.java │ ├── WebSocketURLConnection.java │ ├── WebSocketURLStreamHandler.java │ ├── dto │ ├── ResourceRequest.java │ └── ResourceResponse.java │ ├── handler │ ├── ResourceRequestReadHandler.java │ ├── ResourceRequestWriteHandler.java │ ├── ResourceResponseReadHandler.java │ └── ResourceResponseWriteHandler.java │ └── util │ ├── DigestUtils.java │ ├── FressianUtils.java │ ├── IOUtils.java │ ├── PropertyUtils.java │ └── QueryStringDecoder.java └── test └── java └── net └── unit8 └── wscl ├── ClassLoaderEndpointTest.java ├── ClassProviderStarter.java ├── handler └── ResourceRequestWriteHandlerTest.java └── util └── PropertyUtilsTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | target 3 | .idea 4 | 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.ja.md: -------------------------------------------------------------------------------- 1 | websocket-classloader 2 | ===================== 3 | 4 | A ClassLoader loading remote java class via WebSocket. 5 | [![Build Status](https://travis-ci.org/kawasima/websocket-classloader.png?branch=master)](https://travis-ci.org/kawasima/websocket-classloader) 6 | 7 | ## コンセプト 8 | 9 | 複数台のマシンで分散処理を行うにあたって、面倒なのはアプリケーションの配布です。例えばたくさんのJUnitのテストを、複数台のマシンで実行したい。ふつうにやろうとすると、テストの含まれるjarファイルと依存するjarを全て配布しなくてはなりませんが、これは結構な手間です。 10 | 11 | そんなときに、分散クライアントとなるマシンには必要最低限のクラスを、ランタイムにロードできれば比較的高速に、かつ、いつでも最新のアプリケーションを動かすことができます。 12 | 13 | websocket-classloaderは、そんな分散マシン向けのクラスローダーです。クラスロード要求に応じて、CrassProviderサーバに要求を転送し、CrassProviderサーバではクラスのバイナリーを探しだしてレスポンス返します。 14 | 15 | 16 | ## Usage 17 | 18 | ClassProviderをJSR―356のコンテナ(undertow, tomcatなど)にデプロイします。 19 | 20 | ```java 21 | new ClassProvider().start(port); 22 | ``` 23 | 24 | クライアント側は、ClassProviderのアドレスを指定して、WebSocketClassLoaderを作ります。 25 | 26 | ```java 27 | ClassLoader cl = new WebSocketClassLoader("ws://class-provider-host:port"); 28 | Class hogeClass = cl.loadClass("org.example.HogeHoge", true); 29 | ``` 30 | 31 | ## アーキテクチャ 32 | 33 | class binary format 34 | +-----------------------------------------------+ 35 | v | 36 | +----------------------+ loadClass request +---------------+ 37 | | Thin Application | (WebSocket) | ClassProvider | 38 | | WebSocketClassLoader | ---------------------> | | 39 | +----------------------+ +---------------+ 40 | 41 | 42 | WebSocketClassLoaderを使う側のアプリケーション(クライアントと呼ぶ)から、ClassProvierへWebSocketのコネクションを作成し、クライアントからloadClassが呼ばれたときに、ClassProviderへリクエストを飛ばし、クラスのバイナリフォーマットが帰ってきます。 43 | 44 | データのシリアライズにはFressianを使っています。 45 | 46 | ## License 47 | 48 | Apache License 2.0 49 | (c) 2014-2017 Yoshitaka Kawashima 50 | 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | websocket-classloader 2 | ===================== 3 | 4 | A ClassLoader loading remote java class via WebSocket. 5 | [![Build Status](https://travis-ci.org/kawasima/websocket-classloader.png?branch=master)](https://travis-ci.org/kawasima/websocket-classloader) 6 | 7 | ## Usage 8 | 9 | Deploy ClassProvider to JSR-356 container, e.g. undertow, tomcat. 10 | 11 | Use class loader as following: 12 | 13 | ```java 14 | ClassLoader cl = new WebSocketClassLoader("ws://class-provider-host:port"); 15 | Class hogeClass = cl.loadClass("org.example.HogeHoge", true); 16 | ``` 17 | 18 | ## Architecture 19 | 20 | class binary format 21 | +-----------------------------------------------+ 22 | v | 23 | +----------------------+ loadClass request +---------------+ 24 | | Thin Application | (WebSocket) | ClassProvider | 25 | | WebSocketClassLoader | ---------------------> | | 26 | +----------------------+ +---------------+ 27 | 28 | 29 | 30 | ## License 31 | 32 | Apache License 2.0 33 | (c) 2014-2017 Yoshitaka Kawashima 34 | 35 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | net.unit8.wscl 6 | websocket-classloader 7 | 0.3.0-sp1 8 | 9 | jar 10 | websocket-classloader 11 | https://github.com/kawasima/websocket-classloader 12 | ClassLoader loading classes via websocket. 13 | 2014 14 | 15 | 16 | UTF-8 17 | 1.7 18 | 19 | 20 | 21 | scm:git:https://github.com/kawasima/websocket-classloader.git 22 | scm:git:https://github.com/kawasima/websocket-classloader.git 23 | scm:git:https://github.com/kawasima/websocket-classloader.git 24 | 25 | 26 | 27 | GitHub 28 | https://github.com/kawasima/websocket-classloader 29 | 30 | 31 | 32 | 33 | ossrh 34 | https://oss.sonatype.org/content/repositories/snapshots 35 | 36 | 37 | ossrh 38 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 39 | 40 | 41 | 42 | 43 | 44 | kawasima 45 | kawasima1016@gmail.com 46 | http://unit8.net 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-compiler-plugin 55 | 3.6.1 56 | 57 | ${java.version} 58 | ${java.version} 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-deploy-plugin 64 | 2.8.2 65 | 66 | true 67 | 68 | 69 | 70 | org.sonatype.plugins 71 | nexus-staging-maven-plugin 72 | 1.6.7 73 | true 74 | 75 | ossrh 76 | https://oss.sonatype.org/ 77 | true 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | javax 86 | javaee-api 87 | 7.0 88 | provided 89 | 90 | 91 | org.fressian 92 | fressian 93 | 0.6.6 94 | 95 | 96 | io.undertow 97 | undertow-websockets-jsr 98 | 1.4.11.Final 99 | test 100 | 101 | 102 | junit 103 | junit 104 | 4.12 105 | test 106 | 107 | 108 | org.slf4j 109 | slf4j-api 110 | 1.7.24 111 | 112 | 113 | org.slf4j 114 | slf4j-simple 115 | 1.7.24 116 | test 117 | 118 | 119 | org.mockito 120 | mockito-core 121 | 1.10.19 122 | test 123 | 124 | 125 | org.powermock 126 | powermock-module-junit4 127 | 1.6.4 128 | test 129 | 130 | 131 | org.powermock 132 | powermock-api-mockito 133 | 1.6.4 134 | test 135 | 136 | 137 | 138 | 139 | 140 | The Apache Software License, Version 2.0 141 | http://www.apache.org/licenses/LICENSE-2.0.txt 142 | repo 143 | 144 | 145 | 146 | 147 | 148 | release 149 | 150 | 151 | 152 | org.apache.maven.plugins 153 | maven-source-plugin 154 | 2.4 155 | 156 | 157 | attach-sources 158 | 159 | jar-no-fork 160 | 161 | 162 | 163 | 164 | 165 | org.apache.maven.plugins 166 | maven-javadoc-plugin 167 | 2.10.4 168 | 169 | 170 | attach-javadocs 171 | 172 | jar 173 | 174 | 175 | 176 | 177 | 178 | org.apache.maven.plugins 179 | maven-gpg-plugin 180 | 1.6 181 | 182 | 183 | sign-artifacts 184 | verify 185 | 186 | sign 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/BinaryFrameOutputStream.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import javax.websocket.RemoteEndpoint; 7 | import javax.websocket.SendHandler; 8 | import javax.websocket.SendResult; 9 | import java.io.IOException; 10 | import java.io.OutputStream; 11 | import java.nio.ByteBuffer; 12 | 13 | /** 14 | * The output stream for BinaryFrame. 15 | * 16 | * @author kawasima 17 | */ 18 | public class BinaryFrameOutputStream extends OutputStream { 19 | private static final Logger logger = LoggerFactory.getLogger(BinaryFrameOutputStream.class); 20 | private static final int DEFAULT_BUFFER_SIZE = 65536; 21 | private final ByteBuffer buffer; 22 | private final RemoteEndpoint.Async remote; 23 | 24 | public BinaryFrameOutputStream(RemoteEndpoint.Async remote) { 25 | this.buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE); 26 | this.remote = remote; 27 | } 28 | 29 | @Override 30 | public void write(int b) throws IOException { 31 | if (!buffer.hasRemaining()) flush(); 32 | buffer.put((byte) b); 33 | } 34 | 35 | @Override 36 | public void write(@SuppressWarnings("NullableProblems") byte[] bytes, int offset, int length) throws IOException { 37 | if (buffer.remaining() < length) flush(); 38 | buffer.put(bytes, offset, length); 39 | } 40 | 41 | @Override 42 | public void flush() { 43 | if (buffer.position() > 0) { 44 | buffer.flip(); 45 | remote.sendBinary(buffer, new SendHandler() { 46 | @Override 47 | public void onResult(SendResult sendResult) { 48 | if (!sendResult.isOK()) { 49 | logger.error("Failed to send messages.", sendResult.getException()); 50 | } 51 | } 52 | }); 53 | } 54 | buffer.clear(); 55 | } 56 | 57 | @Override 58 | public void close() { 59 | flush(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/ClassLoaderEndpoint.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import net.unit8.wscl.dto.ResourceResponse; 5 | import net.unit8.wscl.handler.ResourceRequestWriteHandler; 6 | import net.unit8.wscl.handler.ResourceResponseReadHandler; 7 | import net.unit8.wscl.util.FressianUtils; 8 | import net.unit8.wscl.util.PropertyUtils; 9 | import org.fressian.FressianReader; 10 | import org.fressian.FressianWriter; 11 | import org.fressian.handlers.ILookup; 12 | import org.fressian.handlers.ReadHandler; 13 | import org.fressian.handlers.WriteHandler; 14 | import org.fressian.impl.ByteBufferInputStream; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | 18 | import javax.websocket.*; 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.IOException; 21 | import java.nio.ByteBuffer; 22 | import java.util.Map; 23 | import java.util.concurrent.*; 24 | 25 | /** 26 | * @author kawasima 27 | */ 28 | @ClientEndpoint 29 | public class ClassLoaderEndpoint extends Endpoint { 30 | private static final Logger logger = LoggerFactory.getLogger(ClassLoaderEndpoint.class); 31 | 32 | private Session session; 33 | private final ConcurrentMap> waitingResponses = new ConcurrentHashMap<>(); 34 | 35 | public ClassLoaderEndpoint() { 36 | } 37 | 38 | @OnOpen 39 | public void onOpen(Session session, EndpointConfig config) { 40 | this.session = session; 41 | session.addMessageHandler(new MessageHandler.Whole() { 42 | @Override 43 | public void onMessage(ByteBuffer buf) { 44 | try { 45 | FressianReader reader = new FressianReader(new ByteBufferInputStream(buf), 46 | new ILookup() { 47 | @Override 48 | public ReadHandler valAt(Object key) { 49 | if (key.equals(ResourceResponse.class.getName())) 50 | return new ResourceResponseReadHandler(); 51 | else 52 | return null; 53 | } 54 | }); 55 | 56 | Object obj = reader.readObject(); 57 | if (obj instanceof ResourceResponse) { 58 | ResourceResponse response = (ResourceResponse) obj; 59 | BlockingQueue queue = waitingResponses.get(response.getResourceName()); 60 | if (queue != null) { 61 | queue.offer(response); 62 | } else { 63 | ArrayBlockingQueue tempCreateQueue = new ArrayBlockingQueue( 64 | 10); 65 | waitingResponses.putIfAbsent(response.getResourceName(), tempCreateQueue); 66 | tempCreateQueue.offer(response); 67 | } 68 | } else { 69 | logger.warn("Fressian read response: " + obj + "(" + obj.getClass() + ")"); 70 | } 71 | } catch (IOException ex) { 72 | logger.warn("read response error", ex); 73 | } 74 | } 75 | }); 76 | } 77 | 78 | @SuppressWarnings("resource") 79 | public ResourceResponse request(ResourceRequest request) throws IOException { 80 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 81 | FressianWriter fw = new FressianWriter(baos, new ILookup>() { 82 | @Override 83 | public Map valAt(Class key) { 84 | if (key.equals(ResourceRequest.class)) { 85 | return FressianUtils.map(ResourceRequest.class.getName(), new ResourceRequestWriteHandler()); 86 | } else { 87 | return null; 88 | } 89 | } 90 | }); 91 | fw.writeObject(request); 92 | 93 | logger.debug("fetch class:" + request.getResourceName() + ":" + request.getClassLoaderId()); 94 | 95 | BlockingQueue queue = null; 96 | try { 97 | synchronized (waitingResponses) { 98 | waitingResponses.putIfAbsent(request.getResourceName(), new ArrayBlockingQueue( 99 | PropertyUtils.getLongSystemProperty("wscl.queue.size", 10).intValue())); 100 | queue = waitingResponses.get(request.getResourceName()); 101 | session.getAsyncRemote().sendBinary(ByteBuffer.wrap(baos.toByteArray())); 102 | ResourceResponse response = queue.poll(PropertyUtils.getLongSystemProperty("wscl.timeout", 5000), 103 | TimeUnit.MILLISECONDS); 104 | 105 | if (response == null) 106 | throw new IOException("WebSocket request error." + request.getResourceName()); 107 | return response; 108 | } 109 | } catch (InterruptedException ex) { 110 | throw new IOException("Interrupted in waiting for request." + request.getResourceName(), ex); 111 | } finally { 112 | synchronized (waitingResponses) { 113 | if (queue.isEmpty()) { 114 | waitingResponses.remove(request.getResourceName()); 115 | } 116 | } 117 | } 118 | } 119 | 120 | public void close() throws IOException { 121 | if (session != null && session.isOpen()) { 122 | session.close(); 123 | session = null; 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/ClassLoaderHolder.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import java.net.URL; 4 | import java.net.URLClassLoader; 5 | import java.util.HashMap; 6 | import java.util.UUID; 7 | 8 | /** 9 | * @author kawasima 10 | */ 11 | public class ClassLoaderHolder { 12 | private static final ClassLoaderHolder INSTANCE = new ClassLoaderHolder(); 13 | private final HashMap clMap = new HashMap<>(); 14 | 15 | private ClassLoaderHolder() { 16 | } 17 | 18 | public static ClassLoaderHolder getInstance() { 19 | return INSTANCE; 20 | } 21 | 22 | public UUID registerClasspath(URL[] urls, ClassLoader parent) { 23 | UUID classLoaderId = UUID.randomUUID(); 24 | synchronized (clMap) { 25 | clMap.put(classLoaderId, new URLClassLoader(urls, parent)); 26 | } 27 | return classLoaderId; 28 | } 29 | 30 | public ClassLoader get(UUID classLoaderId) { 31 | synchronized (clMap) { 32 | return clMap.get(classLoaderId); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/ClassProvider.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import net.unit8.wscl.dto.ResourceResponse; 5 | import net.unit8.wscl.handler.ResourceRequestReadHandler; 6 | import net.unit8.wscl.handler.ResourceResponseWriteHandler; 7 | import net.unit8.wscl.util.DigestUtils; 8 | import net.unit8.wscl.util.FressianUtils; 9 | import net.unit8.wscl.util.IOUtils; 10 | import org.fressian.FressianReader; 11 | import org.fressian.FressianWriter; 12 | import org.fressian.handlers.ILookup; 13 | import org.fressian.handlers.ReadHandler; 14 | import org.fressian.handlers.WriteHandler; 15 | import org.fressian.impl.ByteBufferInputStream; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | 19 | import javax.websocket.*; 20 | import javax.websocket.server.ServerEndpoint; 21 | import java.io.ByteArrayOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.net.URL; 25 | import java.nio.ByteBuffer; 26 | import java.util.Map; 27 | import java.util.UUID; 28 | 29 | /** 30 | * Provide classes via WebSocket. 31 | * 32 | * @author kawasima 33 | */ 34 | @ServerEndpoint("/") 35 | public class ClassProvider { 36 | private static final Logger logger = LoggerFactory.getLogger(ClassProvider.class); 37 | 38 | @OnOpen 39 | public void onOpen(Session session, EndpointConfig endpointConfig) { 40 | logger.debug("client " + session + " connected"); 41 | } 42 | 43 | private ClassLoader findClassLoader(UUID classLoaderId) { 44 | ClassLoader loader = null; 45 | if (classLoaderId != null) { 46 | loader = ClassLoaderHolder.getInstance().get(classLoaderId); 47 | } 48 | return loader != null ? loader : Thread.currentThread().getContextClassLoader(); 49 | } 50 | 51 | @OnMessage 52 | public void findResource(ByteBuffer msg, Session session) { 53 | ResourceRequest req = null; 54 | try (InputStream is = new ByteBufferInputStream(msg)) { 55 | FressianReader fr = new FressianReader(is, new ILookup() { 56 | @Override 57 | public ReadHandler valAt(Object key) { 58 | if (key.equals(ResourceRequest.class.getName())) 59 | return new ResourceRequestReadHandler(); 60 | else 61 | return null; 62 | } 63 | }); 64 | req = (ResourceRequest) fr.readObject(); 65 | } catch (IOException ignored) { 66 | 67 | } 68 | 69 | if (req == null) { 70 | try { 71 | session.close(new CloseReason(CloseReason.CloseCodes.CLOSED_ABNORMALLY, "")); 72 | } catch(IOException ignore) { 73 | } 74 | return; 75 | } 76 | 77 | ClassLoader cl = findClassLoader(req.getClassLoaderId()); 78 | URL url = cl.getResource(req.getResourceName()); 79 | ResourceResponse res = new ResourceResponse(req.getResourceName()); 80 | 81 | try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { 82 | if (url != null) { 83 | byte[] classBytes = IOUtils.slurp(url); 84 | res.setDigest(DigestUtils.md5hash(classBytes)); 85 | if (!req.isCheckOnly()) { 86 | res.setBytes(classBytes); 87 | } 88 | } 89 | logger.debug("findResource:" + req.getResourceName() + "(" + req.getClassLoaderId() + "):resourceUrl=" + url); 90 | 91 | FressianWriter fw = new FressianWriter(baos, new ILookup>() { 92 | @Override 93 | public Map valAt(Class key) { 94 | if (key.equals(ResourceResponse.class)) { 95 | return FressianUtils.map( 96 | ResourceResponse.class.getName(), 97 | new ResourceResponseWriteHandler()); 98 | } else { 99 | return null; 100 | } 101 | } 102 | }); 103 | fw.writeObject(res); 104 | fw.close(); 105 | 106 | logger.debug("findResource:sendBinary=" + baos.toByteArray().length); 107 | session.getAsyncRemote().sendBinary(ByteBuffer.wrap(baos.toByteArray()), 108 | new SendHandler() { 109 | @Override 110 | public void onResult(SendResult result) { 111 | if (!result.isOK()) { 112 | logger.warn("fail to sendBinary.", result.getException()); 113 | } 114 | } 115 | }); 116 | } catch (IOException ex) { 117 | logger.warn("Client connection is invalid. disconnect " + session, ex); 118 | } 119 | } 120 | 121 | @OnClose 122 | public void onClose(Session session, CloseReason closeReason) { 123 | logger.debug("Client " + session + " closed for" + closeReason); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/ThinClientLauncher.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.io.IOException; 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * The launcher for a thin client. 11 | * 12 | * @author kawasima 13 | */ 14 | public class ThinClientLauncher { 15 | private static final Logger logger = LoggerFactory.getLogger(ThinClientLauncher.class); 16 | 17 | public static void main(String[] args) throws IOException { 18 | String loaderAddress = System.getProperty("wscl.loader"); 19 | if (loaderAddress == null) 20 | loaderAddress = "ws://localhost:5000"; 21 | WebSocketClassLoader cl = null; 22 | try { 23 | cl = new WebSocketClassLoader(loaderAddress); 24 | Class mainClass = cl.loadClass(args[0], true); 25 | Method mainMethod = mainClass.getMethod("main", String[].class); 26 | String[] remoteArgs = new String[args.length - 1]; 27 | System.arraycopy(args, 1, remoteArgs, 0, remoteArgs.length); 28 | Thread.currentThread().setContextClassLoader(cl); 29 | mainMethod.invoke(null, new Object[] {remoteArgs} ); 30 | cl.dispose(); 31 | } catch (Exception ex) { 32 | logger.error("Error in executing " + args[0], ex); 33 | } finally { 34 | if (cl != null) 35 | cl.dispose(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/WebSocketClassLoader.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import net.unit8.wscl.util.DigestUtils; 4 | import net.unit8.wscl.util.IOUtils; 5 | import net.unit8.wscl.util.PropertyUtils; 6 | import net.unit8.wscl.util.QueryStringDecoder; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import javax.websocket.ClientEndpointConfig; 11 | import javax.websocket.ContainerProvider; 12 | import javax.websocket.DeploymentException; 13 | import javax.websocket.WebSocketContainer; 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.net.MalformedURLException; 17 | import java.net.URI; 18 | import java.net.URL; 19 | import java.net.URLConnection; 20 | import java.util.Arrays; 21 | import java.util.Enumeration; 22 | import java.util.List; 23 | import java.util.Vector; 24 | 25 | /** 26 | * ClassLoader fetching classes via WebSocket. 27 | * 28 | * @author kawasima 29 | */ 30 | public class WebSocketClassLoader extends ClassLoader { 31 | private ClassLoaderEndpoint endpoint; 32 | private URL baseUrl; 33 | private File cacheDirectory; 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(WebSocketClassLoader.class); 36 | 37 | public WebSocketClassLoader(String url) throws IOException, DeploymentException { 38 | this(url, Thread.currentThread().getContextClassLoader()); 39 | } 40 | public WebSocketClassLoader(String url, ClassLoader parent) 41 | throws DeploymentException, IOException { 42 | super(parent); 43 | 44 | logger.debug("Parent classloader=" + parent); 45 | cacheDirectory = PropertyUtils.getFileSystemProperty("wscl.cache.directory"); 46 | 47 | if (cacheDirectory != null && !cacheDirectory.exists() && !cacheDirectory.mkdirs()) { 48 | throw new IllegalArgumentException( 49 | "Can't create cache directory: " + cacheDirectory); 50 | } 51 | WebSocketContainer container = ContainerProvider.getWebSocketContainer(); 52 | endpoint = new ClassLoaderEndpoint(); 53 | container.connectToServer(endpoint, 54 | ClientEndpointConfig.Builder.create().build(), URI.create(url)); 55 | try { 56 | URL httpUrl = new URL(url.replaceFirst("ws://", "http://")); 57 | QueryStringDecoder decoder = new QueryStringDecoder(httpUrl.getQuery()); 58 | List classLoaderIds = decoder.parameters().get("classLoaderId"); 59 | WebSocketURLStreamHandler urlStreamHandler = new WebSocketURLStreamHandler(endpoint, cacheDirectory); 60 | if (classLoaderIds != null && !classLoaderIds.isEmpty()) 61 | urlStreamHandler.setClassLoaderId(classLoaderIds.get(0)); 62 | 63 | baseUrl = new URL("ws", httpUrl.getHost(), httpUrl.getPort(), 64 | httpUrl.getFile(), urlStreamHandler); 65 | } catch (Exception e) { 66 | throw new RuntimeException("ClassProvider URL is invalid.", e); 67 | } 68 | } 69 | 70 | private URL findCache(URL url, byte[] digest) { 71 | File cacheFile = new File(cacheDirectory, url.getPath()); 72 | if (cacheFile.exists() && Arrays.equals(digest, DigestUtils.md5hash(cacheFile))) { 73 | try { 74 | return cacheFile.toURI().toURL(); 75 | } catch (MalformedURLException e) { 76 | return url; 77 | } 78 | } else { 79 | return url; 80 | } 81 | } 82 | 83 | @Override 84 | protected URL findResource(String name) { 85 | URL url; 86 | try { 87 | StringBuilder file = new StringBuilder(256); 88 | if (!name.startsWith("/")) { 89 | file.append("/"); 90 | } 91 | file.append(name); 92 | 93 | url = new URL(baseUrl, file.toString()); 94 | 95 | } catch (MalformedURLException ex) { 96 | throw new IllegalArgumentException("name"); 97 | } 98 | 99 | try { 100 | WebSocketURLConnection connection = (WebSocketURLConnection)url.openConnection(); 101 | byte[] digest = connection.getResourceDigest(); 102 | logger.debug("findResource:" + name + ":" + url.toString()); 103 | if (digest == null) 104 | return null; 105 | return cacheDirectory != null ? findCache(url, digest) : url; 106 | } catch(Exception e) { 107 | logger.warn("Exception at fetching.", e); 108 | return null; 109 | } 110 | } 111 | 112 | /** 113 | * Returns an enumeration of URL objects representing all the resources with th given name. 114 | * 115 | * Currently, WebSocketClassLoader returns only the first element. 116 | * 117 | * @param name The name of a resource. 118 | * @return All founded resources. 119 | */ 120 | @Override 121 | protected Enumeration findResources(String name) { 122 | URL url = findResource(name); 123 | Vector urls = new Vector<>(); 124 | if (url != null) { 125 | urls.add(url); 126 | } 127 | return urls.elements(); 128 | } 129 | 130 | 131 | @Override 132 | protected Class loadClass(String className, boolean resolve) 133 | throws ClassNotFoundException { 134 | synchronized (getClassLoadingLock(className)) { 135 | Class clazz = findLoadedClass(className); 136 | if (clazz == null) { 137 | try { 138 | clazz = getParent().loadClass(className); 139 | } catch (ClassNotFoundException ignored) { 140 | } 141 | if (clazz == null) 142 | clazz = findClass(className); 143 | } 144 | if (resolve) { 145 | resolveClass(clazz); 146 | } 147 | return clazz; 148 | } 149 | } 150 | 151 | @Override 152 | protected Class findClass(String className) throws ClassNotFoundException { 153 | return defineClass(className); 154 | } 155 | private Class defineClass(String className) 156 | throws ClassNotFoundException { 157 | String path = className.replace('.', '/').concat(".class"); 158 | URL url = findResource(path); 159 | if (url == null) 160 | throw new ClassNotFoundException(className); 161 | 162 | try { 163 | URLConnection connection = url.openConnection(); 164 | byte[] bytes = IOUtils.slurp(connection.getContent()); 165 | if (bytes != null) { 166 | int idx = className.lastIndexOf("."); 167 | if (idx > 0) { 168 | String packageName = className.substring(0, idx); 169 | Package pkg = getPackage(packageName); 170 | if (pkg == null) { 171 | definePackage(packageName, null, null, null, null, null, null, null); 172 | } 173 | } 174 | return defineClass(className, bytes, 0, bytes.length); 175 | } else { 176 | throw new ClassNotFoundException(className); 177 | } 178 | } catch (Exception ex) { 179 | throw new ClassNotFoundException(className, ex); 180 | } 181 | } 182 | 183 | @Override 184 | public void finalize() throws Throwable{ 185 | try { 186 | dispose(); 187 | } finally { 188 | super.finalize(); 189 | } 190 | } 191 | 192 | public void dispose() throws IOException { 193 | endpoint.close(); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/WebSocketURLConnection.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import net.unit8.wscl.dto.ResourceResponse; 5 | import net.unit8.wscl.util.IOUtils; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.ByteArrayInputStream; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.net.URL; 14 | import java.net.URLConnection; 15 | import java.util.UUID; 16 | 17 | /** 18 | * @author kawasima 19 | */ 20 | public class WebSocketURLConnection extends URLConnection { 21 | private static final Logger logger = LoggerFactory.getLogger(WebSocketURLConnection.class); 22 | private final ClassLoaderEndpoint endpoint; 23 | private final File cacheDirectory; 24 | private UUID classLoaderId; 25 | 26 | public WebSocketURLConnection(URL url, ClassLoaderEndpoint endpoint, File cacheDirectory, UUID classLoaderId) { 27 | super(url); 28 | this.endpoint = endpoint; 29 | this.cacheDirectory = cacheDirectory; 30 | this.classLoaderId = classLoaderId; 31 | } 32 | 33 | @Override 34 | public void connect() { 35 | // Do nothing. 36 | } 37 | 38 | private String getResourcePath() { 39 | String path = getURL().getPath(); 40 | if (path.startsWith("/")) { 41 | return path.substring(1); 42 | } else { 43 | return path; 44 | } 45 | } 46 | 47 | private ResourceResponse doRequest(ResourceRequest request) throws IOException { 48 | if (classLoaderId != null) { 49 | request.setClassLoaderId(classLoaderId); 50 | } 51 | ResourceResponse response = endpoint.request(request); 52 | if (cacheDirectory != null && !request.isCheckOnly()) { 53 | IOUtils.spitQuietly( 54 | new File(cacheDirectory, url.getPath()), 55 | response.getBytes()); 56 | } 57 | return response; 58 | } 59 | 60 | protected byte[] getResourceDigest() throws IOException { 61 | String resourcePath = getResourcePath(); 62 | ResourceResponse response = doRequest(new ResourceRequest(resourcePath, true)); 63 | return response.getDigest(); 64 | } 65 | 66 | @Override 67 | public InputStream getInputStream() { 68 | if (!"ws".equalsIgnoreCase(getURL().getProtocol())) { 69 | try { 70 | return getURL().openStream(); 71 | } catch (IOException ex) { 72 | return null; 73 | } 74 | } 75 | String resourcePath = getResourcePath(); 76 | try { 77 | ResourceResponse response = doRequest(new ResourceRequest(resourcePath)); 78 | if (response.getBytes() != null) { 79 | return new ByteArrayInputStream(response.getBytes()); 80 | } else { 81 | return null; 82 | } 83 | } catch (IOException ex) { 84 | logger.debug("Can't retrieve resources.", ex); 85 | return null; 86 | } 87 | } 88 | 89 | @Override 90 | public Object getContent() { 91 | if (!"ws".equalsIgnoreCase(getURL().getProtocol())) { 92 | return IOUtils.slurpQuietly(getURL()); 93 | } 94 | String resourcePath = getResourcePath(); 95 | try { 96 | ResourceResponse response = doRequest(new ResourceRequest(resourcePath)); 97 | return response.getBytes(); 98 | } catch (IOException ex) { 99 | logger.debug("Can't retrieve resources.", ex); 100 | return null; 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/WebSocketURLStreamHandler.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URL; 6 | import java.net.URLConnection; 7 | import java.net.URLStreamHandler; 8 | import java.util.UUID; 9 | 10 | /** 11 | * @author kawasima 12 | */ 13 | public class WebSocketURLStreamHandler extends URLStreamHandler{ 14 | private final ClassLoaderEndpoint endpoint; 15 | private final File cacheDirectory; 16 | private UUID classLoaderId; 17 | 18 | public WebSocketURLStreamHandler(ClassLoaderEndpoint endpoint, File cacheDirectory) { 19 | this.endpoint = endpoint; 20 | this.cacheDirectory = cacheDirectory; 21 | } 22 | 23 | @Override 24 | protected URLConnection openConnection(URL url) throws IOException { 25 | return new WebSocketURLConnection(url, endpoint, cacheDirectory, classLoaderId); 26 | } 27 | 28 | public void setClassLoaderId(String classLoaderId) { 29 | this.classLoaderId = UUID.fromString(classLoaderId); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/dto/ResourceRequest.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.dto; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Request for loading a resource. 7 | * 8 | * @author kawasima 9 | */ 10 | public class ResourceRequest { 11 | private String resourceName; 12 | private UUID classLoaderId; 13 | private Boolean checkOnly = false; 14 | 15 | public ResourceRequest(String resourceName) { 16 | this.resourceName = resourceName; 17 | } 18 | 19 | public ResourceRequest(String resourceName, Boolean checkOnly) { 20 | this(resourceName); 21 | this.checkOnly = checkOnly; 22 | } 23 | 24 | public String getResourceName() { 25 | return resourceName; 26 | } 27 | 28 | public void setResourceName(String resourceName) { 29 | this.resourceName = resourceName; 30 | } 31 | 32 | public boolean isCheckOnly() { 33 | return checkOnly; 34 | } 35 | 36 | public UUID getClassLoaderId() { 37 | return classLoaderId; 38 | } 39 | 40 | public void setClassLoaderId(UUID classLoaderId) { 41 | this.classLoaderId = classLoaderId; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/dto/ResourceResponse.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.dto; 2 | 3 | /** 4 | * Response for loading a resource. 5 | * 6 | * @author kawasima 7 | */ 8 | public class ResourceResponse { 9 | private String resourceName; 10 | private byte[] bytes; 11 | private byte[] digest; 12 | 13 | public ResourceResponse(String resourceName) { 14 | this.resourceName = resourceName; 15 | this.digest = null; 16 | } 17 | 18 | public ResourceResponse(String resourceName, byte[] bytes, byte[] digest) { 19 | this(resourceName); 20 | this.bytes = bytes; 21 | this.digest = digest; 22 | } 23 | 24 | 25 | public byte[] getDigest() { 26 | return digest; 27 | } 28 | 29 | public void setDigest(byte[] digest) { 30 | this.digest = digest; 31 | } 32 | 33 | public String getResourceName() { 34 | return resourceName; 35 | } 36 | 37 | public void setResourceName(String resourceName) { 38 | this.resourceName = resourceName; 39 | } 40 | 41 | public byte[] getBytes() { 42 | return bytes; 43 | } 44 | 45 | public void setBytes(byte[] bytes) { 46 | this.bytes = bytes; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/handler/ResourceRequestReadHandler.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.handler; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import org.fressian.Reader; 5 | import org.fressian.handlers.ReadHandler; 6 | 7 | import java.io.IOException; 8 | import java.util.UUID; 9 | 10 | /** 11 | * ReadHandler for ResourceRequest 12 | * 13 | * @author kawasima 14 | */ 15 | public class ResourceRequestReadHandler implements ReadHandler { 16 | @Override 17 | public Object read(Reader r, Object tag, int componentCount) throws IOException { 18 | assert(componentCount == 3); 19 | ResourceRequest req = new ResourceRequest((String)r.readObject(), r.readBoolean()); 20 | Object uuid = r.readObject(); 21 | if (uuid != null && uuid instanceof UUID) { 22 | req.setClassLoaderId((UUID) uuid); 23 | } 24 | return req; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/handler/ResourceRequestWriteHandler.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.handler; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import org.fressian.Writer; 5 | import org.fressian.handlers.WriteHandler; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * WriteHandler for ResourceRequest 11 | * 12 | * @author kawasima 13 | */ 14 | public class ResourceRequestWriteHandler implements WriteHandler{ 15 | @Override 16 | public void write(Writer w, Object instance) throws IOException { 17 | w.writeTag(ResourceRequest.class.getName(), 3); 18 | ResourceRequest request = (ResourceRequest) instance; 19 | w.writeObject(request.getResourceName()); 20 | w.writeBoolean(request.isCheckOnly()); 21 | w.writeObject(request.getClassLoaderId()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/handler/ResourceResponseReadHandler.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.handler; 2 | 3 | import net.unit8.wscl.dto.ResourceResponse; 4 | import org.fressian.Reader; 5 | import org.fressian.handlers.ReadHandler; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * ReadHandler for ResourceResponse 11 | * 12 | * @author kawasima 13 | */ 14 | public class ResourceResponseReadHandler implements ReadHandler { 15 | @Override 16 | public Object read(Reader r, Object tag, int componentCount) throws IOException { 17 | assert(componentCount == 3); 18 | return new ResourceResponse( 19 | (String)r.readObject(), 20 | (byte[])r.readObject(), 21 | (byte[])r.readObject()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/handler/ResourceResponseWriteHandler.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.handler; 2 | 3 | import net.unit8.wscl.dto.ResourceResponse; 4 | import org.fressian.Writer; 5 | import org.fressian.handlers.WriteHandler; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * WriteHandler for ResourceResponse 11 | * 12 | * @author kawasima 13 | */ 14 | public class ResourceResponseWriteHandler implements WriteHandler { 15 | @Override 16 | public void write(Writer w, Object instance) throws IOException { 17 | w.writeTag(ResourceResponse.class.getName(), 3); 18 | ResourceResponse response = (ResourceResponse) instance; 19 | w.writeString(response.getResourceName()); 20 | w.writeBytes(response.getBytes()); 21 | w.writeBytes(response.getDigest()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/util/DigestUtils.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import java.io.*; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | 7 | /** 8 | * Utility for MessageDigest. 9 | * 10 | * @author kawasima 11 | */ 12 | public class DigestUtils { 13 | public static byte[] md5hash(byte[] input) { 14 | try { 15 | MessageDigest digest = MessageDigest.getInstance("MD5"); 16 | return digest.digest(input); 17 | } catch (NoSuchAlgorithmException e) { 18 | throw new IllegalArgumentException("Unknown algorithm: MD5"); 19 | } 20 | } 21 | 22 | public static byte[] md5hash(File input) { 23 | InputStream in = null; 24 | byte[] buf = new byte[4096]; 25 | int n; 26 | try { 27 | MessageDigest digest = MessageDigest.getInstance("MD5"); 28 | in = new BufferedInputStream(new FileInputStream(input)); 29 | while((n = in.read(buf, 0, buf.length)) != -1) { 30 | digest.update(buf, 0, n); 31 | } 32 | return digest.digest(); 33 | } catch (NoSuchAlgorithmException e) { 34 | throw new IllegalArgumentException("Unknown algorithm: MD5"); 35 | } catch (IOException e) { 36 | throw new RuntimeException(String.format("Can't read %s.", input), e); 37 | } finally { 38 | if (in != null) { 39 | try { 40 | in.close(); 41 | } catch (IOException ignore) {} 42 | } 43 | } 44 | } 45 | 46 | private DigestUtils() //class DigestUtils cannot be instantiated. 47 | { 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/util/FressianUtils.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | /** 8 | * Utilities for fressian. 9 | * 10 | * @author kawasima 11 | */ 12 | public class FressianUtils { 13 | @SuppressWarnings("unchecked") 14 | public static Map map(Object... keyvals) { 15 | if (keyvals == null) { 16 | return new HashMap<>(); 17 | } else if (keyvals.length % 2 != 0) { 18 | throw new IllegalArgumentException("Map must have an even number of elements"); 19 | } else { 20 | Map m = new HashMap<>(keyvals.length / 2); 21 | for (int i = 0; i < keyvals.length; i += 2) { 22 | m.put((K)keyvals[i], (V)keyvals[i + 1]); 23 | } 24 | return Collections.unmodifiableMap(m); 25 | } 26 | } 27 | 28 | private FressianUtils() //class FressianUtils cannot be instantiated. 29 | { 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/util/IOUtils.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import java.io.*; 4 | import java.net.URL; 5 | 6 | /** 7 | * Utility for handling I/O. 8 | * 9 | * @author kawasima 10 | */ 11 | public class IOUtils { 12 | public static byte[] slurp(InputStream in) throws IOException { 13 | int n; 14 | ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); 15 | byte[] data = new byte[4096]; 16 | while((n = in.read(data, 0, data.length)) != -1) { 17 | buffer.write(data, 0, n); 18 | } 19 | return buffer.toByteArray(); 20 | 21 | } 22 | 23 | public static byte[] slurp(URL url) throws IOException { 24 | InputStream in = null; 25 | try { 26 | in = url.openStream(); 27 | return slurp(in); 28 | } finally { 29 | closeQuietly(in); 30 | } 31 | } 32 | 33 | public static byte[] slurp(Object obj) throws IOException { 34 | if (obj instanceof InputStream) { 35 | return slurp((InputStream) obj); 36 | } else if (obj instanceof byte[]) { 37 | return (byte[]) obj; 38 | } else { 39 | throw new IllegalArgumentException("Unknown object: " + obj); 40 | } 41 | } 42 | 43 | public static byte[] slurpQuietly(URL url) { 44 | try { 45 | return slurp(url); 46 | } catch (IOException ex) { 47 | return null; 48 | } 49 | } 50 | 51 | public static void spit(File file, byte[] content) throws IOException{ 52 | if(file == null) 53 | throw new FileNotFoundException("null"); 54 | 55 | if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { 56 | throw new IOException("Can't create directory" + file.getParent()); 57 | } 58 | 59 | FileOutputStream out = new FileOutputStream(file); 60 | try { 61 | out.write(content); 62 | } finally { 63 | IOUtils.closeQuietly(out); 64 | } 65 | } 66 | 67 | public static void spitQuietly(File file, byte[] content) { 68 | try { 69 | IOUtils.spit(file, content); 70 | } catch (IOException ignore) { 71 | 72 | } 73 | } 74 | 75 | public static void closeQuietly(Closeable closeable) { 76 | try { 77 | if (closeable != null) 78 | closeable.close(); 79 | } catch (IOException ignore) { 80 | 81 | } 82 | } 83 | 84 | private IOUtils() //class IOUtils cannot be instantiated. 85 | { 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/util/PropertyUtils.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.io.File; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | /** 11 | * The utility for properties. 12 | * 13 | * @author kawasima 14 | */ 15 | public class PropertyUtils { 16 | private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class); 17 | private static final Pattern VAR_PTN = Pattern.compile("\\$\\{([^\\}]+)\\}"); 18 | 19 | private static String replace(String value) { 20 | if (value == null) 21 | return null; 22 | StringBuffer sb = new StringBuffer(256); 23 | Matcher m = VAR_PTN.matcher(value); 24 | while (m.find()) { 25 | String propValue = System.getProperty(m.group(1)); 26 | if (propValue == null) 27 | propValue = ""; 28 | m.appendReplacement(sb, Matcher.quoteReplacement(propValue)); 29 | } 30 | m.appendTail(sb); 31 | return sb.toString(); 32 | } 33 | 34 | public static Long getLongSystemProperty(String name, long defaultValue) { 35 | String longStr = System.getProperty(name); 36 | try { 37 | if (longStr != null) 38 | return Long.parseLong(longStr); 39 | } catch (NumberFormatException ignore) { 40 | 41 | } 42 | return defaultValue; 43 | 44 | } 45 | 46 | 47 | public static File getFileSystemProperty(String name) { 48 | return getFileSystemProperty(name, null); 49 | } 50 | 51 | public static File getFileSystemProperty(String name, File defaultFile) { 52 | String fileStr = replace(System.getProperty(name)); 53 | if (fileStr != null) 54 | return new File(fileStr); 55 | else 56 | return defaultFile; 57 | } 58 | 59 | private PropertyUtils() //class PropertyUtils cannot be instantiated. 60 | { 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/net/unit8/wscl/util/QueryStringDecoder.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * The decoder for query string. 10 | * 11 | * @author kawasima 12 | */ 13 | public class QueryStringDecoder { 14 | private final Map> parameters; 15 | 16 | public QueryStringDecoder(String query) { 17 | parameters = new HashMap<>(16); 18 | if (query != null) { 19 | for (String pairStr : query.split("&")) { 20 | String[] pair = pairStr.split("=", 2); 21 | List values = parameters.get(pair[0]); 22 | if (values == null) { 23 | values = new ArrayList<>(); 24 | parameters.put(pair[0], values); 25 | } 26 | values.add(pair[1]); 27 | } 28 | } 29 | } 30 | 31 | public Map> parameters() { 32 | return parameters; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/net/unit8/wscl/ClassLoaderEndpointTest.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import net.unit8.wscl.dto.ResourceResponse; 5 | import org.fressian.FressianWriter; 6 | import org.fressian.Writer; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import static org.mockito.Matchers.*; 11 | import org.powermock.api.mockito.PowerMockito; 12 | import org.powermock.core.classloader.annotations.PrepareForTest; 13 | import org.powermock.modules.junit4.PowerMockRunner; 14 | 15 | import javax.websocket.RemoteEndpoint; 16 | import javax.websocket.Session; 17 | import java.io.IOException; 18 | import java.lang.reflect.Field; 19 | import java.nio.ByteBuffer; 20 | import java.util.UUID; 21 | import java.util.concurrent.*; 22 | 23 | import static org.hamcrest.CoreMatchers.is; 24 | import static org.junit.Assert.assertThat; 25 | import static org.junit.Assert.fail; 26 | import static org.mockito.Mockito.doReturn; 27 | import static org.mockito.Mockito.mock; 28 | 29 | /** 30 | * @author kawasima 31 | */ 32 | @RunWith(PowerMockRunner.class) 33 | @PrepareForTest({FressianWriter.class, ClassLoaderEndpoint.class}) 34 | public class ClassLoaderEndpointTest { 35 | private ClassLoaderEndpoint cle; 36 | private Session session; 37 | private ResourceRequest resourceRequest; 38 | 39 | @SuppressWarnings("ResultOfMethodCallIgnored") 40 | @Before 41 | public void setup() throws Exception{ 42 | //setup mocks 43 | cle = new ClassLoaderEndpoint(); 44 | session = mock(Session.class); 45 | RemoteEndpoint remoteEndpoint = mock(RemoteEndpoint.Async.class); 46 | doReturn(remoteEndpoint).when(session).getAsyncRemote(); 47 | ((RemoteEndpoint.Async) doReturn(null).when(remoteEndpoint)).sendBinary(any(ByteBuffer.class)); 48 | resourceRequest = mock(ResourceRequest.class); 49 | doReturn(UUID.randomUUID()).when(resourceRequest).getClassLoaderId(); 50 | doReturn("resource1").when(resourceRequest).getResourceName(); 51 | FressianWriter fressianWriter = mock(FressianWriter.class); 52 | doReturn(mock(Writer.class)).when(fressianWriter).writeObject(any(ResourceRequest.class)); 53 | PowerMockito.whenNew(FressianWriter.class).withAnyArguments().thenReturn(fressianWriter); 54 | } 55 | 56 | 57 | private Callable createTask(final ClassLoaderEndpoint cle, final ResourceRequest req) { 58 | return new Callable() { 59 | public String call() throws Exception { 60 | return request(cle, req); 61 | } 62 | }; 63 | } 64 | 65 | @Test 66 | public void oneRequest() throws Exception { 67 | cle.onOpen(session, null); 68 | ExecutorService executor = Executors.newCachedThreadPool(); 69 | Future res = executor.submit(createTask(cle, resourceRequest)); 70 | Field f = cle.getClass().getDeclaredField("waitingResponses"); 71 | f.setAccessible(true); 72 | @SuppressWarnings("unchecked") ConcurrentHashMap> waitingResponse = (ConcurrentHashMap>) f.get(cle); 73 | Thread.sleep(1000); 74 | BlockingQueue queue = waitingResponse.get("resource1"); 75 | queue.offer(new ResourceResponse("resource name1")); 76 | assertThat(res.get(1500, TimeUnit.MILLISECONDS),is("resource name1")); 77 | } 78 | 79 | @Test 80 | public void twoRequestAtTheSameTime() throws Exception { 81 | cle.onOpen(session, null); 82 | ExecutorService executor = Executors.newCachedThreadPool(); 83 | Future res1 = executor.submit(createTask(cle, resourceRequest)); 84 | Future res2 = executor.submit(createTask(cle, resourceRequest)); 85 | 86 | Field f = cle.getClass().getDeclaredField("waitingResponses"); 87 | f.setAccessible(true); 88 | @SuppressWarnings("unchecked") ConcurrentHashMap> waitingResponse = (ConcurrentHashMap>) f.get(cle); 89 | Thread.sleep(1000); 90 | BlockingQueue queue = waitingResponse.get("resource1"); 91 | queue.offer(new ResourceResponse("resource name1")); 92 | queue.offer(new ResourceResponse("resource name1")); 93 | assertThat(res1.get(),is("resource name1")); 94 | assertThat(res2.get(),is("resource name1")); 95 | } 96 | 97 | String request(ClassLoaderEndpoint cle, ResourceRequest resourceRequest){ 98 | try { 99 | return cle.request(resourceRequest).getResourceName(); 100 | } catch (IOException e) { 101 | fail(); 102 | } 103 | return null; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/java/net/unit8/wscl/ClassProviderStarter.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl; 2 | 3 | import io.undertow.Undertow; 4 | import io.undertow.servlet.Servlets; 5 | import io.undertow.servlet.api.DeploymentManager; 6 | import io.undertow.websockets.jsr.WebSocketDeploymentInfo; 7 | import org.xnio.OptionMap; 8 | import org.xnio.Xnio; 9 | import org.xnio.XnioWorker; 10 | 11 | import javax.servlet.ServletException; 12 | import java.io.IOException; 13 | 14 | /** 15 | * The bootstrap for ClassProvider. 16 | * 17 | * @author kawasima 18 | */ 19 | public class ClassProviderStarter { 20 | public static void main(String[] args) throws IOException, ServletException { 21 | final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader()); 22 | final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap()); 23 | final WebSocketDeploymentInfo webSockets = new WebSocketDeploymentInfo() 24 | .addEndpoint(ClassProvider.class) 25 | .setWorker(xnioWorker); 26 | final DeploymentManager deploymentManager = Servlets.defaultContainer() 27 | .addDeployment(Servlets.deployment() 28 | .setClassLoader(ClassProviderStarter.class.getClassLoader()) 29 | .setContextPath("/") 30 | .setDeploymentName("class-provider") 31 | .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSockets)); 32 | 33 | deploymentManager.deploy(); 34 | //noinspection deprecation 35 | Undertow.builder() 36 | .addListener(5000, "localhost") 37 | .setHandler(deploymentManager.start()) 38 | .build() 39 | .start(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/net/unit8/wscl/handler/ResourceRequestWriteHandlerTest.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.handler; 2 | 3 | import net.unit8.wscl.dto.ResourceRequest; 4 | import net.unit8.wscl.util.FressianUtils; 5 | import org.fressian.FressianReader; 6 | import org.fressian.FressianWriter; 7 | import org.fressian.handlers.ILookup; 8 | import org.fressian.handlers.ReadHandler; 9 | import org.fressian.handlers.WriteHandler; 10 | import org.junit.Assert; 11 | import org.junit.Test; 12 | 13 | import java.io.ByteArrayInputStream; 14 | import java.io.ByteArrayOutputStream; 15 | import java.io.IOException; 16 | import java.util.Map; 17 | import java.util.UUID; 18 | 19 | /** 20 | * Tests for ResourceRequestWriteHandler. 21 | * 22 | * @author kawasima 23 | */ 24 | public class ResourceRequestWriteHandlerTest { 25 | @Test 26 | public void test() throws IOException { 27 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 28 | ResourceRequest req = new ResourceRequest("hoge"); 29 | UUID uuid = UUID.randomUUID(); 30 | req.setClassLoaderId(uuid); 31 | FressianWriter fw = new FressianWriter(baos, new ILookup>() { 32 | @Override 33 | public Map valAt(Class key) { 34 | if (key.equals(ResourceRequest.class)) { 35 | return FressianUtils.map(ResourceRequest.class.getName(), 36 | new ResourceRequestWriteHandler()); 37 | } else { 38 | return null; 39 | } 40 | 41 | } 42 | }); 43 | fw.writeObject(req); 44 | FressianReader fr = new FressianReader(new ByteArrayInputStream(baos.toByteArray()), 45 | new ILookup() { 46 | @Override 47 | public ReadHandler valAt(Object key) { 48 | if (key.equals(ResourceRequest.class.getName())) 49 | return new ResourceRequestReadHandler(); 50 | else 51 | return null; 52 | } 53 | }); 54 | ResourceRequest restoredReq = (ResourceRequest) fr.readObject(); 55 | Assert.assertEquals(uuid, restoredReq.getClassLoaderId()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/net/unit8/wscl/util/PropertyUtilsTest.java: -------------------------------------------------------------------------------- 1 | package net.unit8.wscl.util; 2 | 3 | import org.junit.After; 4 | import org.junit.Assert; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | import java.io.File; 9 | 10 | /** 11 | * Tests for PropertyUtils 12 | * 13 | * @author kawasima 14 | */ 15 | public class PropertyUtilsTest { 16 | @Before 17 | public void setUp() { 18 | System.setProperty("wscl.home", "/hoge/fuga"); 19 | System.setProperty("wscl.home2", "${wscl.home}/piyo"); 20 | } 21 | @Test 22 | public void test() { 23 | Assert.assertEquals(new File("/hoge/fuga/piyo"), 24 | PropertyUtils.getFileSystemProperty("wscl.home2")); 25 | } 26 | 27 | @After 28 | public void tearDown() { 29 | System.clearProperty("wscl.home"); 30 | System.clearProperty("wscl.home2"); 31 | } 32 | 33 | } 34 | --------------------------------------------------------------------------------