/**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    try {
      SubjectDAO subdao = new SubjectDAO();
      DatastreamDAO dstreamDao = new DatastreamDAO();
      List<JsonSubject> jsubList = new ArrayList<JsonSubject>();
      List<Subject> subList = new ArrayList<Subject>();
      String loginID = "leoncool";
      if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) {
        loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid);
      }
      UserDAO userDao = new UserDAO();
      if (!userDao.existLogin(loginID)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null);
        return;
      }
      if (request.getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects) != null
          && request
              .getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects)
              .equalsIgnoreCase(AllConstants.api_entryPoints.request_api_true)) {
        subList = subdao.findOnlyParentSubjectsByLoginID(loginID);
      } else {
        subList = subdao.findSubjectsByLoginID(loginID);
      }
      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      for (Subject sub : subList) {
        if (sub.getVisibleSet() != null
            && sub.getVisibleSet().equalsIgnoreCase(AllConstants.ProgramConts.visibleSet_PUBLIC)) {
          jsubList.add(dbtoJUtil.convert_a_Subject(sub));
        }
      }
      System.out.println(jsubList.size());
      Gson gson = new Gson();
      JsonElement je = gson.toJsonTree(jsubList);
      JsonObject jo = new JsonObject();
      jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
      jo.add("subject_list", je);
      JsonWriter jwriter = new JsonWriter(response.getWriter());
      //            if (request.getParameter("callback") != null) {
      //                System.out.println("using callback");
      //                out.print(request.getParameter("callback")+"("+ gson.toJson(jo) + ");");
      //            } else {
      //                gson.toJson(jo, jwriter);
      //                jwriter.close();
      //            }
      gson.toJson(jo, jwriter);
      jwriter.close();

    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      out.close();
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    try {
      JsonUtil jutil = new JsonUtil();
      String input = jutil.readJsonStrFromHttpRequest(request);
      System.out.println("input:" + input);
      JsonUserToken jsonUserToken = null;
      Gson gson = new Gson();
      try {
        jsonUserToken = gson.fromJson(input, JsonUserToken.class);
        if (jsonUserToken == null) {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null);
          return;
        }
      } catch (Exception ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null);
        return;
      }
      UserDAO userdao = new UserDAO();
      String username = null;
      String password = null;
      username = jsonUserToken.getLoginid();
      password = jsonUserToken.getPassword();
      if (username == null || username.length() < 1) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_Login_format, null, null);
        return;
      }
      if (password == null || password.length() < 1) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_password_format, null, null);
        return;
      }
      Users user = userdao.getLogin(username);
      if (user == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_LoginID, null, null);
        return;
      }
      if (!user.getPassword().equalsIgnoreCase(password)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_wrong_password, null, null);
        return;
      }
      Date expireTime = null;
      if (jsonUserToken.getExpire_in_seconds() != null
          && jsonUserToken.getExpire_in_seconds().length() > 1) {
        try {
          long expireInSeconds = Long.parseLong(jsonUserToken.getExpire_in_seconds());
          if (expireInSeconds > 1) {
            Date now = new Date();
            long expireLong = now.getTime() + 1000L * expireInSeconds;
            expireTime = new Date();
            expireTime.setTime(expireLong);
          }

        } catch (Exception ex) {
          ex.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_date_format, null, null);
          return;
        }
      }
      String ipAddress = request.getRemoteAddr();
      LoginToken token = userdao.requestNewLoginToken(username, ipAddress, expireTime);
      jsonUserToken.setPassword(null);
      jsonUserToken.setToken(token.getTokenID());

      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      //           dbtoJUtil.convert_a_Subject(null)
      UserDAO userDao = new UserDAO();
      UserInfo userinfo = userDao.getUserInfo(user.getLoginID());
      if (userinfo == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_LoginID, null, null);
        return;
      }
      FollowingDAO followingDao = new FollowingDAO();
      List<Follower> follwerList = followingDao.getFollowers(user.getLoginID());
      List<Follower> follweringList = followingDao.getFollowerings(user.getLoginID());
      Map<String, String> followerMap = null;
      Map<String, String> followeringsMap = null;

      JsonUserInfo juserinfo = dbtoJUtil.convert_a_userinfo(userinfo, followerMap, followeringsMap);
      juserinfo.setTotal_followers(Integer.toString(follwerList.size()));
      juserinfo.setTotal_followings(Integer.toString(follweringList.size()));
      JsonElement je = gson.toJsonTree(juserinfo);
      JsonObject jo = new JsonObject();

      JsonElement je_usertoken = gson.toJsonTree(jsonUserToken);
      jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
      jo.add("usertoken", je_usertoken);
      jo.add("userinfo", je);
      JsonWriter jwriter = new JsonWriter(response.getWriter());
      gson.toJson(jo, jwriter);

    } catch (Exception ex) {
      ex.printStackTrace();
      ReturnParser.outputErrorException(
          response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
      return;
    } finally {
      out.close();
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    //        PrintWriter out = response.getWriter();
    OutputStream outStream = null;
    try {

      long start = 0;
      long end = 0;
      String blockid = null;
      try {
        if (request.getParameter(AllConstants.api_entryPoints.request_api_start) != null) {
          start =
              Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_start));
        }
        if (request.getParameter(AllConstants.api_entryPoints.request_api_end) != null) {
          end = Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_end));
        }
        if (request.getParameter(AllConstants.api_entryPoints.request_api_blockid) != null) {
          blockid = request.getParameter(AllConstants.api_entryPoints.request_api_blockid);
          if (blockid.length() < 5) {}
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      String loginID = "leoncool";
      if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) {
        loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid);
      }
      UserDAO userDao = new UserDAO();
      if (!userDao.existLogin(loginID)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null);
        return;
      }
      SubjectDAO subjDao = new SubjectDAO();
      Subject subject = (Subject) subjDao.findHealthSubject(loginID); // Retreive
      if (subject == null) {
        ReturnParser.outputErrorException(
            response,
            AllConstants.ErrorDictionary.SYSTEM_ERROR_NO_DEFAULT_HEALTH_SUBJECT,
            null,
            null);
        return;
      }
      String streamID = ServerUtil.getHealthStreamID(ServletPath(request));

      DatastreamDAO dstreamDao = new DatastreamDAO();
      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      Datastream datastream = dstreamDao.getDatastream(streamID, true, false);
      if (blockid != null && dstreamDao.getDatastreamBlock(blockid) == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Invalid_Datablock_ID, null, blockid);
        return;
      }
      if (datastream == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unknown_StreamID, null, streamID);
        return;
      }
      HashMap<String, String> mapUnits = new HashMap<String, String>();
      HashMap<String, String> allUnits = new HashMap<String, String>();
      if (request.getParameter(AllConstants.api_entryPoints.request_api_unit_id) != null
          && request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).length() > 0) {
        String[] unitids =
            request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).split(",");
        System.out.println("unitids:size:" + unitids.length);
        allUnits = dbtoJUtil.ToDatastreamUnitsMap(datastream);
        System.out.println("units size:" + datastream.getDatastreamUnitsList().size());
        for (String id : unitids) {
          if (id.length() < 3) {
            // error
            return;
          } else {
            if (allUnits.get(id) == null) {
              // error
              System.out.println("cannot find id" + id + "");
              return;
            } else {
              mapUnits.put(id, id);
            }
          }
        }
      }
      System.out.println("mapUnits.size():" + mapUnits.size() + ", " + mapUnits);
      Gson gson = new Gson();
      int debug = 1;
      if (debug == 1) {
        System.out.println("debuging.....going to hbase");
        HBaseDatapointDAO diDao = new HBaseDatapointDAO();
        System.out.println("datastreamID:" + datastream.getStreamId());
        HBaseDataImport hbaseexport = null;
        try {
          hbaseexport = diDao.exportDatapoints(streamID, start, end, blockid, mapUnits, null, null);
        } catch (ErrorCodeException ex) {
          ex.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
          return;
        } catch (Throwable ex) {
          ex.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
          return;
        }
        if (hbaseexport != null) {
          hbaseexport.setUnits_list(
              dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list());
        } else {
          hbaseexport = new HBaseDataImport();
          hbaseexport.setBlock_id(blockid);
          hbaseexport.setData_points(new ArrayList<JsonDataPoints>());

          hbaseexport.setDatastream_id(streamID);
          hbaseexport.setUnits_list(
              dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list());
          //                    hbaseexport.setDeviceid(streamID);
        }
        outStream = null;
        boolean iftoZip = true;
        String encodings = request.getHeader("Accept-Encoding");
        if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) {
          // Go with GZIP
          response.setHeader("Content-Encoding", "gzip");
          outStream = new GZIPOutputStream(response.getOutputStream());
        } else {
          outStream = response.getOutputStream();
        }
        response.setHeader("Vary", "Accept-Encoding");
        Date timerStart = new Date();
        JsonElement je = gson.toJsonTree(hbaseexport);
        JsonObject jo = new JsonObject();
        jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
        jo.add("datapoints_list", je);
        OutputStreamWriter osWriter = new OutputStreamWriter(outStream);
        JsonWriter jwriter = new JsonWriter(osWriter);
        String callbackStr = null;
        if (request.getParameter(AllConstants.api_entryPoints.requset_api_callback) != null) {
          callbackStr = request.getParameter(AllConstants.api_entryPoints.requset_api_callback);
          osWriter.append(callbackStr + "(");
        }
        gson.toJson(jo, jwriter);
        if (callbackStr != null) {
          osWriter.append(");");
        }
        jwriter.close();
        Date timerEnd = new Date();
        System.out.println(
            "Json Time takes:"
                + (timerEnd.getTime() - timerStart.getTime()) / (1000.00)
                + "seconds");
        osWriter.close();
        outStream.close();
      } else {
        String encodings = request.getHeader("Accept-Encoding");
        boolean iftoZip = true;
        if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) {
          // Go with GZIP
          response.setHeader("Content-Encoding", "gzip");
          outStream = new GZIPOutputStream(response.getOutputStream());
        } else {
          outStream = response.getOutputStream();
        }
        response.setHeader("Vary", "Accept-Encoding");
        File inputFile = new File("E:/IC_Dropbox/Dropbox/java/healthbook/sample_data/download.txt");
        //                File inputFile = new
        // File("F:/Dropbox/Dropbox/java/healthbook/sample_data/download.txt");
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
          outStream.write(inputLine.getBytes());
          //  out.print(inputLine);
        }
        outStream.close();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      ReturnParser.outputErrorException(
          response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
      return;
    } finally {
      System.out.println("running finally");
      //            out.close();
      if (outStream != null) {
        outStream.close();
      }
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader(
        "Access-Control-Allow-Headers", MarketplaceContants.ACCESS_CONTROL_ALLOW_HEADERS);
    response.setHeader(
        "Access-Control-Allow-Methods", MarketplaceContants.ACCESS_CONTROL_ALLOW_METHODS);
    response.setHeader(
        "Access-Control-Expose-Headers", MarketplaceContants.ACCESS_CONTROL_ALLOW_HEADERS);
    PrintWriter out = response.getWriter();

    try {
      Users accessUser = null;
      PermissionFilter filter = new PermissionFilter();
      String loginID = filter.checkAndGetLoginFromToken(request, response);

      UserDAO userDao = new UserDAO();
      if (loginID == null) {
        if (filter.getCheckResult().equalsIgnoreCase(filter.INVALID_LOGIN_TOKEN_ID)) {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_login_token_id, null, null);
          return;
        } else if (filter
            .getCheckResult()
            .equalsIgnoreCase(AllConstants.ErrorDictionary.login_token_expired)) {
          return;
        } else {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_login_token_id, null, null);
          return;
        }
      } else {
        accessUser = userDao.getLogin(loginID);
      }
      String targetLoginID = filter.getTargetUserID(request, response);
      if (targetLoginID != null) {
        Users targetUser = userDao.getLogin(targetLoginID);
        if (targetUser == null) {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_Target_LoginID, null, null);
          return;
        }
      }
      if (targetLoginID == null) {
        targetLoginID = loginID;
      }

      Gson gson = new Gson();

      int marketID = 0;
      if (request.getParameter(MarketplaceContants.RequestParameters.marketID) == null) {
        ReturnParser.outputErrorException(
            response,
            AllConstants.ErrorDictionary.MISSING_DATA,
            null,
            MarketplaceContants.RequestParameters.marketID);
        return;
      }
      try {
        marketID =
            Integer.parseInt(request.getParameter(MarketplaceContants.RequestParameters.marketID));
      } catch (Exception ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response,
            AllConstants.ErrorDictionary.Invalid_data_format,
            null,
            MarketplaceContants.RequestParameters.marketID);
        return;
      }

      DataMarketDAO dmDao = new DataMarketDAO();
      DataMarket dm = dmDao.getDataMarketByID(marketID);

      if (dmDao.existDataSharingItem(loginID, dm.getDatastream().getStreamId())) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.data_sharing_item_exist, null, null);
        return;
      }

      DataSharing ds = new DataSharing();
      ds.setLoginID(loginID);
      ds.setTargetLoginID(dm.getDatastream().getOwner());
      ds.setStreamID(dm.getDatastream());
      ds.setCreatedTime(new Date());
      ds = dmDao.addDataSharing(ds);
      JsonObject jo = new JsonObject();
      jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
      // solve gson error with mulitple level reference
      ds.setStreamID(null);
      JsonElement jelement = gson.toJsonTree(ds);
      jo.add("data_sharing", jelement);
      System.out.println(gson.toJson(jo));
      out.println(gson.toJson(jo));

    } catch (Exception ex) {
      ex.printStackTrace();
      ReturnParser.outputErrorException(
          response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
      return;
    } finally {
      out.close();
    }
  }
  public void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    System.out.println("before checkAndGetLoginFromToken");
    PrintWriter out = response.getWriter();
    try {

      Users accessUser = null;
      PermissionFilter filter = new PermissionFilter();
      String loginID = filter.checkAndGetLoginFromToken(request, response);

      UserDAO userDao = new UserDAO();
      if (loginID == null) {
        if (filter.getCheckResult().equalsIgnoreCase(filter.INVALID_LOGIN_TOKEN_ID)) {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_login_token_id, null, null);
          return;
        } else if (filter
            .getCheckResult()
            .equalsIgnoreCase(AllConstants.ErrorDictionary.login_token_expired)) {
          return;
        } else {
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Invalid_login_token_id, null, null);
          return;
        }
      } else {
        accessUser = userDao.getLogin(loginID);
      }
      SubjectDAO subjDao = new SubjectDAO();
      Subject subject = (Subject) subjDao.findHealthSubject(loginID); // Retreive
      if (subject == null) {
        try {
          subject = subjDao.createDefaultHealthSubject(loginID);
          HealthDataStreamDAO hdsDao = new HealthDataStreamDAO();

          hdsDao.createDefaultDatastreamsOnDefaultSubject(loginID, subject.getId());
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          ReturnParser.outputErrorException(
              response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
        }
      }

      String streamTitle = ServerUtil.getHealthStreamTitle(ServletPath(request));
      streamTitle = "ecg" + nextValue();
      System.out.println("Post Benchmark Data Points Title- " + streamTitle);
      DatastreamDAO dstreamDao = new DatastreamDAO();
      DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil();
      Datastream datastream = null;
      try {
        datastream =
            dstreamDao.getHealthDatastreamByTitle(subject.getId(), streamTitle, true, false);
      } catch (NonUniqueResultException ex) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Internal_Fault, null, streamTitle);
        return;
      }
      if (datastream == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unknown_StreamTitle, null, streamTitle);
        return;
      }
      if (!datastream.getOwner().equalsIgnoreCase(loginID)) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Unauthorized_Access, null, streamTitle);
        return;
      }

      JsonUtil jutil = new JsonUtil();
      Gson gson = new Gson();
      JsonDataImport jdataImport = null;
      int jsonInputTotalByte = 0;
      try {
        String jsonInput = jutil.readJsonStrFromHttpRequest(request);
        jsonInputTotalByte = jsonInput.length();
        jdataImport = gson.fromJson(jsonInput, JsonDataImport.class);
      } catch (JsonSyntaxException ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null);
        return;
      } catch (IOException ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null);
        return;
      }

      List<DatastreamUnits> unitList = datastream.getDatastreamUnitsList();
      HashMap<String, String> unitIDList = new HashMap<String, String>();
      for (DatastreamUnits unit : unitList) {
        if (unit.getShortUnitID() != null && unit.getShortUnitID().length() > 1) {
          unitIDList.put(unit.getShortUnitID(), unit.getShortUnitID());
        } else {
          unitIDList.put(unit.getUnitID(), unit.getUnitID()); // retrieve
        } // all
        // existing
        // units
      }

      if (jdataImport == null) {
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null);
        return;
      }
      if (jdataImport.getBlock_id() != null) {
        DatastreamBlocks block = dstreamDao.getDatastreamBlock(jdataImport.getBlock_id());
        if (block == null) {
          ReturnParser.outputErrorException(
              response,
              AllConstants.ErrorDictionary.Invalid_Datablock_ID,
              jdataImport.getBlock_id(),
              jdataImport.getBlock_id());
          return;
        } else {
          if (!block.getStreamID().getStreamId().equalsIgnoreCase(datastream.getStreamId())) {
            ReturnParser.outputErrorException(
                response,
                AllConstants.ErrorDictionary.Invalid_Datablock_ID_for_such_stream,
                jdataImport.getBlock_id(),
                jdataImport.getBlock_id());
            return;
          }
        }
      }

      HBaseDatapointDAO importDao = null;
      try {
        importDao = new HBaseDatapointDAO();
      } catch (Exception ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
        return;
      }

      HBaseDataImport importData = new HBaseDataImport();

      if (jdataImport.getData_points_single_list() != null
          && jdataImport.getData_points_single_list().size() > 0) {
        System.out.println("--------------dealing with single data point list--------");
        if (unitIDList.size() == 0) {
          ReturnParser.outputErrorException(
              response,
              AllConstants.ErrorDictionary.Unknown_StreamID,
              null,
              datastream.getStreamId());
          return;
        }
        if (unitIDList.size() > 1) {
          ReturnParser.outputErrorException(
              response,
              AllConstants.ErrorDictionary.MORE_THAN_ONE_DATASTREAM_UNIT,
              null,
              datastream.getStreamId());
          return;
        }
        if (jdataImport.getData_points_single_list().size() < 1) {
          ReturnParser.outputErrorException(
              response,
              AllConstants.ErrorDictionary.No_Input_Single_Datapoints,
              null,
              datastream.getStreamId());
          return;
        }
        String singleUnitID = datastream.getDatastreamUnitsList().get(0).getShortUnitID();
        if (singleUnitID == null || singleUnitID.length() < 3) {
          singleUnitID = datastream.getDatastreamUnitsList().get(0).getUnitID();
        }
        importData.setSingle_Unit_ID(singleUnitID);
        importData.setData_points_single_list(jdataImport.getData_points_single_list());
        importData.setDatastream_id(datastream.getStreamId());
        importData.setBlock_id(jdataImport.getBlock_id());
      } else {
        System.out.println("--------------dealing with normal data point list--------");
        if (jdataImport.getData_points() == null || jdataImport.getData_points().size() < 1) {
          ReturnParser.outputErrorException(
              response,
              AllConstants.ErrorDictionary.No_Input_Datapoints,
              null,
              datastream.getStreamId());
          return;
        }
        importData.setDatastream(dbtoJUtil.convertDatastream(datastream, null));
        importData.setData_points(jdataImport.getData_points());
        importData.setDatastream_id(datastream.getStreamId());
        importData.setBlock_id(jdataImport.getBlock_id());
      }

      JsonDataPointsPostResult jsonResult = new JsonDataPointsPostResult();
      try {
        int totalStoredByte = importDao.importDatapointsDatapoints(importData); // submit data
        jsonResult.setTotal_stored_byte(totalStoredByte);

      } catch (ErrorCodeException ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(response, ex.getErrorCode(), null, null);
        return;
      } catch (NumberFormatException ex) {
        ex.printStackTrace();
        ReturnParser.outputErrorException(
            response, AllConstants.ErrorDictionary.INPUT_DATE_FORMAT_ERROR, null, null);
        return;
      }
      int totalInputSize = 0;
      if (jdataImport.getData_points() != null) {
        totalInputSize = jdataImport.getData_points().size();
      } else if (jdataImport.getData_points_single_list() != null) {
        totalInputSize = jdataImport.getData_points_single_list().size();
      }
      jsonResult.setTotal_points(totalInputSize);
      jsonResult.setTotal_input_byte(jsonInputTotalByte);
      JsonElement je = gson.toJsonTree(jsonResult);
      JsonObject jo = new JsonObject();
      jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed);
      jo.add("data_import_stat", je);
      JsonWriter jwriter = new JsonWriter(out);
      gson.toJson(jo, jwriter);
    } catch (Exception ex) {
      ex.printStackTrace();
      ReturnParser.outputErrorException(
          response, AllConstants.ErrorDictionary.Internal_Fault, null, null);
      return;

    } finally {
      out.close();
    }
  }