Full Stack Reactive with React and Spring WebFlux

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] so we're warm welcome to the Java user group an online event we are doing these days and today actually we will have matter Abel from octa I'm doing his food Zak reactive with reactants bring back flux talk for us but actually in a different format as you know we have the corona virus spreading and the idea is actually not to spread it too much so that our healthcare system is actually not all flooded with people so that's why we are now like trying this opportunity to actually use a new format and doing it online so yeah the new format actually was for us in the last few days something where we tried to find a platform how we can do live streaming and actually it pushed us in a direction where we try to work with new tools and let's see what that means also for the future for us so if we are continuing to doing this format or we like like to a mixture of the current or the standard dogs and peers and as well their own format as well so we will have at the end of the talk a feedback forum which should pop about automatically for you so please answer the questions as usual during the Java use group talks so that would be really awesome you will actually see that we will have some delay in the stream so that means if you answer or if you write questions into the chat we cannot immediately see that we will see that a bit later because we are like 15 seconds ahead of you please use for questions and not the chat the chat is meant like if you have technical problems ask your questions there and markers from the Java youth group likely help you so for questions which you have format please use the Q&A because that is like the area to do it because that we just have the questions filtered and that makes it very easy for us to monitor the question so if the question is a good fit to the current talk of net I will pick that up jump in and we'll ask him the questions directly if there are like more general questions we will wait until the end so Matt can answer the questions at the end yes Matt will also will use a feature which is called pods so you will see on your screen and above actually the video some pop up coming up where you have to answer those questions so press one of these options it's not always yes or no sometimes it is sometimes not you might have also multiple option for answering right so we will make sure that you have enough time to answer those questions and then also met will use that in his further presentation so now I would love to hand over directly to Matt and I'm really happy to have him actually online because we just talked before and I was realizing that I saw him about about 20 and not 20 but about 10 years ago and at devoxx the first time and since then he is like a crazy guy traveling the world talking especially about a hipster spring boots and also um all these octa stuff so Matt the stage is yours thank you all right let me share my screen here all right welcome to full-stack reactive with react and spring web flux this whole presentation started from a collaboration that Josh long and I did so I like to give him some credit because this is his work as well and so I throw the slide up there for him first and you can contact him on Twitter or there's his email as well and what Josh did is he actually we collaborated on a blog post and it's a three part series where he does an introduction to reactive programming and then we talk about Spring web flux and how you build api's with it and then in the final series we add react and we do everything that I'm going to show you today well we wrote so much information in those first couple articles that he decided to write a book on reactive spring so if you go to reactive spring book IO there is a beta version of his book that you can download and in a lot of what you'll see here today is in there so my name is Matt rable I like to ski and mountain bike and whitewater raft I was actually born in the backwoods of Montana in a log cabin on the left there my parents had the bedroom on the right and that was built by my great grandparents way back in 1917 and so I grew up there no electricity no running water I had to use an outhouse and all that for 16 years and walked two miles to the bus stop every day so it felt like it was uphill both ways but in the winter we get to ski I live in Denver Colorado with my beautiful wife Trish and my two awesome kids Abby and Jack this photo is a couple years old jack is actually taller and bigger than me now so a lot happens when they start to grow up and become teenagers I also have a middle child his name is jefe for Hefeweizen since he is a German vehicle I bought in my FIBA in 2004 and I spent the next 12 years restoring him I didn't do it myself because I didn't have the tools but I should have because now I have the tools that went through seven different shops and took quite some time so if he followed me on my blog I always thought it was going to be done in six months and so I guess I'm good at hope I work for a company called octa my dad calls it okra so feel free to mispronounce it but octa the word actually is a unit of cloud measurement it means that how many clouds are in the sky if it's an a talk today that's the maximum number it means it's very overcast very cloudy if it's a zero OCH today it means it's nice and sunny so we do users as a software service acronym for that's not great you ask so I like to say user management as a software service and if you sign up for a developer account at developer.com you get up to a thousand monthly active users for free and if you want to up that then of course you can pay for it so now I have a bunch of polls that I'd like to ask to learn a bit more about you and so I'm going to send these polls out and then I'm gonna have a little time here to wait 30 seconds because first of all I know you're delayed and also as soon as I send one poll it erases the the previous one so we'll send that one out first are you using spring boot so I like to get a feel from the audience how many people are using spring boot and I'll start that timer about 15 seconds left here then I'll start the next one the next one's going to be more about using spring wet flux so if your spring flood flux user because I know just because you're using spring boot doesn't necessarily mean you're using spring wet flux so send that one out and then my next question is going to be what's your preferred JVM language between Scala Java groovy and Kotlin so from the first one looks like most people are using spring but-- 85 percent are using spring warp flux 15 percent are and then what you prefer jvm language java is winning all right now I'd like to ask a bit about web frameworks and preferences there so what's your preferred web framework so angular react view struts in JSF I through stress in JSF in there just for fun but I realize you know people are still using them and then finally the one that that I like to ask Java developers in particular do you prefer JavaScript in typescript and this is because I used to speak at conferences and ask Java developers how many people you know like JavaScript and hardly any hands would go up and now it's gotten a lot better but I find that a lot of people like typescript so let's let's see what the answers are here so prefer jvm language 90% Java 10% Kotlin Scotland groovy didn't groovy didn't even register which isn't that out of the ordinary prefer web framework is angular 61% react is 24 we got some with view and a little bit of JSF no struts so it's probably good and then you for JavaScript or typescript looks like 80% like typescript all right so thank you for all your answers there now back to the presentation so like I mentioned this presentation is based on this series of blog posts that Josh and I wrote and if you wanted to read those there's a link at the bottom there bit ly web flex and react so today we'll talk about what is reactive programming first of all and then we'll do an introduction to spring web flux and I'll show you how to develop an API with spring with flux and then what I really wanted and the reason I started this whole idea and wrote this blog post and article with Josh was I wanted to see how to handle streaming data with react because what I've heard from spring with Flex is it's not great for like crud applications but it's really good for streaming data so that's great on the server side but I like the client side so how do you handle streaming data on the client and different techniques for that so I'll show you a few different options there and then I'll show you how to secure web flex and react so to begin what is reactive programming well it all starts with asynchronous i/o so it's an approach to writing software that embraces in a synchronous i/o and it's a small idea that portends big changes for software so it's the idea is pretty simple it's basically just alleviating inefficient resources by reclaiming resources that otherwise would be idle so in a traditional you know non reactive application the threads are used up while processing might not be happening and with asynchronous i/o it just you know kicks off process and then it doesn't wait for any response so let's look at an example that compares and contrasts asynchronous i/o to synchronous i/o so this is a synchronous example you can see here that first of all we source the file using a regular Java dot IO file and then we pull the resorts results out of the source you know one line at a time that's the while loop there and then it accepts a consumer bytes payload that gets called when there's new data versus in a synchronous version so I'll let you look at the synchronous version again all right look at that one a bit so it's it's much more concise first of all and notice that Lombok log4j - annotation that's that's pretty handy if you're using Lombok so the asynchronous version you have to use a java niño file instead of the Java IO file and then you create a channel alright that's where that file channel is this file Channel and you specify an executor service and that will be used to invoke our completion Handler when there's data available and then you start reading passing in a reference to a completion Handler and incompleted we read the bytes out of the byte buffer into a bike holder and the bike data has passed to the consumer right so two slides worth of code instead of about ten lines of code so obviously the asynchronous version is very more verbose but it also allows you to do a lot more handling of files and reading them and not use as many resources on your server so how do you map your java brain to synchronous or asynchronous i/o and the pushback mechanism and flow control and all that in distributed systems well in reactive programming the ability of client to signal how much work can be handled is called back pressure and there's a good deal of projects that actually support this already there's like vertex akka streams and rx Java and they all support reactive programming and the spring team has this project called reactor and so there's common enough ground across all these frameworks that these different approaches were extracted into a de-facto standard called the reactive streams initiative and the reactive streams initiative defines four types so first of all there's a publisher that's a producer of values that may eventually arrive and a publisher produces values of type T - a subscriber and then a subscriber subscribes to that publisher of type T receiving notifications on any new value of type T through its on next method if there's any errors it calls on error and when processing is complete it causes on complete and then there's also a subscription so when a subscriber first connects to a publisher is given a subscription in its subscriber unsubscribe method and then the subscription is arguably the most important part of everything because it enables the backpressure the subscriber uses a subscription dot request method to request more data or the cancel method to halt processing and then there's also a processor that combines both the publisher and the subscribers so a simple interface but allows you to do more in one class and so Spring Framework five was released in September 2017 so it's been you know two and a half years it builds on reactor builds on the reactive stream specification and includes a new reactive runtime known as spring web flux and one of the questions that I get from a lot of people is when should I use spring MVC versus when should I use spring web flux and what I've seen and what I've heard is basically performance differences are negligible until you're doing a lot of API calls of the scale of at least five hundred requests per second give or take so if you have that kind of traffic and that kind of load then maybe look at using spring wet flux but a lot of the load testing and comparisons I've seen is if you're just doing crud applications spring MVC and spring love flex are pretty much similar but if you're doing a lot of streaming data and you have a lot more going on then then spring what bucks will probably work well for you so we all know and love spring boot especially since the spring boot API can be written in very few lines of code this is just a simple example of a demo application and we have an entity that's a blog and we just have some annotations that define its you know properties the getters and setters I eliminate it because then it wouldn't fit on one slide but if you're using java 14 records maybe you could eliminate those or if using Lombok you could just put all the annotations on one line and then you could get rid of those getters and setters but I have heard that you long back with hibernate entities and JPA isn't a great idea so maybe do some more investigation on that first great for demos but not the real world and then at the bottom is another great for demo thing the blog repository extending JPA repository and using the repository rest resource with that annotation does it takes blog and it puts it at a rest endpoint so you can put post get and delete that entity and so that's called an anaemic domain model that is not on that works radar as a recommended thing but it's great for demos again um you know this code right here if you have those getters and setters in there will compile will run and you have a REST API and you know 20 lines of code so now what I'd like to do is build a spring web flex API using start dot spring do one of the happiest places on the Internet and the reason for that is because if you're at start dot spring that i/o you're starting a new project or just doing a demo you're not doing maintenance usually so that's why I like it so what I'm gonna do here is usually I do a spring demo and build the web flex API and then I go into actually building the react component and then I'll come back to the slides and go over some more react stuff but I find it's it's easier if we just do all the coding at once so let me close these slides down here and then get my screen going so here's the blog post here full-stack reacted with spring wet flux WebSockets interact it's the third one in this series and if you go to the very bottom there's a link to a github repo and in this great github repo I have a demo a doc there's also a workshop if you want to you know go through the steps yourself but this has a lot of shortcuts in it that I use for this demo in particular it's written in asciidoctor I have an ASCII doctor plugin installed that's why you see the nice formatting so I can put that on the left also I'm going to use a number of shortcuts those are IntelliJ live templates so just to show you those if you go to my github repo for IntelliJ live templates you could import them all here I just updated an hour ago the full stack reactive ones and so anything that I do today using IntelliJ live templates you could do as well so I'm going to start by creating a new web flex application you'll see I'm going to use an alias called web select start so if I look at that you can see a hit start bat spring dial started zip in point and that allows us to download a zip file it uses data MongoDB reactive as well as web flex dev tools and Lombok so we'll go ahead and run that that download a demo dot zip file so I'll create a we'll call it reactive demo and the take command is handy because it creates a directory and then put you in there and then we can hum zip that demo zip and we'll put it in a web flex directory okay and so now in the web flex directory and open that up and until the day should I asked how many people use IntelliJ versus NetBeans versus Eclipse but I you know the answer is changes a lot it used to be like 50 50 have people using the clips half the people using IntelliJ and what I've seen in the last few months is is like 75% percent of people are using IntelliJ so hopefully eclipse is still doing well I'm not much NetBeans usage out there but that's nice alright so now what I'm gonna do is I'm first gonna create an entity called profile and so this service is just gonna serve up profiles and at one point we'll start streaming profiles but I want to keep the data model really easy just to make things easier to understand so we'll go into the source main Java directory and this demo here and I'll create a profile so I'll just do it right in this class we'll start with my shortcut called web flex entity and then called profile so it uses Lombok there it's just got an ID and an email and then we'll create a web flex repo this will be our profile reactive repository that just extends and it'll give us all that crud functionality and then we'll also create a new class we'll call it a sample beta initializer so I'm just gonna create it here first so create a new class sample bethe initializer you can see here that has a spring profile in it so I only want to run this when I'm in demo mode and we're just extending application listener here we're pulling in that profile repository and then when the application starts delete all the existing records and then grab the reactor one so just pull this in a little more so it's easier to read so we're just we're taking a b c and b we're creating email addresses for the profile and then we're saving them to the database and then we're going to print them out so this is a very important point in reactive programming let's subscribe if you don't actually subscribe to what's going on nothing will actually happen so it's very important to do that at the end and show that we're saving those in the database so now we're good to go there they can save that and so i will actually run this now so from the terminal to activate that demo profile you can do spring profiles active and specified demo so this is just an environment variable pretty much and then mb n and if you're a spring boot developer you've probably seen this before where it gosh darn it no goals have been specified so a quick tip that if you go down to the build section you can add a default goal and we'll call it spring boot run and we can run that and it will actually pull that in and now it executes that is the default goal and so we're just doing this to actually see the data being inserted into the database and you'll see one of the things that happens in normal spring boot if your database is not like you can't connect your application dies but in this case it's actually you know still waiting for the connection so if I started be right here you can see that spring connects to it and actually you know inserts that data a B C and D not in the same order but we don't care about that so that's all working now what I'd like to do is though close this down and we'll go ahead and create a profile service and this will make it because I'm going to create two different types of controllers I'm going to do what you're probably more familiar with which is like a rest controller that looks like spring MVC and then I'm going to create a profile Handler that uses a lot of the newer syntax from spring wet flux so both will work but I'm just going to consolidate this logic in a profile service so it uses a service annotation it pulls in an application event publisher the profile repository and it goes ahead and uses flux to get all for that repository to do a get to do an update to do a delete and then I'm just going to comment out this do on success for now because eventually what we're going to want to do is when we create a new profile we're going to want to publish that and then the publishing of it we can grab it with web sockets or service and events and actually stream it to the client so now I'll create a web light controller write classic controller it will call this profile rest controller if we look at this one it's using classic as its profile so a little only run one are actually using the classic profile and it just calls that service to return different things so you'll notice instead of returning you know an object we're returning publishers and so that has the profile objects in it and you know there's just create delete update all that kind of stuff so now if we were to run that using classic then we'll have our ten points and we can actually talk to it so put that data in there I'll create a new window here minimize that one and we'll start by just getting using HTTP it's kind of like curl but a little better HTTP ie org is where you can download it so I can go to the profiles endpoint and you'll see they're actually in there so I wanted to use a classic one oh I can still don't know without that so classic I guess demo delete them all and since I already ran the the demo mode they're in there already so that's okay so I can just show you how I can add a new one so if I do post 8080 profiles and use email my email mat Raible calm you can use that if you have any questions about this presentation and then I go back to profiles you can see it's been added as bottom there I could put it and update it I could also delete it so if I wanted to go to delete profiles and use that particular ID I can do that and if we clear it and we run it it's gone right so we have a full working credit a P I now let's do a bit more with the events side of things so I'm going to start by creating a profile created event and see it's very simple just extend applications in event and I'll grab that profile and send it to anyone that's listening for it and then I'll create a profile created event publisher you'll see this implements application listener and a consumer and this is you know how you do the the flux stuff within spring to actually send that out and accept that you know event so on the application event here it'll grab it and call that next and then there's where it accepts it and disposes of it so now let's do the profile service update so remember I commented this out we can say do onsuccess actually publish that event now so we have that application event publisher that we're implementing right here for profile created event publisher and now we'll need web sockets so web socket configuration it's a little bigger of a class but you'll see it just has a handler mapping @ws profiles and then it uses a WebSocket handler adapter as a beam and this WebSocket handler will basically grab that event publisher and listen for any messages that come through and then once they come through it will publish it using jackson to basically grab that object and write its value as a string and then it sends it out as a text message here and then finally the WebSocket sends it as well so that's how that message flux is all composed and now what we can do is create the spring web flex version of our API endpoints so we'll create a profile handler you'll see with this similar to our spring MVC controller just calls our profile service but the default read response is the real meat of it where it takes a server response it sends back a 200 error message make sure its application JSON and then whatever body is given to it right here it streams that out so this is how you would do you know more lower-level coding with with spring web flex and now I'll create a profile endpoint configuration to do the mapping so this gives you a lot more flexibility than spring MVC with your actual URLs come on IntelliJ you can do it it's thinking we'll give it like one two three and then it'll kill it and try again not responding okay usually works great I've also noticed every once in a while like when I'm typing in the terminal of the keyboard will stop working the mouse still works but rebooting IntelliJ usually solves that problem as well so let's see if we went ahead and created that class for us yep profile endpoint configuration but it's got a dot Java ending so I'm going to go ahead and delete it because probably doesn't think it's an actual class it'll create it again profile and point configuration and so if you notice this it's using the routing from the router function in spring web flex so it's able to say hey you know for this predicate which is I right here make sure it's insensitive so someone you know sends in like profiles it's not going to care and so that will go to the all handler of the profile Handler and then obviously get goes to get by ID delete goes to delete by ID and all that and then we do need to create a case insensitive request predicate so we'll go ahead and do that a class case since that's the quest predicate so this is just you know lower casing it's doing a test lower casing the URI server request wrapper and making all that work so we won't have a problem if anyone actually uses you know different URLs than we have so we've created all that we got that predicate and now we can restart it and confirm everything works so I'll use the configuration of IntelliJ this time instead of running it from the command line as soon as it finishes processing this is an important thing about Lombok is if you don't enable annotation processing in your IDE whether that's any of the ones I mentioned then some things won't compile so make sure and enable that and then edit the configuration to specify the spring profile to use so we want to use that demo one so we have some data in there so that's what I'm doing they're active profiles hit OK and then run it and at this point we should be able to hit the profiles endpoint well it doesn't like that let's try creating it again profile in point configuration profile handler is empty so I'm kill Jane let's go lost that okay back to our handler configuration and that's all compiling okay let's try again and notice I'm using Java 13 so this all works with the latest versions of Java and now if I were to go to the profiles endpoint should render in my browser all right and it does and of course if we were to hit it here it works there as well and we're using the web flex Handler right instead of the traditional rest controller now so now I'll create a web sockets UI basically so under resources I'm going to create a static ws HTML file I'm just going to use web sockets here and you'll see it's just a profile notification client basically uses a web socket API that's built into JavaScript talks to that endpoint and when a new message comes in it's just going to send out an alert so to make that new message I'll create a shell script will call this create Sh and you'll see it's just going to hit that endpoint and send a random email with a number on the end so now if we go to our terminal here we can make sure that's executable and then if we have a browser window here we do have to have to restart everything because by default spring MVC or spring what flex or even spring MVC spring booth any static files won't be picked up right away unless you do restart there is a way that you can configure an application of property especially the time leaf to look for them without a restart but often it's just easier to restart so I'll go to the rest at HTML so we have that there and then we can create a new let's see what our message is here it failed unrespected response code so let's make sure our web socket configuration though that's got lost too huh flags WebSocket Hey so now restart that that's in there so that was probably cuz I killed IntelliJ and hadn't saved all those files so that shouldn't happen normally but sometimes it does alright so then we refresh here and that's connecting and then if we were to send you can see you know it's popping up with those messages if we're gonna do it again it would pop up with the new one so the next step is to enable server-sent events because this is just a cool feature in my opinion so create a of a class call it server sent event controller and what this does is it's just a simple rest controller but it listens for that same publisher and when the events come in it streams them out at this endpoint SSE profiles and you'll notice it has to be txt event stream value as the media type so then we can restart and once it's restarted make sure that we can hit the endpoint first of all so let's go to HTTP behave you profiles that's working and then what we can do here is we can use HTTP and use - s to stream and so then if we create them actually see them there as you know streaming events so that's all working that's what I wanted to do for the most part on the server side so we'll just leave that running and I'll exit out of here and then we'll create the reactive side right we have or the react side we have web blocks there I'm gonna use MPX create react app MPX is a command that came and I think NPM five that allows you to not only do an npm install but actually execute the CLI command as well so we're just gonna call it react app and we'll do template type script so this will take a minute or two tur veronik kind of depends on your internet connection and you know how much you have going on there because what it's really doing is it's NPM installing all these dependencies and JavaScript doesn't really have binary dependencies like we do in Java so this is actually probably installing you know five hundred thousand lines of code in my node modules directory but you know that's how things work and it's funny because you know we used to complain about maven like downloading the Internet and I think NPM like downloads internet invites all its friends so you know there's a there's a lot that goes on you can see all those dependencies and transitive dependencies there and it initializes as a git repository because it detects that I have get installed and then it makes everything work that way so once that's done what I can run is NPM start I'm you could also use yarn you're on an NPM are very similar they're just you know package managers that run commands on you'll notice it's using yarn and this one but I tend to use NPM because they're pretty much the same these days so you can use NPM start and it'll start a new application now you got to be in it right so it'll start a new application up on port 3000 typescript compiling that's why it takes a bit to start the development server if you're just using regular old JavaScript might be a little faster so that's it right it's just got that spinning logo there and now what we can do is we can add some logic into the project itself so I'm just going to open up IntelliJ in the parent directory so I'm going to close this one but we'll stop Java first and then we'll open it here so your idea then we'll have both projects so if we need to switch back and forth between them it shouldn't be too hard so in the react app there's an app TSX so you'll see it's just a function by default so I'm going to change it to use class-based stuff because that's my preference most react developers are a little different so class app extends own it and then we'll take this return right here and we'll put that into a render method and the reason I'm not getting any help you guys there's still some indexing going on here so it's not you know importing that component but it should shortly so now let's try to import it the show contacts action is not available so IntelliJ is usually great right I mean most of the time you're not waiting for indexing to happen but does happen for time to time demos so now we're extending that component and I'm going to add a component bid mount method we're going to hit Profiles endpoint and we're just gonna use stretch right this is the new xhr it's gonna hit that endpoint it's gonna grab the response in json and then set it to a local profiles state so i'm gonna create a few interfaces create a profile interface and this is just gonna have our ID which is a number and then a email which is a string and then we'll also create an app props for the properties that are coming into the component so that's interface props that's just going to be empty for now and then interface app state this is gonna have is loading right because we're setting that down and that component bid mount is loading is just a boolean and profiles is an array oh hey and so once you have those set up you can pass those into your component so app props and state so the state is basically the data in your component and then the props are what's passed into it and we'll create a constructor and set those profiles to be empty in the beginning and then is loading to be false right and so now that we have that up and running we can we can modify what's rendered down here so it'll take out the edit and the learn react and we'll go ahead and do a list of the profiles so we'll take those profiles map them out again that kind of messed up there I want max program size vanilla so then we have a profile and then it's a type of profile and the profile right here I know I that didn't work it's because I didn't have my my if nothing's there then don't show it so that's a loading logic so profiles is loading and we grab that from the state and if it's still loading it just returns that so profiles like that and now everything will compile so we have this profile list here and we're just looping through those and showing them and so one thing react as requires this key to identify a different unique element so that's why I put the ID in there it's a little scroll a bit up here see where we are now the next thing we need to do is because we're hitting localhost 3000 that's actually not the spring boot endpoint right that's the react end point we're gonna proxy everything to the spring boot just for now because that makes it easier and we don't have to deal with cores so down in your package JSON file we can just add a proxy and specify your endpoint so Drac knows was all its routes are so any routes that aren't in it it'll go ahead and proxy so now we can start our spring boot app so if we go to web flex here we can hit on the palm XML and add that as a maven project and that'll allow us to run it again from the IDE so we'll go into that demo and go into demo application and then we do have to set up an SDK route three lines use 11/0 and wait a bit for that to kick in then go back and see if there's any questions while we wait for that hmm there's a chat see if there's anything in that so Q&A may I ask what use hammer spoon for so that's that's hammer spoon right here that's how I do the things on the left right and and move things around so that's how I'm using hammer spoon I have a script in there that says hey you know for all these different coordinates use these hotkeys and put them in different places so that's all running now and we can we can go on this demo application and run it as soon as it creates that we're going to want to stop it because we need to edit that configuration it has the demo profile so it's going to pop up after compiles everything and say here we're running it but I'll stop it and then we'll run it again and now if we do npm start the terminal here you begin to react and we should be able to connect which is that back-end right and so that's all working or pulling in those profiles so that's good we have the the basics in place the one cool thing about react is the first time I tried to you know create a component I found it was it was very easy so I just want to show you it's it's very intuitive I could create a profile list from what we have in app dot TSX and really isolate the logic that we have for this class so instead of app I'm going to call it profile or file list and we'll replace the name there a name there the name there alright rename those and then as far as all this stuff down here we don't really need it right because that'll be in the app itself so we can kind of get rid of that name this profile list and then we have kind of a self-contained component so we can release remove any imports that we aren't using and reformat and we're not using half dot CSS either and so now everything's in its own you know little spot and we could go back to app dot TSX and take it back to what it was and then just use that component so instead of having this here do profile list now rack here everything still works okay if we refresh it we're still pulling it in so I really like that feature of react that it's very easy to extract components from existing components similar to Java in that way I remember when I worked with GWT it was easier to say ok this can be extracted out and you could use your ID to do that so now what I want to do is show you the different ways of streaming data right so I'm gonna modify this profile list component to first of all just use a one of the bare-bones ways of doing it so we're gonna basically fetch the data set the late loading state to true go grab those profiles and then we'll also have this interval that executes every second and calls that fetch data method again so we need to add an interval variable here type any and then that will all be working and so the next thing is to create a stream creator so we'll go ahead and create a create stream but SH and how this works is it'll go up to you know 120 and it'll just keep adding profiles using that similar you know random one random two random three and so back here if we were to create that stream so go into web blocks make that executable you can see there's a little bit of flickering and if we start to create the stream those will show up and and it's kind of janky at one point you see it now every once a while the screen kind of flashes and part of the problem here is where we're actually reef etching all of the data right we're just fetching the new ones that are coming through we're reef etching all of them so that's not you know a great way but there was a little bit of screen flickering it used to be much worse when I would do this demo maybe it's just the live feed but I want to make it even better so one of the ways to do that is using rxjs so instead of using just those primitives you can use rxjs so I'll go into this react app and MPM I rxjs or maybe I'll use yarn since that's what it did for everything else so rxjs allows you to do is similar to that polling that we had but using their classes so in profile list I'll change this code here using rxjs you see here it kicks off a request that says hey start with zero so as soon as you know you hit this logic go ahead and make a fetch to this endpoint and then when you get the results you know replace all the profiles so again we're doing something very similar to you know interval but a bit different so we'll remove that variable and we'll see if rxjs is installed back here it looks like it is and so now we should get the imports for these close that one up there Oh IntelliJ is not grabbing the import so we can just manually put them in so import see what was it it was uh start with and switch map and interval and then the switch map start with and switch map are both in the operators okay so now we can run that one awkward pause come on react oh it didn't like the back end being down is it ten and it still looks like it's up but we get digits and proxy errors there well let's see what happens if we create new data so it's adding I'm right we didn't clear out our old data so now we're getting one two three it's a bit smoother but like I said we didn't see the janky nough swinter Vil that I am used to so maybe something changed in recent versions of react I'm also going to restart my service so we don't have so many for the next demo so the next one I'm going to show is with WebSockets and WebSockets give us the ability to basically only get the new data that's coming in it is much more efficient so we do have to originally fetch all the data right but then our WebSocket is just going to listen for any new messages coming in and then it just adds it to the existing profile so instead of reef etching all the profiles each time which is inefficient we're just going to grab the latest ones so then we can remove these imports up here and we do have to create a another type of proxy so set up proxy guess you do have to name the file that and then there'll be a react proxy shortcut now we're just using the HTTP proxy middleware and we're going to allow to proxy WebSockets because by default the proxy and that package JSON doesn't support WebSockets so now if we restarted or we shouldn't need oh we do need to restart because we modified and created that file and it won't pick that up by default on startup so now we have that regular list and if we're going to do that create stream you can see that works and it's just getting those new ones that are added instead of reef etching the whole list so much more efficient the last thing I want to show you is how to do it with event source so in profile list we'll change this from using WebSockets geez eventsource alright that server-side event handler that we created that controller so it again there's going to hit profiles and then this event source is built into javascript so it's gonna establish a new event source to that server sent event handler on the server side and I found this on open is very important because when I was first trying to make all this work I was getting this console open but nothing else and so I knew the event source and the important was working it turns out the problem was that the proxies that I set up both for you know just HTTP and for WebSockets don't work with service in events so we actually have to make a direct request to spring boot and to make that work on the spring boot side we have to modify this service an event to have cross origin annotation so it allows you to connect from you know a different client and if you want to you know really lock it down we could do localhost 3000 right only from that origin so then we'll restart the server our profile list should be recompiled here so as soon as that server starts up for you to do this it's just going to be loading alright and then refresh so it's got those server sent events and then if we were to you know send some new ones those will show up as well so everything's working as far as you know streaming data from the server and grabbing out of the client the next thing or the last thing I want to show you is how to add octa for authentication and it's not really aqua so much is just using OAuth so a lot of this leverages spring security more so than anything and so in the web flex application there's there's many ways to do this so if we were to go to its palm XML you can add dependency so there's some that I have stored here if you just want a offspring NBC or spring security these are all the dependencies for that so the starter from security the oauth2 client a lot too resource server we're gonna use both of those in this demo and then Jose for doing JWT handling there's also an octa spring boot starter that basically consolidates all those dependencies down to one so the latest version that one 4.0 but I'm not going to show that the thing I did want to show is if you're using spring security there's different properties that you configure so in application DUP properties actually I believe I'm expecting a yeah muls let's rename this to ya mold because I like pain and if I were to use spring security this is what it would look like so it's got a whole bunch of you know nested properties if you're these properties would be actually simpler but we have an issue or URI we have a client ID and a client secret and scopes and then for setting up the resource server you need the issue or URI again well if you use the octave plug-in which isn't really octave specific it just you know uses spring security and has some octave conditionals in there so if we were to use octave a lot - yeah Mele you can see much simpler less properties and it has all that same configuration but what I'm going to do is I'm not going to use either of those because there's this cool maven plugin we developed that you can actually configure everything so if you're a brand new to octa and you don't have an account you can run cockta octa maven plug-in setup and it'll prompt you for some values like what's your name what's your email and then how to create an app for you well since I've already set things up it's got all that done for me so now if I go to my application you'll see it even put that client ID client secret an issuer in there and if I were to go to palm dot XML down at the bottom here it added that spring food starter for me so pretty handy no tool there so I like to use that and then I'll restart everything hopefully picked up that auto import before restarted because if you didn't auto import and you're running it through the ID then it doesn't know that you added that new dependency and so we'll see here if we go to a DAT profiles now it'll redirect us right to login with octa or no it didn't because it didn't pick up that import yet so start it again and so this is handy because you know on your spring boot side you're protected and if people hit that end point which you wouldn't expect them to do in their browser then they would get you know a a 401 normally but in this case what it configured by default is a lot to login so a reader directs them to login instead of giving them you know for one so you can configure it either way but now if we refresh it'll still do that so that's probably because I'm already logged in so let's try an incognito window how it does prompt me to sign in and now it pulls back everything right so we have the server side working now what do we need to do on the client side so on the client side there's a cool thing that I developed called octa dev schematics to add octa basically to any or most client-side framework so we're gonna need to first create a new app for octo so if I were to go here and go to my org which is dev 1 3 3 2 0 I have to create a spa app or react look at the applications here the spring butuan it reads from your maven information so that's right here it's got that demo name and I actually added some login to redirect your eyes if it if it detects it there's an app with the same name it won't actually create a new one so I'm going to create a new spa react application and normally you could reuse the spring boot application but for spas we have pixie which is proof key for code exchange which is a much more robust authentication mechanism for spas so I'm just going to call this react app and then you do want to change all the ports because the first time you create an app it'll create trusted origins for you with these ports and if you go back and edit them later it won't so and we're using an authorization code right not implicit and then click done and that'll give us a client ID that we can use all right which is right here but we're gonna need an issuer first so if we go to authorization servers we can grab our issuer right here now if we go back to our instructions we'll NPM install octa dev schematics you might be wondering why I didn't NPM install - B - put in a developer dependency well react has a theory that basically there are no developer dependencies everything is main dependency and once you produce your final artifact you know there's things that are in there and there's things they are not so I think it's a worthwhile thing but you could put dash D and put it in your developer dependencies and it wouldn't be a big deal so once that's done running we can run schematics octave dev scream addicts everything right and add still running that installing it a price should he used yarn instead since this is the first time used NPM but we'll see if it works and I did practice this demo beforehand and found that the latest version did not work so i did a release right before this let's hope we get that release or this demo could take a little bit longer than expected come on npm you can do it I realize I'm at an hour so hopefully this is only like five more minutes and then we'll be done should he use join darn it let's see if there's any questions in the meantime it's easy and fast inserting all these prepared code snippets but how much work has it been to write this in the beginning that's so complex and dense code right Josh did all the hard stuff I just did the react stuff so the react side wasn't too bad but I've seen Josh actually do you know compiling and creating all of the code in the back side from hand in like 45 minutes so he's pretty good at that I'll come back to the questions here well that's still going so debugging reactive code can be hard can you tell us how you're doing debugging of your reactive code so there's what's it called block hound pound is one of the recommended ways so it's reactor debugging so it allows you to basically use it and debug like you normally would so that's what I haven't used it personally but that's that's what's recommended for the most part from the spring team so we answered that one okay and then what's the advantage of the handler approach compared to the annotated rest controller personally I'm a fan of the rest controller because I'm familiar with spring every see the handler gives you much more flexibility in the sense of you can map all the URLs out and do like the case insensitive stuff which you can't normally do a spring MBC how many webinars have I done as a speaker I've done a lot yeah probably uh I mean I've been a speaker for you know two thousand four sixteen years so yeah done a lot why are you taking so long NPM that's the last one can you give us some examples for using reactive code well if you're streaming data right so if you're Twitter and you have all these streams coming in then then that's probably a great idea we did recently a Dinge a hipster the ability to do reactive micro services and monoliths and even generate cred I was kind of against the crud generation but because you shouldn't be developing a crud out but maybe you have most of it streaming and you need some small crud in there so yeah streaming apps are usually the best idea you could do with crud but it's really not going to give you a whole lot of advantages over regular spring MVC okay so that finally worked and now we can run this ad off here I'll close that one out so it didn't like what I ran oh this is because I probably used yarn so let's do this yarn again that's the problem with I've seen that I've been mixing NPM install it on had doesn't always work so I was this wait for that to go again check for any new questions nope so yeah I mean running npm install or yarn at during any sort of demo is usually can be very bad in fact the first time i ever did this talk was at spring 1 2018 and in create react app was broke and when i went to create the typescript version of my react app that failed and so i could never actually show a a running UI and it's crazy because that code is out there and that videos out there and like info queue and it still gets lots of views but no one ever actually saw the UI running i just showed them all the code and how it was supposed to work so yeah sorry about this I didn't mean to run npm install should he used yarn ad but I'm pretty confident that after doing this it'll all work or if I had fiber like I had fiber I just moved to this house I'm in right now three years ago and and we had fiber at our old house but we got it like six months before we moved in man if you have fiber you know a gig connection that's pretty darn nice so come on react do your work or yarn you're so close only 73,000 dependencies files there's got build some fresh packages man this is painful all right there we go I'll try it again this doesn't work then I messed up so I'm in the release and we'll just move on so it wants our issue or URL which I copied right and then the OID siaps client ID so I had that in this here and if we go back to our react app and we can grab the client ID there and so what says ads on aqua reactive sdk react router dom and the types for reactor outer dom and then it creates a couple files and it sets up you know tests so it updates the test so those will work with with octet as well as it modifies that apt ESX so we should be able to go into that apt ESX and see what's changed it's not quite ready yet or maybe Intel just hasn't caught up oh there we go so it's got a configuration here that specifies that issue or and that client ID so if some reason you fat-fingered it or paste it wrong you could just go into this file and change it that's only place they are it sets up this security component that makes it so you have to log in to get to you know any particular area and then this login callback the handles setting your access tokens and ID tokens when those come back it also creates a home TSX and so you can see here this has an auth service in the off state which you can talk to there's this with octa off higher-order component and it's got login and logout methods and then there's buttons so our profile list you know was back here and we do need to make some modifications so this profile list will put right in here and we'll path pass the off state to it so the props ah state that we have from this main home component that we're going to use to login and then down here at the bottom we can take those edit links out but it's just gonna have the body which is either going to be a login button or it's going to be a logout button with whatever component you specify there so now we need to import the profile list we're late for IntelliJ to catch up and maybe go on import there we go now we should be able to start our client well I want to make the buttons more visible oh we're still doing that stuff huh great let's modify the app that CSS just to make our buttons a bit bigger so we're just gonna give some margin to them and make them bigger and hopefully this will finish pretty soon I did an NPM install so if this doesn't work then hey it worked earlier I know it works if you actually went through the tutorial and there's actually a on our youtube channel youtube.com slash D slash octave dev I do have this full demo out there it's probably a year old so it's not using spring 2.2 but otherwise it should work so yarn start it up we closed this one here so it's still waiting and so we're gonna have to make some changes after this loads because one thing is logging in but the other thing is talking to our server to get that data and so we'll need to pass to that server an access token and we'll be able to get that from the octo react SDK on the front end but we still need to pass it to the back end oh so it's warning us about the profile list we haven't specified that estate as a prop that's coming in so off state is any and that should cause things to reload and now it's working and you'll notice it's actually talking to the back end so oops it's it's kind of weird that that worked Wow that's because it's proxying and right to the back end so it doesn't require anything so let's modify this profile list to pass in an access token so I'm going to go here and so we're going to use just component bid mouth as a sample and we'll go to that profiles endpoint and we'll pass an authorization header with that bare air token and then get the access token from the off state and you'll notice now we're getting a cores error well we need to do some work on the spring side of things so we'll just create a spring security or spring configuration security configuration class so what this does is it configures things a bit more because currently web flex doesn't support securing WebSockets this is why I left the WebSockets wide open you no permit all and then I ought to login and resource server those are all the defaults so this is just customizing that if you were to run spring boot and react on the same server then you would need to do something like this to bake your CSRF tokens available to the react client so it could read it from a cookie and send it back or read it from yeah read it from a cookie and then send it back to the server and a header but since these are on different ports that really doesn't matter and then this is setting up the course configuration so this error goes away right here so restart after adding that and then while we're waiting for that we can create a new stream or we'll update our create stream to use authentication because now we're going to want to pass in as that authorization header to actually create those records so this should be working now right come on there we go so that's working and if we were to look back at our profile list we lost all that stuff we were doing before so let's change this to use WebSockets again so now what it's doing is again it's going to fetch all the profiles in the beginning but because we actually you know can't secure WebSockets what we need to do is is first of all we're just going to grab the ID of from the WebSocket of the profile and then we'll go ahead and fetch it from the server so it's a little chatty but that's because you know we don't want to pass the whole profile in case there's sensitive information in there we want to make sure that's locked down so the idea I don't think is that sensitive we do have to change our WebSocket configuration so it only sends back an ID though so we'll take this source out of here and we'll just pass a map back to it so we'll call that beta and we'll take the profile here and we'll cast it to profile and then we'll create that map string string and we'll put the idea in there and data output okay and that will just give us an ID on the front-end so now we can restart this and then all the logic in our profile list should work where it grabs all the profiles initially it grabs you know any new ones that are being sent and it goes ahead and fetches and adds them to the list here so to have that create stream work with authentication you can use open IDC debugger or oh I DC debugger so I have an endpoint configured here right for the authorized endpoint to redirect URI is this and I'll just put a state of one two three and I need a token back so they can hit send request it gives me that access token back and I can go to my script create stream and paste it right here alright so now if we go back to our app that should be working all right it's talking to the server it's getting those profiles and if we were to add any new ones down here and it should add those as well so it's posting him in a secure way and we're communicating we're using WebSockets the WebSockets aren't secure but that's a limitation of web flex and WebSockets so that is the majority of the demo sorry it took so long so I'll just fly through the rest of these slides here I'm PS six is seven in typescript you can use typescript and get a lot of the beauties of es6 es6 is what gave us you know actual class objects so you can see here's an example of a bus because I like Volkswagen buses and a lot of what's going on here is actually es6 not so much typescript in fact if using typescript that constructor there right it's using typescript because it has a string parameters or the string types but with typescript you don't need to set that local variable as long as you haven't the constructor argument it'll set it and create it for you with that same name the getters and setters are a little bit different in es6 javascript in typescript you see the get and set it's not like get name and set name like we have in Java and then down at the bottom there there's a string interpolation so you can inline variables and stuff you'll need node HelloWorld with react pretty easy and when react first came out it was very controversial because people were put in HTML right in their JavaScript and so now you know five six years later no one seems to mind and one of the biggest differences with imperative code like jQuery is a lot of times there's so much conditional logic for all the different states with react it's actually much less and a little bit easier to read so this logic here is saying hey Ida actually I didn't know this until I started you know writing this presentation was that is if you get more than 99 notifications on Facebook they like turns into flames and you know lights up has fire so so if the count is more than 99 then an adds fire and there's all this logic if it already has fire then remove it and then if the count is zero then removed the badge and all that and so with react it's a bit different in that second else--if really is the important part this because what will happen is that cat will probably be 0 in the beginning so it'll just render that class name of Bell and then when it comes back and there's actually a count it doesn't need to process that first div again all it adds is that middle span so it's really doing a virtual Dom diff and that's what makes reacts so fast unlike you know having to re-render everything and so create react app is a great way to do that I hope you're hearing my cat in the background cheese want something learning react this is a great video for it Eric this NT basically walks you through creating an app and using a github repository that he created to do it it's a couple years old but everything's still very relevant to handle the streaming data like I showed you there's several different options our socket I did not show you today but that is certainly an option in spring security does have authentication support for that so I should look into using that I showed you this demo of creating a rat client Jay hipster has react support and that web flex support so it's not released yet as far as the generator of the entities but gateway spring cloud gateways in there and the micro services are in there I wrote a book on J hipster doesn't cover react or web bugs though so you're probably not interested so the action is to try a spring low flux try react try open ID connect explore progressive web apps which I never talked about I just think it's a good idea if you're developing web apps to try to make them so they work on mobile devices better and faster and then enjoy the experience so again you could do it all yourself from the blog post and I also wrote another post undoing crud just simple crud with react and spring boot it's one of my most popular post-its I think up to yeah it's got a lot of comments so you can learn all of them you know with this series going through there and we post a lot of interesting topics on our blog the developer blog on octa and you can follow my team a talk to dev so the source for everything you've seen today is at that URL and if you have any questions you know feel free to hit up myself or even Josh for the web flux stuff and I will upload this presentation later today once we're finished may the off be with you so now I'll go and check for any more questions here so like there's no more questions any more on that so this time was the second time you're running a webinar with us so I'm really happy that it went so smooth and I have a question regarding your Forks wagenbach sexually so your Volkswagen bus is all over the place like in your presentation several times and so on but actually how much time do you spend in the folks like mass well here's a picture of them so I have two of them there's a there's not only the old you know 66:1 but there's also this 1990 Vanagon on the left there that is a synchro so it's four wheel drive and so that one tends to be more of my winter vehicle because you know it's four-wheel drive and it snows around here a fair amount and you know you can pop the top and sleep upstairs the other one is more of a summer vehicle but really it gets hot here in the summer so it's more of a spring and fall because you know air conditioning is nice in the summer in the Delaware and doesn't have air conditioning so they drive in the spring and fall out but I've even drove on it this week so it's been nice and warm here that's great another question I had regarding the bed flat stuff so Oracle is still saying you have to wait until project loom fibers and now they are calling it light white threads what do you think about that will that like have an impact on on the react stack how we have it now like from all the way down from the react JavaScript - too bad flux or what do you think about that well I think project loom is very interesting because they do give you the ability to do lightweight threads and what I see happening there is it will probably make it so a lot of the react folks or the reactive projects can just delete code right because it's it's used by you know they can leverage project loom there the problem is project loom is going to come with like Java 16 or something like that and they're still gonna have all these people that aren't willing to use the latest and greatest jdk so I would think that over time I'm you know there's less to maintain for the project like project reactor and you know Java rx and all that but at the same time like are they willing to say like you have to use Java 16 right because that might eliminate a fair amount of users so I do like the idea and hopefully there'll be some maybe new frameworks but you know for the most part as developers and users of the frameworks like we're probably still gonna write the same amount of code right but a lot of the complexity is really underlying in the the projects we're using so will that change was something in the front-end now the front-end I think you know even our socket is probably one of the most interesting things to happen in the backend because it's a new like protocol just like HTTP and it's got like backpressure built in and all that and a lot of the our socket demos I've seen are pretty nice when you're using Java all the way down like you have a Java FX client and a back-end server with you know our socket as soon as you get to the web like all you gots web sockets right and even there's an AR socket project for the web but it leverages WebSockets right and so there's not really much new there on the web side of things that you know allows us to do this streaming data in a secure way okay great thank you very much so it seems like there are not more questions coming up do you want to share something else or no no the only thing I would say is if you do have you know more questions and just hit me up on on Twitter you know I am Raible MRA ible my direct messages are wide open I'm happy to answer questions there send me an email at Matt ray Vela dr.com and I'll try to help so great thank you very much for being our first presenter actually in your online channel and also like to spend the time you spend with on setting up all the things and trying things out as I heard from my colleagues actually things went waste mover than yesterday so I'm really really happy about that except probably sometimes the the audio was not that great when you did like mm this yarn in stock but beside that actually it was really great and and and also like the tooling use was really nice to see that and you can do a lot of things with these code snippets and I'm also like yeah the scripts and also maven plug-in to use that was actually really great thank you very much for for being with us I'm on the first yeah or the first and the second webinar with it and obviously you will get as all our presenters that Java user group Swiss Army knife but we have to send it to the US because nobody of us can come to the US and give it to you personally or each other someone soon again in Europe or in Switzerland would be great to having you again I'd love to visit I'm I'm salad and couldn't be there in person but obviously different times we'll see yeah actually anyway you have to do like the ski trip I mean Switzerland going to summit and doing things there that's great thank you very much thank you very much also thank you to our and and sponsors we had as always like which are helping us to actually organize all the events and I also would love to thank you our and our staff in the back ground so actually Marcus which were setting up all these on I don't like conferencing tool and Thomas also yesterday I'm doing the first run with you and then obviously all the words Allah which is also doing the coordination sending out emails to all the participants and so on so that's actually great yes don't forget actually to give us feedback because when we end the webinar you will see immediately or when you get out of the webinar you will see immediately the feedback form please use this we would love to have your feedback that would actually great so we can improve all the with this new format and yeah let's see each other soon again hopefully also in person great so thank you very much for being with us Matt and thank you the ones who are looking this presentation that's actually great thank you very much [Music]
Info
Channel: Java User Group Switzerland
Views: 868
Rating: undefined out of 5
Keywords:
Id: 3vG4hMIvhEs
Channel Id: undefined
Length: 91min 20sec (5480 seconds)
Published: Sat Apr 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.