Open Source & Free

7. Map Form

Module 12: Creating an Uber Clone Transcript in this section we finally get to the map ui i hope you followed the instructions before for configuring the map if not please follow through with that if things don’t work and if you don’t see the map or it acts funny check out with us in the online support forums you can also check out the map section in the deep dive into mobile development course which comes bundled before we begin we need a class we discussed before in the maps module the map layout i didn’t change much as left it as is since it’s already available elsewhere i won’t go into the full discussion here and go right into the form itself before we proceed i’d like to highlight some subtle things in this screenshot and discuss what we will and will not do i won’t do the side menu right now but i will do it soon the way to field is really a button that leads to a different ui this ui is overlaid on top of the map so it is a part of this form i’ll position one taxi in a hard-coded location as part of the mock-up the icons at the bottom are historic rides i’ll add two hard-coded historic rides for now i won’t go into the notice at the bottom it’s it’s possible but it would be non-trivial let’s jump right into the code you need the js key from google maps as explained in the map extension page this must have a filled up value we usually use border layout which implicitly disables scrollability layout layout doesn’t do that and the form’s content pane is scrollable on the y-axis by default notice we didn’t use a thread here and instead used call serially on idle method on the login form i didn’t use that because the animation might have prevented idle from occurring this shadow is used later on in the show navigation toolbar method the transition and the main application are based on cover and the transition out will only be a problem the map is on the lowest layer and everything is placed on top of it the layer is on top of the map and uses the map layout here we will place the car and other landmarks we need i place a car on top of the map in tel aviv notice that the car is just a label i’ve set the opacity to 140 to match the translucent cars in the native app notice that the map layout takes a quart as constraint so it can properly position the car this is the small square we place next to the where to button i could have used a unicode value too but it wasn’t available in all the fonts notice the where to element is just a button as it moves us to a separate ui and isn’t really a text field the history buttons are floating action button instances that are customized in terms of styling i used text area instead of span label because i wanted the history element to act as a single component with lead component lead components can take over a hierarchy of several components and handle the events for everyone so in this case click on the text area below the history will trigger an event in the floating action button the bottom of the map has a gradient overlay that darkens the bottom this is probably in place to make the history labels readable i just generated a gradient image in photoshop and placed it here we do two important things here we use the overlay toolbar which floats on top of the ui we initialize the side menu which we will discuss soon that was a lot to cover but there is a lot more we did mention three new styles above which isn’t that much all things considered the wear 2 style has some subtle nuances such as dark gray text the padding is large and obvious i played with it a bit to get it right the margin is special we want some margin from the sides so it won’t touch them we need a lot of margin from the top to leave room for the title area the corners are rounded on the native widget this is very subtle so i left it at 0.3 millimeters which should be very easy it also has a shadow which is more obvious and 80 opacity the font isn’t big just slightly bigger than normal but the typical light font the history button is the round button on the bottom of the map leading to historic rides it’s black on white but is implemented as a floating action button so it derives from that and uses the border settings from the floating action button the the history label is the dark text element below which is technically a text area but acts as a label the text color for this is black while the padding is two millimeters on all sides except for the top where we want to be as close as possible to the floating action button which is already well padded margin is zero as usual and the font is a relatively small 2.2 millimeters so we can fit multiple rides in one form

Codename One

Case Study: Performance Problems in the Kitchen Sink

Module 12: Performance and Memory Tuning Performance advice is easiest to remember when it is attached to a real mistake. That is why this case study is valuable. Instead of repeating general rules, it shows how ordinary-looking decisions in a real application created noticeable problems and how those problems were fixed. ...

Codename One

8. Where To UI

Module 12: Creating an Uber Clone Transcript when you tap the where to button on the map form you see something that might look like a new form but it isn’t really what you see initially is this and it seems like a new form but notice that the focus is on the where to text field if we switch focus to the where from text field on top you will see something else you will see the map and the ability to type in a new location so what we really have here are two separate overlays on top of the map one above and one below there is another septal behavior that i only noticed when i started playing with this ui notice the line and the shapes next to the text field when you move the focus between the fields the shapes flip to highlight the focused field we could build something like this with a dialog or interaction dialog but i chose to go with simpler container instances on top of the map to do this i first had to add a listener to the where to button then i add the show navigation button method let’s dive into this method we create a new layer on top of the current layers in the form layers are associated with a component class which allows us to keep it unique and prevents different code from messing with our layer also notice that we replicate the look of the title area without actually creating a title area the square image already exists from before we created it for the where to button we add a new circle image that we can place next to the from two fields we place the text fields in a border layout next to the labels representing the circle and square we place that in a box layout y container and that’s effectively the entire ui of the top portion the background painter allows us to control the shadow from the top area and draw the line between the circle square images the fact that we have a background painter makes some of the aspects of the ui id less significant for instance background color but we still need it for padding margin etc the shadow image is created asynchronously by the call serially on idle code and the constructor so it might might not be ready when this is drawn we fill the rectangle on top of the drop shadow covering half of it this makes it feel like a directional shadow i used fill rect instead of draw line to make a 2 pixel wide line i could have used draw line with stroke but this is simpler and probably faster the entire layer uses border layout north makes sense for this as we wanted to span the width but remain at preferred height in the north we’ll use the center for the rest of the ui soon the component animates down from the top with animate layout we pre position the component location above the from so animate layout will slide everything from the right point this ui requires three new styles first is the wear toolbar which is an opaque white container we have five millimeter padding on the bottom for the shadow of the container and as usual the zero margin the from two text field is opaque with a grayish color background and black foreground it has two millimeters of padding and two millimeters of margin to keep it spaced it uses a standard light font the component also has a selected version which has slightly darker grayish color it derives from the unselected version of the uid we also have a custom ui id which for the most part just uses a darker gray color for the hint text the margin is zero again most everything else is derived from the from to text field

Codename One

9. Where To UI - Part II

Module 12: Creating an Uber Clone Transcript the where2 ui is a pretty big piece of the puzzle and it also includes the navigation ui which is the bottom portion up until now we focused on this part of the toolbar area now we need to do this portion the destination ui toggle is a huge part of the navigation ui it’s the bottom section of the form that contains the list of destinations we can build it on top of the code we wrote for the navigation ui and place it in the center of the layer so it will play nicely with the rest of the ui for now i’ll ignore this portion as it’s mostly a specialization of other things and can be done relatively easily if you understand the rest of the things i did let’s jump right into the show navigation bar method the top elements are relatively simple multi buttons we use container as their ui id so they will be transparent with zero padding and margin the separator is just a label with a specific style notice that blank label buttons etc are hidden by default in codename one and you should invoke set show even if blank if you want such a label to still render we can reuse the form ui id here because that’s effectively what we want we want this ui to appear as if it’s a form we need this to be scrollable but we don’t want the scroll bar on the side as it might cause aesthetic issues the showing of this element is animated from the bottom of the form while this ui is very simple it did define a few ui ids let’s start with where to button line 1 which represents the entries in the list of elements and also adds the underline the color is just black over transparent which in this case leads to white the padding on the left side is relatively low since the icon will take the extra padding on the other sides we have typical four millimeter padding margin is zero as usual we put the underline here because the design placed the underline only under the text and it will place it under the icon which has a different ui id the underline is a gray two pixel high line the font is the standard three millimeter light font the where to button icon style applies to the icon which has less horizontal padding so it won’t drift too far from the text but identical vertical padding so it will align properly with the text it derives from where to button line one so they will fit together well we need the no border version of the style so it will remove the underline border on the last entry otherwise we can see an out of place underline in that one last entry in the list we derive from the same style so everything else is identical the wear separator is just a gray padded line so it has the right gray color and is completely opaque so with no background transparency it’s exactly two millimeters tall so it will stand out but won’t take out an entire line margin is zero so it can reach the edge of the parent container now that we added this we need to show this ui and hide it when the user toggles the focus in the text fields we can do this by binding focus listeners to the to and from text fields when focus is lost or gained we toggle between the square and circle modes by setting the icon to the appropriate labels we always have one container in the layer except for the case where the second component is the where2 container it’s always the second component because it’s always added last we set the position of this container below the forms animate and layout moves the component outside of the screen to the position we asked for using a smooth animation this callback is invoked when the unlayout completes at this point we have an invalid ui that needs a layout but before we do that we remove the component that we animated out of the form now that the ui appears we also need to remove it when going back so i’ll update the back action listener from above to handle the where to ui as well this is the exact same unlayout operation we did before and finally we need to make a subtle but important change to the background painter code from before because of the drop shadow a gap is formed between the top and bottom pieces so a special case here paints a white rectangle under the shadow to hide the gap without that the shadow would appear on top of the map and not on top of the white background once this is done opening the where to ui and toggling the fields should work as expected

Codename One

10. Side Menu

Module 12: Creating an Uber Clone Transcript we are nearing the end of the mock-up code the next thing on the agenda is the side menu ui i’ve moved that code into a separate hard-coded class for reuse in other forms frankly i’m not sure if this ui is used in other forms but i think it’s a good habit to separate the menu from the component code the code in the common code class which i used for the black toolbar as well it’s a sort of util class that’s really convenient when you have repeating ui elements one thing you will notice is that there just isn’t all that much code here the main reason is that most of the ui is within the theme and we already defined most of these ui elements such as side command uid let’s dive into the code we’ll discuss the get avatar method soon this code generates the avatar image at the top with the name next to it the gap between the text and the icon in the avatar is larger than average the legal button is a south component it’s a special case in the on top side menu that allows you to place an element below the menu itself its styling is separate and it slides in out so we need to give it the psi navigation panel styling to let’s move to the get avatar method which generates the round image of the user we create an opaque 10 millimeter black image to use as a mask masks allow us to crop out unwanted pieces of an image in this case we want to make the image round we fill the shape we want in white in this case as an arc notice we activate anti-aliasing otherwise the resulting image will look jagged which is also why we avoided shape clipping here the font image class can use the given color and opacity settings we use the version of the class that accepts a style object and size so we’ll have fine grained control from code we can’t apply a mask to an image of a size that’s different from the mask size masking doesn’t work well with complex images such as font images so we convert it to a regular image first

Codename One

11. The Spring Boot Server

Module 12: Creating an Uber Clone Transcript now that we got the mock-up running let’s jump to the other side of the fence and set up the server if you aren’t familiar with spring boot or mysql or don’t understand why i picked both of them i suggest checking the previous modules where i discussed the reasons for this extensively and gave a long overview over both you can create a new database by logging into mysql and issuing a create database command i created a new spring boot project which includes maven dependencies for jpa which is the java persistence architecture or hibernate jersey which is the json and xml serialization framework web which is useful for web service development websocket for connecting over the newer websocket protocol security is mostly used for password hashing which we will discuss and mysql support is needed for the jdbc connectivity and finally braintree for the payment processing we’ll need later on before we get into the code let’s take a minute or so to think about the things we need from the server the first thing the server needs to offer is an ability to add a new user we also need authentication and authorization for the user such as password validation and authentication we need a way to update the user information we need to track car positions so we can show them on the map we need the ability to hail a car and pick up a driver we need a we need to pay the hailed car so the system knows the car is paired to us we need to log every trip taken including distance path etc and finally we need to provide rating facility so we can rate the drivers i’m glossing over some things here such as billing push etc now that we have a spring boot project let’s skip ahead to the server code we’ll start with storage which is a good place to start a common design strategy is deciding on the data structure and then filling in the blanks a good way to decide on the elements we need in the user object is through the ui the account setting class contains a lot of the data we need the user jpa entity uses an auto increment id value for simplicity let’s go over the various pieces here these are part of the user settings such as just general configuration the password stores the hashed value of password and not the plain text version we’ll discuss hashing passwords soon we will use these when we need to enable login with a social network account these are the internal network ids we’ll use for verification a driver is also a user in the system if this user is a driver this is marked as true by referring to both the end user and the driver with the same class we can simplify the code if this is a driver this is the description of his car we’ll need for the app this field is set to true if we are currently in the process of hailing a taxi if the taxi is taken by user this field maps to the user id it is set to null if the taxi is available we will have a separate object dealing with rating but we can sum it for every query so the rating value will be cached here this is the position and direction of the current user whether it’s a taxi or an end user notice i chose to just store the location values instead of using one of the custom location based apis supported by hibernate and mysql i looked into those apis and they are very powerful if you need complex location based apis but for most simple purposes like we have here they are an overkill and would have made the project more complex than it needs to be if you are building a complex gis application i would suggest delving into some of those custom apis this is a picture of the user stored in the database blob one last column is the auth token which we initialize with a unique random id we will use this token to update the user and perform operations only the user is authorized for think of authorization as a key to the server we want to block a different user from sending a request that pretends to be our user this is possible to do if a hacker sniffs out our network traffic and tries to pretend he’s our app one approach would be sending the password to the server every time but that means storing and sending a password which holds risk in this case we generate a random and long key that’s hard to brute force we send the key to the client and it stores that key from that point on we have proof that this user is valid i’ve discussed this before in the restaurant app if you want to check that out the repository class for the user starts off pretty standard entries we first have the option to find a user based on common features you would expect such as the auth token phone etc however we also need some more elaborate location-based queries in this case i verify that the entry is a driver by always passing true to the driver value i also use the between keyword to make sure that the entries i find fall between the given latitude longitude values the find by driver method finds all the drivers in a region it’s useful to draw the driver on the map even if they are currently busy the second method returns only the available drivers and is used when hailing like before we need a data access object or dao to abstract the underlying user object and make client server communication easier notice several things about this dao first notice that we don’t provide the of avatar in the dial it doesn’t really fit here as we’ll apply it directly to the image also notice that the auth token and password are never returned from the server they are there for the client requests only in this case the password would be the actual password and not the hash as the client doesn’t know the hash and the server doesn’t store the password i’ll skip the rest of the code as it’s pretty obvious including constructors setters and getters we create the user dao instances in the server by asking the user object notice we have two versions of the method one of which includes some private information and is useful internally the other is the one we need to ask for when dealing with client requests the user service class is a business object that abstracts the user access code if we think of the user object as the database abstraction and the dao as a communication abstraction the service is the actual api of the server we will later wrap it with a web service call to make that api accessible to the end user this might seem like an overkill with too many classes which is a common problem for java developers however in this case it’s justified by using the service class i can build unit tests that test the server logic only without going through the complexities of the web tier i can also connect some of the common apis to the websocket layer moving forward so having most of my business logic in this class makes a lot of sense i have two other wired values here first is the crude interface we discussed earlier the tarkan used to work with users and drivers the second one is this spring boot interface used to hash and salt the passwords just using this interface means that even in a case of a hack your user’s passwords would still be safe i’ll discuss this further soon adding a user consists of creating a new user object with the dao and invoking the built-in crude save method here we encode the password this is pretty seamless in spring but remarkably secure as it uses a salted hash passwords aren’t encrypted they are hashed and salted encryption is a two-way algorithm you can encode data and then decode it back hashing codes the data in such a way that can’t be reversed to verify the password we need to rehash it and check the hashed strings hashing alone isn’t enough as it can be assaulted with various attacks one of the tricks against hash attacks is salt the salt is random data that’s injected into the hash an attacker can distinguish between the salt and hash data which makes potential attacks much harder the password hashing algorithm of spring boot always produces a 60 character string which would be pretty hard to crack i’ll soon discuss the process of checking a password for validity as it’s a pretty big subject notice that get avatar uses the id value that leaves a small security weakness where a user can scan the ids for images of the drivers users i’m not too concerned about that issue so i’m leaving it in place however letting a user update the avatar is something that needs a secure token continuing with the security aspect notice that things such as password and token are special cases that we don’t want to update using the same flow as they are pretty sensitive we have three login methods and they are all technically very similar so they all delegate to a single login api call they all throw the user authentication exception which is a simple subclass of exception if a user wasn’t found in the list we failed this should never ever happen but it’s important to test against such conditions as during a hack these should never happen conditions might occur since the passwords are hashed and sorted we can’t just compare regenerating the hash and comparing that wouldn’t work either as salt is random the only way to test is to use the matches method we need to manually set the auth value as it’s not there by default to prevent a credential leak the one place where the auth value should exist is in the login process when we log in at first we need to check if the user with the given phone or social network exists the ui flow for users that exist and don’t exist is slightly different a small piece of the puzzle i skipped before is the security configuration class in spring boot we can use configuration classes like this instead of xml which i prefer by far first we need to disable some oauth and csrf attack protection both of these make a lot of sense for web-based javascript applications which are vulnerable to attacks and can use the built-in authentication but in a native app they just add complexity and overhead so they aren’t really necessary and can cause problems if you recall the password encoded from before this is the location where we include the actual implementation of this encoder you can place it in any configuration class but i thought it’s fitting to put it into the security configuration class so far so good but the user service is a server-only class we’d like to expose this functionality to the client code to do that we can add a json-based web service by using user web the user web service class notice that this is just a thin layer on top of the injected user service class the user service class we throw a user authentication exception when login failed this code automatically translates an exception of that type to an error dao object which returns a different error json effectively this means that when this exception type is thrown a user will receive a forbidden http response with the json body containing an error message of invalid password maps the user exists with phone number url so it will return true or false strings based on whether the user actually exists images just map to our url for the given image id so the url user slash avatar slash user id will return the image for the given user with the mime type image jpeg if the image isn’t there we’ll return an http not found error 404 which we can handle in the client code the user update avatar auth token api is a mime multipart upload request which we can use to upload an image a multi-part upload is encoded using base64 and is the http standard for file upload we check whether an id is set to determine if this is an add or an update operation however we don’t use the id value for editing then internally as the underlying api uses the token

Codename One

12. Server WebSocket Handler

Module 12: Creating an Uber Clone Transcript continuing the server side code will now delve into the location logic which maps to the websocket support in spring boot WebSockets websocket is a special type of socket that is created through http or https request a web server that supports web sockets opens a regular http connection and then uses the socket open there to continue working as a regular socket as a result the websocket setup is slower than a regular tcp socket but they provide the same level of flexibility after creation the advantage over tcp sockets is compatibility and the ability to patch pass through potential problematic firewalls as those would see a websocket as another http connection the websocket api includes two types of packets text and binary in this case i’ll use the binary protocol because it’s pretty easy to do this in java up until now all our communications went through web services which is convenient and scalable the fact we can use tools like curl and the network monitor to see what is going on under the hood is very helpful however web services suffer from the performance overhead and fixed structure issues of http for more interactive data we would prefer something like websockets some people use websockets for all their communications and it might work for your use cases a lot of developers use the text-based websocket as a substitute to web services altogether and in some cases that makes sense however as i mentioned before we have decades of experience with http it works well and has a huge infrastructure of tools behind it websockets are a low level api there are some higher level abstractions on top of them but these often go back to the problems of http without giving much in return WebSocketConfig spring boot has decent support for websockets but you need to activate it first we need to define a configuration class that sets up the websocket environment this class serves as a configuration tool for the websocket api defining limits quotas and handlers here i set common configuration arguments for websocket messages setting buffer sizes for the different types here i find the handler class to the ws msg url which will receive all of the websocket callbacks before we go into the handler class let’s create a special service class to handle location-based callbacks similarly to the user service LocationService most of the location apis map to the user class but it’s logically separate from the user service we will periodically update the user’s location notice that location can only be updated by the user himself as the token is required for that operation it’s more intuitive to work with radius from the client but the jpa query language makes it easier to work in absolute coordinates so i convert the kilometer radius unit to latitude longitude values we have two versions of the query one finds all of the drivers in the area so we can draw them on the map the second searches for available drivers only for hailing purposes i use a version of the method that only returns a part of the user data as we normally don’t need all of the data once this is in place we can implement the handler class which is the actual websocket implementation but first let’s review the communication Handler - Packet structure for location update protocol this is the binary structure we will use when receiving request on the server for a location update so when a user changes his current location we will send this data the message type should be 1 for a location update from the user the length of the user token string followed by a byte array of the token length representing the string notice that i used bytes instead of cars since the token is 100 ascii i can rely on that fact and reduce the packet size further the location data and the radius slash direction of the user a byte which is set to one when we are hailing a taxi in which case it will seek only the available drivers once this packet is processed the server would return the cars within the search radius by sending a packet back Handler - Packet structure for response in this case we don’t need the token as this is a message from the server the response type can be 2 for driver position update and 3 for available driver position update the entry indicates the number of drivers in the returned data the rest of the lines repeat for every driver response size times and include the position data for every driver now that we understand the protocol let’s dig into the code that implements it the handler class is a binary websocket handler that receives callbacks on incoming packets let’s go over the code these are constants used in the binary protocol to communicate the type of request or response this is a callback for a binary message from the client the api works with nios bytebuffer which allows us to run through a request efficiently we get the length of the user token string and the battery again i used bytes instead of cars since the token is 100 ascii we can rely on that assuming this is a location update we pull out the data and update the user object we prepare to return a response based on the seeking flag we also need to mark the response type correctly i used a bytearray output stream to construct the response i use try with resources to close the streams automatically when i’m done i just write out the response data to the stream and finally we convert the battery data from the stream to a battery then send to the client this is it for the basic server code

Codename One

13. Client Side UserService

Module 12: Creating an Uber Clone Transcript now that we have a server and a mock client we need to connect them together so we have a working prototype we also need to implement some core functionality such as sms activation before we get started we need to add some things to the client project first we need to add the websockets cn1 lib from the extension manager this is pretty simple to do if you already added a cn1 lib before next we need to sign up to twillow.com as developers they have a free trial account notice we don’t need to install support for the twillow lib since we already installed the sms activation cn1 lib before notice that we are sending the sms activation code from the client side this is a bad practice you should use the server twillo api and send the sms activation code from there i chose this approach because it’s seamless and shows the usage of the apis on the client which is what i’m trying to teach however keeping authentication code in the server is far more secure you will need the following values from the twillow developer account account id sid account sid auth token and phone number make sure to pick a us phone number for the free account otherwise payment would be required once you have those values you can create a new globals class which we will use for the global application data notice you might want to replace localhost with your ip during development so you can test the device against a server running on your machine the device would obviously need to be connected to the same wifi the following values are the values we have from twillow for convenience i used static import for these constants within the code the user class on the client side mirrors the user dao but uses the properties syntax so we can leverage observability json persistence and other core capabilities if you are familiar with properties already you won’t notice anything special about this class it’s just a standard property object if you aren’t familiar with properties please check out the video covering them as it would be helpful moving forward we need to define a connection layer that will abstract the server access code this will allow us flexibility as we modify the server implementation and the client implementation it will also make testing far easier by separating the different pieces into tiers the abstraction is similar to the one we have in the server i chose to go with a mostly static class implementation for the user service as it’s inherently a static web service it makes no sense to have more than one user service once logged in we will cache the current user object here so we have all the data locally and don’t need server communication for every query we bind the user object to preferences so changes to the user object implicitly connect to the preferences storage api and vice versa preferences allow us to store keys and values in storage which maps every entry to a similar key value pay whether we are logged in or not or out is determined by the token value we need that to send updates to the server side i’m creating the four digit verification code and sending it via the twillow sms web service api i’m also storing the value and preferences so i can check against it when it’s received even if the app dies for some reason this method is invoked to validate the received sms code notice i don’t just use equals instead the validation string might include the four sms text this can happen on android where we can automatically validate notice i still limit the length of the string to prevent an attack where a user can inject all possible four code combinations into this method maps to the user exists method in the server which we use to determine add slash login flows i use the rest api to make a single connection with the get method in this case the response is the string true or the string force so i can just check against the letter t when adding a user i use the rest api’s post method here i can set the body to the json content content of the user object the response is a string token representing the user which we can now store into preferences the login method accepts a phone and password and is invoked after we’ve validated the phone it can succeed or fail if we get back a token that means the user authentication exception wasn’t thrown in the server and we can set it into the preferences otherwise we need to send a failure callback

Codename One

14. SMS Activation and Interception

Module 12: Creating an Uber Clone Transcript the next step is binding this to the ui for a fully working sms activation process the sms activation process is practically done the first step is in the enter mobile number form where we need to change the event handling on the floating action button this code might produce a dialog if we show it in the current form it might go back to this form instead of enter sms verification digits form by using this callback we can make sure the next form is shown only android supports intercepting sms’s so this code will only run on that platform in that case we automatically validate against the string we get from the next sms if that works we automatically skip ahead to the password form regardless of the above we send an sms message to the given phone number next we need to validate the input in a case where sms isn’t validated automatically or if the user rejected the permission on android we can do this in the enter sms verification digits form class by editing the is valid method this pretty much does the sms activation but we’d also want the countdown functionality to work if you recall the ui there is a countdown label for resending the sms to implement that we need to first define two new member variables and define two helper methods the vari the variables represent the countdown value in seconds for resending the sms and the timer object which we need to cancel once it elapses the format method formats time in seconds as two digits four minutes and two digits for seconds next we need to make the following changes to the constructor code we schedule the timer to elapse every second and repeat on the current form we update the text which we draws automatically notice that it’s also a good practice to revalidate normally but since the string size would be roughly the same this shouldn’t be necessary we cancel the timer so we don’t keep sending the sms’s over again notice we don’t cancel the timer in case of success we don’t need to since it’s a ui timer it’s bound to the form and once we leave the current form it will no longer elapse this sends us to the password entry form where we now have two versions of the ui we connect to the server to check if the user exists and shown infinite progress ui over the previous form if the user exists we show a welcome back prompt otherwise we enter a new password we also need to change the code that handles the floating action button event to actually add or load the user if the user exists we call the login method and show the map on success if the server returned an error on the login we dispose the progress dialog and show the error message label we prepared before we use revalidate as the error label size changed and will occupy more space if the user didn’t exist before we create a new user object and add that user to the server then show the map if the operation is successful the error handling code is pretty similar to the previous code

Codename One

15. Location Service - Client Side

Module 12: Creating an Uber Clone Transcript next we’ll bind the websocket logic and map UI to bring this all together we can get started with a location service class similarly to the user service class that would abstract the local location unlock the user service class the location service class should also deal with the physical location of the device these are the same constants we have on the server when sending a location update to the server I don’t want to exceed a fixed amount of updates so we won’t burden the server or our Network the Clause has a private Constructor so the only way to create the location service is via the bind method which in turn invokes the instance method bind impul we provide two callbacks one is for a car being added which we will use to bind a new car to the UI and the other is for location updates so we can position the map location update notifies the server about changes to the location and also invokes the Callback once we can position the map we invoke the callback with the location so the map can be shifted to our current position once the server socket is connected we start sending location updates there we open the websocket connection using the connect call we cache the last set of values so we don’t send data to the server unless something changed easy threads lets us Post jobs onto a dedicated thread so we don’t have to block the main EDT it also means we don’t need to deal with synchronization or any other complexity related to that as all operations happen on that thread until on open is invoked the connection isn’t ready that’s why the server member field is only initialized here when it’s actually ready if we already have a location we should send a user location update one we have once we have the socket Connection in place the connection is single threaded as I mentioned before there is this it method is similar to is EDT and indicates if the current thread is the one managed by the easy thread if not we use the run runnable which invokes the Target runnable on the easy thread similarly to call serially if the values didn’t change since last update so we do nothing we don’t update too much there is a chance we’ll miss an update here but it’s probably not a deal breaker if a user didn’t move much we create a byte array output stream into which we construct the message that we received on the server with the header location Etc I currently hard coded a one kilometer search radius and find explicitly that we aren’t in taxi hailing mode one line to actually send the binary data it would be similar with text Data with the exception of passing overhead the IR exception isn’t likely as this is a ram-based stream the here we received the messages sent from the server specifically driver search result we store user instances in a map where the user ID is the key this saves us from sending duplicate core added events and allows us to just mutate the user properties which other code can observe using the built-in listeners and properties notice that this code is running on the websocket thread so events need to go back into the EDT to prevent potential issues this is really important we need to handle errors properly in a websocket application otherwise a failure can leave us without a connection the Callback interface is Trivial it’s mostly used as a Lambda expression in the code and that’s it for the location service

Codename One