├── .gitignore ├── LICENSE ├── README.md ├── completable-future-demo ├── .gitignore └── src │ └── org │ └── iproduct │ └── cfdemo │ ├── CompletableFutureComposition.java │ ├── CompletableFutureCompositionTimeout.java │ ├── CompletableFutureCompositionTimeoutJava9.java │ ├── CompletableFutureDelayedStream.java │ ├── CompletableFutureStream.java │ ├── Currency.java │ ├── Price.java │ └── SimpleTaskStream.java ├── completable-future-jaxrs-cdi-cxf ├── README.md ├── myannotation.jar ├── pom.xml └── src │ └── main │ ├── java │ └── org │ │ └── iproduct │ │ ├── demo │ │ └── profiler │ │ │ ├── cdi │ │ │ └── qualifiers │ │ │ │ └── CpuProfiling.java │ │ │ └── server │ │ │ ├── ProfilerStreamingServer.java │ │ │ ├── app │ │ │ └── ProfilerApplication.java │ │ │ ├── model │ │ │ ├── CpuLoad.java │ │ │ └── ProcessInfo.java │ │ │ ├── resources │ │ │ ├── ProcessesRestResource.java │ │ │ ├── StatsRestResource.java │ │ │ └── StatsRestResourceRxJava2.java │ │ │ ├── service │ │ │ └── Profiler.java │ │ │ └── utility │ │ │ └── LoadCPU.java │ │ └── flow │ │ ├── FlowSubscriber.java │ │ ├── HotPublisher.java │ │ └── IntervalPublisher.java │ └── resources │ ├── META-INF │ ├── beans-old.xml │ ├── beans.xml │ ├── cxf │ │ └── org.apache.cxf.Logger │ └── log4j.properties │ └── web-ui │ ├── index.html │ └── javascripts │ ├── highcharts.js │ └── jquery-1.9.0.min.js ├── completable-future-jaxrs-cdi-jersey-client ├── README.md ├── myannotation.jar ├── pom.xml └── src │ └── main │ ├── java │ └── org │ │ └── iproduct │ │ └── demo │ │ └── profiler │ │ └── client │ │ ├── ProfilerAppClient.java │ │ └── model │ │ ├── CpuLoad.java │ │ └── ProcessInfo.java │ └── resources │ └── META-INF │ ├── beans.xml │ └── log4j.properties ├── completable-future-jaxrs-cdi-jersey ├── README.md ├── myannotation.jar ├── pom.xml └── src │ └── main │ ├── java │ └── org │ │ └── iproduct │ │ ├── demo │ │ └── profiler │ │ │ ├── cdi │ │ │ └── qualifiers │ │ │ │ └── CpuProfiling.java │ │ │ └── server │ │ │ ├── ProfilerStreamingServer.java │ │ │ ├── app │ │ │ └── ProfilerApplication.java │ │ │ ├── model │ │ │ ├── CpuLoad.java │ │ │ └── ProcessInfo.java │ │ │ ├── resources │ │ │ ├── ProcessesRestResource.java │ │ │ ├── StatsRestResource.java │ │ │ └── StatsRestResourceRxJava2.java │ │ │ ├── service │ │ │ └── Profiler.java │ │ │ └── utility │ │ │ └── LoadCPU.java │ │ └── flow │ │ ├── FlowSubscriber.java │ │ ├── HotPublisher.java │ │ └── IntervalPublisher.java │ └── resources │ ├── META-INF │ ├── beans.xml │ └── log4j.properties │ └── web-ui │ ├── index.html │ └── javascripts │ ├── highcharts.js │ └── jquery-1.9.0.min.js ├── flow-demo ├── .gitignore └── src │ └── org │ └── iproduct │ └── flowdemo │ ├── CompletableFutureFromPublisher.java │ ├── CompletableFuturePublisher.java │ ├── FlowProcessor.java │ ├── FlowSubscriber.java │ └── ScheduledFuturePublisher.java ├── http2-client ├── .gitignore ├── lib │ └── gson.jar └── src │ ├── module-info.java │ └── org │ └── iproduct │ └── demo │ └── profiler │ └── client │ ├── ProfilerAppClient.java │ └── model │ ├── CpuLoad.java │ └── ProcessInfo.java ├── modularity-demo-intellij ├── client │ └── src │ │ ├── client │ │ └── HelloModularityClient.java │ │ └── module-info.java ├── lib │ └── java-modularity-demo.jar ├── out │ └── production │ │ ├── client │ │ ├── client │ │ │ └── HelloModularityClient.class │ │ └── module-info.class │ │ ├── provider │ │ ├── module-info.class │ │ └── provider │ │ │ ├── MessageProvider.class │ │ │ └── impl │ │ │ └── HelloWorldMessageProvider.class │ │ └── renderer │ │ ├── module-info.class │ │ └── renderer │ │ ├── MessageRenderer.class │ │ └── impl │ │ └── StandardOutMessageRenderer.class ├── provider │ └── src │ │ ├── module-info.java │ │ └── provider │ │ ├── MessageProvider.java │ │ └── impl │ │ └── HelloWorldMessageProvider.java └── renderer │ └── src │ ├── module-info.java │ └── renderer │ ├── MessageRenderer.java │ └── impl │ └── StandardOutMessageRenderer.java ├── modularity-demo ├── client │ ├── bin │ │ ├── client │ │ │ └── HelloModularityClient.class │ │ └── module-info.class │ └── src │ │ ├── client │ │ └── HelloModularityClient.java │ │ └── module-info.java ├── modules │ ├── client.jar │ ├── provider.jar │ └── renderer.jar ├── provider │ ├── bin │ │ ├── module-info.class │ │ └── provider │ │ │ ├── MessageProvider.class │ │ │ └── impl │ │ │ └── HelloWorldMessageProvider.class │ └── src │ │ ├── module-info.java │ │ └── provider │ │ ├── MessageProvider.java │ │ └── impl │ │ └── HelloWorldMessageProvider.java └── renderer │ ├── bin │ ├── module-info.class │ └── renderer │ │ ├── MessageRenderer.class │ │ └── impl │ │ └── StandardOutMessageRenderer.class │ └── src │ ├── module-info.java │ └── renderer │ ├── MessageRenderer.java │ └── impl │ └── StandardOutMessageRenderer.java └── rxjava2-demo ├── pom.xml └── src └── main └── java └── org └── iproduct └── rxjava ├── HelloInterval.java ├── HelloIntervalHot.java └── HelloRxJava.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .mvn/ 3 | *.iml 4 | *.ipr 5 | *.iws 6 | .DS_Store 7 | .checkstyle 8 | .classpath 9 | .ekstazi 10 | .pmd 11 | .pmdruleset 12 | .pmdruleset.xml 13 | .project 14 | .ruleset 15 | .settings/ 16 | target/ 17 | velocity.log 18 | /bin/ 19 | node_modules/ 20 | derby.log 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # reactive-demos-java-9 2 | Stream processieng with Java 9 - Flow and Completable Future 3 | 4 | Applications with Java EE 8 - JAX-RS 2.1 (SSE, Client), CDI 2.0 (fireAsync - ObserveAsync) 5 | 6 | -------------------------------------------------------------------------------- /completable-future-demo/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .mvn/ 3 | *.iml 4 | *.ipr 5 | *.iws 6 | .DS_Store 7 | .checkstyle 8 | .classpath 9 | .ekstazi 10 | .pmd 11 | .pmdruleset 12 | .pmdruleset.xml 13 | .project 14 | .ruleset 15 | .settings/ 16 | target/ 17 | velocity.log 18 | /bin/ 19 | node_modules/ 20 | derby.log 21 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/CompletableFutureComposition.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import static org.iproduct.cfdemo.Currency.*; 4 | 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.concurrent.ExecutionException; 7 | 8 | public class CompletableFutureComposition { 9 | 10 | public void testlCompletableFutureComposition() throws InterruptedException, ExecutionException { 11 | Double priceInEuro = CompletableFuture.supplyAsync(() -> getStockPrice("GOOGL")) 12 | .thenCombine(CompletableFuture.supplyAsync(() -> getExchangeRate(USD, EUR)), this::convertPrice) 13 | .exceptionally(throwable -> { 14 | System.out.println("Error: " + throwable.getMessage()); 15 | return -1d; 16 | }).get(); 17 | 18 | System.out.println("GOOGL stock price in Euro: " + priceInEuro ); 19 | } 20 | 21 | public Price getStockPrice(String stockSymbol) { 22 | switch (stockSymbol) { 23 | case "GOOGL" : return new Price(950.28, USD); 24 | case "AAPL" : return new Price(148.96, USD); 25 | case "MSFT" : return new Price(69.00, USD); 26 | case "FB" : return new Price(150.24, USD); 27 | default: 28 | throw new RuntimeException("Stocks symbol not found."); 29 | } 30 | } 31 | 32 | public Double getExchangeRate(Currency from, Currency to) { 33 | if(from.equals(USD) && to.equals(EUR)) { 34 | return 1.11815d; 35 | } 36 | throw new RuntimeException("Exchange rate not available."); 37 | } 38 | 39 | public Double convertPrice(Price price, Double exchangeRate) { 40 | return price.getAmount() * exchangeRate; 41 | } 42 | 43 | 44 | public static void main(String[] args) throws InterruptedException, ExecutionException { 45 | CompletableFutureComposition demo = new CompletableFutureComposition(); 46 | demo.testlCompletableFutureComposition(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/CompletableFutureCompositionTimeout.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import static org.iproduct.cfdemo.Currency.*; 4 | 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.concurrent.CompletionStage; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.ScheduledExecutorService; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.TimeoutException; 11 | 12 | public class CompletableFutureCompositionTimeout { 13 | private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 14 | 15 | public void testlCompletableFutureComposition() { 16 | CompletableFuture.supplyAsync(() -> getStockPrice("GOOGL")) 17 | .thenCombine(CompletableFuture.supplyAsync(() -> getExchangeRate(USD, EUR)), this::convertPrice) 18 | .applyToEither(scheduleTimeout(scheduler, 1, TimeUnit.SECONDS), p -> p) 19 | .exceptionally(throwable -> { 20 | System.out.println("Error: " + throwable.getMessage()); 21 | return -1d; 22 | }).whenComplete((price, throwable) -> { 23 | if (price > 0) 24 | System.out.println("GOOGL stock price in Euro: " + price); 25 | else 26 | System.out.println("Timeout: Service took too long to respond."); 27 | }).join(); 28 | scheduler.shutdownNow(); 29 | } 30 | 31 | public Price getStockPrice(String stockSymbol) { 32 | //Simulate long running task 33 | try { 34 | Thread.sleep(1100); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } 38 | switch (stockSymbol) { 39 | case "GOOGL": 40 | return new Price(950.28, USD); 41 | case "AAPL": 42 | return new Price(148.96, USD); 43 | case "MSFT": 44 | return new Price(69.00, USD); 45 | case "FB": 46 | return new Price(150.24, USD); 47 | default: 48 | throw new RuntimeException("Stocks symbol not found."); 49 | } 50 | } 51 | 52 | public Double getExchangeRate(Currency from, Currency to) { 53 | if (from.equals(USD) && to.equals(EUR)) { 54 | return 1.11815d; 55 | } 56 | throw new RuntimeException("Exchange rate not available."); 57 | } 58 | 59 | public Double convertPrice(Price price, Double exchangeRate) { 60 | return price.getAmount() * exchangeRate; 61 | } 62 | 63 | public CompletionStage scheduleTimeout(ScheduledExecutorService scheduler, long delay, TimeUnit unit) { 64 | CompletableFuture future = new CompletableFuture<>(); 65 | scheduler.schedule(() -> { 66 | future.completeExceptionally(new TimeoutException(String.format("Timeout after %s %s", delay, unit))); 67 | }, delay, unit); 68 | return future; 69 | } 70 | 71 | public static void main(String[] args) { 72 | CompletableFutureCompositionTimeout demo = new CompletableFutureCompositionTimeout(); 73 | demo.testlCompletableFutureComposition(); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/CompletableFutureCompositionTimeoutJava9.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import static org.iproduct.cfdemo.Currency.BGN; 4 | import static org.iproduct.cfdemo.Currency.EUR; 5 | import static org.iproduct.cfdemo.Currency.USD; 6 | 7 | import java.util.concurrent.CompletableFuture; 8 | import java.util.concurrent.CompletionStage; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.ScheduledExecutorService; 11 | import java.util.concurrent.TimeUnit; 12 | import java.util.concurrent.TimeoutException; 13 | import java.util.function.Function; 14 | 15 | public class CompletableFutureCompositionTimeoutJava9 { 16 | private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 17 | 18 | public void testlCompletableFutureComposition() { 19 | CompletableFuture.supplyAsync(() -> getStockPrice("GOOGL")) 20 | .thenCombine(CompletableFuture.supplyAsync(() -> getExchangeRate(USD, EUR)), this::convertPrice) 21 | .orTimeout(1, TimeUnit.SECONDS) 22 | .exceptionally(throwable -> { 23 | System.out.println("Error: " + throwable.getMessage()); 24 | return -1d; 25 | }).whenComplete((price, throwable) -> { 26 | if (price > 0) 27 | System.out.println("GOOGL stock price in Euro: " + price); 28 | else 29 | System.out.println("Timeout: Service took too long to respond."); 30 | }).join(); 31 | } 32 | 33 | public Price getStockPrice(String stockSymbol) { 34 | //Simulate long running task 35 | try { 36 | Thread.sleep(900); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | switch (stockSymbol) { 41 | case "GOOGL": 42 | return new Price(950.28, USD); 43 | case "AAPL": 44 | return new Price(148.96, USD); 45 | case "MSFT": 46 | return new Price(69.00, USD); 47 | case "FB": 48 | return new Price(150.24, USD); 49 | default: 50 | throw new RuntimeException("Stocks symbol not found."); 51 | } 52 | } 53 | 54 | public Double getExchangeRate(Currency from, Currency to) { 55 | if (from.equals(USD) && to.equals(EUR)) { 56 | return 1.11815d; 57 | } 58 | throw new RuntimeException("Exchange rate not available."); 59 | } 60 | 61 | public Double convertPrice(Price price, Double exchangeRate) { 62 | return price.getAmount() * exchangeRate; 63 | } 64 | 65 | public static void main(String[] args) { 66 | CompletableFutureCompositionTimeoutJava9 demo = new CompletableFutureCompositionTimeoutJava9(); 67 | demo.testlCompletableFutureComposition(); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/CompletableFutureDelayedStream.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CompletableFuture; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.Executor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | import java.util.stream.Collectors; 10 | import java.util.stream.IntStream; 11 | 12 | public class CompletableFutureDelayedStream { 13 | // private ExecutorService executor = ForkJoinPool.commonPool(); 14 | 15 | // private ExecutorService executor = Executors.newCachedThreadPool(); 16 | 17 | public void testlCompletableFutureSequence() { 18 | List> futuresList = IntStream.range(0, 20) 19 | .boxed() 20 | .map(i -> 21 | completableFutureTask(i, CompletableFuture.delayedExecutor(i, TimeUnit.SECONDS)) 22 | .exceptionally(t -> t.getMessage()) 23 | .whenComplete((result, exception) -> { 24 | System.out.println(result); 25 | }) 26 | ).collect(Collectors.toList()); 27 | 28 | CompletableFuture> results = CompletableFuture.allOf(futuresList.toArray(new CompletableFuture[0])) 29 | .thenApply(v -> futuresList.stream() 30 | .map(CompletableFuture::join) 31 | .collect(Collectors.toList()) 32 | ); 33 | System.out.println(results.join()); 34 | } 35 | 36 | private CompletableFuture completableFutureTask(int i, Executor executor) { 37 | 38 | return CompletableFuture.supplyAsync(() -> { 39 | // try { 40 | // Thread.sleep(1000); 41 | // } catch (InterruptedException e) { 42 | // e.printStackTrace(); 43 | // } 44 | // if (i == 13) { 45 | // throw new RuntimeException("Exception - result can not be 13!"); 46 | // } 47 | return i + "-" + "test"; 48 | }, executor); 49 | } 50 | 51 | public static void main(String[] args) { 52 | CompletableFutureDelayedStream cfStream = new CompletableFutureDelayedStream(); 53 | cfStream.testlCompletableFutureSequence(); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/CompletableFutureStream.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CompletableFuture; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.Executor; 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.ForkJoinPool; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.TimeoutException; 11 | import java.util.stream.Collectors; 12 | import java.util.stream.IntStream; 13 | 14 | public class CompletableFutureStream { 15 | private ExecutorService executor = ForkJoinPool.commonPool(); 16 | 17 | // private ExecutorService executor = Executors.newCachedThreadPool(); 18 | 19 | public void testlCompletableFutureSequence() { 20 | List> futuresList = IntStream.range(0, 20) 21 | .boxed() 22 | .map(i -> longCompletableFutureTask(i, executor).exceptionally(t -> t.getMessage())) 23 | .collect(Collectors.toList()); 24 | 25 | CompletableFuture> results = CompletableFuture.allOf(futuresList.toArray(new CompletableFuture[0])) 26 | .thenApply(v -> futuresList.stream() 27 | .map(CompletableFuture::join) 28 | .collect(Collectors.toList()) 29 | ); 30 | // try { 31 | // System.out.println(results.get(10, TimeUnit.SECONDS)); 32 | // } catch (ExecutionException e) { 33 | // e.printStackTrace(); 34 | // } catch (TimeoutException e) { 35 | // e.printStackTrace(); 36 | // } catch (InterruptedException e) { 37 | // e.printStackTrace(); 38 | // } 39 | System.out.println(results.join()); 40 | executor.shutdown(); 41 | } 42 | 43 | private CompletableFuture longCompletableFutureTask(int i, Executor executor) { 44 | 45 | return CompletableFuture.supplyAsync(() -> { 46 | try { 47 | Thread.sleep(1000); 48 | } catch (InterruptedException e) { 49 | e.printStackTrace(); 50 | } 51 | if (i == 13) { 52 | throw new RuntimeException("Exception - result can not be 13!"); 53 | } 54 | return i + "-" + "test"; 55 | }, executor); 56 | } 57 | 58 | public static void main(String[] args) { 59 | CompletableFutureStream cfStream = new CompletableFutureStream(); 60 | cfStream.testlCompletableFutureSequence(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/Currency.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | public enum Currency { 4 | BGN, GBP, EUR, USD 5 | } 6 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/Price.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | public class Price { 4 | private Double amount; 5 | private Currency currency; 6 | public Price(Double amount, Currency currency) { 7 | super(); 8 | this.amount = amount; 9 | this.currency = currency; 10 | } 11 | public Double getAmount() { 12 | return amount; 13 | } 14 | public void setAmount(Double amount) { 15 | this.amount = amount; 16 | } 17 | public Currency getCurrency() { 18 | return currency; 19 | } 20 | public void setCurrency(Currency currency) { 21 | this.currency = currency; 22 | } 23 | 24 | public String toString() { 25 | return amount + " " + currency; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /completable-future-demo/src/org/iproduct/cfdemo/SimpleTaskStream.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.cfdemo; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.IntStream; 6 | 7 | public class SimpleTaskStream { 8 | 9 | public void testTaskSequence() { 10 | List results = IntStream.range(0, 20) 11 | .boxed() 12 | .map(this::longTask) 13 | .collect(Collectors.toList()); 14 | System.out.println(results); 15 | } 16 | 17 | private String longTask(int i) { 18 | //Simulate long running task 19 | try { 20 | Thread.sleep(1000); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | return "result-" + i; 25 | } 26 | 27 | public static void main(String[] args) { 28 | SimpleTaskStream sStream = new SimpleTaskStream(); 29 | sStream.testTaskSequence(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/README.md: -------------------------------------------------------------------------------- 1 | # CompletableFuture with JAX-RS 2.1 CDI 2.0 (Java 9 + Java EE 8) Demo 2 | 3 | For this demo you need installed latest Java 9 JDK. 4 | 5 | Follow next steps to start the server: 6 | 7 | 1. Run `mvn install` in project's main folder 8 | 9 | 2. Run `org.iproduct.demo.profiler.StreamingServer` with following VM arguments: 10 | ``` 11 | --add-modules=java.se.ee --patch-module java.xml.ws.annotation=./myannotation.jar 12 | ``` 13 | 14 | 3. Open http://localhost:8080/javacpu/ 15 | 16 | Enjoy! -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/myannotation.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/completable-future-jaxrs-cdi-cxf/myannotation.jar -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | ipt-demos 5 | completable-future-jaxrs-cdi-cxf 6 | 0.0.1 7 | 8 | 9 | UTF-8 10 | 9.3.5.v20151012 11 | 12 | 13 | 14 | 15 | my-repo1 16 | CFX repository 17 | 18 | https://repository.apache.org/content/groups/snapshots/ 19 | 20 | 21 | 22 | 23 | 24 | javax.enterprise 25 | cdi-api 26 | 2.0 27 | 28 | 29 | 30 | org.apache.cxf 31 | cxf-integration-cdi 32 | 3.2.1 33 | 34 | 35 | 36 | org.apache.cxf 37 | cxf-rt-frontend-jaxrs 38 | 3.2.1 39 | 40 | 41 | 42 | org.apache.cxf 43 | cxf-rt-rs-sse 44 | 3.2.1 45 | 46 | 47 | 48 | org.apache.cxf 49 | cxf-rt-rs-client 50 | 3.2.1 51 | 52 | 53 | 54 | com.fasterxml.jackson.jaxrs 55 | jackson-jaxrs-json-provider 56 | 2.8.8 57 | 58 | 59 | 60 | com.fasterxml.jackson.core 61 | jackson-core 62 | 2.8.8 63 | 64 | 65 | 66 | 67 | org.jboss.weld.servlet 68 | weld-servlet-core 69 | 3.0.1.Final 70 | 71 | 72 | 73 | org.eclipse.jetty 74 | jetty-server 75 | ${cxf.jetty9.version} 76 | 77 | 78 | 79 | org.eclipse.jetty 80 | jetty-plus 81 | ${cxf.jetty9.version} 82 | 83 | 84 | 85 | org.eclipse.jetty 86 | apache-jsp 87 | ${cxf.jetty9.version} 88 | 89 | 90 | 91 | org.eclipse.jetty 92 | jetty-webapp 93 | ${cxf.jetty9.version} 94 | 95 | 96 | 97 | org.eclipse.jetty.websocket 98 | websocket-server 99 | ${cxf.jetty9.version} 100 | 101 | 102 | 103 | org.atmosphere 104 | atmosphere-runtime 105 | 2.4.9 106 | 107 | 108 | 109 | io.reactivex.rxjava2 110 | rxjava 111 | 2.0.7 112 | 113 | 114 | 115 | 116 | org.slf4j 117 | slf4j-api 118 | 1.7.25 119 | 120 | 121 | 122 | 123 | org.slf4j 124 | slf4j-simple 125 | 1.7.25 126 | 127 | 128 | 129 | org.jboss.weld.servlet 130 | weld-servlet-shaded 131 | 3.0.1.Final 132 | 133 | 134 | 135 | 136 | junit 137 | junit 138 | 4.12 139 | 140 | 141 | 142 | 143 | 144 | 145 | server 146 | 147 | test 148 | 149 | 150 | org.codehaus.mojo 151 | exec-maven-plugin 152 | 153 | 154 | test 155 | 156 | java 157 | 158 | 159 | org.iproduct.demo.profiler.server.ProfilerStreamingServer 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | org.apache.maven.plugins 173 | maven-compiler-plugin 174 | 175 | 1.9 176 | 1.9 177 | 178 | 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/cdi/qualifiers/CpuProfiling.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.cdi.qualifiers; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import javax.inject.Qualifier; 7 | import static java.lang.annotation.RetentionPolicy.*; 8 | import static java.lang.annotation.ElementType.*; 9 | 10 | @Qualifier 11 | @Retention(RUNTIME) 12 | @Target({TYPE, METHOD, FIELD, PARAMETER}) 13 | public @interface CpuProfiling {} 14 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/ProfilerStreamingServer.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.iproduct.demo.profiler.server; 20 | 21 | import javax.servlet.Servlet; 22 | 23 | //For running with java 9 use the following JVM options: 24 | //--add-modules=java.se.ee --permit-illegal-access --patch-module java.xml.ws.annotation=./myannotation.jar 25 | import org.apache.cxf.cdi.CXFCdiServlet; 26 | import org.apache.cxf.transport.sse.SseHttpTransportFactory; 27 | import org.eclipse.jetty.server.Server; 28 | import org.eclipse.jetty.server.handler.HandlerList; 29 | import org.eclipse.jetty.servlet.DefaultServlet; 30 | import org.eclipse.jetty.servlet.ServletContextHandler; 31 | import org.eclipse.jetty.servlet.ServletHolder; 32 | import org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener; 33 | import org.jboss.weld.environment.servlet.Listener; 34 | 35 | public final class ProfilerStreamingServer { 36 | 37 | public static void main(final String[] args) throws Exception { 38 | final Server server = new Server(8080); 39 | 40 | final ServletHolder staticHolder = new ServletHolder(new DefaultServlet()); 41 | final ServletContextHandler staticContext = new ServletContextHandler(); 42 | staticContext.setContextPath("/javacpu"); 43 | staticContext.addServlet(staticHolder, "/*"); 44 | staticContext.setResourceBase( 45 | ProfilerStreamingServer.class.getResource("/web-ui") 46 | .toURI() 47 | .toString()); 48 | 49 | // CXF dispatcher servlet registration 50 | final CXFCdiServlet cxfServlet = new CXFCdiServlet(); 51 | final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet); 52 | cxfServletHolder.setInitParameter(CXFCdiServlet.TRANSPORT_ID, SseHttpTransportFactory.TRANSPORT_ID); 53 | final ServletContextHandler context = new ServletContextHandler(); 54 | context.setContextPath("/"); 55 | 56 | // Add CDI (Weld) listener 57 | context.addEventListener(new Listener()); 58 | context.addEventListener(new BeanManagerResourceBindingListener()); 59 | context.addServlet(cxfServletHolder, "/rest/*"); 60 | 61 | HandlerList handlers = new HandlerList(); 62 | handlers.addHandler(staticContext); 63 | handlers.addHandler(context); 64 | 65 | server.setHandler(handlers); 66 | server.start(); 67 | server.join(); 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/app/ProfilerApplication.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.iproduct.demo.profiler.server.app; 20 | 21 | import java.util.HashSet; 22 | import java.util.Set; 23 | 24 | import javax.enterprise.context.ApplicationScoped; 25 | import javax.inject.Inject; 26 | import javax.ws.rs.ApplicationPath; 27 | import javax.ws.rs.core.Application; 28 | 29 | import org.apache.cxf.jaxrs.sse.SseFeature; 30 | import org.iproduct.demo.profiler.server.resources.ProcessesRestResource; 31 | import org.iproduct.demo.profiler.server.resources.StatsRestResource; 32 | 33 | import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; 34 | 35 | @ApplicationPath("api") 36 | @ApplicationScoped 37 | public class ProfilerApplication extends Application { 38 | @Inject private StatsRestResource statsRestService; 39 | // @Inject private StatsRestServiceRxJava2 statsRestService; 40 | @Inject private ProcessesRestResource processesRestService; 41 | 42 | @Override 43 | public Set getSingletons() { 44 | final Set singletons = new HashSet<>(); 45 | singletons.add(new SseFeature()); 46 | singletons.add(statsRestService); 47 | singletons.add(processesRestService); 48 | singletons.add(new JacksonJsonProvider()); 49 | return singletons; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/model/CpuLoad.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.iproduct.demo.profiler.server.model; 20 | 21 | import java.io.Serializable; 22 | 23 | import com.fasterxml.jackson.annotation.JsonInclude; 24 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 25 | 26 | @JsonInclude(value = Include.NON_NULL) 27 | public class CpuLoad implements Serializable { 28 | private static final long serialVersionUID = -6705829915457870975L; 29 | 30 | private long timestamp; 31 | private int load; 32 | private boolean changed; 33 | 34 | public CpuLoad() { 35 | } 36 | 37 | public CpuLoad(long timestamp, int load, boolean changed) { 38 | this.timestamp = timestamp; 39 | this.load = load; 40 | this.changed = changed; 41 | } 42 | 43 | public long getTimestamp() { 44 | return timestamp; 45 | } 46 | 47 | public void setTimestamp(long timestamp) { 48 | this.timestamp = timestamp; 49 | } 50 | 51 | public int getLoad() { 52 | return load; 53 | } 54 | 55 | public void setLoad(int load) { 56 | this.load = load; 57 | } 58 | 59 | public boolean isChanged() { 60 | return changed; 61 | } 62 | 63 | public void setChanged(boolean changed) { 64 | this.changed = changed; 65 | } 66 | 67 | public String toString() { 68 | return "CpuLoad[" + timestamp + ", " + load + ", changed: " + changed + "]"; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/model/ProcessInfo.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.iproduct.demo.profiler.server.model; 20 | 21 | import java.io.Serializable; 22 | 23 | import com.fasterxml.jackson.annotation.JsonInclude; 24 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 25 | 26 | @JsonInclude(value = Include.NON_NULL) 27 | public class ProcessInfo implements Serializable { 28 | private static final long serialVersionUID = -6705829915457870975L; 29 | 30 | private long pid; 31 | private String command; 32 | 33 | public ProcessInfo() { 34 | } 35 | 36 | public ProcessInfo(long pid, String command) { 37 | this.pid = pid; 38 | this.command = command; 39 | } 40 | 41 | public long getPid() { 42 | return pid; 43 | } 44 | 45 | public void setPid(long pid) { 46 | this.pid = pid; 47 | } 48 | 49 | public String getCommand() { 50 | return command; 51 | } 52 | 53 | public void setCommand(String command) { 54 | this.command = command; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | final int prime = 31; 60 | int result = 1; 61 | result = prime * result + ((command == null) ? 0 : command.hashCode()); 62 | result = prime * result + (int) (pid ^ (pid >>> 32)); 63 | return result; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) 69 | return true; 70 | if (obj == null) 71 | return false; 72 | if (getClass() != obj.getClass()) 73 | return false; 74 | ProcessInfo other = (ProcessInfo) obj; 75 | if (command == null) { 76 | if (other.command != null) 77 | return false; 78 | } else if (!command.equals(other.command)) 79 | return false; 80 | if (pid != other.pid) 81 | return false; 82 | return true; 83 | } 84 | 85 | public String toString() { 86 | return "ProcessInfo[" + pid + ", " + command + "]"; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/resources/ProcessesRestResource.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.List; 22 | import java.util.concurrent.CompletableFuture; 23 | import java.util.concurrent.atomic.AtomicInteger; 24 | 25 | import javax.enterprise.context.ApplicationScoped; 26 | import javax.enterprise.event.ObservesAsync; 27 | import javax.inject.Inject; 28 | import javax.ws.rs.GET; 29 | import javax.ws.rs.Path; 30 | import javax.ws.rs.Produces; 31 | import javax.ws.rs.container.AsyncResponse; 32 | import javax.ws.rs.container.Suspended; 33 | import javax.ws.rs.core.Context; 34 | import javax.ws.rs.core.MediaType; 35 | import javax.ws.rs.sse.OutboundSseEvent; 36 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 37 | import javax.ws.rs.sse.Sse; 38 | import javax.ws.rs.sse.SseBroadcaster; 39 | import javax.ws.rs.sse.SseEventSink; 40 | 41 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 42 | import org.iproduct.demo.profiler.server.model.ProcessInfo; 43 | import org.iproduct.demo.profiler.server.service.Profiler; 44 | import org.slf4j.Logger; 45 | import org.slf4j.LoggerFactory; 46 | 47 | @Path("/processes") 48 | @ApplicationScoped 49 | public class ProcessesRestResource { 50 | private Logger logger = LoggerFactory.getLogger(ProcessesRestResource.class); 51 | 52 | @Inject 53 | Profiler profiler; 54 | 55 | @GET 56 | @Produces(MediaType.APPLICATION_JSON) 57 | public void getJavaProcesses(@Suspended AsyncResponse asyncResp) { 58 | CompletableFuture.supplyAsync(() -> { 59 | List result = profiler.getJavaProcesses(); //List.of("A", "B", "C", "D"); //.stream().reduce("", (acc, item) -> acc + item); 60 | System.out.println(result); 61 | return result; 62 | }).thenAccept(result -> asyncResp.resume(result)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/resources/StatsRestResource.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | import javax.enterprise.context.ApplicationScoped; 24 | import javax.enterprise.event.ObservesAsync; 25 | import javax.ws.rs.GET; 26 | import javax.ws.rs.Path; 27 | import javax.ws.rs.Produces; 28 | import javax.ws.rs.core.Context; 29 | import javax.ws.rs.core.MediaType; 30 | import javax.ws.rs.sse.OutboundSseEvent; 31 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 32 | import javax.ws.rs.sse.Sse; 33 | import javax.ws.rs.sse.SseBroadcaster; 34 | import javax.ws.rs.sse.SseEventSink; 35 | 36 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 37 | import org.iproduct.demo.profiler.server.model.CpuLoad; 38 | import org.slf4j.Logger; 39 | import org.slf4j.LoggerFactory; 40 | 41 | @Path("/stats") 42 | @ApplicationScoped 43 | public class StatsRestResource { 44 | private Logger logger = LoggerFactory.getLogger(StatsRestResource.class); 45 | 46 | private AtomicInteger i = new AtomicInteger(); 47 | private SseBroadcaster broadcaster; 48 | private volatile Builder builder; 49 | 50 | @Context 51 | public void setSse(Sse sse) { 52 | this.broadcaster = sse.newBroadcaster(); 53 | this.builder = sse.newEventBuilder(); 54 | } 55 | 56 | @GET 57 | @Path("sse") 58 | @Produces(MediaType.SERVER_SENT_EVENTS) 59 | public void stats(@Context SseEventSink sink) { 60 | broadcaster.register(sink); 61 | } 62 | 63 | public void asyncProcessingCpuLoad(@ObservesAsync @CpuProfiling CpuLoad cpuLoad) { 64 | OutboundSseEvent sseEvent = createStatsEvent(builder, cpuLoad); 65 | broadcaster.broadcast(sseEvent); 66 | 67 | } 68 | 69 | private OutboundSseEvent createStatsEvent(final OutboundSseEvent.Builder builder, CpuLoad cpuLoad) { 70 | OutboundSseEvent event = builder 71 | .name("stats") 72 | .data(CpuLoad.class, cpuLoad) 73 | .mediaType(MediaType.APPLICATION_JSON_TYPE) 74 | .build(); 75 | return event; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/resources/StatsRestResourceRxJava2.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.Date; 22 | import java.util.Random; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import javax.enterprise.context.ApplicationScoped; 26 | import javax.inject.Inject; 27 | import javax.ws.rs.GET; 28 | import javax.ws.rs.Path; 29 | import javax.ws.rs.Produces; 30 | import javax.ws.rs.core.Context; 31 | import javax.ws.rs.core.MediaType; 32 | import javax.ws.rs.sse.OutboundSseEvent; 33 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 34 | import javax.ws.rs.sse.Sse; 35 | import javax.ws.rs.sse.SseBroadcaster; 36 | import javax.ws.rs.sse.SseEventSink; 37 | 38 | import org.iproduct.demo.profiler.server.model.CpuLoad; 39 | import org.iproduct.demo.profiler.server.service.Profiler; 40 | 41 | import io.reactivex.Emitter; 42 | import io.reactivex.Flowable; 43 | import io.reactivex.schedulers.Schedulers; 44 | 45 | @Path("/stats2") 46 | @ApplicationScoped 47 | public class StatsRestResourceRxJava2 { 48 | private static final Random RANDOM = new Random(); 49 | 50 | private SseBroadcaster broadcaster; 51 | private Builder builder; 52 | @Inject 53 | private Profiler profiler; 54 | 55 | 56 | @Context 57 | public void setSse(Sse sse) { 58 | this.broadcaster = sse.newBroadcaster(); 59 | this.builder = sse.newEventBuilder(); 60 | 61 | Flowable 62 | .interval(500, TimeUnit.MILLISECONDS) 63 | .zipWith( 64 | Flowable.generate((Emitter emitter) -> emitter.onNext(builder.name("stats"))), 65 | (id, bldr) -> createStatsEvent(bldr, id) 66 | ) 67 | .subscribeOn(Schedulers.single()) 68 | .subscribe(broadcaster::broadcast); 69 | } 70 | 71 | @GET 72 | @Path("sse") 73 | @Produces(MediaType.SERVER_SENT_EVENTS) 74 | public void stats(@Context SseEventSink sink) { 75 | broadcaster.register(sink); 76 | } 77 | 78 | private OutboundSseEvent createStatsEvent(final OutboundSseEvent.Builder builder, final long eventId) { 79 | return builder 80 | .id("" + eventId) 81 | .data(CpuLoad.class, new CpuLoad(new Date().getTime(), (int) profiler.getJavaCPULoad(), profiler.areProcessesChanged())) 82 | .mediaType(MediaType.APPLICATION_JSON_TYPE) 83 | .build(); 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/service/Profiler.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.server.service; 2 | 3 | import java.time.Duration; 4 | import java.time.temporal.ChronoUnit; 5 | import java.util.List; 6 | import java.util.Optional; 7 | import java.util.concurrent.Flow.Subscriber; 8 | import java.util.concurrent.Flow.Subscription; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | import javax.annotation.PostConstruct; 14 | import javax.enterprise.context.ApplicationScoped; 15 | import javax.enterprise.event.Event; 16 | import javax.inject.Inject; 17 | 18 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 19 | import org.iproduct.demo.profiler.server.model.CpuLoad; 20 | import org.iproduct.demo.profiler.server.model.ProcessInfo; 21 | import org.iproduct.flow.IntervalPublisher; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | @ApplicationScoped 26 | public class Profiler { 27 | 28 | @Inject 29 | @CpuProfiling 30 | private Event event; 31 | 32 | private List oldProcesses; 33 | 34 | private Logger logger = LoggerFactory.getLogger(Profiler.class); 35 | 36 | public Profiler() { 37 | logger.info("!!!!! Profiler bean created successfully."); 38 | } 39 | 40 | // public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { 41 | // logger.info("Profiler successfully initialized."); 42 | // } 43 | // 44 | // public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) { 45 | // logger.info("Profiler destroyed."); 46 | // } 47 | 48 | public Stream getJavaProcessesStream() { 49 | return ProcessHandle.allProcesses() 50 | .filter(ph -> ph.info().toString().indexOf("java") >= 0); 51 | } 52 | 53 | public List getJavaProcesses() { 54 | List allProcesses = getJavaProcessesStream() 55 | .filter( ph -> ph.info().command().isPresent() ) 56 | .map( ph -> new ProcessInfo(ph.pid(), ph.info().command().get()) ) 57 | .collect(Collectors.toList()); 58 | return allProcesses; 59 | } 60 | 61 | public double getJavaCPULoad() { 62 | double allTime = getJavaProcessesStream().map(ph -> { 63 | // System.out.println(info); 64 | Optional time = ph.info().totalCpuDuration(); 65 | return (time.isPresent()) ? time.get().get(ChronoUnit.NANOS) : 0d; 66 | }).collect(Collectors.summingDouble(time -> time)); 67 | return allTime / 1000000d; 68 | } 69 | 70 | public boolean areProcessesChanged() { 71 | List newProcesses = getJavaProcesses(); 72 | boolean result = ! newProcesses.equals(oldProcesses); 73 | oldProcesses = newProcesses; 74 | return result; 75 | } 76 | 77 | @PostConstruct 78 | public void subscribeForCpuEvents() { 79 | IntervalPublisher.getDefaultIntervalPublisher(500, TimeUnit.MILLISECONDS) 80 | .subscribe(new Subscriber() { 81 | 82 | @Override 83 | public void onComplete() {} 84 | 85 | @Override 86 | public void onError(Throwable t) {} 87 | 88 | @Override 89 | public void onNext(Integer i) { 90 | event.fireAsync(new CpuLoad(System.currentTimeMillis(), (int) getJavaCPULoad(), areProcessesChanged())) 91 | .thenAccept(event -> { 92 | logger.info("CPU load event fired: " + event); 93 | }); 94 | } 95 | 96 | @Override 97 | public void onSubscribe(Subscription subscription) { 98 | subscription.request(Long.MAX_VALUE); 99 | } 100 | }); 101 | } 102 | 103 | public static void main(String[] args) throws InterruptedException { 104 | // Profiler profiler = new Profiler(); 105 | // Flowable.interval(1000, TimeUnit.MILLISECONDS).map(t -> profiler.getJavaCPULoad()) 106 | // .subscribe(System.out::println); 107 | // Thread.sleep(100000); 108 | 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/demo/profiler/server/utility/LoadCPU.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.server.utility; 2 | 3 | public class LoadCPU { 4 | 5 | public static void main(String[] args) { 6 | long result = 0; 7 | for(long n = 0; n < 10000000000L; n++) { 8 | result += n; 9 | } 10 | System.out.println(result); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/flow/FlowSubscriber.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.Flow.Subscriber; 5 | import java.util.concurrent.Flow.Subscription; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | public class FlowSubscriber implements Subscriber { 9 | 10 | private static final String LOG_FORMAT = " Subscriber %s >> [%s] %s%n"; 11 | private final Random random = new Random(); 12 | 13 | private Subscription subscription; 14 | private AtomicInteger remaining; 15 | 16 | private String name; 17 | private int demand = 0; 18 | 19 | public FlowSubscriber(String name) { 20 | this.name = name; 21 | } 22 | 23 | @Override 24 | public void onSubscribe(Subscription subscription) { 25 | log("Subscribed..."); 26 | this.subscription = subscription; 27 | 28 | request(demand); 29 | } 30 | 31 | public void setDemand(int n) { 32 | this.demand = n; 33 | remaining = new AtomicInteger(demand); 34 | } 35 | 36 | private void request(int n) { 37 | log("requesting " + n + " new items..."); 38 | subscription.request(n); 39 | } 40 | 41 | @Override 42 | public void onNext(T item) { 43 | log("item: " + item); 44 | 45 | if (remaining.decrementAndGet() == 0) { 46 | if (random.nextBoolean()) { 47 | request(demand); 48 | remaining.set(demand); 49 | } else { 50 | log("Cancel subscription..."); 51 | subscription.cancel(); 52 | } 53 | } 54 | 55 | } 56 | 57 | @Override 58 | public void onComplete() { 59 | log("Complete!"); 60 | } 61 | 62 | @Override 63 | public void onError(Throwable t) { 64 | log("Error: " + t.getMessage()); 65 | } 66 | 67 | private void log(String message, Object... args) { 68 | String fullMessage = String.format(LOG_FORMAT, this.name, Thread.currentThread().getName(), message); 69 | System.out.printf(fullMessage, args); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/flow/HotPublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.concurrent.Flow.Publisher; 4 | 5 | public interface HotPublisher extends Publisher{ 6 | void cancel(boolean mayInterruptIfRunning); 7 | void join(); 8 | } 9 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/java/org/iproduct/flow/IntervalPublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.ForkJoinPool; 6 | import java.util.concurrent.SubmissionPublisher; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | import java.util.function.Function; 10 | import java.util.function.Supplier; 11 | 12 | public class IntervalPublisher extends SubmissionPublisher implements HotPublisher { 13 | public static final int DEFAULT_MAX_BUFFER_CAPACITY = 256; 14 | private volatile CompletableFuture finished = new CompletableFuture(); 15 | private Supplier supplier; 16 | private Executor executor; 17 | private long period; 18 | private TimeUnit unit; 19 | private boolean wasActivated; 20 | private Function onerror = throwable -> { 21 | closeExceptionally(throwable); 22 | finished.completeExceptionally(throwable); 23 | return null; 24 | }; 25 | 26 | public static HotPublisher getDefaultIntervalPublisher(long period, TimeUnit unit) { 27 | AtomicInteger i = new AtomicInteger(0); 28 | return new IntervalPublisher(i::incrementAndGet, period, unit); 29 | } 30 | 31 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit, Executor executor, int maxBufferCapacity) { 32 | super(executor, maxBufferCapacity); 33 | this.supplier = supplier; 34 | this.executor = executor; 35 | this.period = period; 36 | this.unit = unit; 37 | 38 | CompletableFuture 39 | .supplyAsync(supplier, CompletableFuture.delayedExecutor(delay, unit, executor)) 40 | .thenAccept(this::onCompletion) 41 | .exceptionally( onerror ); 42 | } 43 | 44 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit, Executor executor) { 45 | this(supplier, delay, period, unit, executor, DEFAULT_MAX_BUFFER_CAPACITY); 46 | } 47 | 48 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit) { 49 | this(supplier, delay, period, unit, ForkJoinPool.commonPool()); 50 | } 51 | 52 | public IntervalPublisher(Supplier supplier, long period, TimeUnit unit) { 53 | this(supplier, 0, period, unit); 54 | } 55 | 56 | private void onCompletion(T item) { 57 | if(hasSubscribers()) { 58 | wasActivated = true; 59 | submit(item); 60 | } else if(wasActivated) { 61 | close(); 62 | return; 63 | } 64 | 65 | CompletableFuture 66 | .supplyAsync(supplier, CompletableFuture.delayedExecutor(period, unit, executor)) 67 | .thenAccept(this::onCompletion) 68 | .exceptionally( onerror ); 69 | } 70 | 71 | @Override 72 | public void close() { 73 | // System.out.println("Closing..."); 74 | finished.complete(null); 75 | super.close(); 76 | } 77 | 78 | public void cancel(boolean mayInterruptIfRunning) { 79 | finished.cancel(mayInterruptIfRunning); 80 | }; 81 | 82 | public void join() { 83 | finished.join(); 84 | } 85 | 86 | public static void main(String[] args) { 87 | 88 | HotPublisher publisher = IntervalPublisher.getDefaultIntervalPublisher(1, TimeUnit.SECONDS); 89 | 90 | FlowSubscriber subA = new FlowSubscriber<>("A"); 91 | subA.setDemand(2); 92 | 93 | FlowSubscriber subB = new FlowSubscriber<>("B"); 94 | subB.setDemand(5); 95 | 96 | publisher.subscribe(subA); 97 | publisher.subscribe(subB); 98 | 99 | // when all subscribers have unsubscribed - finish 100 | publisher.join(); 101 | 102 | System.out.println("Demo finished."); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/resources/META-INF/beans-old.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/resources/META-INF/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/resources/META-INF/cxf/org.apache.cxf.Logger: -------------------------------------------------------------------------------- 1 | org.apache.cxf.common.logging.Slf4jLogger -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/resources/META-INF/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # JBoss, Home of Professional Open Source 3 | # Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual 4 | # contributors by the @authors tag. See the copyright.txt in the 5 | # distribution for a full listing of individual contributors. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # Set root logger level to DEBUG and its only appender to A1. 18 | log4j.rootLogger=WARN, A1 19 | 20 | # A1 is set to be a ConsoleAppender. 21 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 22 | 23 | # A1 uses PatternLayout. 24 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 25 | log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 26 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-cxf/src/main/resources/web-ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SSE: Apache CXF example 5 | 6 | 7 | 12 | 13 | 14 | 15 |
16 |
17 |
18 |

Active Java Processes:

19 |
    20 |
    21 |
    22 | 23 | 24 | 92 | 93 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/README.md: -------------------------------------------------------------------------------- 1 | # CompletableFuture with JAX-RS 2.1 CDI 2.0 (Java 9 + Java EE 8) Demo 2 | 3 | For this demo you need installed latest Java 9 JDK. 4 | 5 | Follow next steps to start the server: 6 | 7 | 1. Run `mvn install` in project's main folder 8 | 9 | 2. Run `org.iproduct.demo.profiler.StreamingServer` from `completable-future-jaxrs-cdi-jersey` project 10 | with following VM arguments: 11 | ``` 12 | --add-modules=java.se.ee --patch-module java.xml.ws.annotation=./myannotation.jar 13 | ``` 14 | 15 | 3. (Optional) Open http://localhost:8080/javacpu/ 16 | 17 | 4. Run the `org.iproduct.demo.profiler.client.ProfilerAppClient` from this project. 18 | 19 | Enjoy! -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/myannotation.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/completable-future-jaxrs-cdi-jersey-client/myannotation.jar -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 4.0.0 5 | 6 | org.iproduct.demos 7 | completable-future-jaxrs-cdi-jersey 8 | 0.0.1-SNAPSHOT 9 | completable-future-jaxrs-cdi-jersey 10 | 11 | 12 | UTF-8 13 | 2.26 14 | 9.4.7.v20170914 15 | 16 | 17 | 18 | completable-future-jaxrs-cdi-jersey 19 | 20 | 21 | org.apache.maven.plugins 22 | maven-compiler-plugin 23 | 24 | 1.9 25 | 1.9 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.glassfish.jersey 35 | jersey-bom 36 | ${jersey.version} 37 | pom 38 | import 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.glassfish.jersey.containers 46 | jersey-container-servlet-core 47 | 48 | 49 | 50 | 51 | org.glassfish.jersey.core 52 | jersey-client 53 | provided 54 | 55 | 56 | org.glassfish.jersey.connectors 57 | jersey-jetty-connector 58 | provided 59 | 60 | 61 | 62 | org.glassfish.jersey.inject 63 | jersey-hk2 64 | provided 65 | 66 | 67 | javax.ws.rs 68 | javax.ws.rs-api 69 | 2.1-m08 70 | 71 | 72 | javax.annotation 73 | javax.annotation-api 74 | 1.3 75 | 76 | 77 | 78 | 79 | org.glassfish.jersey.media 80 | jersey-media-moxy 81 | 82 | 83 | 84 | 85 | org.glassfish.jersey.media 86 | jersey-media-sse 87 | provided 88 | 89 | 90 | 91 | 92 | org.slf4j 93 | slf4j-api 94 | 1.7.25 95 | 96 | 97 | org.slf4j 98 | slf4j-simple 99 | 1.7.25 100 | 101 | 102 | 103 | 104 | io.reactivex.rxjava2 105 | rxjava 106 | 2.0.7 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/src/main/java/org/iproduct/demo/profiler/client/ProfilerAppClient.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.client; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.concurrent.CompletionStage; 6 | 7 | import javax.ws.rs.client.Client; 8 | import javax.ws.rs.client.ClientBuilder; 9 | import javax.ws.rs.client.WebTarget; 10 | import javax.ws.rs.core.GenericType; 11 | import javax.ws.rs.sse.SseEventSource; 12 | 13 | import org.iproduct.demo.profiler.client.model.ProcessInfo; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | 17 | // Run the ProfilerStreamingServer first (from completable-future-jaxrs-cdi-jersey project) 18 | 19 | public class ProfilerAppClient { 20 | public static final String PROFILER_API_URL = "http://localhost:8080/rest/api/"; 21 | public static Logger logger = LoggerFactory.getLogger(ProfilerAppClient.class); 22 | 23 | public static void main(String[] args) { 24 | // Default client instance 25 | Client client = ClientBuilder.newClient(); 26 | final WebTarget processes = client.target(PROFILER_API_URL + "processes"); 27 | final WebTarget stats = client.target(PROFILER_API_URL + "stats/sse"); 28 | 29 | CompletionStage> processesStage = processes.request() 30 | .rx() 31 | .get(new GenericType>() {}) 32 | .exceptionally(throwable -> { 33 | logger.error("Error receiving active Java processes: " + throwable.getMessage()); 34 | return Collections.emptyList(); 35 | }); 36 | 37 | CompletionStage printProcessesStage = 38 | processesStage.thenApply(proc -> { 39 | System.out.println("Active JAVA Processes: " + proc); 40 | return null; 41 | }); 42 | 43 | printProcessesStage.thenRun( () -> { 44 | try (SseEventSource source = SseEventSource.target(stats).build()) { 45 | source.register(System.out::println); 46 | source.open(); 47 | Thread.sleep(20000); // Consume events for 20 sec 48 | } catch (InterruptedException e) { 49 | logger.info("SSE consumer interrupted: " + e); 50 | } 51 | }) 52 | .thenRun(() -> {System.exit(0);}); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/src/main/java/org/iproduct/demo/profiler/client/model/CpuLoad.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.iproduct.demo.profiler.client.model; 20 | 21 | import java.io.Serializable; 22 | 23 | //@JsonInclude(value = Include.NON_NULL) 24 | public class CpuLoad implements Serializable { 25 | private static final long serialVersionUID = -6705829915457870975L; 26 | 27 | private long timestamp; 28 | private int load; 29 | private boolean changed; 30 | 31 | public CpuLoad() { 32 | } 33 | 34 | public CpuLoad(long timestamp, int load, boolean changed) { 35 | this.timestamp = timestamp; 36 | this.load = load; 37 | this.changed = changed; 38 | } 39 | 40 | public long getTimestamp() { 41 | return timestamp; 42 | } 43 | 44 | public void setTimestamp(long timestamp) { 45 | this.timestamp = timestamp; 46 | } 47 | 48 | public int getLoad() { 49 | return load; 50 | } 51 | 52 | public void setLoad(int load) { 53 | this.load = load; 54 | } 55 | 56 | public boolean isChanged() { 57 | return changed; 58 | } 59 | 60 | public void setChanged(boolean changed) { 61 | this.changed = changed; 62 | } 63 | 64 | public String toString() { 65 | return "CpuLoad[" + timestamp + ", " + load + ", changed: " + changed + "]"; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/src/main/java/org/iproduct/demo/profiler/client/model/ProcessInfo.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.iproduct.demo.profiler.client.model; 20 | 21 | import java.io.Serializable; 22 | 23 | import javax.xml.bind.annotation.XmlRootElement; 24 | 25 | @XmlRootElement 26 | //@JsonInclude(value = Include.NON_NULL) 27 | public class ProcessInfo implements Serializable { 28 | private static final long serialVersionUID = -6705829915457870975L; 29 | 30 | private long pid; 31 | private String command; 32 | 33 | public ProcessInfo() { 34 | } 35 | 36 | public ProcessInfo(long pid, String command) { 37 | this.pid = pid; 38 | this.command = command; 39 | } 40 | 41 | public long getPid() { 42 | return pid; 43 | } 44 | 45 | public void setPid(long pid) { 46 | this.pid = pid; 47 | } 48 | 49 | public String getCommand() { 50 | return command; 51 | } 52 | 53 | public void setCommand(String command) { 54 | this.command = command; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | final int prime = 31; 60 | int result = 1; 61 | result = prime * result + ((command == null) ? 0 : command.hashCode()); 62 | result = prime * result + (int) (pid ^ (pid >>> 32)); 63 | return result; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) 69 | return true; 70 | if (obj == null) 71 | return false; 72 | if (getClass() != obj.getClass()) 73 | return false; 74 | ProcessInfo other = (ProcessInfo) obj; 75 | if (command == null) { 76 | if (other.command != null) 77 | return false; 78 | } else if (!command.equals(other.command)) 79 | return false; 80 | if (pid != other.pid) 81 | return false; 82 | return true; 83 | } 84 | 85 | public String toString() { 86 | return "ProcessInfo[" + pid + ", " + command + "]"; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/src/main/resources/META-INF/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey-client/src/main/resources/META-INF/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # JBoss, Home of Professional Open Source 3 | # Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual 4 | # contributors by the @authors tag. See the copyright.txt in the 5 | # distribution for a full listing of individual contributors. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # Set root logger level to DEBUG and its only appender to A1. 18 | log4j.rootLogger=WARN, A1 19 | 20 | # A1 is set to be a ConsoleAppender. 21 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 22 | 23 | # A1 uses PatternLayout. 24 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 25 | log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 26 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/README.md: -------------------------------------------------------------------------------- 1 | # CompletableFuture with JAX-RS 2.1 CDI 2.0 (Java 9 + Java EE 8) Demo 2 | 3 | For this demo you need installed latest Java 9 JDK. 4 | 5 | Follow next steps to start the server: 6 | 7 | 1. Run `mvn install` in project's main folder 8 | 9 | 2. Run `org.iproduct.demo.profiler.StreamingServer` with following VM arguments: 10 | ``` 11 | --add-modules=java.se.ee --patch-module java.xml.ws.annotation=./myannotation.jar 12 | ``` 13 | 14 | 3. Open http://localhost:8080/javacpu/ 15 | 16 | Enjoy! -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/myannotation.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/completable-future-jaxrs-cdi-jersey/myannotation.jar -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 4.0.0 5 | 6 | org.iproduct.demos 7 | completable-future-jaxrs-cdi-jersey 8 | 0.0.1-SNAPSHOT 9 | completable-future-jaxrs-cdi-jersey 10 | 11 | 12 | UTF-8 13 | 2.26 14 | 9.4.7.v20170914 15 | 16 | 17 | 18 | 19 | server 20 | 21 | test 22 | 23 | 24 | org.codehaus.mojo 25 | exec-maven-plugin 26 | 27 | 28 | test 29 | 30 | java 31 | 32 | 33 | org.iproduct.demo.profiler.server.ProfilerStreamingServer 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | completable-future-jaxrs-cdi-jersey 45 | 46 | 47 | org.apache.maven.plugins 48 | maven-compiler-plugin 49 | 50 | 1.9 51 | 1.9 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | org.glassfish.jersey 61 | jersey-bom 62 | ${jersey.version} 63 | pom 64 | import 65 | 66 | 67 | 68 | 69 | 70 | 71 | org.glassfish.jersey.inject 72 | jersey-hk2 73 | provided 74 | 75 | 76 | org.glassfish.jersey.ext.cdi 77 | jersey-cdi1x 78 | provided 79 | 80 | 81 | org.glassfish.jersey.ext.cdi 82 | jersey-cdi1x-ban-custom-hk2-binding 83 | compile 84 | 85 | 86 | org.glassfish.jersey.core 87 | jersey-common 88 | 89 | 90 | javax.ws.rs 91 | javax.ws.rs-api 92 | 93 | 94 | 95 | 96 | javax.ws.rs 97 | javax.ws.rs-api 98 | 2.1-m08 99 | 100 | 101 | javax.annotation 102 | javax.annotation-api 103 | 1.3 104 | 105 | 106 | javax.enterprise 107 | cdi-api 108 | 2.0 109 | 110 | 111 | org.glassfish.jersey.containers 112 | jersey-container-servlet-core 113 | provided 114 | 115 | 116 | org.glassfish.jersey.core 117 | jersey-server 118 | provided 119 | 120 | 121 | org.glassfish.jersey.containers 122 | jersey-container-servlet 123 | compile 124 | 125 | 126 | 127 | 128 | org.glassfish.jersey.media 129 | jersey-media-moxy 130 | 131 | 132 | 133 | 134 | org.glassfish.jersey.media 135 | jersey-media-sse 136 | provided 137 | 138 | 139 | 140 | 141 | org.jboss.weld.servlet 142 | weld-servlet-shaded 143 | 3.0.1.Final 144 | 145 | 146 | 147 | 148 | org.glassfish.jersey.containers 149 | jersey-container-jetty-servlet 150 | provided 151 | 152 | 153 | 154 | org.eclipse.jetty 155 | jetty-server 156 | ${jetty9.version} 157 | 158 | 159 | 160 | org.eclipse.jetty 161 | jetty-plus 162 | ${jetty9.version} 163 | 164 | 165 | 166 | org.eclipse.jetty 167 | apache-jsp 168 | ${jetty9.version} 169 | 170 | 171 | 172 | org.eclipse.jetty 173 | jetty-webapp 174 | ${jetty9.version} 175 | 176 | 177 | 178 | org.eclipse.jetty.websocket 179 | websocket-server 180 | ${jetty9.version} 181 | 182 | 183 | 191 | 192 | 193 | 194 | org.slf4j 195 | slf4j-api 196 | 1.7.25 197 | 198 | 199 | org.slf4j 200 | slf4j-simple 201 | 1.7.25 202 | 203 | 204 | 205 | 206 | io.reactivex.rxjava2 207 | rxjava 208 | 2.0.7 209 | 210 | 211 | 212 | 213 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/cdi/qualifiers/CpuProfiling.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.cdi.qualifiers; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import javax.inject.Qualifier; 7 | import static java.lang.annotation.RetentionPolicy.*; 8 | import static java.lang.annotation.ElementType.*; 9 | 10 | @Qualifier 11 | @Retention(RUNTIME) 12 | @Target({TYPE, METHOD, FIELD, PARAMETER}) 13 | public @interface CpuProfiling {} 14 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/ProfilerStreamingServer.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.iproduct.demo.profiler.server; 20 | 21 | import java.net.URI; 22 | 23 | import javax.ws.rs.core.UriBuilder; 24 | 25 | import org.eclipse.jetty.server.Server; 26 | import org.eclipse.jetty.server.handler.HandlerList; 27 | import org.eclipse.jetty.servlet.DefaultServlet; 28 | import org.eclipse.jetty.servlet.ServletContextHandler; 29 | import org.eclipse.jetty.servlet.ServletHolder; 30 | import org.glassfish.jersey.server.ResourceConfig; 31 | import org.glassfish.jersey.servlet.ServletContainer; 32 | import org.iproduct.demo.profiler.server.app.ProfilerApplication; 33 | import org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener; 34 | import org.jboss.weld.environment.servlet.Listener; 35 | 36 | //--add-modules=java.se.ee --permit-illegal-access --patch-module java.xml.ws.annotation=./myannotation.jar 37 | 38 | public final class ProfilerStreamingServer { 39 | private static final URI BASE_URI = UriBuilder.fromUri("http://localhost:8080/rest").port(8080).build(); 40 | 41 | public static void main(final String[] args) throws Exception { 42 | 43 | final Server server = new Server(8080); 44 | 45 | final ServletContainer jerseyServlet = new ServletContainer(); 46 | final ServletHolder jerseyServletHolder = new ServletHolder(jerseyServlet); 47 | jerseyServletHolder.setInitParameter("javax.ws.rs.Application", ProfilerApplication.class.getName()); 48 | 49 | final ServletContextHandler context = new ServletContextHandler(); 50 | context.setContextPath("/"); 51 | 52 | // Add CDI (Weld) listener 53 | context.addEventListener(new Listener()); 54 | context.addEventListener(new BeanManagerResourceBindingListener()); 55 | 56 | context.addServlet(jerseyServletHolder, "/rest/api/*"); 57 | 58 | 59 | 60 | final ServletHolder staticHolder = new ServletHolder(new DefaultServlet()); 61 | final ServletContextHandler staticContext = new ServletContextHandler(); 62 | staticContext.setContextPath("/javacpu"); 63 | staticContext.addServlet(staticHolder, "/*"); 64 | staticContext.setResourceBase(ProfilerStreamingServer.class.getResource("/web-ui").toURI().toString()); 65 | 66 | HandlerList handlers = new HandlerList(); 67 | handlers.addHandler(staticContext); 68 | handlers.addHandler(context); 69 | server.setHandler(handlers); 70 | 71 | server.start(); 72 | server.join(); // Jetty 73 | 74 | // server.shutdownNow(); //Grizzly 75 | // weld.shutdown(); 76 | } 77 | 78 | public static ResourceConfig createJaxRsApp() { 79 | return ResourceConfig.forApplicationClass(ProfilerApplication.class); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/app/ProfilerApplication.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.iproduct.demo.profiler.server.app; 20 | 21 | import javax.ws.rs.ApplicationPath; 22 | 23 | import org.glassfish.jersey.server.ResourceConfig; 24 | import org.iproduct.demo.profiler.server.resources.ProcessesRestResource; 25 | import org.iproduct.demo.profiler.server.resources.StatsRestResource; 26 | 27 | @ApplicationPath("/api/*") 28 | public class ProfilerApplication extends ResourceConfig { 29 | 30 | public ProfilerApplication() { 31 | register(ProcessesRestResource.class); 32 | register(StatsRestResource.class); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/model/CpuLoad.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.iproduct.demo.profiler.server.model; 20 | 21 | import java.io.Serializable; 22 | 23 | //@JsonInclude(value = Include.NON_NULL) 24 | public class CpuLoad implements Serializable { 25 | private static final long serialVersionUID = -6705829915457870975L; 26 | 27 | private long timestamp; 28 | private int load; 29 | private boolean changed; 30 | 31 | public CpuLoad() { 32 | } 33 | 34 | public CpuLoad(long timestamp, int load, boolean changed) { 35 | this.timestamp = timestamp; 36 | this.load = load; 37 | this.changed = changed; 38 | } 39 | 40 | public long getTimestamp() { 41 | return timestamp; 42 | } 43 | 44 | public void setTimestamp(long timestamp) { 45 | this.timestamp = timestamp; 46 | } 47 | 48 | public int getLoad() { 49 | return load; 50 | } 51 | 52 | public void setLoad(int load) { 53 | this.load = load; 54 | } 55 | 56 | public boolean isChanged() { 57 | return changed; 58 | } 59 | 60 | public void setChanged(boolean changed) { 61 | this.changed = changed; 62 | } 63 | 64 | public String toString() { 65 | return "CpuLoad[" + timestamp + ", " + load + ", changed: " + changed + "]"; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/model/ProcessInfo.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.iproduct.demo.profiler.server.model; 20 | 21 | import java.io.Serializable; 22 | 23 | import javax.xml.bind.annotation.XmlRootElement; 24 | 25 | @XmlRootElement 26 | //@JsonInclude(value = Include.NON_NULL) 27 | public class ProcessInfo implements Serializable { 28 | private static final long serialVersionUID = -6705829915457870975L; 29 | 30 | private long pid; 31 | private String command; 32 | 33 | public ProcessInfo() { 34 | } 35 | 36 | public ProcessInfo(long pid, String command) { 37 | this.pid = pid; 38 | this.command = command; 39 | } 40 | 41 | public long getPid() { 42 | return pid; 43 | } 44 | 45 | public void setPid(long pid) { 46 | this.pid = pid; 47 | } 48 | 49 | public String getCommand() { 50 | return command; 51 | } 52 | 53 | public void setCommand(String command) { 54 | this.command = command; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | final int prime = 31; 60 | int result = 1; 61 | result = prime * result + ((command == null) ? 0 : command.hashCode()); 62 | result = prime * result + (int) (pid ^ (pid >>> 32)); 63 | return result; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) 69 | return true; 70 | if (obj == null) 71 | return false; 72 | if (getClass() != obj.getClass()) 73 | return false; 74 | ProcessInfo other = (ProcessInfo) obj; 75 | if (command == null) { 76 | if (other.command != null) 77 | return false; 78 | } else if (!command.equals(other.command)) 79 | return false; 80 | if (pid != other.pid) 81 | return false; 82 | return true; 83 | } 84 | 85 | public String toString() { 86 | return "ProcessInfo[" + pid + ", " + command + "]"; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/resources/ProcessesRestResource.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.List; 22 | import java.util.concurrent.CompletableFuture; 23 | import java.util.concurrent.atomic.AtomicInteger; 24 | 25 | import javax.enterprise.context.ApplicationScoped; 26 | import javax.enterprise.event.ObservesAsync; 27 | import javax.inject.Inject; 28 | import javax.ws.rs.GET; 29 | import javax.ws.rs.Path; 30 | import javax.ws.rs.Produces; 31 | import javax.ws.rs.container.AsyncResponse; 32 | import javax.ws.rs.container.Suspended; 33 | import javax.ws.rs.core.Context; 34 | import javax.ws.rs.core.GenericEntity; 35 | import javax.ws.rs.core.MediaType; 36 | import javax.ws.rs.sse.OutboundSseEvent; 37 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 38 | import javax.ws.rs.sse.Sse; 39 | import javax.ws.rs.sse.SseBroadcaster; 40 | import javax.ws.rs.sse.SseEventSink; 41 | 42 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 43 | import org.iproduct.demo.profiler.server.model.ProcessInfo; 44 | import org.iproduct.demo.profiler.server.service.Profiler; 45 | import org.slf4j.Logger; 46 | import org.slf4j.LoggerFactory; 47 | 48 | @Path("/processes") 49 | @ApplicationScoped 50 | public class ProcessesRestResource { 51 | private Logger logger = LoggerFactory.getLogger(ProcessesRestResource.class); 52 | 53 | @Inject 54 | Profiler profiler; 55 | 56 | @GET 57 | @Produces(MediaType.APPLICATION_JSON) 58 | public void getJavaProcesses(@Suspended final AsyncResponse asyncResp) { 59 | CompletableFuture.supplyAsync(() -> { 60 | GenericEntity> result = new GenericEntity>(profiler.getJavaProcesses()) {}; //List.of("A", "B", "C", "D"); //.stream().reduce("", (acc, item) -> acc + item); 61 | System.out.println(result.getEntity()); 62 | return result; 63 | }).thenAccept(result -> asyncResp.resume(result)); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/resources/StatsRestResource.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | import javax.enterprise.context.ApplicationScoped; 24 | import javax.enterprise.event.ObservesAsync; 25 | import javax.ws.rs.GET; 26 | import javax.ws.rs.Path; 27 | import javax.ws.rs.Produces; 28 | import javax.ws.rs.core.Context; 29 | import javax.ws.rs.core.MediaType; 30 | import javax.ws.rs.sse.OutboundSseEvent; 31 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 32 | import javax.ws.rs.sse.Sse; 33 | import javax.ws.rs.sse.SseBroadcaster; 34 | import javax.ws.rs.sse.SseEventSink; 35 | 36 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 37 | import org.iproduct.demo.profiler.server.model.CpuLoad; 38 | import org.slf4j.Logger; 39 | import org.slf4j.LoggerFactory; 40 | 41 | @Path("/stats") 42 | @ApplicationScoped 43 | public class StatsRestResource { 44 | private Logger logger = LoggerFactory.getLogger(StatsRestResource.class); 45 | 46 | private AtomicInteger i = new AtomicInteger(); 47 | private SseBroadcaster broadcaster; 48 | private volatile Builder builder; 49 | 50 | @Context 51 | public void setSse(Sse sse) { 52 | this.broadcaster = sse.newBroadcaster(); 53 | this.builder = sse.newEventBuilder(); 54 | } 55 | 56 | @GET 57 | @Path("sse") 58 | @Produces(MediaType.SERVER_SENT_EVENTS) 59 | public void stats(@Context SseEventSink sink) { 60 | broadcaster.register(sink); 61 | } 62 | 63 | public void asyncProcessingCpuLoad(@ObservesAsync @CpuProfiling CpuLoad cpuLoad) { 64 | OutboundSseEvent sseEvent = createStatsEvent(builder, cpuLoad); 65 | broadcaster.broadcast(sseEvent); 66 | } 67 | 68 | private OutboundSseEvent createStatsEvent(final OutboundSseEvent.Builder builder, CpuLoad cpuLoad) { 69 | OutboundSseEvent event = builder 70 | .id(""+i.getAndIncrement()) 71 | .name("stats") 72 | .data(CpuLoad.class, cpuLoad) 73 | .mediaType(MediaType.APPLICATION_JSON_TYPE) 74 | .build(); 75 | return event; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/resources/StatsRestResourceRxJava2.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.iproduct.demo.profiler.server.resources; 20 | 21 | import java.util.Date; 22 | import java.util.Random; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | import javax.enterprise.context.ApplicationScoped; 26 | import javax.inject.Inject; 27 | import javax.ws.rs.GET; 28 | import javax.ws.rs.Path; 29 | import javax.ws.rs.Produces; 30 | import javax.ws.rs.core.Context; 31 | import javax.ws.rs.core.MediaType; 32 | import javax.ws.rs.sse.OutboundSseEvent; 33 | import javax.ws.rs.sse.OutboundSseEvent.Builder; 34 | import javax.ws.rs.sse.Sse; 35 | import javax.ws.rs.sse.SseBroadcaster; 36 | import javax.ws.rs.sse.SseEventSink; 37 | 38 | import org.iproduct.demo.profiler.server.model.CpuLoad; 39 | import org.iproduct.demo.profiler.server.service.Profiler; 40 | 41 | import io.reactivex.Emitter; 42 | import io.reactivex.Flowable; 43 | import io.reactivex.schedulers.Schedulers; 44 | 45 | @Path("/rxstats") 46 | @ApplicationScoped 47 | public class StatsRestResourceRxJava2 { 48 | private static final Random RANDOM = new Random(); 49 | 50 | private SseBroadcaster broadcaster; 51 | private Builder builder; 52 | @Inject 53 | private Profiler profiler; 54 | 55 | 56 | @Context 57 | public void setSse(Sse sse) { 58 | this.broadcaster = sse.newBroadcaster(); 59 | this.builder = sse.newEventBuilder(); 60 | 61 | Flowable 62 | .interval(500, TimeUnit.MILLISECONDS) 63 | .zipWith( 64 | Flowable.generate((Emitter emitter) -> emitter.onNext(builder.name("stats"))), 65 | (id, bldr) -> createStatsEvent(bldr, id) 66 | ) 67 | .subscribeOn(Schedulers.single()) 68 | .subscribe(broadcaster::broadcast); 69 | } 70 | 71 | @GET 72 | @Path("sse") 73 | @Produces(MediaType.SERVER_SENT_EVENTS) 74 | public void stats(@Context SseEventSink sink) { 75 | broadcaster.register(sink); 76 | } 77 | 78 | private OutboundSseEvent createStatsEvent(final OutboundSseEvent.Builder builder, final long eventId) { 79 | return builder 80 | .id("" + eventId) 81 | .data(CpuLoad.class, new CpuLoad(new Date().getTime(), (int) profiler.getJavaCPULoad(), profiler.areProcessesChanged())) 82 | .mediaType(MediaType.APPLICATION_JSON_TYPE) 83 | .build(); 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/service/Profiler.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.server.service; 2 | 3 | import java.time.Duration; 4 | import java.time.temporal.ChronoUnit; 5 | import java.util.List; 6 | import java.util.Optional; 7 | import java.util.concurrent.Flow.Subscriber; 8 | import java.util.concurrent.Flow.Subscription; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | import javax.annotation.PostConstruct; 14 | import javax.enterprise.context.ApplicationScoped; 15 | import javax.enterprise.event.Event; 16 | import javax.inject.Inject; 17 | 18 | import org.iproduct.demo.profiler.cdi.qualifiers.CpuProfiling; 19 | import org.iproduct.demo.profiler.server.model.CpuLoad; 20 | import org.iproduct.demo.profiler.server.model.ProcessInfo; 21 | import org.iproduct.flow.IntervalPublisher; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | @ApplicationScoped 26 | public class Profiler { 27 | 28 | @Inject 29 | @CpuProfiling 30 | private Event event; 31 | 32 | private List oldProcesses; 33 | 34 | private Logger logger = LoggerFactory.getLogger(Profiler.class); 35 | 36 | public Profiler() { 37 | logger.info("!!!!! Profiler bean created successfully."); 38 | } 39 | 40 | // public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { 41 | // logger.info("Profiler successfully initialized."); 42 | // } 43 | // 44 | // public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) { 45 | // logger.info("Profiler destroyed."); 46 | // } 47 | 48 | public Stream getJavaProcessesStream() { 49 | return ProcessHandle.allProcesses() 50 | .filter(ph -> ph.info().toString().indexOf("java") >= 0); 51 | } 52 | 53 | public List getJavaProcesses() { 54 | List allProcesses = getJavaProcessesStream() 55 | .filter( ph -> ph.info().command().isPresent() ) 56 | .map( ph -> new ProcessInfo(ph.pid(), ph.info().command().get()) ) 57 | .collect(Collectors.toList()); 58 | return allProcesses; 59 | } 60 | 61 | public double getJavaCPULoad() { 62 | double allTime = getJavaProcessesStream().map(ph -> { 63 | // System.out.println(info); 64 | Optional time = ph.info().totalCpuDuration(); 65 | return (time.isPresent()) ? time.get().get(ChronoUnit.NANOS) : 0d; 66 | }).collect(Collectors.summingDouble(time -> time)); 67 | return allTime / 1000000d; 68 | } 69 | 70 | public boolean areProcessesChanged() { 71 | List newProcesses = getJavaProcesses(); 72 | boolean result = ! newProcesses.equals(oldProcesses); 73 | oldProcesses = newProcesses; 74 | return result; 75 | } 76 | 77 | @PostConstruct 78 | public void subscribeForCpuEvents() { 79 | IntervalPublisher.getDefaultIntervalPublisher(500, TimeUnit.MILLISECONDS) 80 | .subscribe(new Subscriber() { 81 | 82 | @Override 83 | public void onComplete() {} 84 | 85 | @Override 86 | public void onError(Throwable t) {} 87 | 88 | @Override 89 | public void onNext(Integer i) { 90 | event.fireAsync(new CpuLoad(System.currentTimeMillis(), (int) getJavaCPULoad(), areProcessesChanged())) 91 | .thenAccept(event -> { 92 | // logger.info("CPU load event fired: " + event); 93 | }); 94 | } 95 | 96 | @Override 97 | public void onSubscribe(Subscription subscription) { 98 | subscription.request(Long.MAX_VALUE); 99 | } 100 | }); 101 | } 102 | 103 | public static void main(String[] args) throws InterruptedException { 104 | // Profiler profiler = new Profiler(); 105 | // Flowable.interval(1000, TimeUnit.MILLISECONDS).map(t -> profiler.getJavaCPULoad()) 106 | // .subscribe(System.out::println); 107 | // Thread.sleep(100000); 108 | 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/demo/profiler/server/utility/LoadCPU.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.server.utility; 2 | 3 | public class LoadCPU { 4 | 5 | public static void main(String[] args) { 6 | long result = 0; 7 | for(long n = 0; n < 10000000000L; n++) { 8 | result += n; 9 | } 10 | System.out.println(result); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/flow/FlowSubscriber.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.Flow.Subscriber; 5 | import java.util.concurrent.Flow.Subscription; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | public class FlowSubscriber implements Subscriber { 9 | 10 | private static final String LOG_FORMAT = " Subscriber %s >> [%s] %s%n"; 11 | private final Random random = new Random(); 12 | 13 | private Subscription subscription; 14 | private AtomicInteger remaining; 15 | 16 | private String name; 17 | private int demand = 0; 18 | 19 | public FlowSubscriber(String name) { 20 | this.name = name; 21 | } 22 | 23 | @Override 24 | public void onSubscribe(Subscription subscription) { 25 | log("Subscribed..."); 26 | this.subscription = subscription; 27 | 28 | request(demand); 29 | } 30 | 31 | public void setDemand(int n) { 32 | this.demand = n; 33 | remaining = new AtomicInteger(demand); 34 | } 35 | 36 | private void request(int n) { 37 | log("requesting " + n + " new items..."); 38 | subscription.request(n); 39 | } 40 | 41 | @Override 42 | public void onNext(T item) { 43 | log("item: " + item); 44 | 45 | if (remaining.decrementAndGet() == 0) { 46 | if (random.nextBoolean()) { 47 | request(demand); 48 | remaining.set(demand); 49 | } else { 50 | log("Cancel subscription..."); 51 | subscription.cancel(); 52 | } 53 | } 54 | 55 | } 56 | 57 | @Override 58 | public void onComplete() { 59 | log("Complete!"); 60 | } 61 | 62 | @Override 63 | public void onError(Throwable t) { 64 | log("Error: " + t.getMessage()); 65 | } 66 | 67 | private void log(String message, Object... args) { 68 | String fullMessage = String.format(LOG_FORMAT, this.name, Thread.currentThread().getName(), message); 69 | System.out.printf(fullMessage, args); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/flow/HotPublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.concurrent.Flow.Publisher; 4 | 5 | public interface HotPublisher extends Publisher{ 6 | void cancel(boolean mayInterruptIfRunning); 7 | void join(); 8 | } 9 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/java/org/iproduct/flow/IntervalPublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flow; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.ForkJoinPool; 6 | import java.util.concurrent.SubmissionPublisher; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | import java.util.function.Function; 10 | import java.util.function.Supplier; 11 | 12 | public class IntervalPublisher extends SubmissionPublisher implements HotPublisher { 13 | public static final int DEFAULT_MAX_BUFFER_CAPACITY = 256; 14 | private volatile CompletableFuture finished = new CompletableFuture(); 15 | private Supplier supplier; 16 | private Executor executor; 17 | private long period; 18 | private TimeUnit unit; 19 | private boolean wasActivated; 20 | private Function onerror = throwable -> { 21 | closeExceptionally(throwable); 22 | finished.completeExceptionally(throwable); 23 | return null; 24 | }; 25 | 26 | public static HotPublisher getDefaultIntervalPublisher(long period, TimeUnit unit) { 27 | AtomicInteger i = new AtomicInteger(0); 28 | return new IntervalPublisher(i::incrementAndGet, period, unit); 29 | } 30 | 31 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit, Executor executor, int maxBufferCapacity) { 32 | super(executor, maxBufferCapacity); 33 | this.supplier = supplier; 34 | this.executor = executor; 35 | this.period = period; 36 | this.unit = unit; 37 | 38 | CompletableFuture 39 | .supplyAsync(supplier, CompletableFuture.delayedExecutor(delay, unit, executor)) 40 | .thenAccept(this::onCompletion) 41 | .exceptionally( onerror ); 42 | } 43 | 44 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit, Executor executor) { 45 | this(supplier, delay, period, unit, executor, DEFAULT_MAX_BUFFER_CAPACITY); 46 | } 47 | 48 | public IntervalPublisher(Supplier supplier, long delay, long period, TimeUnit unit) { 49 | this(supplier, delay, period, unit, ForkJoinPool.commonPool()); 50 | } 51 | 52 | public IntervalPublisher(Supplier supplier, long period, TimeUnit unit) { 53 | this(supplier, 0, period, unit); 54 | } 55 | 56 | private void onCompletion(T item) { 57 | if(hasSubscribers()) { 58 | wasActivated = true; 59 | submit(item); 60 | } else if(wasActivated) { 61 | close(); 62 | return; 63 | } 64 | 65 | CompletableFuture 66 | .supplyAsync(supplier, CompletableFuture.delayedExecutor(period, unit, executor)) 67 | .thenAccept(this::onCompletion) 68 | .exceptionally( onerror ); 69 | } 70 | 71 | @Override 72 | public void close() { 73 | // System.out.println("Closing..."); 74 | finished.complete(null); 75 | super.close(); 76 | } 77 | 78 | public void cancel(boolean mayInterruptIfRunning) { 79 | finished.cancel(mayInterruptIfRunning); 80 | }; 81 | 82 | public void join() { 83 | finished.join(); 84 | } 85 | 86 | public static void main(String[] args) { 87 | 88 | HotPublisher publisher = IntervalPublisher.getDefaultIntervalPublisher(1, TimeUnit.SECONDS); 89 | 90 | FlowSubscriber subA = new FlowSubscriber<>("A"); 91 | subA.setDemand(2); 92 | 93 | FlowSubscriber subB = new FlowSubscriber<>("B"); 94 | subB.setDemand(5); 95 | 96 | publisher.subscribe(subA); 97 | publisher.subscribe(subB); 98 | 99 | // when all subscribers have unsubscribed - finish 100 | publisher.join(); 101 | 102 | System.out.println("Demo finished."); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/resources/META-INF/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/resources/META-INF/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # JBoss, Home of Professional Open Source 3 | # Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual 4 | # contributors by the @authors tag. See the copyright.txt in the 5 | # distribution for a full listing of individual contributors. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # Set root logger level to DEBUG and its only appender to A1. 18 | log4j.rootLogger=WARN, A1 19 | 20 | # A1 is set to be a ConsoleAppender. 21 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 22 | 23 | # A1 uses PatternLayout. 24 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout 25 | log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n 26 | -------------------------------------------------------------------------------- /completable-future-jaxrs-cdi-jersey/src/main/resources/web-ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SSE: Apache CXF example 5 | 6 | 7 | 12 | 13 | 14 | 15 |
    16 |
    17 |
    18 |

    Active Java Processes:

    19 |
      20 |
      21 |
      22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /flow-demo/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .mvn/ 3 | *.iml 4 | *.ipr 5 | *.iws 6 | .DS_Store 7 | .checkstyle 8 | .classpath 9 | .ekstazi 10 | .pmd 11 | .pmdruleset 12 | .pmdruleset.xml 13 | .project 14 | .ruleset 15 | .settings/ 16 | target/ 17 | velocity.log 18 | /bin/ 19 | node_modules/ 20 | derby.log 21 | -------------------------------------------------------------------------------- /flow-demo/src/org/iproduct/flowdemo/CompletableFutureFromPublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flowdemo; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.Flow.Publisher; 5 | import java.util.concurrent.Flow.Subscriber; 6 | import java.util.concurrent.Flow.Subscription; 7 | 8 | public class CompletableFutureFromPublisher extends CompletableFuture { 9 | private Subscription subscription; 10 | 11 | public CompletableFutureFromPublisher(Publisher publisher) { 12 | publisher.subscribe(new Subscriber<>() { 13 | 14 | @Override 15 | public void onComplete() { 16 | CompletableFutureFromPublisher.this.complete(null); 17 | } 18 | 19 | @Override 20 | public void onError(Throwable t) { 21 | CompletableFutureFromPublisher.this.completeExceptionally(t); 22 | } 23 | 24 | @Override 25 | public void onNext(T item) { 26 | } 27 | 28 | @Override 29 | public void onSubscribe(Subscription subscription) { 30 | CompletableFutureFromPublisher.this.subscription = subscription; 31 | subscription.request(Integer.MAX_VALUE); 32 | } 33 | }); 34 | } 35 | 36 | @Override 37 | public boolean cancel(boolean mayInterruptIfRunning) { 38 | subscription.cancel(); 39 | return super.cancel(mayInterruptIfRunning); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /flow-demo/src/org/iproduct/flowdemo/CompletableFuturePublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flowdemo; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.concurrent.CompletionException; 7 | import java.util.concurrent.Executor; 8 | import java.util.concurrent.ForkJoinPool; 9 | import java.util.concurrent.SubmissionPublisher; 10 | import java.util.concurrent.TimeUnit; 11 | import java.util.concurrent.atomic.AtomicInteger; 12 | import java.util.function.Supplier; 13 | import java.util.stream.Collectors; 14 | import java.util.stream.IntStream; 15 | 16 | public class CompletableFuturePublisher extends SubmissionPublisher { 17 | static final int MAX_BUFFER_CAPACITY = 2048; 18 | private static final String LOG_FORMAT = "Publisher >> [%s] %s%n"; 19 | private final List> futuresList; 20 | private final Random random = new Random(); 21 | 22 | CompletableFuturePublisher(Executor executor, int maxBufferCapacity, Supplier supplier, long period, 23 | TimeUnit unit) { 24 | super(executor, maxBufferCapacity); 25 | 26 | futuresList = IntStream.range(0, 15).boxed() 27 | // .map(i -> supplier.get()) 28 | .map(i -> CompletableFuture 29 | .supplyAsync(supplier, CompletableFuture.delayedExecutor(i, TimeUnit.SECONDS, executor)) 30 | // .supplyAsync(() -> i, CompletableFuture.delayedExecutor(random.nextInt(1000), TimeUnit.MILLISECONDS, executor)) 31 | .whenComplete((item, throwable) -> { 32 | if (throwable == null) { 33 | log("publishing item: " + item); 34 | submit(item); 35 | // log("estimateMaximumLag: " + super.estimateMaximumLag()); 36 | // log("estimateMinimumDemand: " + super.estimateMinimumDemand()); 37 | } else { 38 | log("error: " + throwable); 39 | closeExceptionally(throwable); 40 | } 41 | })) 42 | .collect(Collectors.toList()); 43 | 44 | // Remember to send onComplete to downstream subscribers when all items have 45 | // been generated 46 | CompletableFuture.allOf(futuresList.toArray(new CompletableFuture[0])).whenComplete(this::close); 47 | } 48 | 49 | public void close(Void v, Throwable t) { 50 | log("Closing..."); 51 | futuresList.forEach(future -> future.cancel(false)); 52 | super.close(); 53 | } 54 | 55 | private void log(String message, Object... args) { 56 | String fullMessage = String.format(LOG_FORMAT, Thread.currentThread().getName(), message); 57 | System.out.printf(fullMessage, args); 58 | } 59 | 60 | public static void main(String[] args) { 61 | AtomicInteger i = new AtomicInteger(0); 62 | Supplier supplier = () -> "result-" + i.incrementAndGet(); 63 | // Supplier supplier = () -> { 64 | // if( i.get() != 13 ) 65 | // return "result-" + i.incrementAndGet(); 66 | // else 67 | // throw new RuntimeException("Exception - result can not be 13!"); 68 | // }; 69 | 70 | CompletableFuturePublisher publisher = new CompletableFuturePublisher<>(ForkJoinPool.commonPool(), 71 | MAX_BUFFER_CAPACITY, supplier, 1, TimeUnit.SECONDS); 72 | FlowSubscriber subA = new FlowSubscriber<>("A"); 73 | subA.setDemand(5); 74 | 75 | FlowSubscriber subB = new FlowSubscriber<>("B"); 76 | subB.setDemand(10); 77 | 78 | publisher.subscribe(subA); 79 | publisher.subscribe(subB); 80 | 81 | CompletableFutureFromPublisher complete = new CompletableFutureFromPublisher<>(publisher); 82 | try { 83 | complete.join(); 84 | } catch (CompletionException ex) { 85 | System.out.println("Demo completed with error: " + ex.getMessage() ); 86 | } 87 | 88 | System.out.println("Demo finished."); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /flow-demo/src/org/iproduct/flowdemo/FlowProcessor.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flowdemo; 2 | 3 | import java.util.concurrent.CompletionException; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Flow; 6 | import java.util.concurrent.Flow.Subscription; 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | import java.util.concurrent.ForkJoinPool; 9 | import java.util.concurrent.SubmissionPublisher; 10 | import java.util.concurrent.TimeUnit; 11 | import java.util.function.Function; 12 | import java.util.function.Supplier; 13 | 14 | public class FlowProcessor extends SubmissionPublisher implements Flow.Processor { 15 | private static final int MAX_BUFFER_CAPACITY = 1024; 16 | private static final String LOG_FORMAT = " Processor >> [%s] %s%n"; 17 | private final Function function; 18 | private Subscription subscription; 19 | 20 | FlowProcessor(Executor executor, int maxBufferCapacity, Function function) { 21 | super(executor, maxBufferCapacity); 22 | this.function = function; 23 | } 24 | 25 | @Override 26 | public void onSubscribe(Flow.Subscription subscription) { 27 | (this.subscription = subscription).request(1); 28 | } 29 | 30 | @Override 31 | public void onNext(I item) { 32 | subscription.request(1); 33 | O output = function.apply(item); 34 | log("Transforming: %s --> %s", item, output); 35 | submit(output); 36 | 37 | } 38 | 39 | @Override 40 | public void onError(Throwable ex) { 41 | closeExceptionally(ex); 42 | } 43 | 44 | @Override 45 | public void onComplete() { 46 | close(); 47 | } 48 | 49 | private void log(String message, Object... args) { 50 | String formatted = String.format(LOG_FORMAT, Thread.currentThread().getName(), message); 51 | System.out.printf(formatted, args); 52 | } 53 | 54 | public static void main(String[] args) { 55 | AtomicInteger i = new AtomicInteger(0); 56 | Supplier supplier = () -> i.incrementAndGet(); 57 | // Supplier supplier = () -> { 58 | // if( i.get() != 13 ) 59 | // return "result-" + i.incrementAndGet(); 60 | // else 61 | // throw new RuntimeException("Exception - result can not be 13!"); 62 | // }; 63 | 64 | CompletableFuturePublisher publisher = new CompletableFuturePublisher<>(ForkJoinPool.commonPool(), MAX_BUFFER_CAPACITY, supplier, 65 | 1, TimeUnit.SECONDS); 66 | 67 | FlowProcessor transformer = 68 | new FlowProcessor<>(ForkJoinPool.commonPool(), MAX_BUFFER_CAPACITY, n -> "transformation-result-" + n); 69 | 70 | FlowSubscriber subA = new FlowSubscriber<>("A"); 71 | subA.setDemand(5); 72 | 73 | FlowSubscriber subB = new FlowSubscriber<>("B"); 74 | subB.setDemand(10); 75 | 76 | publisher.subscribe(transformer); 77 | transformer.subscribe(subA); 78 | transformer.subscribe(subB); 79 | 80 | CompletableFutureFromPublisher complete = new CompletableFutureFromPublisher<>(publisher); 81 | try { 82 | complete.join(); 83 | } catch (CompletionException ex) { 84 | System.out.println("Demo completed with error: " + ex.getMessage()); 85 | } 86 | 87 | System.out.println("Demo finished."); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /flow-demo/src/org/iproduct/flowdemo/FlowSubscriber.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flowdemo; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.Flow.Subscriber; 5 | import java.util.concurrent.Flow.Subscription; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | public class FlowSubscriber implements Subscriber { 9 | 10 | private static final String LOG_FORMAT = " Subscriber %s >> [%s] %s%n"; 11 | private final Random random = new Random(); 12 | 13 | private Subscription subscription; 14 | private AtomicInteger remaining; 15 | 16 | private String name; 17 | private int demand = 0; 18 | 19 | public FlowSubscriber(String name) { 20 | this.name = name; 21 | } 22 | 23 | @Override 24 | public void onSubscribe(Subscription subscription) { 25 | log("Subscribed..."); 26 | this.subscription = subscription; 27 | 28 | request(demand); 29 | } 30 | 31 | public void setDemand(int n) { 32 | this.demand = n; 33 | remaining = new AtomicInteger(demand); 34 | } 35 | 36 | private void request(int n) { 37 | log("requesting " + n + " new items..."); 38 | subscription.request(n); 39 | } 40 | 41 | @Override 42 | public void onNext(T item) { 43 | log("item: " + item); 44 | 45 | if (remaining.decrementAndGet() == 0) { 46 | if (random.nextBoolean()) { 47 | request(demand); 48 | remaining.set(demand); 49 | } else { 50 | log("Cancel subscription..."); 51 | subscription.cancel(); 52 | } 53 | } 54 | 55 | } 56 | 57 | @Override 58 | public void onComplete() { 59 | log("Complete!"); 60 | } 61 | 62 | @Override 63 | public void onError(Throwable t) { 64 | log("Error: " + t.getMessage()); 65 | } 66 | 67 | private void log(String message, Object... args) { 68 | String fullMessage = String.format(LOG_FORMAT, this.name, Thread.currentThread().getName(), message); 69 | System.out.printf(fullMessage, args); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /flow-demo/src/org/iproduct/flowdemo/ScheduledFuturePublisher.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.flowdemo; 2 | 3 | import java.util.concurrent.Executor; 4 | import java.util.concurrent.ForkJoinPool; 5 | import java.util.concurrent.ScheduledExecutorService; 6 | import java.util.concurrent.ScheduledFuture; 7 | import java.util.concurrent.ScheduledThreadPoolExecutor; 8 | import java.util.concurrent.SubmissionPublisher; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | import java.util.function.Supplier; 12 | 13 | public class ScheduledFuturePublisher extends SubmissionPublisher { 14 | private static final String LOG_FORMAT = "Publisher >> [%s] %s%n"; 15 | static final int MAX_BUFFER_CAPACITY = 256; 16 | static final int MAX_ITEMS = 9; 17 | final ScheduledFuture periodicTask; 18 | final ScheduledExecutorService scheduler; 19 | 20 | 21 | ScheduledFuturePublisher(Executor executor, int maxBufferCapacity, 22 | Supplier supplier, 23 | long period, TimeUnit unit) { 24 | super(executor, maxBufferCapacity); 25 | scheduler = new ScheduledThreadPoolExecutor(1); 26 | periodicTask = scheduler.scheduleAtFixedRate( 27 | () -> { 28 | T item = supplier.get(); 29 | log("publishing item: " + item); 30 | submit(item); 31 | if(item.equals("result-" + MAX_ITEMS)) { 32 | close(); 33 | } 34 | }, 0, period, unit); 35 | } 36 | 37 | public void close() { 38 | log("Closing..."); 39 | periodicTask.cancel(false); 40 | scheduler.shutdown(); 41 | super.close(); 42 | log("Demo finished."); 43 | } 44 | 45 | private void log(String message, Object... args) { 46 | String fullMessage = String.format(LOG_FORMAT, Thread.currentThread().getName(), message); 47 | System.out.printf(fullMessage, args); 48 | } 49 | 50 | public static void main(String[] args) { 51 | AtomicInteger i = new AtomicInteger(0); 52 | Supplier supplier = () -> "result-" + i.incrementAndGet(); 53 | ScheduledFuturePublisher publisher = 54 | new ScheduledFuturePublisher<>(ForkJoinPool.commonPool(), MAX_BUFFER_CAPACITY, supplier, 1, TimeUnit.SECONDS); 55 | FlowSubscriber subA = new FlowSubscriber<>("A"); 56 | subA.setDemand(5); 57 | 58 | FlowSubscriber subB = new FlowSubscriber<>("B"); 59 | subB.setDemand(10); 60 | 61 | publisher.subscribe(subA); 62 | publisher.subscribe(subB); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /http2-client/.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | -------------------------------------------------------------------------------- /http2-client/lib/gson.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/http2-client/lib/gson.jar -------------------------------------------------------------------------------- /http2-client/src/module-info.java: -------------------------------------------------------------------------------- 1 | 2 | module org.iproduct.demo.profiler.client { 3 | requires java.se; 4 | requires jdk.incubator.httpclient; 5 | requires gson; 6 | exports org.iproduct.demo.profiler.client; 7 | exports org.iproduct.demo.profiler.client.model; 8 | opens org.iproduct.demo.profiler.client.model to gson; 9 | } -------------------------------------------------------------------------------- /http2-client/src/org/iproduct/demo/profiler/client/ProfilerAppClient.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.demo.profiler.client; 2 | 3 | import java.net.URI; 4 | import java.net.URISyntaxException; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | //import javax.ws.rs.core.GenericType; 9 | //import javax.ws.rs.sse.SseEventSource; 10 | 11 | import org.iproduct.demo.profiler.client.model.ProcessInfo; 12 | //import org.slf4j.Logger; 13 | //import org.slf4j.LoggerFactory; 14 | 15 | import com.google.gson.Gson; 16 | import com.google.gson.GsonBuilder; 17 | import com.google.gson.reflect.TypeToken; 18 | 19 | import jdk.incubator.http.HttpClient; 20 | import jdk.incubator.http.HttpRequest; 21 | import jdk.incubator.http.HttpResponse; 22 | 23 | 24 | public class ProfilerAppClient { 25 | public static final String PROFILER_API_URL = "http://localhost:8080/rest/api/"; 26 | 27 | 28 | public static void main(String[] args) throws URISyntaxException, InterruptedException { 29 | 30 | HttpClient client = HttpClient.newHttpClient(); 31 | 32 | HttpRequest processesReq = HttpRequest.newBuilder() 33 | .uri(new URI(PROFILER_API_URL + "processes")) 34 | .GET() 35 | .build(); 36 | 37 | TypeToken> token = new TypeToken>() {}; 38 | Gson gson = new GsonBuilder().create(); 39 | 40 | client.sendAsync(processesReq, HttpResponse.BodyHandler.asString()) 41 | .thenApply( (HttpResponse processesStr) -> { 42 | List something = gson.fromJson(processesStr.body(), token.getType()); 43 | return something; 44 | }).thenApply(proc -> { 45 | proc.stream().forEach(System.out::println); 46 | return null; 47 | }).exceptionally((Throwable ex) -> { 48 | System.out.println("Error: " + ex); 49 | return null; 50 | }).thenRun(() -> {System.exit(0);}); 51 | 52 | 53 | Thread.sleep(5000); 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /http2-client/src/org/iproduct/demo/profiler/client/model/CpuLoad.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.iproduct.demo.profiler.client.model; 20 | 21 | import java.io.Serializable; 22 | 23 | //@JsonInclude(value = Include.NON_NULL) 24 | public class CpuLoad implements Serializable { 25 | private static final long serialVersionUID = -6705829915457870975L; 26 | 27 | private long timestamp; 28 | private int load; 29 | private boolean changed; 30 | 31 | public CpuLoad() { 32 | } 33 | 34 | public CpuLoad(long timestamp, int load, boolean changed) { 35 | this.timestamp = timestamp; 36 | this.load = load; 37 | this.changed = changed; 38 | } 39 | 40 | public long getTimestamp() { 41 | return timestamp; 42 | } 43 | 44 | public void setTimestamp(long timestamp) { 45 | this.timestamp = timestamp; 46 | } 47 | 48 | public int getLoad() { 49 | return load; 50 | } 51 | 52 | public void setLoad(int load) { 53 | this.load = load; 54 | } 55 | 56 | public boolean isChanged() { 57 | return changed; 58 | } 59 | 60 | public void setChanged(boolean changed) { 61 | this.changed = changed; 62 | } 63 | 64 | public String toString() { 65 | return "CpuLoad[" + timestamp + ", " + load + ", changed: " + changed + "]"; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /http2-client/src/org/iproduct/demo/profiler/client/model/ProcessInfo.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.iproduct.demo.profiler.client.model; 20 | 21 | import java.io.Serializable; 22 | 23 | //import javax.xml.bind.annotation.XmlRootElement; 24 | 25 | //@XmlRootElement 26 | //@JsonInclude(value = Include.NON_NULL) 27 | public class ProcessInfo implements Serializable { 28 | private static final long serialVersionUID = -6705829915457870975L; 29 | 30 | private long pid; 31 | private String command; 32 | 33 | public ProcessInfo() { 34 | } 35 | 36 | public ProcessInfo(long pid, String command) { 37 | this.pid = pid; 38 | this.command = command; 39 | } 40 | 41 | public long getPid() { 42 | return pid; 43 | } 44 | 45 | public void setPid(long pid) { 46 | this.pid = pid; 47 | } 48 | 49 | public String getCommand() { 50 | return command; 51 | } 52 | 53 | public void setCommand(String command) { 54 | this.command = command; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | final int prime = 31; 60 | int result = 1; 61 | result = prime * result + ((command == null) ? 0 : command.hashCode()); 62 | result = prime * result + (int) (pid ^ (pid >>> 32)); 63 | return result; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) 69 | return true; 70 | if (obj == null) 71 | return false; 72 | if (getClass() != obj.getClass()) 73 | return false; 74 | ProcessInfo other = (ProcessInfo) obj; 75 | if (command == null) { 76 | if (other.command != null) 77 | return false; 78 | } else if (!command.equals(other.command)) 79 | return false; 80 | if (pid != other.pid) 81 | return false; 82 | return true; 83 | } 84 | 85 | public String toString() { 86 | return "ProcessInfo[" + pid + ", " + command + "]"; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /modularity-demo-intellij/client/src/client/HelloModularityClient.java: -------------------------------------------------------------------------------- 1 | package client; 2 | 3 | import provider.impl.HelloWorldMessageProvider; 4 | import renderer.impl.StandardOutMessageRenderer; 5 | 6 | public class HelloModularityClient { 7 | 8 | public static void main(String[] args) { 9 | HelloWorldMessageProvider provider = new HelloWorldMessageProvider(); 10 | StandardOutMessageRenderer renderer = new StandardOutMessageRenderer(); 11 | renderer.setMessageProvider(provider); 12 | renderer.render(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /modularity-demo-intellij/client/src/module-info.java: -------------------------------------------------------------------------------- 1 | module client { 2 | requires provider; 3 | requires renderer; 4 | } -------------------------------------------------------------------------------- /modularity-demo-intellij/lib/java-modularity-demo.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/lib/java-modularity-demo.jar -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/client/client/HelloModularityClient.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/client/client/HelloModularityClient.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/client/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/client/module-info.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/provider/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/provider/module-info.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/provider/provider/MessageProvider.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/provider/provider/MessageProvider.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/provider/provider/impl/HelloWorldMessageProvider.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/provider/provider/impl/HelloWorldMessageProvider.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/renderer/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/renderer/module-info.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/renderer/renderer/MessageRenderer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/renderer/renderer/MessageRenderer.class -------------------------------------------------------------------------------- /modularity-demo-intellij/out/production/renderer/renderer/impl/StandardOutMessageRenderer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo-intellij/out/production/renderer/renderer/impl/StandardOutMessageRenderer.class -------------------------------------------------------------------------------- /modularity-demo-intellij/provider/src/module-info.java: -------------------------------------------------------------------------------- 1 | module provider { 2 | exports provider; 3 | exports provider.impl; 4 | } -------------------------------------------------------------------------------- /modularity-demo-intellij/provider/src/provider/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package provider; 2 | 3 | public interface MessageProvider { 4 | String getMessage(); 5 | } 6 | -------------------------------------------------------------------------------- /modularity-demo-intellij/provider/src/provider/impl/HelloWorldMessageProvider.java: -------------------------------------------------------------------------------- 1 | package provider.impl; 2 | 3 | import provider.MessageProvider; 4 | 5 | public class HelloWorldMessageProvider implements MessageProvider { 6 | @Override 7 | public String getMessage() { 8 | return "Hello Java 9 Modularity!!!"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /modularity-demo-intellij/renderer/src/module-info.java: -------------------------------------------------------------------------------- 1 | module renderer { 2 | requires provider; 3 | exports renderer; 4 | exports renderer.impl; 5 | } -------------------------------------------------------------------------------- /modularity-demo-intellij/renderer/src/renderer/MessageRenderer.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import provider.MessageProvider; 4 | 5 | public interface MessageRenderer { 6 | void render(); 7 | void setMessageProvider(MessageProvider provider); 8 | MessageProvider getMessageProvider(); 9 | } 10 | -------------------------------------------------------------------------------- /modularity-demo-intellij/renderer/src/renderer/impl/StandardOutMessageRenderer.java: -------------------------------------------------------------------------------- 1 | package renderer.impl; 2 | 3 | import provider.MessageProvider; 4 | import renderer.MessageRenderer; 5 | 6 | public class StandardOutMessageRenderer implements MessageRenderer { 7 | private MessageProvider provider; 8 | 9 | @Override 10 | public void render() { 11 | if (provider == null) { 12 | throw new RuntimeException( 13 | "You must set the property messageProvider of class:" 14 | + StandardOutMessageRenderer.class.getName()); 15 | } 16 | System.out.println(provider.getMessage()); 17 | } 18 | 19 | @Override 20 | public void setMessageProvider(MessageProvider provider) { 21 | this.provider = provider; 22 | } 23 | 24 | @Override 25 | public MessageProvider getMessageProvider() { 26 | return provider; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /modularity-demo/client/bin/client/HelloModularityClient.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/client/bin/client/HelloModularityClient.class -------------------------------------------------------------------------------- /modularity-demo/client/bin/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/client/bin/module-info.class -------------------------------------------------------------------------------- /modularity-demo/client/src/client/HelloModularityClient.java: -------------------------------------------------------------------------------- 1 | package client; 2 | 3 | import java.util.Iterator; 4 | import java.util.ServiceLoader; 5 | 6 | import provider.MessageProvider; 7 | import renderer.MessageRenderer; 8 | //import provider.impl.HelloWorldMessageProvider; 9 | //import renderer.impl.StandardOutMessageRenderer; 10 | 11 | public class HelloModularityClient { 12 | 13 | public static void main(String[] args) { 14 | // MessageProvider provider = new MessageProvider(); 15 | ServiceLoader loaderProvider = ServiceLoader.load(MessageProvider.class); 16 | Iterator iterProvider = loaderProvider.iterator(); 17 | if (!iterProvider.hasNext()) throw new RuntimeException("No MessageProvider providers found!"); 18 | MessageProvider provider = iterProvider.next(); 19 | 20 | // MessageRenderer renderer = new StandardOutMessageRenderer(); 21 | ServiceLoader loaderRenderer = ServiceLoader.load(MessageRenderer.class); 22 | Iterator iterRenderer = loaderRenderer.iterator(); 23 | if (!iterRenderer.hasNext()) throw new RuntimeException("No MessageRenderer providers found!"); 24 | MessageRenderer renderer = iterRenderer.next(); 25 | 26 | renderer.setMessageProvider(provider); 27 | renderer.render(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /modularity-demo/client/src/module-info.java: -------------------------------------------------------------------------------- 1 | import provider.MessageProvider; 2 | import renderer.MessageRenderer; 3 | 4 | module client { 5 | requires provider; 6 | requires renderer; 7 | uses MessageProvider; 8 | uses MessageRenderer; 9 | exports client; 10 | } -------------------------------------------------------------------------------- /modularity-demo/modules/client.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/modules/client.jar -------------------------------------------------------------------------------- /modularity-demo/modules/provider.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/modules/provider.jar -------------------------------------------------------------------------------- /modularity-demo/modules/renderer.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/modules/renderer.jar -------------------------------------------------------------------------------- /modularity-demo/provider/bin/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/provider/bin/module-info.class -------------------------------------------------------------------------------- /modularity-demo/provider/bin/provider/MessageProvider.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/provider/bin/provider/MessageProvider.class -------------------------------------------------------------------------------- /modularity-demo/provider/bin/provider/impl/HelloWorldMessageProvider.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/provider/bin/provider/impl/HelloWorldMessageProvider.class -------------------------------------------------------------------------------- /modularity-demo/provider/src/module-info.java: -------------------------------------------------------------------------------- 1 | module provider { 2 | exports provider; 3 | provides provider.MessageProvider with provider.impl.HelloWorldMessageProvider; 4 | } -------------------------------------------------------------------------------- /modularity-demo/provider/src/provider/MessageProvider.java: -------------------------------------------------------------------------------- 1 | package provider; 2 | 3 | public interface MessageProvider { 4 | String getMessage(); 5 | } 6 | -------------------------------------------------------------------------------- /modularity-demo/provider/src/provider/impl/HelloWorldMessageProvider.java: -------------------------------------------------------------------------------- 1 | package provider.impl; 2 | 3 | import provider.MessageProvider; 4 | 5 | public class HelloWorldMessageProvider implements MessageProvider { 6 | @Override 7 | public String getMessage() { 8 | return "Hello Java 9 Modularity!!!"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /modularity-demo/renderer/bin/module-info.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/renderer/bin/module-info.class -------------------------------------------------------------------------------- /modularity-demo/renderer/bin/renderer/MessageRenderer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/renderer/bin/renderer/MessageRenderer.class -------------------------------------------------------------------------------- /modularity-demo/renderer/bin/renderer/impl/StandardOutMessageRenderer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iproduct/reactive-demos-java-9/17645d8d620e9ce3c86598222bc07009fcca190a/modularity-demo/renderer/bin/renderer/impl/StandardOutMessageRenderer.class -------------------------------------------------------------------------------- /modularity-demo/renderer/src/module-info.java: -------------------------------------------------------------------------------- 1 | module renderer { 2 | requires provider; 3 | exports renderer; 4 | // exports renderer.impl; 5 | provides renderer.MessageRenderer with renderer.impl.StandardOutMessageRenderer; 6 | } -------------------------------------------------------------------------------- /modularity-demo/renderer/src/renderer/MessageRenderer.java: -------------------------------------------------------------------------------- 1 | package renderer; 2 | 3 | import provider.MessageProvider; 4 | 5 | public interface MessageRenderer { 6 | void render(); 7 | void setMessageProvider(MessageProvider provider); 8 | MessageProvider getMessageProvider(); 9 | } 10 | -------------------------------------------------------------------------------- /modularity-demo/renderer/src/renderer/impl/StandardOutMessageRenderer.java: -------------------------------------------------------------------------------- 1 | package renderer.impl; 2 | 3 | import provider.MessageProvider; 4 | import renderer.MessageRenderer; 5 | 6 | public class StandardOutMessageRenderer implements MessageRenderer { 7 | private MessageProvider provider; 8 | 9 | @Override 10 | public void render() { 11 | if (provider == null) { 12 | throw new RuntimeException( 13 | "You must set the property messageProvider of class:" 14 | + StandardOutMessageRenderer.class.getName()); 15 | } 16 | System.out.println(provider.getMessage()); 17 | } 18 | 19 | @Override 20 | public void setMessageProvider(MessageProvider provider) { 21 | this.provider = provider; 22 | } 23 | 24 | @Override 25 | public MessageProvider getMessageProvider() { 26 | return provider; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /rxjava2-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | ipt-demos 5 | rxjava2-demo 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | io.reactivex.rxjava2 10 | rxjava 11 | 2.0.7 12 | 13 | 14 | -------------------------------------------------------------------------------- /rxjava2-demo/src/main/java/org/iproduct/rxjava/HelloInterval.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.rxjava; 2 | import java.util.concurrent.TimeUnit; 3 | 4 | import io.reactivex.Flowable; 5 | import io.reactivex.schedulers.Schedulers; 6 | 7 | public class HelloInterval { 8 | 9 | public static void main(String[] args) throws InterruptedException { 10 | Flowable cold = Flowable.intervalRange(1,10,0,200, TimeUnit.MILLISECONDS); 11 | cold.subscribe(i -> System.out.println("First: " + i)); 12 | Thread.sleep(500); 13 | cold.subscribe(i -> System.out.println("Second: " + i)); 14 | Thread.sleep(2000); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /rxjava2-demo/src/main/java/org/iproduct/rxjava/HelloIntervalHot.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.rxjava; 2 | import java.util.concurrent.TimeUnit; 3 | 4 | import io.reactivex.Flowable; 5 | import io.reactivex.flowables.ConnectableFlowable; 6 | 7 | public class HelloIntervalHot { 8 | 9 | public static void main(String[] args) throws InterruptedException { 10 | ConnectableFlowable hot = Flowable.intervalRange(1,10,0,200, TimeUnit.MILLISECONDS).publish();; 11 | 12 | // Instructs the ConnectableObservable to begin emitting the items 13 | // from its underlying Flowable to its Subscribers. 14 | hot.connect(); 15 | 16 | hot.subscribe(i -> System.out.println("First: " + i)); 17 | Thread.sleep(500); 18 | hot.subscribe(i -> System.out.println("Second: " + i)); 19 | Thread.sleep(2000); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rxjava2-demo/src/main/java/org/iproduct/rxjava/HelloRxJava.java: -------------------------------------------------------------------------------- 1 | package org.iproduct.rxjava; 2 | import io.reactivex.*; 3 | 4 | public class HelloRxJava { 5 | 6 | public static void main(String[] args) throws InterruptedException { 7 | Flowable cold = Flowable.just("Hello", "Reactive", "World", "from", "RxJava", "!"); 8 | cold.subscribe(i -> System.out.println("First: " + i)); 9 | Thread.sleep(500); 10 | cold.subscribe(i -> System.out.println("Second: " + i)); 11 | } 12 | } 13 | --------------------------------------------------------------------------------