Java IV

Asynchronousicity

  • In Computer Science, Asynchronous is used to describe when a program doesnt wait for one instruction to finish before going on to the next.
    • Asynchronous I/O means that a program can continue to execute while the expensive operations of reading and writing are done
    • Asynchronous execution means that some part of a program, usually a method/function, is started but then the next operation in the main code is executed, with out waiting for the subprogram to return
  • The implementation and organization of these systems can be complex, for this class you just need to understand the idea

Web Workers

  • Web workers are a way run computationally intensive code while allowing the main scripts to continue
    • Uses a form of event handling to communicate with the main script
    • Must be defined in their own file
  • Without webworkers, the script would pause during computationally heavy parts
    • No events could be handled

Creating and Messaging Web Workers

  • A Web Worker is created by instantiating a new Worker object and passing the location of the worker script
    var theWorker = new Worker('workerFile.js')
    
  • The web worker will return results by creating an event of type 'message'
  • To listen for it:

    theWorker.addEventHandler('message',function(event){
      //Grab the result and do something with it
      process(event.data)
    });
    
  • To call the function defined in the web worker, we pass the arguments to the postMessage method of the worker object

    theWorker.postMessage(arguments)
    

Code in a Web Worker

  • The web worker file has one enterence function, which is an event handler for a message
addEventHandler('message',function(event){
    //The arguments from postMessage are held in event.data
    var value = doBigCalcuation(event.data)
    //Again post message is used to pass data
    postMessage(value)

})

Web Worker Examples

In [ ]:
%load 'js/primes.js'
In [ ]:
%%html
<html>
    <head>
        <style>
            p#primes {width:800px;word-wrap: break-word;}
        </style>
        <script>
            var primeWorker = new Worker('js/primes.js')
            
            var primes = [];
            primeWorker.addEventListener('message',function(event){
                    primes.push(event.data)
                    document.querySelector("#primes").innerHTML = primes.join(", ")
                })
            
            primeWorker.postMessage([100000,1000000])
        </script>
    </head>
    <body>
        <p id="primes"></p>
    </body>
</html>

Web Worker Practice

  • Write a web worker and associated event handler to find the first n square numbers

AJAX

  • AJAX is an acronym for Asynchronous Javascript And XML
  • JavaScript allowed the user to interact with what was on the page
    • What about getting new data after the page loaded
    • Prediction of Text in search
    • Allows to request data from multiple sources on one webpage
      • Google Maps
      • Yelp
      • Twitter

Brief History of AJAX

  • Was first implemented in Internet Explorer
  • Other browers quickly adopted it, but changed the method names
  • Was based on XML (eXtensible Markup Language) due to heavy use in businuess at the time
  • Today is standardized and XML is hardly used anymore

XMLHTTPRequest

  • XMLHTTPRequest is the object used to initiate and interact with the request
    var theRequest = new XMLHttpRequest();
    
  • After we have the object, open is used to set where the data is from and how to get it
    • For security reasons, this location needs to be part of the same website
  • Send is used to add parameters and send the request to the URL given in the open parameter
    theRequest.open('METHOD','location',Asynchronous?)
    theRequest.send(ParametersObject)
    

Listening for XMLHTTPRequest Response

  • The reponse to the request is accessed by attaching an event listener to the request object
  • There are 4 events that can be handled
    • abort
    • error
    • progress
    • load
  • Upon completetion of the request, the request attributes of responseText and status will have useful values
    theRequest.addEventListener('load',function(){
      if(theRequest.stauts === 200){
          doSomething(theRequest.responseText)
      }
    }
    

XMLHTTPRequest Example

In [ ]:
%%html
<html>
    <head>
        <script>
        var theRequest = new XMLHttpRequest()
        var typeAhead = document.querySelector("#typeAhead")
        
        theRequest.addEventListener('load',function(){
        if(theRequest.status === 200){
            typeAhead.value = theRequest.responseText
            }
        })
                                    
        typeAhead.addEventListener("keyup",
            function(){
              theRequest.open('GET','http://www.csee.umbc.edu/~bwilk1/ajaxExample1.php?q=' + typeAhead.value ,true)
              theRequest.send(null)
            })                                  
                                    
        </script>
    </head>
    <body>
        <input type="text" class="input" id="typeAhead"/>
    </body>
</html>

JSON

  • As indicated in the acronym AJAX and the name of the object, XMLHTTPRequest, responses were originally intended to be sent with XML
  • XML needs to be parsed to be turned in to a JavaScript object
  • A simplier and less data intensive way to send an JS object would be as the Javascript needed to define that object
    {
      "property1":val1,
      .
      .
      .
      "propertyN":[ anArray1, anArray2, anArray3 ]
    }
    

XML Example

<api batchcomplete="">
    <continue gapcontinue="Programming_language_for_Computable_Functions" continue="gapcontinue||"/>
    <query>
        <pages>
            <page _idx="23015" pageid="23015" ns="0" title="Programming language"/>
            <page _idx="36706283" pageid="36706283" ns="0" title="Programming language-independent"/>
            <page _idx="23521" pageid="23521" ns="0" title="Programming language/Timeline"/>
            <page _idx="23523" pageid="23523" ns="0" title="Programming language/assembly"/>
            <page _idx="20828640" pageid="20828640" ns="0" title="Programming language C"/>
            <page _idx="43277179" pageid="43277179" ns="0" title="Programming language comparisons"/>
            <page _idx="33500129" pageid="33500129" ns="0" title="Programming language compiler"/>
            <page _idx="2848168" pageid="2848168" ns="0" title="Programming language design"/>
            <page _idx="18073370" pageid="18073370" ns="0" title="Programming language dialect"/>
            <page _idx="30873250" pageid="30873250" ns="0" title="Programming language error codes"/>
        </pages>
    </query>
</api>

JSON Example

"batchcomplete": "",
  "continue": {
    "gapcontinue": "Programming_language_for_Computable_Functions",
    "continue": "gapcontinue||"
  },
  "query": {
    "pages": {
      "23015": {
        "pageid": 23015,
        "ns": 0,
        "title": "Programming language"
      },
      "36706283": {
        "pageid": 36706283,
        "ns": 0,
        "title": "Programming language-independent"
      },
      "23521": {
        "pageid": 23521,
        "ns": 0,
        "title": "Programming language\/Timeline"
      },
      "23523": {
        "pageid": 23523,
        "ns": 0,
        "title": "Programming language\/assembly"
      },
      "20828640": {
        "pageid": 20828640,
        "ns": 0,
        "title": "Programming language C"
      },
      "43277179": {
        "pageid": 43277179,
        "ns": 0,
        "title": "Programming language comparisons"
      },
      "33500129": {
        "pageid": 33500129,
        "ns": 0,
        "title": "Programming language compiler"
      },
      "2848168": {
        "pageid": 2848168,
        "ns": 0,
        "title": "Programming language design"
      },
      "18073370": {
        "pageid": 18073370,
        "ns": 0,
        "title": "Programming language dialect"
      },
      "30873250": {
        "pageid": 30873250,
        "ns": 0,
        "title": "Programming language error codes"
      }
    }
  }
}

JSON

  • This formant is known as JavaScript Object Notation, or JSON
  • JSON needs to be parsed too, but the parser is already part of the langauge
    • Originally JSON was made into an object by a statement like
      var obj = eval("(" + json + ")")
      
    • This works but is insecure, any code in the string will be executed
    • Today, the JSON object is a part of JavaScript officially so JSON responses can be processed like:
      var obj = JSON.parse(json)
      

JSON Example

In [ ]:
%%html
<html>
<head>
    <script>
        var wikiRequest = new XMLHttpRequest()
        wikiRequest.addEventListener('load',
            function(){
                if(theRequest.status === 200){
                    var response  = JSON.parse(wikiRequest.responseText)
                    var pages = response.query.pages
                    for(page in pages){
                        document.querySelector("#wikiResults").insertAdjacentHTML('beforeend',
                            "<li>" + pages[page].title + "</p>")
                    }
                }
        })
        
        document.querySelector('#wikiSearch').addEventListener('input',
            function(){
                wikiRequest.open('GET',"https://en.wikipedia.org/w/api.php?action=query& " +
                             "generator=allpages&gaplimit=5&format=json&gapfrom=" + 
                             document.querySelector("#wikiSearch").value)
                wikiRequest.setRequestHeader('Api-User-Agent', 'UBMC 331 Class Example/1.0 (bryan.wilkinson@umbc.edu)' );
                wikiRequest.setRequestHeader("Origin", "http://localhost:8888/notebooks/Lecture20.ipynb");
                wikiRequest.send()
                             
            })
    </script>
</head>
    <body>
        <input type="text" id="wikiSearch"/>
        <ul id="wikiResults">
            
        </ul>
    </body>
</html>

JQuery

  • While today JavaScript is more standardized and the standards are more widely accepted, this hasn't always been the case
  • To cope with the number of idiosyncracies??RIGHTWORD? encountered when developing for multiple interpreters, several libraries emerged to provide a common interface for certain tasks.
  • The most sucessful of these was JQuery, and it is still extremely popular today

The JQuery object

  • One of the biggest benefits JQuery provided was a simple way to get elements of a document
//Selects all paragraph elements
$('p')

//Selects all elements of class highlight
$('.highlight')

JQuery Event Handling

  • jQuery not only makes selection of elements easy, but allows to attach event handlers to all of the selected events in one method call
  • In pure JS the method addEventListener is used, while in jQuery the method is known as on
    • They are pretty much the same and both accept and event type and handler function
$(selector).on(eventType,
    function(event){

    })

JQuery Event Handling Practice

In [ ]:
%%html
<html>
<head> 
    <script src='https://code.jquery.com/jquery-2.1.4.min.js'></script>
    <script>
        $('p').on('click',function(){
             this.style.background = "green"   
            })
    </script>
    
</head>
<body>
   <div class="contain2">
            <p> A Paragraph</p>
            <p> A Second Paragraph</p>
            <p> A Third Paragraph</p>
    </div>
</body>
</html>

JQuery AJAX

  • The other feature that popularized jQuery was it's simplification of AJAX calls.
  • Much of the method calls needed to create an ajax request are boilierplate
  • With jQuery, there are many simple methods such as getJSON that take al the paremeters in one method call
    $.getJSON(url, parameters, function(json, status, jqueryRequestObject){
         });
    

JQuery AJAX Practice