private void waitForAutorization() {
    try {
      is = sock.getInputStream();
      os = sock.getOutputStream();

      Queue<JSONObject> receiveData = new LinkedList<JSONObject>();
      InputStream is = sock.getInputStream();

      NetParser parser = new NetParser(is, receiveData);
      while (receiveData.isEmpty()) {
        parser.goParse();
      }
      JSONObject data = receiveData.remove();
      String action = (String) data.get("action");
      if (!action.isEmpty()) {
        if (action.equals("login")) {
          JSONObject tmp = (JSONObject) data.get("content");
          String email = (String) tmp.get("email");
          String password = (String) tmp.get("md5_password");
          isLogged = true;
          LogException.saveToLog("client loginned as " + email, "main server");
        }
      } else {
        // TODO: add error json processing
        throw new ParseException("Incorrect message", 0);
      }

    } catch (IOException e) {
      LogException.saveToLog(e.getMessage(), e.getStackTrace().toString());
    } catch (ParseException e) {
      LogException.saveToLog(e.getMessage(), e.getStackTrace().toString());
    }
  }
  /**
   * Searches the db using input and returns xml of the resulting list. Each result has channel
   * name, programId, startTime, endTime, title and a short description.
   *
   * @param channel_name name for channel (mapped)
   * @param fromInput date
   * @param toInput date
   * @param title titel
   * @param description Kortomtale, langomtale1 eller langomtale2.
   * @return xml containing a list of results.
   */
  @GET
  @Path("search")
  @Produces(MediaType.APPLICATION_XML)
  public List<ReducedRitzauProgram> search(
      @QueryParam("channelName") String channel_name,
      @QueryParam("from") String fromInput,
      @QueryParam("to") String toInput,
      @QueryParam("title") String title,
      @QueryParam("description") String description) {
    Date from = null;
    Date to = null;
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm");
    if (fromInput != null && fromInput.trim().length() > 0) {
      try {
        from = format.parse(fromInput);
      } catch (ParseException ex) {
        log.debug("Date parse error: From: " + fromInput);
        log.debug("Date parse error stacktrace: " + ex.getStackTrace());
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        result +=
            "<error code=\"400\">Bad Request: From could not be parsed. Use following format: yyyy-MM-dd_HH:mm</error>";
        throw new WebApplicationException(Response.status(400).entity(result).build());
      }
    }
    if (toInput != null && toInput.trim().length() > 0) {
      try {
        to = format.parse(toInput);
      } catch (ParseException ex) {
        log.debug("Date parse error: To: " + toInput);
        log.debug("Date parse error stacktrace: " + ex.getStackTrace());
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        result +=
            "<error code=\"400\">Bad Request: To could not be parsed. Use following format: yyyy-MM-dd_HH:mm</error>";
        throw new WebApplicationException(Response.status(400).entity(result).build());
      }
    }
    if (from != null && to != null) {
      if (from.compareTo(to) > 0) {
        String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        result += "<error code=\"400\">Bad Request: From is not before To.</error>";
        throw new WebApplicationException(Response.status(400).entity(result).build());
      }
    }

    return service.search(channel_name, from, to, title, description);
  }
  /** 案件推送的核心处理.从案件表中查询出所有数据,逐条推送到案件主题 */
  @Override
  protected void push() {
    List<Case> lstCase = caseMapper.findAll();
    for (int i = 0; i < lstCase.size(); i++) {

      if (this.flagStop) break;
      long nextWaitingTime = 5000;

      try {
        Case case1 = lstCase.get(i);
        Case case2 = lstCase.get(i + 1);
        nextWaitingTime =
            DateManager.getTimePlusInMilliseconds(
                    case1.getBjsj(), case2.getBjsj(), "yyyy-MM-dd HH:mm:ss")
                / pushSpeed;
      } catch (ParseException e2) {
        e2.printStackTrace();
        System.out.println(e2.getStackTrace());
      } catch (Exception e3) {
        // e3.printStackTrace();
      }

      if (nextWaitingTime > 30000) nextWaitingTime = 30000;
      System.out.println("下一次案件推送将在 " + nextWaitingTime / 1000 + "秒后");

      try {
        Case case110 = lstCase.get(i);
        try {
          Bjlxdm bjlxdm = bjlxdmMapper.getBjlxdmByDm(case110.getBjlx().substring(11));

          if (bjlxdm != null) {
            case110.setBjlxmc(bjlxdm.getBjlxmc());
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
        String strJson = JovianJsonUtil.convertBean2Json(case110);
        service.sendMessage(destination, strJson);
      } catch (JsonConvertException e1) {
        e1.printStackTrace();
      }

      try {
        Thread.sleep(nextWaitingTime);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * 转换字符串为时间格式;
   *
   * @param dateStr 时间字符串;
   * @param dateFormat 日期字符串格式化的类型 1为"yyyy-MM-dd"格式 2为"yyyy-MM-dd hh:mm:ss"格式,3为yyyy/MM/dd格式
   * @return 返回为 格式化后的java.util.date;
   */
  public static java.util.Date dateConvert(String dateStr, int dateFormat) {

    if (null == dateStr || dateStr.trim().equals("")) {
      return null;
    }
    SimpleDateFormat dateFormatType = null;
    if (1 == dateFormat) {
      dateFormatType = new SimpleDateFormat("yyyy-MM-dd");
    } else if (2 == dateFormat) {
      dateFormatType = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    } else if (3 == dateFormat) {
      dateFormatType = new SimpleDateFormat("yyyy/MM/dd");
    }
    try {
      return dateFormatType.parse(dateStr);
    } catch (ParseException e) {
      try {
        // 当转换为2时,当日期字符串为yyyy-MM-dd,而不为yyyy-MM-dd hh:mm:ss 时,
        // 也会出现ParseException 异常,但我们大多时,是使用yyyy-MM-dd格式的date类
        // 因此为了方便在下面,试着转换为yyyy-MM-dd的date类的实例
        dateFormatType = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormatType.parse(dateStr);
      } catch (ParseException e1) {
        StackTraceElement trace[] = e1.getStackTrace();
        //                System.out.println(trace[0].getClass() + "."
        //                        + trace[0].getMethodName() + "方法中的第 "
        //                        + trace[0].getLineNumber() + " 行出现" + e1);
        return null;
      }
    } catch (Exception e) {
      StackTraceElement trace[] = e.getStackTrace();
      //            System.out.println(trace[0].getClass() + "."
      //                    + trace[0].getMethodName() + "方法中的第 "
      //                    + trace[0].getLineNumber() + " 行出现" + e);
      return null;
    }
  }
 /**
  * Finds and uploads interval on a channel, based on channel and interval, to the FtpServer as a
  * file with requested filename. Sends back a response with a status code based on whether or not
  * it was successful. Status codes: 200: OK. 400: Bad information in url. 404: Content not
  * available in main archive. Try again later. 409: A file with chosen filename already exists on
  * FtpServer. 410: Content not available. 500: Internal server error or unexpected status code.
  *
  * @param channel Which channel
  * @param filename Wanted filename
  * @param fromRaw from when, format: yyyy-MM-dd_HH:mm:ss
  * @param toRaw to when, format: yyyy-MM-dd_HH:mm:ss
  * @return Status code in Response and requested file on FtpServer.
  */
 @GET
 @Path("rawCut")
 @Produces("text/plain")
 public Response rawCut(
     @QueryParam("channel") String channel,
     @QueryParam("filename") String filename,
     @QueryParam("from") String fromRaw,
     @QueryParam("to") String toRaw) {
   if (channel == null
       || channel.trim().length() == 0
       || filename == null
       || filename.trim().length() == 0) {
     String text = "Bad information in url. Make sure to set channel, filename, from and to.";
     log.info("-----------rawCut first opportunity exit with 400---------------");
     return Response.status(400).entity(text).build();
   }
   Date from = null;
   Date to = null;
   if (fromRaw != null
       && fromRaw.trim().length() > 0
       && toRaw != null
       && toRaw.trim().length() > 0) {
     DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
     try {
       from = format.parse(fromRaw);
       to = format.parse(toRaw);
     } catch (ParseException ex) {
       log.debug("Date parse error: From: " + fromRaw + " | To: " + toRaw);
       log.debug("Date parse error stacktrace: " + ex.getStackTrace());
       String text =
           "Failed to parse dates, make sure it is of following format: yyyy-MM-dd_HH:mm:ss";
       return Response.status(400).entity(text).build();
     }
   } else {
     String text = "Bad information in url. Make sure to set channel, filename, from and to.";
     log.info("-----------rawCut second opportunity exit with 400---------------");
     return Response.status(400).entity(text).build();
   }
   if (from.after(to)) {
     return Response.status(400).entity("From must be before To.").build();
   }
   try {
     int statusCode = service.getRawCut(channel, filename, from, to);
     if (statusCode == 200) {
       String text = "OK";
       log.info("-----------rawCut exit with 200---------------" + statusCode);
       return Response.status(statusCode).entity(text).build();
     }
     if (statusCode == 400) {
       String text = "Bad information in url (for instance, unknown channel id)";
       log.info("-----------rawCut exit with 400---------------" + statusCode);
       return Response.status(statusCode).entity(text).build();
     }
     if (statusCode == 404) {
       String text =
           "Content unavailable on primary archive server, but exists on secondary. Try later.";
       log.info("-----------rawCut exit with 404---------------" + statusCode);
       return Response.status(statusCode).entity(text).build();
     }
     if (statusCode == 409) {
       String text = "A file with that filename already exists.";
       log.info("-----------rawCut exit with 409---------------" + statusCode);
       return Response.status(statusCode).entity(text).build();
     }
     if (statusCode == 410) {
       String text = "Content unavailable, request cannot be fulfilled.";
       log.info("-----------rawCut exit with 410---------------" + statusCode);
       return Response.status(statusCode).entity(text).build();
     }
     log.info(
         "-----------rawCut exit with 500, unexpected status code---------------" + statusCode);
     return Response.status(500)
         .entity("Unexpected status code.")
         .build(); // Unexpected status code
   } catch (ServiceException ex) {
     log.info(
         "-----------rawCut exit with 500, internal server---------------" + ex.getMessage(), ex);
     return Response.status(500).entity("Internal server error.").build();
   }
 }
 /**
  * Finds and uploads a program, based on id and offsets, to the FtpServer as a file with requested
  * filename, along with PBCore xml about the program. Sends back a response with a status code
  * based on whether or not it was successful. Status codes: 200: OK. 400: Bad information in url.
  * 404: Content not available in main archive. Try again later. 409: A file with chosen filename
  * already exists on FtpServer. 410: Content not available. 500: Internal server error or
  * unexpected status code.
  *
  * @param programIdRaw Id of the program.
  * @param filename Wanted filename.
  * @param offsetStartRaw Offset from start of the program in HH:mm:ss format.
  * @param offsetEndRaw Offset from end of the program in HH:mm:ss format.
  * @return Status code in Response and requested file and associated PBCore xml on FtpServer.
  */
 @GET
 @Path("programSnippet")
 @Produces("text/plain")
 public Response programSnippet(
     @QueryParam("id") String programIdRaw,
     @QueryParam("filename") String filename,
     @QueryParam("offsetStart") String offsetStartRaw,
     @QueryParam("offsetEnd") String offsetEndRaw) {
   if (programIdRaw == null
       || programIdRaw.trim().length() == 0
       || filename == null
       || filename.trim().length() == 0) {
     String text = "Bad information in url. Make sure to set id, filename and offsets.";
     log.info("-----------programSnippet first opportunity exit with 400---------------");
     return Response.status(400).entity(text).build();
   }
   Date offsetStart = null;
   Date offsetEnd = null;
   if (offsetStartRaw != null
       && offsetStartRaw.trim().length() > 0
       && offsetEndRaw != null
       && offsetEndRaw.trim().length() > 0) {
     DateFormat format = new SimpleDateFormat("HH:mm:ss");
     try {
       offsetStart = format.parse(offsetStartRaw);
       offsetEnd = format.parse(offsetEndRaw);
     } catch (ParseException ex) {
       log.debug("Date parse error: From: " + offsetStartRaw + " | To: " + offsetEndRaw);
       log.debug("Date parse error stacktrace: " + ex.getStackTrace());
       String text = "Failed to parse offsets, make sure it is of following format: HH:mm:ss";
       return Response.status(400).entity(text).build();
     }
   } else {
     String text = "Bad information in url. Make sure to set id, filename and offsets.";
     log.info("-----------programSnippet second opportunity exit with 400---------------");
     return Response.status(400).entity(text).build();
   }
   try {
     Long programId = Long.parseLong(programIdRaw);
     try {
       int statusCode = service.getProgramSnippet(programId, filename, offsetStart, offsetEnd);
       if (statusCode == 200) {
         String text = "OK";
         log.info("-----------programSnippet exit with 200---------------" + statusCode);
         return Response.status(statusCode).entity(text).build();
       }
       if (statusCode == 400) {
         String text = "Bad information in url (for instance, unknown channel id)";
         log.info("-----------programSnippet exit with 400---------------" + statusCode);
         return Response.status(statusCode).entity(text).build();
       }
       if (statusCode == 404) {
         String text =
             "Content unavailable on primary archive server, but exists on secondary. Try later.";
         log.info("-----------programSnippet exit with 404---------------" + statusCode);
         return Response.status(statusCode).entity(text).build();
       }
       if (statusCode == 409) {
         String text = "A file with that filename already exists.";
         log.info("-----------programSnippet exit with 409---------------" + statusCode);
         return Response.status(statusCode).entity(text).build();
       }
       if (statusCode == 410) {
         String text = "Content unavailable, request cannot be fulfilled.";
         log.info("-----------programSnippet exit with 410---------------" + statusCode);
         return Response.status(statusCode).entity(text).build();
       }
       if (statusCode == -0) {
         String text = "Program id not found.";
         log.info("-----------programSnippet exit with 410---------------" + statusCode);
         return Response.status(410).entity(text).build();
       }
       log.info(
           "-----------programSnippet exit with 500, unexpected status code---------------"
               + statusCode);
       return Response.status(500)
           .entity("Unexpected status code.")
           .build(); // Unexpected status code
     } catch (ServiceException ex) {
       log.info(
           "-----------programSnippet exit with 500, internal server---------------"
               + ex.getMessage(),
           ex);
       return Response.status(500).entity("Internal server error.").build();
     }
   } catch (NumberFormatException ex) {
     log.info("-----------programSnippet exit with 400, invalid program id---------------");
     return Response.status(400).entity("Invalid program id, must only contain numbers.").build();
   }
 }