title: Stream videos in client app using Ajax and java Restlet
body: <p>Hi I want to stream videos in client app but videos are located in server app. I am using java Restlet and Jquery Ajax to connect client app to server app. Through Ajax call i am connecting to Restlet. I don't know how to send response to ajax after streaming video from server side, how ajax receives response and how to play video in browser.  Can any one help me to handle this. </p>
  
  <p>Here is my code</p>
  
  <p><strong>Html:</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="playVideo" class="btn-primary"&gt;PlayVideo&lt;/button&gt;
  &lt;video id="videoTab" height="300" width="500" style="display: none" controls &gt;&lt;/video&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>Ajax Call to server</strong></p>
  
  <pre><code>    $('#playVideo').click(function (){
          var jsonObj = {};
          jsonObj.userId = "siva";
          jsonObj.file = "sample.mp4";
          //console.log("json obje :"+ JSON.stringify(jsonObj))
          // Rest call to play videos.
          $.ajax({
              type : 'GET',
              url : config.streamVideo,
              //dataType : 'json',
              data : JSON.stringify(jsonObj),
              contentType : "application/json",
              mimeType : "video/mp4",
              processData : false,
              crossDomain : true,
              success : function(result) {
                  //console.log("login result : " + JSON.stringify(result));
                  if (result) {
                      console.log("success.....");
                      srcPath = "data:video/mp4;"+result;
                      $('#videoTab').attr('src', srcPath);
                      $('#videoTab').css('display', 'block');
                      $('#videoTab').attr('autoplay', true);
                  } else {
                      alert('failed...');
                  }
              },
              error : function(){
                  alert('error')
              }
          });
      });
  </code></pre>
  
  <p><strong>RestletCode:</strong></p>
  
  <pre><code>@Get
  public InputRepresentation handleRequest(Representation entity) throws IOException,        ResourceException {
  // Set response headers
  Series&lt;Header&gt; responseHeaders = (Series&lt;Header&gt;)    getResponse().getAttributes().get("org.restlet.http.headers");
  if (responseHeaders == null) {
    responseHeaders = new Series&lt;Header&gt;(Header.class);
    getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
  }
  responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
  
  logger.debug("+++++++++++++++++++Entered in play video restlet +++++++++++++++");
  // Convert Rest type request to Servlet request
  httpServletRequest = ServletUtils.getRequest(getRequest());
  // Get Servlet context object.
  sc = httpServletRequest.getServletContext();
  // Get input file path.
  logger.debug("-------&gt;getRealPath " + sc.getRealPath("/"));
  String filePath = sc.getRealPath("/") + "WEB-INF\\data\\videos\\sample.mp4";
  
  final File file = new File(filePath);
  if (file.exists()) {
    logger.debug("Requested file path : " + file.getAbsolutePath());
    logger.debug("inputRepresentation :" + inputRepresentation);
    fis = new FileInputStream(file);
    inputRepresentation = new InputRepresentation(new InputStream() {
      private boolean waited = false;
  
      @Override
      public int read() throws IOException {
        waited = false;
  
        // read the next byte of the FileInputStream, when reaching the
        // end of the file, wait for 2 seconds and try again, in case
        // the file was not completely created yet
        while (true) {
          byte[] b = new byte[1];
  
          if (fis.read(b, 0, 1) &gt; 0) {
            return b[0] + 256;
          } else {
            if (waited) {
              return -1;
            } else {
              try {
                Thread.sleep(2000);
              } catch (InterruptedException ex) {
                logger.error("Exception while streaming video : ", ex);
              }
              waited = true;
            }
          }
        }
      }
  
    }, MediaType.VIDEO_MP4);
  } else {
    logger.debug("Requested file not found : " + filePath);
  }
  //logger.debug("inputRepresentation :");
  return inputRepresentation;
  }
  </code></pre>
  
  <p>Thanks in advance</p>