Download By Yakov Fain - Farata Systems

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Hey Yakov, I want to learn Java Why? Cause my grandpa used to code in it What’s your aAenBon span? 20 min Let’s do it Java For Blonds and Blondes By Yakov Fain (c) Farata Systems, L.L.C. 2011 Part 1. Core Java in 20 min public class HelloWorld { public staBc void main(String[] args){ System.out.println(“Hello World”); } } In Java, you start with creaBng a class. Our class is called HelloWorld. A class can have methods, like main(), goShopping(), etc. If a class has this special method main() you can run it as a program (c) Farata Systems, L.L.C. 2011 1. Compile = translate Java text into a computer language 2. Run the program = make it working I hate command windows! (c) Farata Systems, L.L.C. 2011 Eclipse is a place for blondes who hate command windows Any alternaBves to Eclipse? Eclipse is our religion. Ignore the rest. We use Eclipse for Java EE Developers (c) Farata Systems, L.L.C. 2011 WriBng a Useful Program I want to write a useful Java program: Calculate the final prices if Bloomingdales runs “Friends and Family” event and everything is 40% off Simple screen? Fancy looking screen. Then Learn Adobe Flex. Java is not there yet. My grandpa doesn’t like Flex. Let’s keep it , but in Java. (c) Farata Systems, L.L.C. 2011 Lather, Rinse, Repeat import java.uBl.Scanner; public class FriendsAndFamily { public staBc void main(String[] args) { Scanner input= new Scanner(System.in); // Lather, Rinse, Repeat, lather, rinse, repeat, lather, rinse, repeat, lather, rinse, re do { System.out.println("\n Enter list price: " ); double listPrice = input.nextDouble(); System.out.println(" Enter discount %: " ); int discount = input.nextInt(); System.out.prinh(" You'll pay only $%2.2f", listPrice -­‐ listPrice*discount/100); } while (true); } } (c) Farata Systems, L.L.C. 2011 Part 2. Web ApplicaBons in 20 min Now that I’ve mastered the Java language, teach me how to create cool looking Web Sites in Java. Learn Adobe Flex. My grandpa doesn’t like Flex. Let’s do a plain Web site, but in Java. It’s easy! Just give me 20 min (c) Farata Systems, L.L.C. 2011 WOW! Is this for Blondes? Oops… Sorry…Wrong slide… (c) Farata Systems, L.L.C. 2011 Web ApplicaBons With Servlets Web Browser Java Server with your Servlet Data storage I like the data Ber. My grandpa told me that Oracle DBAs used to make good money… Their Bme is gone. The new trend is Cloud CompuBng. What’s Cloud CompuBng? It’s when no one really knows where the servers and data are, but it works somehow. (c) Farata Systems, L.L.C. 2011 Increase your vegetable preparaBon efficiency with this Easy Dicer Two-­‐Way Vegetable CuAer (N55100E) from Nemco. Capable of slicing a variety of vegetables, all it takes is a pull of the lever to quickly dice your ingredients. (c) Farata Systems, L.L.C. 2011 Install GlassFish 3.1 Server and Configure it in Eclipse 1.  Download and install GlassFish from hAp://bit.ly/eTD4Fy 2.  In Eclipse, Open the view Servers (menu Windows | Show View | Others |Server) 3.  Select File | New | Other | Server, and add GlassFish 3.1. If you don’t see GlassFish in the list of servers, hit the link Download addiBonal server adapters and select GlassFish Server Tools. 4.  Open your Web Browser and go to hAp://localhost:8080 to see the GlassFish Welcome page What’s localhost and port? What’s your address? 11 Fixh Ave, Apt. 85 And Glassfish lives in your notebook, apt. 8080 (c) Farata Systems, L.L.C. 2011 CreaBng Dynamic Web Project 1. In Java EE perspecBve, go to File | New | Dynamic Web Project. 2. Give it a name and keep GlassFish 3.1 as target runBme. Click Finish. 3. You’ll see the code of index.jsp. Change “Hello World” to “Hello Blondes” 4. <%@page Right-­‐click on your project, then Run As | Run on Server contentType="text/html" pageEncoding="UTF-­‐8"%> "-­‐//W3C//DTD HTML 4.01 TransiBonal//EN" in your Web Browser. 5. <!DOCTYPE Enter the HUTML RL PhUBLIC Ap://localhost:8080/HelloFromServer hAp://www.w3.org/TR/html4/loose.dtd> You’ll see the same greeBng! <html> <head> <meta hAp-­‐equiv="Content-­‐Type" content="text/html; charset=UTF-­‐8"> <Btle>GlassFish JSP Page</Btle> </head> <body> <h1>Hello World!</h1> </body> </html> (c) Farata Systems, L.L.C. 2011 CalculaBng Sales Price on the Server 1.  Create a new servlet: File | New | Servlet. Name it FriendsAndFamilyServlet. Keep the superclass as HApServlet. Press Next. (c) Farata Systems, L.L.C. 2011 CalculaBng Sales Price on the Server(cont.) 1.  Change the URL mappings field to be /sale. Now any URL that has the word sale will be re-­‐directed to the FriendsAndFamilyServlet. Press Finish. (c) Farata Systems, L.L.C. 2011 The generated servlet code will look like this: @WebServlet("/sale") // this is called annotaBon public class FriendsAndFamilyServlet extends HApServlet { public FriendsAndFamilyServlet() { super(); // TODO Auto-­‐generated constructor stub } protected void doGet(HApServletRequest request, HApServletResponse response) throws ServletExcepBon, IOExcepBon { // TODO Auto-­‐generated method stub } protected void doPost(HApServletRequest request, HApServletResponse response) throws ServletExcepBon, IOExcepBon { // TODO Auto-­‐generated method stub } Seems I sBll have some gaps in my Java skills. What’s throws? } In case of an error, your program will throw it -­‐ like a ball -­‐ to the caller Got it. What’s extends? (c) Fh
arata You ave Systems, mom La.L.C. nd 2p011 op, but a program can have only mom. CalculaBng Sales Price on the Server Eclipse generated this code: @WebServlet("/FriendsAndFamiliServlet") // this is annotaPon – won’t be covered in this presentaPon public class FriendsAndFamiliServlet extends HApServlet { private staBc final long serialVersionUID = 1L; public FriendsAndFamiliServlet() { super(); // TODO Auto-­‐generated constructor stub } protected void doGet(HApServletRequest request, HApServletResponse response) throws ServletExcepBon, IOExcepBon { // TODO Auto-­‐generated method stub } protected void doPost(HApServletRequest request, HApServletResponse response) throws ServletExcepBon, IOExcepBon { // TODO Auto-­‐generated method stub } } Your code calculaBng the final price should replace one of the TODO comments (c) Farata Systems, L.L.C. 2011 CalculaBng Sales Price on the Server Right click on the FriendsAndFamily class and select Run As | Run on Server. Note the URL: hAp://localhost:8080/HelloFromServer/sale. The servlet won’t return anything, because methods doGet() and doPost() don’t have code. The project HelloFromServer has been deployed under GlassFish server. Check the Servers view.
(c) Farata Systems, L.L.C. 2011 Add these two lines to doGet(). You’ll need to import PrintWriter too: PrintWriter out = response.getWriter(); out.println("Hello from your Java Server!"); Run the servlet again. Now we’re talking! Farata Systems, L.L.C. 2011 Paste the URL to your W(c) eb browser – works the same. CreaBng HTML Client 1. Create HTML page by selecBng File | New | HTML file. Keep the WebContent as parent folder and name it PriceCalculator.html. Press Next. 2. Select HTML 5 template, and Eclipse will generate the code: <!DOCTYPE html> <html> <head> <meta charset="UTF-­‐8"> <Btle>Insert Btle here</Btle> </head> <body> </body> </html> Right-­‐click on the file and select R(c) un as | Run on Server. NoBce the URL: Farata Systems, L.L.C. 2011 hAp://localhost:8080/HelloFromServer/PriceCalculator.html Adding a <form> Tag to HTML file <!DOCTYPE html> <html> <head> <meta charset="UTF-­‐8"> <Btle>My Price Calculator</Btle> </head> <body> <form acPon="h#p://localhost:8080/HelloFromServer/sale"> Enter list price: <input type="text" name="listPrice"/> <br> Enter discount %: <input name="discount" /> <input type="Submit" value="Get discounted price" /> </form> </body> </html> Pressing Submit buAon Sends a request to the URL you put in the acBon parameter of your form. (c) Farata Systems, L.L.C. 2011 $2 Quiz What will the browser display A[er clicking on this bu]on? Processing Request on the Server and Sending Response 1.  Get the parameters from HApServletRequest 2.  Apply the applicaBon logic 3.  Return the result via HApServletResponse protected void doGet(HApServletRequest request, HApServletResponse response) throws ServletExcepBon, IOExcepBon { String listPrice = request.getParameter("listPrice"); String discount = request.getParameter("discount"); // Convert Strings to numeric values double price = Double.parseDouble(listPrice); int disc = Integer.parseInt(discount); //Calculate the discounted price and send the result to the caller
PrintWriter out = response.getWriter(); out.prinh(" You'll pay only $%2.2f", price -­‐ price*disc/100);
} (c) Farata Systems, L.L.C. 2011 Now that I’ve mastered the Java language, and Web programming, is there anything else I don’t know yet? Are you ready to deep dive into the boring world of communicaBon protocols? What’s a protocol? It’s an agreement between two parBes on what leAers and words are allowed in the conversaBon. It’s like don’t use the F-­‐word in some places? PreAy much. Let’s spend another 20 min on that (c) Farata Systems, L.L.C. 2011 Part 3. HTTP vs. WebSockets in 20 min What this narrow bridge has to do with network protocols? This is an illustraBon of HTTP half-­‐duplex communicaBons. Got it! One direcBon at a Bme! (c) Farata Systems, L.L.C. 2011 HTTP-­‐based communicaPon techniques Connect-­‐Poll Client Nothing Connect-­‐Poll Nothing Connect-­‐Poll Server Polling. Web browser periodically checks if the server has some data for the client. Data (c) Farata Systems, L.L.C. 2011 HTTP-­‐based communicaPon techniques Connect-­‐Poll Client Nothing Connect-­‐Poll Nothing Connect-­‐Poll Server Polling. Web browser periodically checks if the server has some data for the client. Data Connect-­‐Poll Data Client Connect-­‐Poll Server Long Polling. Similar to polling, but the Web browser holds the connecBon unBl the server has the data. Data (c) Farata Systems, L.L.C. 2011 HTTP-­‐based communicaPon techniques Connect-­‐Poll Client Nothing Connect-­‐Poll Nothing Connect-­‐Poll Server Polling. Web browser periodically checks if the server has some data for the client. Data Connect-­‐Poll Data Client Poll Server Long Polling. Similar to polling, but the Web browser holds the connecBon unBl the server has the data. Data Connect Client Push Push Push Server Streaming. It’s like Youtube. The server pushes the data to the client pretending that the response never ends. Push Close Conn. All these HTTP-­‐based soluBons have overhead: request and response include hundreds of (c) Farata Systems, L.L.C. 2011 addiBonal bytes. I want to see it to believe it! OK. Let’s sniff. HTTPRequest: 515 bytes HTTPResponse: 304 bytes This is Wireshark Network Monitor (c) Farata Systems, L.L.C. 2011 How HTTP Overhead Affects the Web The eBay server pushes the latest Louis VuiAon bag prices to 1000 people. The 20-­‐byte price info inside HTTPResponse becomes 300 bytes. Add 500 bytes for HTTPRequest for polling. Just for one push eBay uses 300Kb bandwidth for 1000 people! (c) Farata Systems, L.L.C. 2011 eBay sells more than 1,000,000 items a day, and the prices change frequently. What other real-­‐Bme Web applicaBons need low-­‐overhead and low-­‐
latency protocols? •  Trading (price changes, order execuBons) •  Monitoring servers •  Video streaming •  Controlling medical equipment •  Online games (c) Farata Systems, L.L.C. 2011 Network socket is an endpoint of a bidirecBonal traffic Websocket is a standardized technology to support low-­‐overhead bidirecPonal traffic from your Web browser (c) Farata Systems, L.L.C. 2011 hAp://dev.w3.org/html5/websockets/ Web browser opens an HTML file, which includes this JavaScript code: Hey, Server, ain’t no talking to you in HTTP slang . Upgrade me to WebSockets protocol, will you? JavaScript is not Java. It’s mainly used inside Web pages to do some processing on the client ws = new WebSocket("ws://localhost:8080/HelloFromWebSocketServer/salews"); // Set event handlers for onopen, onmessage, onclose, and onerror. ws.onopen = funcBon() { output("The client WebSocket.onopen was invoked"); }; ws.onmessage = funcBon(e) { // e.data contains a String received from server output(”In the client WebSocket.onmessage. Received from server: " + e.data); }; ws.onclose = funcBon() { output(”In the client WebSocket.onclose"); }; ws.onerror = funcBon() { output(”In the client WebSocket.onerror"); }; (c) Farata Systems, L.L.C. 2011 Submi•ng Price and Discount via WebSockets funcBon onSubmit() { var listPrice = document.getElementById("listPrice"); var discount = document.getElementById("discount"); // Send the message to the server using ws.send. var priceAndDiscount = listPrice.value + "," + discount.value; ws.send(priceAndDiscount); output("Sent to Server via WebSocket: " + priceAndDiscount); } … </head> <body onload="init();"> <form onsubmit="onSubmit(); return false;"> Enter list price: <input type="text" id="listPrice"/> <br> Enter discount %: <input type="text" id="discount" /> <input type="submit" value="Get discounted price" /> <buAon onclick="onCloseClick(); return false;">Disconnect</buAon>
</form> <div id="log"></div> </body> </html> (c) Farata Systems, L.L.C. 2011 The handshake upgrades protocol from HTTP to WebSockets (c) Farata Systems, L.L.C. 2011 Sending request to with WebSockets adds just two bytes on top of TCP/IP! Data overhead is 2 bytes: starts with 00 byte, ends with FF Price: 100, Discount: 12 (c) Farata Systems, L.L.C. 2011 The server side (Glassfish version) The servlet FriendsAndFamilyServletWS just -­‐ upgrades the protocol from HTTP to WebSockets, -­‐ registers MyWebsocketApplicaBon, -­‐ and stops parBcipaBng in any future client/server communicaBons! @WebServlet(descripBon = "WebSocket servlet", urlPaAerns = { "/salews" }, loadOnStartup=1) public class FriendsAndFamilyServletWS extends HApServlet { private final WebSocketApplicaBon app = new MyWebsocketApplicaPon(); public void init(ServletConfig config) throws ServletExcepBon { WebSocketEngine.getEngine().register(app); } } (c) Farata Systems, L.L.C. 2011 The server side’s MyWebsocketApplicaBon.java public class MyWebsocketApplicaPon extends WebSocketApplicaBon { public boolean isApplicaBonRequest(Request arg0) { return true; } public void onConnect(WebSocket socket) { super.onConnect(socket); } public WebSocket createSocket(WebSocketListener... listeners) throws IOExcepBon { return new BaseServerWebSocket(listeners); } public WebSocket createSocket(WebSocketListener... listeners) throws IOExcepBon { return new MyServerWebSocket(listeners); } public void onMessage(WebSocket socket, DataFrame frame) throws IOExcepBon { // Parse the input that arrived from the client String delimiter=","; // we expect comma separated list price and discount String[] parsedData; String receivedFromClient=frame.getTextPayload(); parsedData=receivedFromClient.split(delimiter); // Calculate the final price double price = Double.parseDouble(parsedData[0]); int disc = Integer.parseInt(parsedData[1]); double finalPrice = price -­‐ price*disc/100; // Broadcast to all clients for(WebSocket websocket : getWebSockets()){ w
socket.send("You'll pay " + finalPrice);
ebsocket.send(“ …“+finalPrice); } } public void onClose(WebSocket socket) throws IOExcepBon { super.onClose(socket); } (c) Farata Systems, L.L.C. 2011 } It was great, Yakov! I feel like I’m ready to work as a junior Java developer! Now you know more than mid-­‐level developers! Sweet! Can you recommend me a good book to conBnue studying? This is the best one: (c) Farata Systems, L.L.C. 2011