├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── ozark-react-flow.gif ├── package.json ├── pom.xml ├── src └── main │ ├── java │ └── dasniko │ │ └── ozark │ │ └── react │ │ ├── Book.java │ │ ├── BookApplication.java │ │ ├── BookController.java │ │ ├── BookService.java │ │ ├── NashornPool.java │ │ ├── NashornPoolFactory.java │ │ ├── React.java │ │ ├── ReactController.java │ │ └── ReactViewEngine.java │ ├── resources │ ├── META-INF │ │ └── resources │ │ │ └── js │ │ │ └── app.js │ ├── jsx │ │ ├── book.jsx │ │ ├── bookBox.jsx │ │ ├── bookForm.jsx │ │ ├── bookList.jsx │ │ └── index.jsx │ └── nashorn-polyfill.js │ └── webapp │ ├── WEB-INF │ ├── beans.xml │ └── views │ │ └── react.jsp │ └── index.jsp └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | build 3 | .gradle 4 | .DS_Store 5 | 6 | # IntelliJ IDEA 7 | *.iml 8 | .idea 9 | 10 | # Eclipse IDE 11 | .classpath 12 | .project 13 | .settings 14 | node 15 | node_modules 16 | src/main/resources/js 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | before_cache: 5 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 6 | cache: 7 | directories: 8 | - $HOME/.gradle/caches/ 9 | - $HOME/.gradle/wrapper/ 10 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Niko Köbler 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Isomorphic (Universal) Ozark ReactJS ViewEngine Demo 2 | 3 | [![Release](https://img.shields.io/github/release/dasniko/ozark-react.svg)](https://jitpack.io/#dasniko/ozark-react) 4 | [![Build Status](https://img.shields.io/travis/dasniko/ozark-react.svg)](https://travis-ci.org/dasniko/ozark-react) 5 | [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/dasniko/ozark-react/blob/master/LICENSE) 6 | 7 | This is a simple demo application demonstrating how to use isomorphic/universal JavaScript with server-side pre-rendered [ReactJS](http://www.reactjs.org) templates with the new Java EE MVC 1.0 ([JSR-371](https://jcp.org/en/jsr/detail?id=371)) reference implementation [Ozark](https://github.com/mvc-spec/ozark). 8 | 9 | To establish the use of React.JS on the Java server-side, I created a `ViewEngine` implementation for Ozark/MVC 1.0, which uses the server-side rendering option of React.JS. 10 | 11 | ## Basics 12 | 13 | MVC 1.0 is at a very early stage and this project uses snapshot versions of Ozark. 14 | So there might be some not yet known effects/troubles when running the application. 15 | 16 | - [MVC 1.0](https://java.net/projects/mvc-spec/pages/Home) specification / [JSR-371](https://www.jcp.org/en/jsr/detail?id=371) 17 | - [Ozark reference implementation](https://github.com/mvc-spec/ozark) 18 | 19 | For your convenience, this project comes with all dependencies which are needed to run the application in a pure servlet-container like [Apache Tomcat](http://tomcat.apache.org) or [Jetty](http://eclipse.org/jetty/). 20 | So you don't have to rely on your container to provide all of the technology and libraries 21 | (Ozark itself is yet developed for [Glassfish](https://glassfish.java.net) only, but this might (hopefully) change in the future). 22 | 23 | 24 | ## Getting Started 25 | 26 | This project is Gradle based and comes with a Gradle Wrapper, so you don't have to have Gradle installed on your machine. 27 | To build the WAR file, just type 28 | 29 | $ ./gradlew build 30 | 31 | in your console/terminal. This will build a `ozark-react.war` in the `build/libs` folder. 32 | 33 | The project comes with all mechanisms to install and bundle all dependencies. 34 | Not only the Java deps, but also the NPM JavaScript dependencies like React.JS (the actual runtime lib), Webpack and Babel (for transpiling and bundling) 35 | 36 | _For your convenience, also a Maven `pom.xml` file is available._ 37 | 38 | You can deploy this WAR into an [Apache Tomcat](http://tomcat.apache.org) or [Jetty](http://eclipse.org/jetty/) servlet container. 39 | After starting your server, you should be able to access the application at this address: 40 | 41 | [http://localhost:8080/ozark/react](http://localhost:8080/ozark/react) 42 | 43 | ## Building the JavaScript artifacts 44 | 45 | I worked a lot on building, bundling and packaging (frontend) JavaScript artifacts with toolks like Maven and Gradle, which are not really meant for JavaScript (although it is possible, somehow). 46 | But after all, I came (again) to the end, that you should _use the right tool for the right job._ 47 | In case of JavaScript artifacts, this means you should definetely use tools from this ecosystem, like NPM, Webpack, Babel, Grunt, Gulp, and/or whatever. 48 | 49 | For this reason, I use Webpack with integrated Babel.js to transpile the JSX/ES6 components into executable JS (ES5) code and bundle it together with React.JS into one app file. 50 | This file is then used within the application at runtime (server- and client-side). 51 | 52 | Also, if this means that you have two different build tools (like Gradle and NPM here) for one project, the configuration and result of the tools is much better than trying something else. 53 | Luckily, it's easily possible, to start the NPM tasks from within the Gradle build process, so it won't become pain in the ass to run both when needed. 54 | 55 | ## Class Diagram / Data Flow 56 | 57 | This diagram gives you a rough overview of how the related classes depend on each other, resp. are communicating with each other 58 | _(it's no correct UML syntax!)_. 59 | 60 | ![](ozark-react-flow.gif) 61 | 62 | ## Contribution / Issues 63 | 64 | Don't hesitate to contribute to this project in any kind of sending [PRs](https://github.com/dasniko/ozark-react/pulls) for improvements, enhancements, and/or bug-fixes. 65 | 66 | I appreciate every issue that will be [reported](https://github.com/dasniko/ozark-react/issues). 67 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.moowork.node' version '0.12' 3 | } 4 | 5 | apply plugin: 'war' 6 | 7 | sourceCompatibility = JavaVersion.VERSION_1_8 8 | targetCompatibility = JavaVersion.VERSION_1_8 9 | 10 | repositories { 11 | mavenCentral() 12 | mavenLocal() 13 | // for glassfish/mvc/ozark dependencies 14 | maven { url 'https://maven.java.net/content/groups/public/' } 15 | } 16 | 17 | dependencies { 18 | // servlet-api 19 | providedCompile 'javax:javaee-web-api:7.0' 20 | // mvc api and ri 21 | compile 'javax.mvc:javax.mvc-api:1.0-edr2' 22 | compile 'org.glassfish.ozark:ozark:1.0.0-m03-SNAPSHOT' 23 | // required dependencies to be able to deploy to a plain servlet container like tomcat 24 | compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.22.2' 25 | compile 'org.glassfish.jersey.ext.cdi:jersey-cdi1x:2.22.2' 26 | compile 'org.glassfish.jersey.ext:jersey-bean-validation:2.22.2' 27 | compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.22.2' 28 | compile 'javax.enterprise:cdi-api:2.0-EDR1' 29 | compile 'org.jboss.weld.servlet:weld-servlet-core:3.0.0.Alpha12' 30 | compile 'org.apache.commons:commons-pool2:2.4.2' 31 | // some needed webjars (frontend-stuff) 32 | compile 'org.webjars:jquery:2.2.3' 33 | compile 'org.webjars:materializecss:0.97.5' 34 | } 35 | 36 | npm_run { 37 | args = ['webpack'] 38 | } 39 | 40 | processResources.dependsOn('npm_install', 'npm_run') 41 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dasniko/ozark-react/0bac867f2ab98b6afc040804b60256e53ceba15a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Sep 26 15:43:25 CEST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /ozark-react-flow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dasniko/ozark-react/0bac867f2ab98b6afc040804b60256e53ceba15a/ozark-react-flow.gif -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ozark-react", 3 | "version": "1.0.0", 4 | "description": "A ViewEngine for ReactJS templates for the Java EE MVC 1.0 reference implementation Ozark.", 5 | "main": "index.js", 6 | "dependencies": { 7 | "react": "^15.3.1", 8 | "react-dom": "^15.3.1" 9 | }, 10 | "devDependencies": { 11 | "babel-core": "^5.8.38", 12 | "babel-loader": "^5.4.2", 13 | "webpack": "^1.13.2" 14 | }, 15 | "scripts": { 16 | "test": "echo \"Error: no test specified\" && exit 1", 17 | "webpack": "./node_modules/.bin/webpack" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/dasniko/ozark-react.git" 22 | }, 23 | "keywords": [ 24 | "react", 25 | "ozark", 26 | "mvc", 27 | "java" 28 | ], 29 | "author": "Niko Köbler (http://www.n-k.de)", 30 | "license": "MIT", 31 | "bugs": { 32 | "url": "https://github.com/dasniko/ozark-react/issues" 33 | }, 34 | "homepage": "https://github.com/dasniko/ozark-react#readme" 35 | } 36 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | de.dasniko 7 | ozark-react 8 | 0.0.1-SNAPSHOT 9 | war 10 | 11 | Ozark React 12 | React.js ViewEngine for Ozark 13 | 14 | 15 | UTF-8 16 | 1.8 17 | 1.8 18 | 2.22.2 19 | 20 | 21 | 22 | 23 | javax 24 | javaee-web-api 25 | 7.0 26 | 27 | 28 | javax.mvc 29 | javax.mvc-api 30 | 1.0-edr2 31 | 32 | 33 | org.glassfish.ozark 34 | ozark 35 | 1.0.0-m03-SNAPSHOT 36 | 37 | 38 | org.glassfish.jersey.containers 39 | jersey-container-servlet 40 | ${jersey.version} 41 | 42 | 43 | org.glassfish.jersey.ext.cdi 44 | jersey-cdi1x 45 | ${jersey.version} 46 | 47 | 48 | org.glassfish.jersey.ext 49 | jersey-bean-validation 50 | ${jersey.version} 51 | 52 | 53 | org.glassfish.jersey.media 54 | jersey-media-json-jackson 55 | ${jersey.version} 56 | 57 | 58 | javax.enterprise 59 | cdi-api 60 | 2.0-EDR1 61 | 62 | 63 | org.jboss.weld.servlet 64 | weld-servlet-core 65 | 3.0.0.Alpha12 66 | 67 | 68 | org.apache.commons 69 | commons-pool2 70 | 2.4.2 71 | 72 | 73 | org.webjars 74 | jquery 75 | 2.2.3 76 | 77 | 78 | org.webjars 79 | materializecss 80 | 0.97.5 81 | 82 | 83 | 84 | 85 | ${project.artifactId} 86 | 87 | 88 | maven-war-plugin 89 | 2.6 90 | 91 | false 92 | 93 | 94 | 95 | com.github.eirslett 96 | frontend-maven-plugin 97 | 1.0 98 | 99 | 100 | install node and npm 101 | 102 | install-node-and-npm 103 | 104 | 105 | v6.2.2 106 | 3.9.5 107 | 108 | 109 | 110 | npm install 111 | 112 | npm 113 | 114 | 115 | 116 | webpack build 117 | 118 | webpack 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | java.net 129 | https://maven.java.net/content/groups/public/ 130 | 131 | true 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/Book.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | /** 4 | * @author Niko Köbler, http://www.n-k.de, @dasniko 5 | */ 6 | public class Book { 7 | 8 | private String author; 9 | private String title; 10 | 11 | public Book() { 12 | } 13 | 14 | public Book(String author, String title) { 15 | this.author = author; 16 | this.title = title; 17 | } 18 | 19 | public String getAuthor() { 20 | return author; 21 | } 22 | 23 | public void setAuthor(String author) { 24 | this.author = author; 25 | } 26 | 27 | public String getTitle() { 28 | return title; 29 | } 30 | 31 | public void setTitle(String title) { 32 | this.title = title; 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/BookApplication.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import javax.ws.rs.ApplicationPath; 4 | import javax.ws.rs.core.Application; 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | /** 10 | * @author Niko Köbler, http://www.n-k.de, @dasniko 11 | */ 12 | @ApplicationPath("/ozark") 13 | public class BookApplication extends Application { 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/BookController.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import javax.inject.Inject; 4 | import javax.ws.rs.*; 5 | import java.util.List; 6 | 7 | /** 8 | * @author Niko Köbler, http://www.n-k.de, @dasniko 9 | */ 10 | @Path("/books.json") 11 | public class BookController { 12 | 13 | @Inject 14 | private BookService service; 15 | 16 | @GET 17 | public List getBooks() { 18 | return service.getBooks(); 19 | } 20 | 21 | @POST 22 | public List addBook(Book book) { 23 | return service.addBook(book); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/BookService.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import javax.annotation.PostConstruct; 4 | import javax.enterprise.context.ApplicationScoped; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author Niko Köbler, http://www.n-k.de, @dasniko 10 | */ 11 | @ApplicationScoped 12 | public class BookService { 13 | 14 | private List books = new ArrayList<>(); 15 | 16 | @PostConstruct 17 | public void init() { 18 | books.add(new Book("George Orwell", "1984")); 19 | books.add(new Book("Douglas Adams", "Hitchhiker’s Guide to the Galaxy")); 20 | } 21 | 22 | public List getBooks() { 23 | return books; 24 | } 25 | 26 | public List addBook(Book book) { 27 | books.add(book); 28 | return books; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/NashornPool.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import org.apache.commons.pool2.ObjectPool; 4 | import org.apache.commons.pool2.impl.GenericObjectPool; 5 | import org.apache.commons.pool2.impl.GenericObjectPoolConfig; 6 | 7 | import javax.enterprise.context.ApplicationScoped; 8 | import javax.enterprise.context.Initialized; 9 | import javax.enterprise.event.Observes; 10 | import javax.enterprise.inject.Produces; 11 | import javax.script.ScriptEngine; 12 | 13 | /** 14 | * @author Niko Köbler, http://www.n-k.de, @dasniko 15 | */ 16 | @ApplicationScoped 17 | public class NashornPool { 18 | 19 | private GenericObjectPool pool; 20 | 21 | public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { 22 | GenericObjectPoolConfig config = new GenericObjectPoolConfig(); 23 | config.setMinIdle(1); 24 | 25 | pool = new GenericObjectPool<>(new NashornPoolFactory(), config); 26 | } 27 | 28 | @Produces 29 | public ObjectPool getObjectPool() { 30 | return this.pool; 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/NashornPoolFactory.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import org.apache.commons.pool2.BasePooledObjectFactory; 4 | import org.apache.commons.pool2.PooledObject; 5 | import org.apache.commons.pool2.impl.DefaultPooledObject; 6 | 7 | import javax.script.ScriptEngine; 8 | import javax.script.ScriptEngineManager; 9 | import javax.script.ScriptException; 10 | import java.io.File; 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.io.Reader; 14 | import java.net.URISyntaxException; 15 | import java.net.URL; 16 | import java.util.ArrayList; 17 | import java.util.Arrays; 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | 21 | /** 22 | * @author Niko Köbler, http://www.n-k.de, @dasniko 23 | */ 24 | public class NashornPoolFactory extends BasePooledObjectFactory { 25 | 26 | private static final String DEFAULT_JS_RESOURCE_PATH = "/js"; 27 | private static final String RESOURCE_PATH = System.getProperty("mvc.reactjs.resourcePath", DEFAULT_JS_RESOURCE_PATH); 28 | 29 | @Override 30 | public ScriptEngine create() throws Exception { 31 | ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); 32 | 33 | // initial basically needed files for dealing with react 34 | List jsResources = new ArrayList<>(); 35 | jsResources.add("nashorn-polyfill.js"); 36 | 37 | // add all resources from custom application 38 | jsResources.addAll(getAllFilesFromResourcePath()); 39 | // and load/evaluate them within nashorn 40 | jsResources.forEach(p -> { 41 | try { 42 | nashorn.eval(read(p)); 43 | } catch (ScriptException e) { 44 | throw new RuntimeException(e); 45 | } 46 | }); 47 | 48 | return nashorn; 49 | } 50 | 51 | @Override 52 | public PooledObject wrap(ScriptEngine scriptEngine) { 53 | return new DefaultPooledObject<>(scriptEngine); 54 | } 55 | 56 | private List getAllFilesFromResourcePath() { 57 | URL url = this.getClass().getClassLoader().getResource(RESOURCE_PATH); 58 | if (url != null && url.getProtocol().equals("file")) { 59 | try { 60 | return Arrays.stream(new File(url.toURI()).list()).map(p -> RESOURCE_PATH + "/" + p).collect(Collectors.toList()); 61 | } catch (URISyntaxException e) { 62 | throw new RuntimeException(e); 63 | } 64 | } else { 65 | // TODO do something 66 | return new ArrayList<>(); 67 | } 68 | } 69 | 70 | private Reader read(String path) { 71 | InputStream in = getClass().getClassLoader().getResourceAsStream(path); 72 | return new InputStreamReader(in); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/React.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import jdk.nashorn.api.scripting.ScriptObjectMirror; 4 | import org.apache.commons.pool2.ObjectPool; 5 | 6 | import javax.inject.Inject; 7 | import javax.script.Invocable; 8 | import javax.script.ScriptEngine; 9 | 10 | /** 11 | * @author Niko Köbler, http://www.n-k.de, @dasniko 12 | */ 13 | public class React { 14 | 15 | @Inject 16 | private ObjectPool scriptEnginePool; 17 | 18 | String render(String function, Object object) { 19 | try { 20 | Object html; 21 | ScriptEngine scriptEngine = scriptEnginePool.borrowObject(); 22 | if (function.contains(".")) { 23 | String[] parts = function.split("\\."); 24 | html = ((ScriptObjectMirror) scriptEngine.get(parts[0])).callMember(parts[1], object); 25 | } else { 26 | html = ((Invocable) scriptEngine).invokeFunction(function, object); 27 | } 28 | scriptEnginePool.returnObject(scriptEngine); 29 | return String.valueOf(html); 30 | } catch (Exception e) { 31 | throw new IllegalStateException("failed to render react component", e); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/ReactController.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import javax.inject.Inject; 4 | import javax.mvc.Models; 5 | import javax.mvc.annotation.Controller; 6 | import javax.ws.rs.GET; 7 | import javax.ws.rs.Path; 8 | import java.util.List; 9 | 10 | /** 11 | * @author Niko Köbler, http://www.n-k.de, @dasniko 12 | */ 13 | @Controller 14 | @Path("/react") 15 | public class ReactController { 16 | 17 | @Inject 18 | private Models models; 19 | 20 | @Inject 21 | private BookService service; 22 | 23 | @GET 24 | public String index() throws Exception { 25 | List books = service.getBooks(); 26 | models.put("data", books); 27 | return "react:react.jsp?function=BookApp.renderServer"; 28 | } 29 | 30 | // @GET 31 | // public String index() throws Exception { 32 | // List books = service.getBooks(); 33 | // ObjectMapper mapper = new ObjectMapper(); 34 | // models.put("data", mapper.writeValueAsString(books)); 35 | // return "react.jsp"; 36 | // } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/dasniko/ozark/react/ReactViewEngine.java: -------------------------------------------------------------------------------- 1 | package dasniko.ozark.react; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import javax.annotation.Priority; 7 | import javax.inject.Inject; 8 | import javax.mvc.Models; 9 | import javax.mvc.engine.Priorities; 10 | import javax.mvc.engine.ViewEngine; 11 | import javax.mvc.engine.ViewEngineContext; 12 | import javax.mvc.engine.ViewEngineException; 13 | import javax.servlet.RequestDispatcher; 14 | import javax.servlet.ServletContext; 15 | import javax.servlet.ServletException; 16 | import javax.servlet.ServletRegistration; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletRequestWrapper; 19 | import java.io.IOException; 20 | import java.util.Arrays; 21 | import java.util.Collection; 22 | import java.util.Map; 23 | import java.util.stream.Collectors; 24 | 25 | /** 26 | * @author Niko Köbler, http://www.n-k.de, @dasniko 27 | */ 28 | @Priority(Priorities.FRAMEWORK) 29 | public class ReactViewEngine implements ViewEngine { 30 | 31 | private static final String viewPrefix = "react:"; 32 | 33 | @Inject 34 | React react; 35 | @Inject 36 | ServletContext servletContext; 37 | 38 | private ObjectMapper mapper = new ObjectMapper(); 39 | 40 | @Override 41 | public boolean supports(String view) { 42 | return view.startsWith(viewPrefix); 43 | } 44 | 45 | @Override 46 | public void processView(ViewEngineContext context) throws ViewEngineException { 47 | // parse view and extract the actual template and the react.js function to call 48 | String view = context.getView(); 49 | String[] viewParts = view.substring(viewPrefix.length()).split("\\?"); 50 | if (viewParts.length < 2) { 51 | throw new ViewEngineException("You have to specify at least a view and a function (e.g. react:view.jsp?function=renderOnServer)!"); 52 | } 53 | 54 | String template = viewParts[0]; 55 | 56 | Map params = parseQueryString(viewParts[1]); 57 | String function = params.get("function"); 58 | 59 | String dataKey = params.getOrDefault("data", "data"); 60 | String contentKey = params.getOrDefault("content", "content"); 61 | 62 | // get "data" from model 63 | Models models = context.getModels(); 64 | Object data = models.get(dataKey); 65 | 66 | // call given js function on data 67 | String content = react.render(function, data); 68 | 69 | // and put results as string in model 70 | models.put(contentKey, content); 71 | try { 72 | models.put(dataKey, mapper.writeValueAsString(data)); 73 | } catch (JsonProcessingException e) { 74 | throw new ViewEngineException(e); 75 | } 76 | 77 | try { 78 | processRequest(context, models, template); 79 | } catch (ServletException | IOException e) { 80 | throw new ViewEngineException(e); 81 | } 82 | } 83 | 84 | private Map parseQueryString(final String query) { 85 | return Arrays.asList(query.split("&")).stream().map(p -> p.split("=")).collect(Collectors.toMap(s -> s[0], s -> s[1])); 86 | } 87 | 88 | private void processRequest(final ViewEngineContext context, final Models models, final String view) throws ServletException, IOException { 89 | RequestDispatcher requestDispatcher = null; 90 | HttpServletRequest request = context.getRequest(); 91 | 92 | for (String name : models) { 93 | request.setAttribute(name, models.get(name)); 94 | } 95 | 96 | final String viewExtension = getViewExtension(view); 97 | for (Map.Entry e : servletContext.getServletRegistrations().entrySet()) { 98 | final Collection mappings = e.getValue().getMappings(); 99 | if (mappings.contains(viewExtension)) { 100 | requestDispatcher = servletContext.getNamedDispatcher(e.getKey()); 101 | request = new HttpServletRequestWrapper(context.getRequest()) { 102 | @Override 103 | public String getRequestURI() { 104 | return resolveView(context, view); 105 | } 106 | 107 | @Override 108 | public String getServletPath() { 109 | return getRequestURI(); 110 | } 111 | 112 | @Override 113 | public String getPathInfo() { 114 | return null; 115 | } 116 | 117 | @Override 118 | public StringBuffer getRequestURL() { 119 | return new StringBuffer(getRequestURI()); 120 | } 121 | }; 122 | } 123 | } 124 | 125 | if (requestDispatcher == null) { 126 | requestDispatcher = servletContext.getRequestDispatcher(resolveView(context, view)); 127 | } 128 | 129 | requestDispatcher.forward(request, context.getResponse()); 130 | } 131 | 132 | private String getViewExtension(final String view) { 133 | return "*" + view.substring(view.lastIndexOf(".")); 134 | } 135 | 136 | private String resolveView(final ViewEngineContext context, final String view) { 137 | if (!view.startsWith("/")) { 138 | String viewFolder = (String) context.getConfiguration().getProperty(VIEW_FOLDER); 139 | viewFolder = viewFolder == null ? DEFAULT_VIEW_FOLDER : viewFolder; 140 | viewFolder += !viewFolder.endsWith("/") ? "/" : ""; 141 | return viewFolder + view; 142 | } 143 | return view; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/resources/js/app.js: -------------------------------------------------------------------------------- 1 | // we need this empty file as a reference to /resources/js/app.js, so we can use it from the browser -------------------------------------------------------------------------------- /src/main/resources/jsx/book.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default class Book extends React.Component { 4 | render() { 5 | return ( 6 |
7 |

{this.props.author}

8 |
{this.props.title}
9 |
10 |
11 | ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/jsx/bookBox.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import BookForm from "./bookForm"; 3 | import BookList from "./bookList"; 4 | 5 | export default class BookBox extends React.Component { 6 | constructor(props) { 7 | super(props); 8 | this.handleBookSubmit = this.handleBookSubmit.bind(this); 9 | this.loadBooksFromServer = this.loadBooksFromServer.bind(this); 10 | this.state = {data: props.data}; 11 | } 12 | 13 | handleBookSubmit(book) { 14 | var books = this.state.data; 15 | books.push(book); 16 | this.setState({data: books}, function () { 17 | $.ajax({ 18 | url: this.props.url, 19 | contentType: 'application/json', 20 | dataType: 'json', 21 | type: 'POST', 22 | data: JSON.stringify(book), 23 | success: function (data) { 24 | this.setState({data: data}); 25 | }.bind(this), 26 | error: function (xhr, status, err) { 27 | console.error(this.props.url, status, err.toString()); 28 | }.bind(this) 29 | }); 30 | }); 31 | } 32 | 33 | loadBooksFromServer() { 34 | $.ajax({ 35 | url: this.props.url, 36 | dataType: 'json', 37 | success: function (data) { 38 | this.setState({data: data}); 39 | }.bind(this), 40 | error: function (xhr, status, err) { 41 | console.error(this.props.url, status, err.toString()); 42 | }.bind(this) 43 | }); 44 | } 45 | 46 | componentDidMount() { 47 | this.loadBooksFromServer(); 48 | setInterval(this.loadBooksFromServer, this.props.pollInterval); 49 | } 50 | 51 | render() { 52 | return ( 53 |
54 |

Best Books ever!

55 | 56 | 57 |
58 | ); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/resources/jsx/bookForm.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default class BookForm extends React.Component { 4 | constructor(props) { 5 | super(props); 6 | this.handleSubmit = this.handleSubmit.bind(this); 7 | } 8 | 9 | handleSubmit(e) { 10 | e.preventDefault(); 11 | var author = this.refs.author.value.trim(); 12 | var title = this.refs.title.value.trim(); 13 | if (!author || !title) { 14 | return; 15 | } 16 | this.props.onBookSubmit({author: author, title: title}); 17 | this.refs.author.value = ''; 18 | this.refs.title.value = ''; 19 | } 20 | 21 | render() { 22 | return ( 23 |
24 |
25 |
Add a new book:
26 |
27 | 28 | 29 |
30 |
31 | 32 | 33 |
34 | 37 |
38 |
39 | ); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/resources/jsx/bookList.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Book from "./book"; 3 | 4 | export default class BookList extends React.Component { 5 | render() { 6 | let bookNodes = this.props.data.map(function (book, index) { 7 | return ( 8 | 9 | ); 10 | }); 11 | return ( 12 |
13 | {bookNodes} 14 |
15 | ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/resources/jsx/index.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import ReactDOMServer from "react-dom/server"; 4 | import BookBox from "./bookBox"; 5 | 6 | let renderClient = function (books) { 7 | var data = books || []; 8 | if (typeof window !== 'undefined') { 9 | ReactDOM.render( 10 | , 11 | document.getElementById("content") 12 | ); 13 | } 14 | }; 15 | 16 | let renderServer = function (books) { 17 | var data = Java.from(books); 18 | return ReactDOMServer.renderToString( 19 | 20 | ); 21 | }; 22 | 23 | module.exports = { 24 | renderClient: renderClient, 25 | renderServer: renderServer 26 | }; 27 | -------------------------------------------------------------------------------- /src/main/resources/nashorn-polyfill.js: -------------------------------------------------------------------------------- 1 | var global = this; 2 | var process = {env:{}}; 3 | 4 | var console = { 5 | debug: print, 6 | warn: print, 7 | error: print, 8 | log: print 9 | }; 10 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/react.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ReactJS Bookstore with Ozark 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
${content}
21 | 22 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page import="javax.enterprise.inject.spi.CDI" %> 2 | <%@ page import="javax.mvc.MvcContext" %> 3 | <%@ page contentType="text/html;charset=UTF-8" language="java" %> 4 | <% 5 | MvcContext mvc = CDI.current().select(MvcContext.class).get(); 6 | response.sendRedirect(mvc.getContextPath() + mvc.getApplicationPath() + "/react"); 7 | %> 8 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | var ROOT = path.resolve(__dirname, 'src/main/resources'); 3 | var SRC = path.resolve(ROOT, 'jsx'); 4 | var DEST = path.resolve(ROOT, 'js'); 5 | 6 | module.exports = { 7 | entry: SRC, 8 | resolve: { 9 | extensions: ['', '.js', '.jsx' ] 10 | }, 11 | output: { 12 | path: DEST, 13 | filename: 'app.js', 14 | publicPath: '/js/', 15 | library: "BookApp" 16 | }, 17 | module: { 18 | loaders: [ 19 | { 20 | test: /\.jsx?$/, 21 | loaders: ['babel'], 22 | include: SRC 23 | } 24 | ] 25 | } 26 | }; --------------------------------------------------------------------------------