WebRequester.java :  » Game » letsgo-imerir » com » letsgo » Android Open Source

Android Open Source » Game » letsgo imerir 
letsgo imerir » com » letsgo » WebRequester.java
package com.letsgo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import android.sax.RootElement;
import android.util.Xml;

public class WebRequester implements Requester {
  private Player currentOwner=null;
  private HttpClient httpClient;
  private static final String VERSION = "1.0";
  private String baseURL = "http://192.168.0.13:8081/";
  private static final String USERS = "users/";
  private static final String BOARDS = "boards/";
  private static final String REQUESTS = "requests/";
  private static final String MOVES = "moves/";
  private static final String INVITES = "invites/";
  private boolean versionOk = false;
  
  /**
   * This method will done an HTTP Get request on the server configured into the variable baseURL
   * The server will respond with an XML file with the current version of the server application
   * and the baseUrl used currently.
   * @param p is a Player object that represent the owner player information
   * @throws ClientProtocolException
   * @throws IOException
   * @throws ParserConfigurationException
   * @throws SAXException
   */
  public WebRequester(Player p) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException{
    currentOwner = p;
    httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(baseURL+"?un="+currentOwner.getNick_name());
    HttpResponse response = httpClient.execute(get);
    
    StatusLine sl = response.getStatusLine();
    HttpEntity entity= response.getEntity();
    BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
    String line;
    String responseContent="";
    while ((line = rd.readLine()) != null) {
      responseContent = responseContent+line;
    }
    rd.close();
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();      
    Document doc = db.parse(new InputSource(new BufferedReader(new StringReader(responseContent))));
    doc.getDocumentElement().normalize();
    Node fc = doc.getFirstChild();
    if(fc.getNodeName().equals("goimerir")){
      Element elmnt = (Element) fc;
      if(elmnt.getAttribute("version").equals(VERSION))
        versionOk=true;
    }
    if(versionOk){
      NodeList nodeList= doc.getElementsByTagName("url");
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Element elmnt = (Element) node;
        baseURL = elmnt.getAttribute("href")+"/";
      }
    }
  }
  /**
   * This method will make an XML String with different informations about the new Player p
   * And will send the XML String in parameter of an HTTP Post request.
   */
  @Override
  public void createUser(Player p) throws RequesterMissingPwdException {
     XmlSerializer serializer = Xml.newSerializer();
     StringWriter writer = new StringWriter();
     try {
          serializer.setOutput(writer);
          serializer.startDocument("UTF-8", true);
          serializer.startTag("", "goimerir");
          serializer.attribute("", "version", "1.0");
          serializer.startTag("", "user_create");
          
          serializer.startTag("", "fullname");
          serializer.attribute("", "value", p.getName());
          serializer.endTag("", "fullname");
          
          serializer.startTag("", "screenname");
          serializer.attribute("", "value", p.getNick_name());
          serializer.endTag("", "screenname");
          
          serializer.startTag("", "password");
          serializer.attribute("", "value", p.getPwd());
          serializer.endTag("", "password");
          
          serializer.endTag("", "user_create");
          serializer.endTag("", "goimerir");
          serializer.endDocument();
          HttpPost post = new HttpPost(baseURL+USERS);// /users
          StringEntity se = new StringEntity(writer.toString(),HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
        post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
          
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
      
  }
  /**
    * This method will done an HTTP GET Resquest, taking the list of users between the start and the end variable.
    * When the list of users is returned from the server, if the header of the server is equals to the status code 200
    * then the function will extract the content message in our case it is an xml message and we will do an extraction from
   * the XML of the differents values that we need to returned.
   */
  @Override
  public ArrayList<Player> listUsers(int start, int end, boolean last) {
    if(versionOk){
      ArrayList<Player> listPlayer = new ArrayList<Player>();
      httpClient = new DefaultHttpClient();
      
      HttpGet get=null;
      if(last)
        get = new HttpGet(baseURL+USERS+"?start="+start+"&end="+end+"&last=1");
      else
        get = new HttpGet(baseURL+USERS+"?start="+start+"&end="+end+"&last=0");
      HttpResponse response;
      try {
        response = httpClient.execute(get);
        StatusLine sl = response.getStatusLine();
        /*
         *  If the status code is correct we can take the content message
         */
        if(sl.getStatusCode()==200){
          HttpEntity entity= response.getEntity();
          BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
          String line;
          String responseContent="";
          while ((line = rd.readLine()) != null) {
            responseContent = responseContent+line;
          }
          rd.close();
          /*
           * Extraction of the differents informations from the XML
           */
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db;
          try {
            db = dbf.newDocumentBuilder();
            Document doc;
            try {
              doc = db.parse(new InputSource(new BufferedReader(new StringReader(responseContent))));
              doc.getDocumentElement().normalize();
              Node fc = doc.getFirstChild();
              if(fc.getNodeName().equals("goimerir")){
                NodeList nodeList= doc.getElementsByTagName("user");
                for (int i = 0; i < nodeList.getLength(); i++) {
                  Node node = nodeList.item(i);
                  Element elmnt = (Element) node;
                  listPlayer.add(new Player(elmnt.getAttribute("name"), elmnt.getAttribute("fullname"), "") );
                }
              }
            } catch (SAXException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }      
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
      
      return listPlayer;
    }else{return null;}
  }
  /**
   * This method make an XML String with all information about the creation of a new game
   * When is done, we send the XML String en parameter of the HTTP POST request.
   * When the server response us, we checked if the status code is correct or not.
   * If is not correct, we throw the good Exception from the status code recieve.
   */
  @Override
  public void createGame(Game g) throws RequesterUnauthorizedException,
      RequesterUnsupportedMediaTypeException {
     XmlSerializer serializer = Xml.newSerializer();
     StringWriter writer = new StringWriter();
     try {
          serializer.setOutput(writer);
          serializer.startDocument("UTF-8", true);
          serializer.startTag("", "goimerir");
          serializer.attribute("", "version", "1.0");
          serializer.startTag("", "create_board");
          
          serializer.startTag("", "name");
          serializer.attribute("", "value", ""+g.getId());
          serializer.endTag("", "name");
          
          serializer.startTag("", "creation_date");
          serializer.attribute("", "value", "");
          serializer.endTag("", "creation_date");
          
          serializer.startTag("", "owner");
          serializer.attribute("", "value", g.getOwner().getNick_name());
          serializer.endTag("", "owner");
          
          if(g.getInvitee()!=null){
            serializer.startTag("", "invitee");
            serializer.attribute("", "value", g.getInvitee().getNick_name());
            serializer.endTag("", "invitee");
          }
          
          serializer.startTag("", "status");
          switch(g.getStatus()){
          case OPEN:
            serializer.attribute("", "value", "OPEN");
            break;
          case CLOSED:
            serializer.attribute("", "value", "CLOSE");
            break;
          case FULL:
            serializer.attribute("", "value", "FULL");
            break;
          }
          serializer.endTag("", "status");
          
          serializer.startTag("", "size");
          serializer.attribute("", "value", g.getSize()[0]+"x"+g.getSize()[1]);
          serializer.endTag("", "size");
          
          serializer.startTag("", "owner_white");
          if(g.isOwnerWhite())
            serializer.attribute("", "value","true");
          else
            serializer.attribute("", "value","false");
          serializer.endTag("", "owner_white");
          
          serializer.endTag("", "create_board");
          serializer.endTag("", "goimerir");
          serializer.endDocument();
          
          HttpPost post = new HttpPost(baseURL+BOARDS);// /boards
          StringEntity se = new StringEntity(writer.toString(),HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
        post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
      StatusLine sl = response.getStatusLine();
      switch( sl.getStatusCode() ){
        case 401:
          throw new RequesterUnauthorizedException();
        case 415:
          throw new RequesterUnsupportedMediaTypeException();
      }    
      } catch (Exception e) {
          throw new RuntimeException(e);
      } 
  }
  /**
    * This method will done an HTTP GET Resquest, taking the list of Boards between the start and the end variable.
    * When the list of boards is returned from the server, if the header of the server is equals to the status code 200
    * then the function will extract the content message in our case it is an XML message and we will do an extraction from
   * the XML of the differents values that we need to returned.
   */
  @Override
  public ArrayList<Game> listGames(int start, int end, boolean last) {
    if(versionOk){
      ArrayList<Game> listGame = new ArrayList<Game>();
      httpClient = new DefaultHttpClient();
      HttpGet get=null;
      if(last)
        get = new HttpGet(baseURL+BOARDS+"?start="+start+"&end="+end+"&last=1");
      else
        get = new HttpGet(baseURL+BOARDS+"?start="+start+"&end="+end+"&last=0");
      HttpResponse response;
      try {
        response = httpClient.execute(get);
        StatusLine sl = response.getStatusLine();
        /*
         *  If the status code is correct we can take the content message
         */
        if(sl.getStatusCode()==200){
          HttpEntity entity= response.getEntity();
          BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
          String line;
          String responseContent="";
          while ((line = rd.readLine()) != null) {
            responseContent = responseContent+line;
          }
          rd.close();
          /*
           * Extraction of the differents informations from the XML
           */
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db;
          try {
            db = dbf.newDocumentBuilder();
            Document doc;
            try {
              doc = db.parse(new InputSource(new BufferedReader(new StringReader(responseContent))));
              doc.getDocumentElement().normalize();
              Node fc = doc.getFirstChild();
              if(fc.getNodeName().equals("goimerir")){
                NodeList nodeList= doc.getElementsByTagName("board");
                for (int i = 0; i < nodeList.getLength(); i++) {
                  Node node = nodeList.item(i);
                  Element elmnt = (Element) node;
                  if(elmnt.getAttribute("status").equals("FULL")){
                    try {
                      listGame.add( new Game(new Integer(elmnt.getAttribute("name")), new Date(elmnt.getAttribute("creation_date")), new Player("",elmnt.getAttribute("owner"),""), new Player("",elmnt.getAttribute("invitee"),""), GAME_STATUS.FULL, true, new Board() ));
                    } catch (NumberFormatException e2) {
                      return null;
                    } catch (GameNoRequesterSetException e2) {
                      return null;
                    }
                  }
                  else if(elmnt.getAttribute("status").equals("OPEN")){
                    try {
                      listGame.add( new Game(new Integer(elmnt.getAttribute("name")), new Date(elmnt.getAttribute("creation_date")), new Player("",elmnt.getAttribute("owner"),""), new Player("",elmnt.getAttribute("invitee"),""), GAME_STATUS.OPEN, true, new Board() ));
                    } catch (NumberFormatException e1) {
                      return null;
                    } catch (GameNoRequesterSetException e1) {
                      return null;
                    }
                  }
                  else{
                    try {
                      listGame.add( new Game(new Integer(elmnt.getAttribute("name")), new Date(elmnt.getAttribute("creation_date")), new Player("",elmnt.getAttribute("owner"),""), new Player("",elmnt.getAttribute("invitee"),""), GAME_STATUS.CLOSED, true, new Board() ));
                    } catch (NumberFormatException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    } catch (GameNoRequesterSetException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                  }
                  //elmnt.getAttribute("name")
                }
              }
            } catch (SAXException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }      
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
      
      return listGame;
    }else{return null;}
  }
  /**
   * This function is used to invite an user into a specific board.
   * This method will created the XML file and send it with an HTTP POST request
   * If the server return us an HTTP code ERROR then we handler it with the throw of differents exceptions.
   */
  @Override
  public void inviteUser(Game g) throws RequesterUnauthorizedException,
      RequesterNotFoundException, RequesterUnsupportedMediaTypeException {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
          serializer.setOutput(writer);
          serializer.startDocument("UTF-8", true);
          serializer.startTag("", "goimerir");
          serializer.attribute("", "version", "1.0");
          serializer.startTag("", "create_invite");
          
          serializer.startTag("", "board");
          serializer.attribute("", "name",""+g.getId());
          serializer.endTag("", "board");
          
          serializer.endTag("", "create_invite");
          serializer.endTag("", "goimerir");
          serializer.endDocument();
          
          HttpPost post = new HttpPost(baseURL+USERS+g.getOwner().getNick_name()+"/"+INVITES);// users/[user]/invites/
          StringEntity se = new StringEntity(writer.toString(),HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
        post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
      StatusLine sl = response.getStatusLine();
      /*
       * Check of the differents status codes
       */
      switch( sl.getStatusCode() ){
        case 401:
          throw new RequesterUnauthorizedException();
        case 404:
          throw new RequesterNotFoundException();
        case 415:
          throw new RequesterUnsupportedMediaTypeException();
      }    
      } catch (Exception e) {
          throw new RuntimeException(e);
      } 

  }
  /**
   * This function is used to allow an user to join a board.
   * This method will created the XML file and send it with an HTTP POST request
   * If the server return us an HTTP code ERROR then we handler it with the throw of differents exceptions.
   */
  @Override
  public void joinGame(Game g) throws RequesterUnauthorizedException,
      RequesterNotFoundException, RequesterUnsupportedMediaTypeException {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
          serializer.setOutput(writer);
          serializer.startDocument("UTF-8", true);
          serializer.startTag("", "goimerir");
          serializer.attribute("", "version", "1.0");
          serializer.startTag("", "create_board_request");
          
          serializer.startTag("", "sender");
          serializer.attribute("", "name", currentOwner.getNick_name());
          serializer.endTag("", "sender");
          
          serializer.endTag("", "create_board_request");
          serializer.endTag("", "goimerir");
          serializer.endDocument();
          
          HttpPost post = new HttpPost(baseURL+BOARDS+g.getId()+"/"+REQUESTS);
          StringEntity se = new StringEntity(writer.toString(),HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
        post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
      StatusLine sl = response.getStatusLine();
      /*
       * Check of the differents status codes
       */
      switch( sl.getStatusCode() ){
        case 401:
          throw new RequesterUnauthorizedException();
        case 404:
          throw new RequesterNotFoundException();
        case 415:
          throw new RequesterUnsupportedMediaTypeException();
      }    
      } catch (Exception e) {
          throw new RuntimeException(e);
      } 
  }
  /**
   * This method is used to delete an board on the server.
   * To proccess, we create an HTTP DELETE request with the board id and
   * send it on the server.
   * If the server return us an HTTP ERROR then we handler it with the status code and throw the exception for each of them.
   */
  @Override
  public void deleteGame(Game g) throws RequesterUnauthorizedException,
      RequesterForbiddenException, RequesterNotFoundException {
    if(versionOk){
      httpClient = new DefaultHttpClient();
      HttpDelete delete = new HttpDelete(baseURL+BOARDS+g.getId());
      HttpResponse response;
      try {
        response = httpClient.execute(delete);
        StatusLine sl = response.getStatusLine();
        /*
         * Check of the differents status codes
         */
        switch(sl.getStatusCode()){
          case 401:
            throw new RequesterUnauthorizedException();
          case 403:
            throw new RequesterForbiddenException();
          case 404:
            throw new RequesterNotFoundException();
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

  }
  /**
   * This method is used to take all the informations about a special game
   * To do that we send an HTTP GET request to the server and wait the response.
   * When the server response us , we check if the status code is good.
   * If the status code is good, we take the content message (XML DATA) and
   * extract all the information that we need to make a new Game object.
   * If the server return us an HTTP ERROR then we handler it with the status code and throw the exception for each of them.
   */
  @Override
  public Game retrieveGame(Game g) throws RequesterNotFoundException {
    if(versionOk){
      Game gr=null;
      httpClient = new DefaultHttpClient();
      HttpGet get = new HttpGet(baseURL+BOARDS);
      HttpResponse response;
      try {
        response = httpClient.execute(get);
        StatusLine sl = response.getStatusLine();
        if(sl.getStatusCode()==404)
          throw new RequesterNotFoundException();
        if(sl.getStatusCode()==200){
          HttpEntity entity= response.getEntity();
          BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
          String line;
          String responseContent="";
          while ((line = rd.readLine()) != null) {
            responseContent = responseContent+line;
          }
          rd.close();
          
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db;
          try {
            db = dbf.newDocumentBuilder();
            Document doc;
            try {
              doc = db.parse(new InputSource(new BufferedReader(new StringReader(responseContent))));
              doc.getDocumentElement().normalize();
              Node fc = doc.getFirstChild();
              if(fc.getNodeName().equals("goimerir")){
                NodeList nodeList= doc.getElementsByTagName("board");
                for (int i = 0; i < nodeList.getLength(); i++) {
                  Node node = nodeList.item(i);
                  Element elmnt = (Element) node;
                  Board b = new Board();
                  ArrayList<BoardMovement> listMove = new ArrayList<BoardMovement>();
                  NodeList nodeMoves= elmnt.getElementsByTagName("move");
                  for (int j = 0; j < nodeMoves.getLength(); j++) {
                    Node nodeMove = nodeMoves.item(j);
                    Element elmntMove = (Element) nodeMove;
                    listMove.add( new BoardMovement(new Integer(elmntMove.getAttribute("seq")), new Integer(elmntMove.getAttribute("row")), new Integer(elmntMove.getAttribute("column")))  );
                  }
                  try {
                    b.fillFromHistory(listMove);
                  } catch (BoardBadHistory e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                  }
                  NodeList nodeSize= elmnt.getElementsByTagName("size");
                  for (int j = 0; j < nodeSize.getLength(); j++) {
                    Node nodS= nodeSize.item(j);
                    Element elmntS = (Element) nodS;
                    if(elmntS.getAttribute("value").equals("9x9") ){
                      b.setWidth(9);
                      b.setHeight(9);
                    }
                    else if(elmntS.getAttribute("value").equals("13x13") ){
                      b.setWidth(13);
                      b.setHeight(13);
                    }
                    else if(elmntS.getAttribute("value").equals("19x19") ){
                      b.setWidth(19);
                      b.setHeight(19);
                    }  
                  }
                  Boolean owner = false;
                  NodeList nodeWhite= elmnt.getElementsByTagName("owner_white");
                  for (int j = 0; j < nodeWhite.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    if(elmntS.getAttribute("value").equals("true") )
                      owner=true;
                    else
                      owner=false;
                  }
                  
                  Player powner=null;
                  Player pinvitee=null;
                  Integer name=null;
                  GAME_STATUS gs = GAME_STATUS.CLOSED;
                  Date creation = null;
                  NodeList nodeOwner= elmnt.getElementsByTagName("owner");
                  for (int j = 0; j < nodeOwner.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    powner = new Player("",elmntS.getAttribute("value"),"");
                  }
                  NodeList nodeCreation= elmnt.getElementsByTagName("creation_date");
                  for (int j = 0; j < nodeCreation.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    creation = new Date(elmntS.getAttribute("value"));
                  }
                  NodeList nodeInvitee= elmnt.getElementsByTagName("invitee");
                  for (int j = 0; j < nodeInvitee.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    pinvitee = new Player("",elmntS.getAttribute("value"),"");
                  }
                  NodeList nodeStatus= elmnt.getElementsByTagName("status");
                  for (int j = 0; j < nodeStatus.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    if(elmntS.getAttribute("value").equals("FULL"))
                      gs = GAME_STATUS.FULL;
                    else if(elmntS.getAttribute("value").equals("OPEN"))
                      gs = GAME_STATUS.OPEN;
                    else
                      gs = GAME_STATUS.CLOSED;
                  }
                  NodeList nodeName= elmnt.getElementsByTagName("name");
                  for (int j = 0; j < nodeName.getLength(); j++) {
                    Node nodS= nodeWhite.item(j);
                    Element elmntS = (Element) nodS;
                    name = new Integer(elmntS.getAttribute("value"));
                  }
                  
                  try {
                      gr = new Game(name, creation, powner, pinvitee, gs, owner,b );
                    } catch (NumberFormatException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    } catch (GameNoRequesterSetException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                  //elmnt.getAttribute("name")
                }
              }
            } catch (SAXException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }      
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return gr;
    }else{return null;}
  }
  /**
   * This method take the game and the movement done by the player.
   * To do that, we created an XML with the movement and send it on the server
   * with an HTTP POST request.
   * If the server return us an HTTP ERROR then we handler it with the status code and throw the exception for each of them.
   */
  @Override
  public void playMove(Game g, BoardMovement b)
      throws RequesterUnauthorizedException, RequesterForbiddenException,
      RequesterNotFoundException {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
          serializer.setOutput(writer);
          serializer.startDocument("UTF-8", true);
          serializer.startTag("", "goimerir");
          serializer.attribute("", "version", "1.0");
          serializer.startTag("", "create_move");
          
          serializer.startTag("", "row");
          serializer.attribute("", "value", ""+b.getRow());
          serializer.endTag("", "row");
          
          serializer.startTag("", "column");
          serializer.attribute("", "value", ""+b.getColumn());
          serializer.endTag("", "column");
          
          serializer.endTag("", "create_move");
          serializer.endTag("", "goimerir");
          serializer.endDocument();
          HttpPost post = new HttpPost(baseURL+BOARDS+g.getId()+"/"+MOVES);// boards/[board]/moves/
          StringEntity se = new StringEntity(writer.toString(),HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
        post.setEntity(se);
      HttpResponse response = httpClient.execute(post);
      StatusLine sl = response.getStatusLine();
      /*
       * Check of the differents status codes
       */
      switch( sl.getStatusCode() ){
        case 401:
          throw new RequesterUnauthorizedException();
        case 403:
          throw new RequesterForbiddenException();
        case 404:
          throw new RequesterNotFoundException();
      }    
      } catch (Exception e) {
          throw new RuntimeException(e);
      } 

  }
  /**
    * This method will done an HTTP GET Resquest, taking the list of moves from a board between the start and the end variable.
    * When the list of moves is returned from the server, if the header of the server is equals to the status code 200
    * then the function will extract the content message in our case it is an XML message and we will do an extraction from
   * the XML of the differents values that we need to returned.
   * If the status code is 404 we need to call an exception and stop the function.
   */
  @Override
  public ArrayList<BoardMovement> moveHistory(Game g, int start, int end,
      boolean last) throws RequesterNotFoundException {
    if(versionOk){
      ArrayList<BoardMovement> listMove = new ArrayList<BoardMovement>();
      httpClient = new DefaultHttpClient();
      HttpGet get=null;
      if(last)
        get = new HttpGet(baseURL+BOARDS+g.getId()+"/"+MOVES+"?start="+start+"&end="+end+"&last=1");
      else
        get = new HttpGet(baseURL+BOARDS+g.getId()+"/"+MOVES+"?start="+start+"&end="+end+"&last=0");
      HttpResponse response;
      try {
        response = httpClient.execute(get);
        StatusLine sl = response.getStatusLine();
        if(sl.getStatusCode()==404)
          throw new RequesterNotFoundException();
        
        else if(sl.getStatusCode()==200){
          HttpEntity entity= response.getEntity();
          BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
          String line;
          String responseContent="";
          while ((line = rd.readLine()) != null) {
            responseContent = responseContent+line;
          }
          rd.close();
          
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db;
          try {
            db = dbf.newDocumentBuilder();
            Document doc;
            try {
              doc = db.parse(new InputSource(new BufferedReader(new StringReader(responseContent))));
              doc.getDocumentElement().normalize();
              Node fc = doc.getFirstChild();
              if(fc.getNodeName().equals("goimerir")){
                NodeList nodeList= doc.getElementsByTagName("moves");
                for (int i = 0; i < nodeList.getLength(); i++) {
                  Node node = nodeList.item(i);
                  Element elmnt = (Element) node;
                  Board b = new Board();
                  NodeList nodeMoves= elmnt.getElementsByTagName("move");
                  for (int j = 0; j < nodeMoves.getLength(); j++) {
                    Node nodeMove = nodeMoves.item(j);
                    Element elmntMove = (Element) nodeMove;
                    listMove.add( new BoardMovement(new Integer(elmntMove.getAttribute("seq")), new Integer(elmntMove.getAttribute("row")), new Integer(elmntMove.getAttribute("column")))  );
                  }
                }
              }
            } catch (SAXException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }      
        }
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return listMove;
    }else{return null;}
  }
  @Override
  public Player getOwner() {
    return currentOwner;
  }
  @Override
  public void setOwner(Player p) {
    currentOwner=p;
    
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.