private void update(
      String client,
      ProgramProp programProp,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {

    programProp =
        Program.setSpecialInstruction(
            client, programProp.programId, ServletUtils.getStrParam(request, "specialInstruction"));

    List<String> batch1SessionTimings = new ArrayList<>();
    batch1SessionTimings.addAll(ServletUtils.getStringParamsAsSet(request, "batch1SessionTimings"));
    Collections.sort(batch1SessionTimings);

    programProp =
        Program.setSessionTimings(
            client, programProp.programId, batch1SessionTimings, null, null, null, null);

    programProp =
        Program.setMaxParticipants(
            client, programProp.programId, ServletUtils.getIntParam(request, "maxParticipants"));

    programProp =
        Program.setDisabled(
            client, programProp.programId, ServletUtils.getBoolParam(request, "disabled"));

    ServletUtils.setJson(response, new APIResponse().status(Status.SUCCESS).object(programProp));
  }
  private void queryDetailed(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    Set<Long> groupIds = new HashSet<>();
    groupIds.add(
        Group.safeGetByIdOrName(client, ServletUtils.getStrParam(request, "group"))
            .toProp()
            .groupId);
    List<ProgramProp> programProps =
        Program.query(
            client,
            ServletUtils.getIntParam(request, "startYYYYMMDD"),
            ServletUtils.getIntParam(request, "endYYYYMMDD"),
            ServletUtils.getLongParamsAsSet(request, "programTypeId"),
            groupIds,
            null,
            null);

    for (ProgramProp programProp : programProps) {
      programProp.regSummary =
          Registration.getSummary(client, programProp.programId, User.SUPER_USER);
    }

    ServletUtils.setJson(response, new APIResponse().status(Status.SUCCESS).object(programProps));
  }
  private void get(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ProgramProp programProp =
        Program.safeGet(client, ServletUtils.getLongParam(request, "programId")).toProp(client);

    ServletUtils.setJson(response, new APIResponse().status(Status.SUCCESS).object(programProp));
  }
  private void getOngoingSessions(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    List<SessionProp> sessionProps =
        Program.getOngoingSessions(
            client, ServletUtils.getIntParam(request, "dateYYYYMMDD"), login);

    ServletUtils.setJson(response, new APIResponse().status(Status.SUCCESS).object(sessionProps));
  }
 /** Redirect to HTTP port. */
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   HttpClient client = HttpConnectionUtil.getClient(connectionTimeout);
   // setup POST
   HttpPost post = null;
   try {
     post = new HttpPost(postAcceptorURL);
     String path = req.getContextPath();
     if (path == null) {
       path = "";
     }
     log.debug("Path: {}", path);
     if (req.getPathInfo() != null) {
       path += req.getPathInfo();
     }
     log.debug("Path 2: {}", path);
     int reqContentLength = req.getContentLength();
     if (reqContentLength > 0) {
       log.debug("Request content length: {}", reqContentLength);
       IoBuffer reqBuffer = IoBuffer.allocate(reqContentLength);
       ServletUtils.copy(req, reqBuffer.asOutputStream());
       reqBuffer.flip();
       post.setEntity(new InputStreamEntity(reqBuffer.asInputStream(), reqContentLength));
       post.addHeader("Content-Type", REQUEST_TYPE);
       // get.setPath(path);
       post.addHeader("Tunnel-request", path);
       // execute the method
       HttpResponse response = client.execute(post);
       int code = response.getStatusLine().getStatusCode();
       log.debug("HTTP response code: {}", code);
       if (code == HttpStatus.SC_OK) {
         HttpEntity entity = response.getEntity();
         if (entity != null) {
           resp.setContentType(REQUEST_TYPE);
           // get the response as bytes
           byte[] bytes = EntityUtils.toByteArray(entity);
           IoBuffer resultBuffer = IoBuffer.wrap(bytes);
           resultBuffer.flip();
           ServletUtils.copy(resultBuffer.asInputStream(), resp.getOutputStream());
           resp.flushBuffer();
         }
       } else {
         resp.sendError(code);
       }
     } else {
       resp.sendError(HttpStatus.SC_BAD_REQUEST);
     }
   } catch (Exception ex) {
     log.error("", ex);
     if (post != null) {
       post.abort();
     }
   }
 }
Example #6
0
  /** 分析并设置contentType与headers. */
  private static HttpServletResponse initResponseHeader(
      final String contentType, final String... headers) {
    // 分析headers参数
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
      String headerName = StringUtils.substringBefore(header, ":");
      String headerValue = StringUtils.substringAfter(header, ":");

      if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
        encoding = headerValue;
      } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
        noCache = Boolean.parseBoolean(headerValue);
      } else {
        throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
      }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    // 设置headers参数
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
      ServletUtils.setDisableCacheHeader(response);
    }

    return response;
  }
  private void getAllVenues(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    List<VenueProp> props = Venue.getAll(client);
    ServletUtils.setJson(response, new APIResponse().status(Status.SUCCESS).object(props));
  }
  private void create(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    long groupId =
        Group.safeGetByIdOrName(client, ServletUtils.getStrParam(request, "group"))
            .toProp()
            .groupId;

    ProgramProp programProp =
        Program.create(
            client,
            groupId,
            ServletUtils.getLongParam(request, "programTypeId"),
            ServletUtils.getLongParam(request, "venueId"),
            ServletUtils.getLongParam(request, "teacherId"),
            ServletUtils.getIntParam(request, "startYYYYMMDD"),
            ServletUtils.getIntParam(request, "endYYYYMMDD"),
            1,
            "",
            ServletUtils.getDoubleParam(request, "fee"),
            Utils.Currency.SGD,
            login);

    update(client, programProp, request, response);
  }
  protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    StringBuffer buf = req.getRequestURL();
    if (req.getQueryString() != null) {
      buf.append('?').append(req.getQueryString());
    }

    AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString());

    String code = responseUrl.getCode();
    if (responseUrl.getError() != null) {
      String state = URLDecoder.decode(req.getParameter("state"), "UTF-8");
      String[] params = state.split("\\|");
      resp.sendRedirect(params[1]);
    } else if (code == null) {
      resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      resp.getWriter().print("Missing authorization code");
    } else {
      String redirectUri = ServletUtils.getRedirectUri(req);
      lock.lock();
      try {
        if (flow == null) {
          flow = ServletUtils.newFlow();
        }
        TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();

        HttpSession sess = req.getSession(true);
        Credential credential = flow.createAndStoreCredential(response, sess.getId());
        String[] params = URLDecoder.decode(req.getParameter("state"), "UTF-8").split("\\|");
        String client = params[2];
        String email = ServletUtils.getEmail(credential);
        UserEntity user = User.get(client, email);
        if (user != null) {
          sess.setAttribute("login", email);
          sess.setAttribute("loginType", "google");
        }

        resp.sendRedirect(params[0]);
      } finally {
        lock.unlock();
      }
    }
  }
 protected void doRets(RetsServletRequest request, RetsServletResponse response)
     throws RetsServerException, IOException {
   GetObjectParameters parameters = new GetObjectParameters(request.getParameterMap());
   GetObjectTransaction transaction = new GetObjectTransaction(parameters);
   RetsConfig retsConfig = RetsServer.getRetsConfiguration();
   transaction.setRootDirectory(retsConfig.getGetObjectRoot());
   transaction.setPhotoPattern(retsConfig.getPhotoPattern());
   transaction.setObjectSetPattern(retsConfig.getObjectSetPattern());
   StringBuffer location = ServletUtils.getContextPath(request);
   location.append("/objects/");
   transaction.setBaseLocationUrl(location.toString());
   transaction.execute(new Response(response));
 }
Example #11
0
 @Override
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String ctlExportKeyBase64 =
       URLDecoder.decode(request.getParameter(CTL_EXPORT_KEY_PARAMETER), "UTF-8");
   try {
     CtlSchemaExportKey key =
         (CtlSchemaExportKey) Base64.decodeToObject(ctlExportKeyBase64, Base64.URL_SAFE, null);
     FileData ctlExportData = cacheService.getExportedCtlSchema(key);
     ServletUtils.prepareDisposition(request, response, ctlExportData.getFileName());
     response.setContentType(ctlExportData.getContentType());
     response.setContentLength(ctlExportData.getFileData().length);
     response.setBufferSize(BUFFER);
     response.getOutputStream().write(ctlExportData.getFileData());
     response.flushBuffer();
   } catch (Exception e) {
     LOG.error("Unexpected error in CtlExportServlet.doGet: ", e);
     response.sendError(
         HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get file: " + e.getMessage());
   }
 }
  private void update(
      String client, String login, HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ProgramProp programProp =
        Program.update(
            client,
            ServletUtils.getLongParam(request, "programId"),
            ServletUtils.getLongParam(request, "venueId"),
            ServletUtils.getLongParam(request, "teacherId"),
            ServletUtils.getIntParam(request, "startYYYYMMDD"),
            ServletUtils.getIntParam(request, "endYYYYMMDD"),
            1,
            "",
            ServletUtils.getDoubleParam(request, "fee"),
            Utils.Currency.SGD,
            login);

    update(client, programProp, request, response);
  }
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ServletUtils.addAllAdditionalAttributesToServletContext(getServletContext());
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String client = request.getParameter("client");
    if (client == null) {
      ServletUtils.setJson(
          response, new APIResponse().status(Status.ERROR_RESOURCE_NOT_FULLY_SPECIFIED));
      return;
    }

    String action = request.getParameter("action");
    if (action == null) {
      ServletUtils.setJson(response, new APIResponse().status(Status.ERROR_RESOURCE_NOT_FOUND));
      return;
    }

    String login = ServletUtils.getLogin(request);
    try {
      switch (action) {
        case "getOngoingSessions":
          getOngoingSessions(client, login, request, response);
          break;
        case "query":
          query(client, login, request, response);
          break;
        case "queryDetailed":
          queryDetailed(client, login, request, response);
          break;
        case "get":
          get(client, login, request, response);
          break;
        case "getAllProgramTypes":
          getAllProgramTypes(client, login, request, response);
          break;
        case "getAllPractices":
          getAllPractices(client, login, request, response);
          break;
        case "getAllTeachers":
          getAllTeachers(client, login, request, response);
          break;
        case "getAllVenues":
          getAllVenues(client, login, request, response);
          break;
        case "create":
          create(client, login, request, response);
          break;
        case "update":
          update(client, login, request, response);
          break;
        case "setDisabled":
          setDisabled(client, login, request, response);
          break;
        default:
          ServletUtils.setJson(response, new APIResponse().status(Status.ERROR_RESOURCE_INCORRECT));
      }
    } catch (Exception ex) {
      ServletUtils.setJson(
          response,
          APIUtils.toAPIResponse(
              ex, true, new RequestInfo().client(client).req(request).login(login)));
    }
  }