Example #1
0
 @Override
 public void run() {
   if (isr != null && osw != null) {
     String body;
     try {
       body = readJson();
       System.out.println(body);
       JSONRPC2Request request = JSONRPC2Request.parse(body);
       JSONRPC2Response response = dispatcher.process(request, null);
       String res = response.toJSONString();
       System.out.println(res);
       sendResponse(res);
     } catch (NumberFormatException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (JSONRPC2ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       try {
         isr.close();
         osw.close();
         socket.close();
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
     }
   }
 }
 public StreamData getStream(UUID streamID) {
   // probably should do this over UDP.
   try {
     JSONRPC2Request jr = new JSONRPC2Request("getstream", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("streamid", streamID.toString());
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess()) {
       Map<String, Object> jo = (Map<String, Object>) jres.getResult();
       if ((Boolean) jo.get("present")) {
         StreamData sd = new StreamData();
         sd.currentLog = UUID.fromString((String) jo.get("currentlog"));
         sd.startPos = (Long) jo.get("startpos");
         sd.epoch = (Long) jo.get("epoch");
         sd.startLog = UUID.fromString((String) jo.get("startlog"));
         return sd;
       } else {
         return null;
       }
     }
   } catch (Exception e) {
     log.error("other error", e);
     return null;
   }
   return null;
 }
 public void resetAll() {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("reset", id.getAndIncrement());
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess() && (Boolean) jres.getResult()) {}
   } catch (Exception e) {
   }
 }
 /**
  * Force the configuration master to install a new view. This method should only be called during
  * testing.
  *
  * @param v The new view to install.
  */
 @Override
 public void forceNewView(CorfuDBView v) {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("newview", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("newview", v.getSerializedJSONView().toString());
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess() && (Boolean) jres.getResult()) {}
   } catch (Exception e) {
   }
 }
  public static String testJSONRequest(String server_URL_text, String method) {
    // Creating a new session to a JSON-RPC 2.0 web service at a specified URL

    Log.d("Debug serverURL", server_URL_text);

    // The JSON-RPC 2.0 server URL
    URL serverURL = null;

    try {
      serverURL = new URL("http://" + server_URL_text);
    } catch (MalformedURLException e) {
      // handle exception...
    }

    // Create new JSON-RPC 2.0 client session
    JSONRPC2Session mySession = new JSONRPC2Session(serverURL);

    // Once the client session object is created, you can use to send a series
    // of JSON-RPC 2.0 requests and notifications to it.

    // Sending an example "getTime" request:
    // Construct new request

    int requestID = 0;
    Log.d("debug serv", "bef call");
    JSONRPC2Request request = new JSONRPC2Request(method, requestID);
    Log.d("debug serv", "bef aft");

    // Send request
    JSONRPC2Response response = null;

    try {
      response = mySession.send(request);

    } catch (JSONRPC2SessionException e) {

      Log.e("error", e.getMessage().toString());
      // handle exception...
    }

    if (response != null) {
      // Print response result / error
      Log.d("runtime12", "res not null");
      if (response.indicatesSuccess()) Log.d("debug", response.getResult().toString());
      else Log.e("error", response.getError().getMessage().toString());

      return response.getResult().toString();
    } else {
      Log.d("main in bg", "in jsonrpc error");
      return " Error ";
    }
  }
  public boolean ping() {
    try {
      JSONRPC2Request jr = new JSONRPC2Request("ping", id.getAndIncrement());
      JSONRPC2Response jres = jsonSession.send(jr);
      if (jres.indicatesSuccess() && jres.getResult().equals("pong")) {
        return true;
      }
    } catch (Exception e) {
      return false;
    }

    return false;
  }
 public String getLog(UUID logID) {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("getlog", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("logid", logID.toString());
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess()) {
       return (String) jres.getResult();
     }
     return null;
   } catch (Exception e) {
     return null;
   }
 }
 /**
  * Request reconfiguration due to a network exception.
  *
  * @param e The network exception that caused the reconfiguration request.
  */
 @Override
 public void requestReconfiguration(NetworkException e) {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("reconfig", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     if (e != null) {
       params.put(
           "exception",
           java.util.Base64.getEncoder().encodeToString(Serializer.serialize_compressed(e)));
     }
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess() && (Boolean) jres.getResult()) {}
   } catch (Exception ex) {
   }
 }
 public boolean addLog(UUID logID, String path) {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("addlog", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("logid", logID.toString());
     params.put("path", path);
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess() && (Boolean) jres.getResult()) {
       return true;
     }
     return false;
   } catch (Exception e) {
     return false;
   }
 }
 @SuppressWarnings("unchecked")
 public Map<UUID, String> getAllLogs() {
   try {
     JSONRPC2Request jr = new JSONRPC2Request("getalllogs", id.getAndIncrement());
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess()) {
       Map<UUID, String> resultMap = new HashMap<UUID, String>();
       Map<String, String> iresultMap = (Map<String, String>) jres.getResult();
       for (String s : iresultMap.keySet()) {
         resultMap.put(UUID.fromString(s), iresultMap.get(s));
       }
       return resultMap;
     }
     return null;
   } catch (Exception e) {
     return null;
   }
 }
  public boolean addStreamCM(UUID logID, UUID streamID, long pos, boolean nopass) {
    try {
      JSONRPC2Request jr = new JSONRPC2Request("addstream", id.getAndIncrement());
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("logid", logID.toString());
      params.put("streamid", streamID.toString());
      params.put("startpos", pos);
      params.put("nopass", nopass);

      jr.setNamedParams(params);
      JSONRPC2Response jres = jsonSession.send(jr);
      if (jres.indicatesSuccess() && (Boolean) jres.getResult()) {
        return true;
      }
      return false;
    } catch (Exception e) {
      log.debug("Error sending addstream", e);
      return false;
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // declare rpc objects
    JSONRPC2Request req = null;
    JSONRPC2Response resp = null;

    try {
      /*
       * Had to change this, since after switching to the JS json-rpc lib
       * the request has no params ("json=" in our case) and the whole payload is the request data itself
       */
      StringBuffer jb = new StringBuffer();
      String line = null;
      // Getting the request reader in order to load the whole request date into a single string
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) jb.append(line);

      // populate rpc objects
      req = JSONRPC2Request.parse(jb.toString());
      resp = new JSONRPC2Response(req.getID());

      // define jsonResult
      JSONObject jsonResult = new JSONObject();

      // retrieve request information
      String method = req.getMethod();
      System.out.println(req.getMethod());

      // find the requested method
      if (method.equals("login")) {
        // login user
        jsonResult = loginUser(request, response, req);
        System.out.println("json result: " + jsonResult.toString());
        // resp.setResult(jsonResult.toJSONString());
        resp.setResult(jsonResult);
      } else if (method.equals("register")) {
        // register user
        // TODO duplicates!
        jsonResult = registerUser(req, resp);
        System.out.println("json result to string: " + jsonResult.toString());
        resp.setResult(jsonResult);
      } else if (isLoggedIn(request)) {
        if (method.equals("logout")) {
          // logout user
          jsonResult = logoutUser(request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("loadAllQuestions")) {
          // return all questions as QuestionsList
          QuestionsList questions = QuestionController.loadAllQuestions();
          if (questions != null) {
            JSONObject jsonQuestions = new JSONObject();
            JSONArray allQuestions = questions.toJSONArray();
            jsonQuestions.put("allQuestions", allQuestions);
            System.out.println("jsonQuestions: " + jsonQuestions.toString());
            resp.setResult(jsonQuestions);
          } else {
            resp.setError(JSONRPC2Error.INTERNAL_ERROR);
          }
        } else if (method.equals("loadQuestion")) {
          jsonResult = loadQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("addQuestion")) {
          // add question
          jsonResult = addQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("deleteQuestion")) {
          // delete question
          jsonResult = deleteQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("udpateQuestion")) {
          // update question
          jsonResult = updateQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("loadTestAndAllQuestions")) {
          // return the test and all questions from the database
          jsonResult = loadTestAndAllQuestions(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("loadAllTests")) {
          // return all questions as QuestionsList
          TestsList tests = TestController.loadAllTests();
          if (tests != null) {
            JSONObject jsonTests = new JSONObject();
            JSONArray allTests = tests.toJSONArray();
            jsonTests.put("allTests", allTests);
            System.out.println("jsonTests: " + jsonTests.toString());
            resp.setResult(jsonTests);

          } else {
            resp.setError(JSONRPC2Error.INTERNAL_ERROR);
          }
        } else if (method.equals("loadQuestionsByTest")) {
          JSONArray testQuestions = new JSONArray();
          testQuestions = loadQuestionsByTest(req, request);
          jsonResult.put("testQuestions", testQuestions);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("addTest")) {
          // add question
          jsonResult = addTest(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("deleteTest")) {
          // delete question
          jsonResult = deleteTest(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("updateTest")) {
          // update question
          jsonResult = updateTest(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("addTestQuestion")) {
          // bind question to test
          jsonResult = addTestQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("removeTestQuestion")) {
          // delete question from test
          jsonResult = removeTestQuestion(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        } else if (method.equals("checkTest")) {
          // check if test is asnwered correctly
          jsonResult = checkTest(req, request);
          System.out.println("json result: " + jsonResult.toString());
          resp.setResult(jsonResult);
        }
        /*
        JSONObject json = new JSONObject();
        json.put("hi", "opa");
        resp.setResult(json.toJSONString());
        */
      }
    } catch (Throwable t) {
      JSONRPC2Error error = new JSONRPC2Error(1, t.getMessage());

      resp.setError(error);
    } finally {
      // dispatch result
      response.getWriter().print(resp.toJSONObject().toJSONString());
      System.out.println("final result: " + resp.toJSONObject().toJSONString());
    }
  }