示例#1
0
  @RequestMapping(value = "{appid}/callback")
  public void acceptMessageAndEvent(HttpServletRequest request, HttpServletResponse response)
      throws IOException, AesException, DocumentException {
    String msgSignature = request.getParameter("msg_signature");
    // LogUtil.info("第三方平台全网发布-------------{appid}/callback-----------验证开始。。。。msg_signature="+msgSignature);
    if (!StringUtils.isNotBlank(msgSignature)) return; // 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息

    StringBuilder sb = new StringBuilder();
    BufferedReader in = request.getReader();
    String line;
    while ((line = in.readLine()) != null) {
      sb.append(line);
    }
    in.close();

    String xml = sb.toString();
    Document doc = DocumentHelper.parseText(xml);
    Element rootElt = doc.getRootElement();
    String toUserName = rootElt.elementText("ToUserName");

    // 微信全网测试账号
    //        if (StringUtils.equalsIgnoreCase(toUserName, APPID)) {
    //           LogUtil.info("全网发布接入检测消息反馈开始---------------APPID="+ APPID
    // +"------------------------toUserName="+toUserName);
    checkWeixinAllNetworkCheck(request, response, xml);
    //        }
  }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      req.setCharacterEncoding("UTF-8");
      resp.setContentType(req.getContentType());

      IOUtils.copy(req.getReader(), resp.getWriter());
    }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
      reader.close();
    } catch (Exception e) {
      /* report an error */
    }

    try {
      JSONObject input = new JSONObject(jb.toString());
      JSONArray array = null;
      if (input.has("lat") && input.has("lon")) {
        double lat = (Double) input.get("lat");
        double lon = (Double) input.get("lon");
        array = connection.GetRestaurantsNearLoationViaYelpAPI(lat, lon);
      }
      response.setContentType("application/json");
      response.addHeader("Access-Control-Allow-Origin", "*");
      PrintWriter out = response.getWriter();
      out.print(array);
      out.flush();
      out.close();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
示例#4
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Long id = getId(req);
    if (id == null) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }

    Movie movie;
    try {
      movie = gson.fromJson(req.getReader(), Movie.class);
    } catch (Exception ignore) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }

    if (!isMovieValid(movie) || movie.getId() != null && !movie.getId().equals(id)) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }
    movie.setId(id);
    Movie prevMovieVersion = service.updateMovie(movie);
    if (prevMovieVersion == null) {
      resp.setStatus(SC_NOT_FOUND);
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);

    JSONObject params = new JSONObject(data);
    String email = (String) params.get("email");
    String password = (String) params.get("password");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("logindetails");

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.append("$set", new BasicDBObject().append("password", password));
    BasicDBObject searchQuery = new BasicDBObject().append("email", email);
    WriteResult result = users.update(searchQuery, newDocument);

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    response.getWriter().write(result.toString());
  }
示例#6
0
 /**
  * Parse the parameter of route (content of request body).
  *
  * @param request http request.
  * @param route the route.
  * @return the parameters parsed.
  * @throws IOException in case of IO error.
  */
 private Object getRouteParam(HttpServletRequest request, Route route) throws IOException {
   Object param = null;
   if (route.getParamType() != null && route.getParamType() != Void.class) {
     param = gson.fromJson(request.getReader(), route.getParamType());
   }
   return param;
 }
示例#7
0
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    Object obj = JSONValue.parse(req.getReader());

    JSONArray array = (JSONArray) obj;

    JSONObject requestParams = (JSONObject) array.get(0);
    int radioID =
        requestParams.get("radio") == null
            ? 0
            : Integer.parseInt((String) requestParams.get("radio"));
    long userID = requestParams.get("userId") == null ? 0 : (long) requestParams.get("userId");
    @SuppressWarnings("unchecked")
    ArrayList<String> checkboxList = (ArrayList<String>) requestParams.get("checkboxes");

    String query = queryBuilder(radioID, userID, checkboxList);

    PrintWriter out = res.getWriter();
    res.setContentType("text/html; charset=UTF-8");
    String endJson = "";
    if (query != null) {
      try {
        java.sql.DriverManager.registerDriver(new com.google.appengine.api.rdbms.AppEngineDriver());
        c = java.sql.DriverManager.getConnection("jdbc:google:rdbms://valiminee:evalimine2/db");
        if (c != null) {
          java.sql.ResultSet rs = c.createStatement().executeQuery(query);
          endJson = ResultSetConverter.convert(rs).toString();
        }
      } catch (java.sql.SQLException | JSONException e) {
        e.printStackTrace();
      }
    }
    out.print(endJson);
  }
示例#8
0
  /**
   * 处理授权事件的推送
   *
   * @param request
   * @throws IOException
   * @throws AesException
   * @throws DocumentException
   */
  public void processAuthorizeEvent(HttpServletRequest request)
      throws IOException, DocumentException, AesException {
    String nonce = request.getParameter("nonce");
    String timestamp = request.getParameter("timestamp");
    String signature = request.getParameter("signature");
    String msgSignature = request.getParameter("msg_signature");

    if (!StringUtils.isNotBlank(msgSignature)) return; // 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息
    boolean isValid = checkSignature(COMPONENT_TOKEN, signature, timestamp, nonce);
    if (isValid) {
      StringBuilder sb = new StringBuilder();
      BufferedReader in = request.getReader();
      String line;
      while ((line = in.readLine()) != null) {
        sb.append(line);
      }
      String xml = sb.toString();
      //            LogUtil.info("第三方平台全网发布-----------------------原始 Xml="+xml);
      String encodingAesKey = COMPONENT_ENCODINGAESKEY; // 第三方平台组件加密密钥
      String appId = getAuthorizerAppidFromXml(xml); // 此时加密的xml数据中ToUserName是非加密的,解析xml获取即可
      // LogUtil.info("第三方平台全网发布-------------appid----------getAuthorizerAppidFromXml(xml)-----------appId="+appId);
      WXBizMsgCrypt pc = new WXBizMsgCrypt(COMPONENT_TOKEN, encodingAesKey, COMPONENT_APPID);
      xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
      //            LogUtil.info("第三方平台全网发布-----------------------解密后 Xml="+xml);
      processAuthorizationEvent(xml);
    }
  }
 @SuppressWarnings("unchecked")
 @Override
 protected void doPut(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   traceRequest(req);
   IEclipsePreferences node = getNode(req, resp, true);
   if (node == null) return;
   String key = req.getParameter("key");
   try {
     if (key != null) {
       node.put(key, req.getParameter("value"));
     } else {
       JSONObject newNode = new JSONObject(new JSONTokener(req.getReader()));
       node.clear();
       for (Iterator<String> it = newNode.keys(); it.hasNext(); ) {
         key = it.next();
         node.put(key, newNode.getString(key));
       }
     }
     prefRoot.flush();
     resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
   } catch (Exception e) {
     handleException(
         resp, NLS.bind("Failed to store preferences for {0}", req.getRequestURL()), e);
     return;
   }
 }
 private String getNotificationDataString(HttpServletRequest request) {
   String result = null;
   try {
     BufferedReader reader = request.getReader();
     StringBuffer notificationBuffer = new StringBuffer();
     String nextLine = null;
     while ((nextLine = reader.readLine()) != null) {
       notificationBuffer.append(nextLine);
       notificationBuffer.append(NEW_LINE);
     }
     result = notificationBuffer.toString();
   } catch (UnsupportedEncodingException uex) {
     logError(
         "NotificationTaskHandler.getNotificationDataString:" + " Failed to read notification",
         uex);
   } catch (IllegalStateException iex) {
     logError(
         "NotificationTaskHandler.getNotificationDataString:" + "Failed to read notification",
         iex);
   } catch (IOException ioex) {
     logError(
         "NotificationTaskHandler.getNotificationDataString:" + "Failed to read notification",
         ioex);
   }
   return result;
 }
示例#11
0
  public static String getBodyAsString(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = request.getReader();

    try {
      char[] charBuffer = new char[128];
      int bytesRead = -1;
      while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
        stringBuilder.append(charBuffer, 0, bytesRead);
      }
    } catch (IOException ex) {
      throw ex;
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException ex) {
          throw ex;
        }
      }
    }

    body = stringBuilder.toString();
    return body;
  }
示例#12
0
  private PutMethod convertHttpServletRequestToPutMethod(String url, HttpServletRequest request) {
    PutMethod method = new PutMethod(url);

    for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
      String headerName = (String) headers.nextElement();
      String headerValue = (String) request.getHeader(headerName);
      method.addRequestHeader(headerName, headerValue);
    }

    method.removeRequestHeader("Host");
    method.addRequestHeader("Host", request.getRequestURL().toString());

    StringBuilder requestBody = new StringBuilder();
    try {
      BufferedReader reader = request.getReader();
      String line;
      while (null != (line = reader.readLine())) {
        requestBody.append(line);
      }
      reader.close();
    } catch (IOException e) {
      requestBody.append("");
    }

    method.setRequestEntity(new StringRequestEntity(requestBody.toString()));

    return method;
  }
示例#13
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    char[] cbuf = new char[500];
    int amtread;

    PrintWriter out = response.getWriter();
    BufferedReader in = request.getReader();
    amtread = in.read(cbuf);
    cbuf[amtread] = '\0';
    String invalue = new String(cbuf, 0, amtread);
    System.out.println(invalue);
    try {
      String temporary = "Any Model,";

      CarsBean carsBean = new CarsBean();
      List<ModelInfo> listin = carsBean.getModel(invalue);
      for (int i = 0; i < listin.size(); i++) {
        System.out.println(listin.get(i).getModel());

        temporary += listin.get(i).getModel() + ",";
      }
      char[] temp = temporary.toCharArray();
      String result = new String(temp, 0, temp.length - 2);
      System.out.println(result);
      out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("list Error");
    } finally {
      out.close();
    }
  }
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   JSONObject reqJSON = StringUtil.fromReaderToJSON(request.getReader());
   JSONObject result = dao.uploadImage(reqJSON);
   response.setContentType("text/json;charset=UTF-8");
   response.getWriter().write(result.toString());
 }
示例#15
0
  @SuppressWarnings("unused")
  @Override
  public ActionForward execute(
      ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    JSONArray result = null;
    BufferedReader bf = request.getReader();
    StringBuffer sb = new StringBuffer();
    String line = null;
    while ((line = bf.readLine()) != null) {
      sb.append(line);
    }
    JSONObject json = JSONObject.fromObject(sb.toString());

    String holidayDate = json.getString("holidayDate");
    int a[] = {10, 20};
    List<Holidays> holidays = HolidaysFactory.findByDate(new Date(holidayDate));
    if (holidays.size() != 0) {
      a[0] = 0;
    }

    result = JSONArray.fromObject(a);

    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    if (result == null) {
      out.print("");
    } else {
      out.print(result.toString());
    }
    out.flush();

    return null;
  }
示例#16
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try {

      Payload payload = gson.fromJson(req.getReader(), Payload.class);

      if (payload != null && payload.getMarkdown() != null) {

        String html = "";
        if (payload.getLinkAttributes() != null && payload.getLinkAttributes().size() > 0) {
          AttributesLinkRederer linkRenderer =
              new AttributesLinkRederer(payload.getLinkAttributes());
          html = processor.markdownToHtml(payload.getMarkdown(), linkRenderer);
        } else {
          html = processor.markdownToHtml(payload.getMarkdown());
        }

        resp.getWriter().write(html);
      }

      resp.getWriter().close();
      resp.setStatus(200);
    } catch (Exception e) {
      e.printStackTrace();
      resp.setStatus(500);
    }
  }
示例#17
0
 private void remove(HttpServletRequest req, HttpServletResponse resp) throws Exception {
   Device device = JsonConverter.objectFromJson(req.getReader(), new Device());
   Context.getPermissionsManager().checkDevice(getUserId(req), device.getId());
   Context.getDataManager().removeDevice(device);
   Context.getPermissionsManager().refresh();
   sendResponse(resp.getWriter(), true);
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    BufferedReader reader = request.getReader();

    // Read the xml from the request
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
      sb.append(line + "\n");
      line = reader.readLine();
    }
    reader.close();
    String data = sb.toString();

    try {
      // Measurement measurement = (Measurement)
      // sz.deserialize(Measurement.class, data);
      PositioningRequest req = (PositioningRequest) sz.deserialize(PositioningRequest.class, data);

      WLANFingerprint measurement = req.fp;
      PositioningAlgorithmType algoType = req.algorithm;

      context.setPositioningAlgorithm(algoType);

      // Calculate the position from the measurements

      String xmlRes = "";

      switch (algoType) {
        case NearestNeighbors:
          NNResults posRes = (NNResults) context.calculatePosition(measurement);
          xmlRes = Serializer.getInstance().serializeToXML(posRes);
          break;
        case BayesPositioning:
          PositioningResult posRes1 = context.calculatePosition(measurement);
          xmlRes = Serializer.getInstance().serializeToXML(posRes1);
          break;
      }

      // Prepare the response
      // Set content type to json
      response.setHeader("content-type", "text/xml");
      // OutputStream outStream = response.getOutputStream();

      // outStream.write(new ByteArrayOutputStream().w

      PrintWriter out = response.getWriter();

      out.write(xmlRes);

      // out.println(xmlPos);

      out.flush();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   JSONObject reqJSON = StringUtil.fromReaderToJSON(request.getReader());
   Thought t = (Thought) JSONObject.toBean(reqJSON, Thought.class, Thought.loadClassMap());
   JSONObject result = dao.postThought(t);
   response.setContentType("text/json;charset=UTF-8");
   response.getWriter().write(result.toString());
 }
示例#20
0
 @Converter
 public static BufferedReader toReader(HttpMessage message) throws IOException {
   HttpServletRequest request = toServletRequest(message);
   if (request != null) {
     return request.getReader();
   }
   return null;
 }
示例#21
0
 private void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
   Device device = JsonConverter.objectFromJson(req.getReader(), new Device());
   long userId = getUserId(req);
   Context.getDataManager().addDevice(device);
   Context.getDataManager().linkDevice(userId, device.getId());
   Context.getPermissionsManager().refresh();
   sendResponse(resp.getWriter(), JsonConverter.objectToJson(device));
 }
示例#22
0
  /**
   * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as
   * was sent in the given {@link HttpServletRequest}.
   *
   * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard
   *     POST request
   * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent
   *     via the {@link PostMethod}
   */
  private void handleContentPost(
      PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
      throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (; ; ) {
      String line = reader.readLine();
      if (line == null) {
        break;
      }
      content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this
    // servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module
    // 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
      String clientHost = httpServletRequest.getLocalName();
      if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
        clientHost = "localhost";
      }

      int clientPort = httpServletRequest.getLocalPort();
      String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
      String serverUrl =
          targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

      // Replace more completely if destination server is https :
      if (targetSsl) {
        clientUrl = "http://" + clientUrl;
        serverUrl = "https://" + serverUrl;
      }
      postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace(
        "POST Content Type: {} Encoding: {} Content: {}",
        new Object[] {contentType, encoding, postContent});
    StringRequestEntity entity;
    try {
      entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
  }
示例#23
0
  @Override
  public void doPost(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
      throws ServletException, IOException {

    Gson gson = new Gson();
    JsonObject result = new JsonObject();
    JsonObject responseJSON = new JsonObject();
    result.addProperty("code", 0);
    result.add("response", responseJSON);

    try (Connection con = Main.mainConnection.getConnection();
        PreparedStatement stmt = con.prepareStatement(query)) {
      JsonObject json = gson.fromJson(request.getReader(), JsonObject.class);
      String follower = json.get("follower").getAsString();
      String followee = json.get("followee").getAsString();

      //            int follower_id = UserDetailsServlet.GetID(follower, "email", "User", con);
      int follower_id = UserDetailsServlet.GetUserID(follower, con);
      if (follower_id == -1)
        throw new com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException();
      //            int followee_id = UserDetailsServlet.GetID(followee, "email", "User", con);
      int followee_id = UserDetailsServlet.GetUserID(followee, con);
      if (followee_id == -1)
        throw new com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException();

      // stmt = con.prepareStatement(query);
      stmt.setInt(1, follower_id);
      stmt.setInt(2, followee_id);
      stmt.executeUpdate();

    } catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException icvEx) {
      APIErrors.ErrorMessager(1, result);
    } catch (com.google.gson.JsonSyntaxException jsEx) {
      APIErrors.ErrorMessager(2, result);
    } catch (java.lang.NullPointerException npEx) {
      APIErrors.ErrorMessager(3, result);
    } catch (SQLException sqlEx) {
      APIErrors.ErrorMessager(4, result);
      sqlEx.printStackTrace();
    } finally {
      // close connection ,stmt and resultset here
      // try {if (con != null) {con.close();}} catch (SQLException se) { /*can't do anything */ }
      //            try {
      //                if (stmt != null) {
      //                    stmt.close();
      //                }
      //            } catch (SQLException se) {}
      //            try {
      //                if (rs != null) {
      //                    rs.close();
      //                }
      //            } catch (SQLException se) {}
    }
    response.setContentType("application/json; charset=utf-8");
    response.getWriter().println(result);
  }
示例#24
0
 @Override
 protected void filter(
     HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
     throws IOException, ServletException {
   //
   //   find mapped view if any
   //   -----------------------------
   //
   String servletPath = httpRequest.getServletPath();
   UrlPath path = UrlPathString.urlPathOf(servletPath);
   MapUrlPath2View.Result resolved = viewMap.urlPath2View().viewAt(path);
   if (resolved.resultIsEmpty()) {
     chain.doFilter(httpRequest, httpResponse);
     return;
   }
   //
   //   handle component resource if any
   //   --------------------------------
   //
   NamedParams queryParams = namedParamsFromRawQuery(httpRequest.getQueryString());
   String resourceParam = queryParams.valueOrNullOf(ResourceUrlResolver.RESOURCE_PARAM_NAME);
   if (resourceParam != null) {
     ResourceUrlResolver.ParamValue value = ParamValue.from(resourceParam);
     Component componentWithResources = viewMap.componentByName(value.componentName);
     Request request = createRequest(servletPath, queryParams, resolved, httpRequest);
     componentWithResources.serveResource(
         value.resourceName, request, new ControllerResponse(renderer, httpResponse));
     return;
   }
   //
   //   handle FormAction if any
   //   ------------------------
   //
   if (Objects.equal(httpRequest.getMethod(), "POST")) {
     Request request = createRequest(servletPath, queryParams, resolved, httpRequest);
     NamedParams postParams = namedParamsFromRawQuery(httpRequest.getReader().readLine());
     Optional<FormResponse> formRC = formResponseFor(request, postParams, viewMap.formName2Form());
     if (formRC.isPresent()) {
       FormResponse formResponse = formRC.get();
       if (formResponse instanceof FormResponseRedirectToUrlString) {
         httpResponse.sendRedirect(((FormResponseRedirectToUrlString) formResponse).urlString);
         return;
       }
       if (!(formResponse instanceof FormResponseRenderCurrentPage)) {
         throw new RuntimeException("Unsupported Form response: " + formResponse);
       }
     }
   }
   //
   //   handle View response
   //   --------------------------
   //
   Request request = createRequest(servletPath, queryParams, resolved, httpRequest);
   Response response = new ControllerResponse(renderer, httpResponse);
   resolved.view.render(request, response);
 }
示例#25
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      System.out.println(request.getReader().readLine());
    } catch (Exception e) {
      // e.printStackTrace();
      _log.error(" error " + e.getMessage());
    }
  }
  private String content(HttpServletRequest request) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader reader = request.getReader();

    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line);
    }
    return sb.toString();
  }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      assertThat(req.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualToIgnoringCase(PLAIN_TEXT_UTF_8);
      assertThat(req.getHeader(HttpHeaders.CONTENT_ENCODING)).isNull();
      System.out.println(CharStreams.toString(req.getReader()));

      resp.setContentType(PLAIN_TEXT_UTF_8);
      resp.getWriter().write("Banner has been updated");
    }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    StringBuffer postBody = new StringBuffer();
    String line = null;

    BufferedReader reader = req.getReader();
    while ((line = reader.readLine()) != null) {
      postBody.append(line);
    }

    resp.setHeader("content-type", "application/json;charset=UTF-8");
    resp.setCharacterEncoding("UTF-8");

    String action = req.getParameter("action");
    String response = null;

    try {
      if (action.equals(ACTION_DEPLOY)) {
        List<DeployRequest> deployReq = JSONSerDe.deSer(postBody.toString(), DEPLOY_REQ_REF);
        // List of DeployRequest
        log.info(
            Thread.currentThread().getName() + ": Deploy request received [" + deployReq + "]");
        for (DeployRequest request : deployReq) {
          if (request.getReplicationMap() == null || request.getReplicationMap().size() < 1) {
            throw new IllegalArgumentException(
                "Invalid deploy request with empty replication map [" + request + "]");
          }
          if (request.getPartitionMap().size() != request.getReplicationMap().size()) {
            throw new IllegalArgumentException(
                "Invalid deploy request with non-coherent replication / partition maps ["
                    + request
                    + "]");
          }
        }
        response = JSONSerDe.ser(qNodeHandler.deploy(deployReq));
      } else if (action.equals(ACTION_ROLLBACK)) {
        ArrayList<SwitchVersionRequest> rReq =
            JSONSerDe.deSer(postBody.toString(), ROLLBACK_REQ_REF);
        // List of RollbackRequest
        log.info(Thread.currentThread().getName() + ": Rollback request received [" + rReq + "]");
        response = JSONSerDe.ser(qNodeHandler.rollback(rReq));
      } else {
        throw new ServletException("Unknown action: " + action);
      }

      resp.getWriter().append(response);
    } catch (Exception e) {
      log.error(e);
      throw new ServletException(e);
    }
  }
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //        processRequest(request, response);
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
      String datt = String.valueOf(jb.toString());

      JSONObject jsonObj = new JSONObject(datt);

      //            BCicloAcademico oBCicloAcademico = new BCicloAcademico();
      String value;
      value = (String) jsonObj.get("tipoCicloAcademico");
      oBCicloAcademico.setTipoCiclo(value);

      value = (String) jsonObj.get("fechaInicio");
      Date fechaIni = convertStringToDate(value);
      java.sql.Date sqlDateIni = new java.sql.Date(fechaIni.getTime());
      oBCicloAcademico.setFechaInicio(sqlDateIni);

      value = (String) jsonObj.get("fechaFin");
      Date fechaFin = convertStringToDate(value);
      java.sql.Date sqlDateFin = new java.sql.Date(fechaFin.getTime());
      oBCicloAcademico.setFechaFin(sqlDateFin);

      value = (String) jsonObj.get("costo");
      oBCicloAcademico.setCosto(Double.parseDouble(value));

      int idCiclo = new DAOCicloAcademico().registrarCicloAcademico(oBCicloAcademico);

      if (idCiclo != 0) {
        //                String json1 = new Gson().toJson("Ciclo Academico Registrado!");
        String json1 = new Gson().toJson(oBCicloAcademico.getIdCiclo());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json1);
      } else {
        String json1 = new Gson().toJson("Error al registrar Ciclo academico");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json1);
      }

      BTipoCobro oBTipoCobro = new BTipoCobro();
      oBTipoCobro.setIdCiclo(idCiclo);
    } catch (Exception e) {
    }
  }
示例#30
-3
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) jb.append(line);
    } catch (Exception e) {
      System.out.println("Erreur");
    }
    JSONObject json = new JSONObject(jb.toString());
    System.out.println(jb.toString());

    Petition p = new Petition();

    p.setTitle(json.getValue("title"));
    p.setDescription(json.getValue("text"));
    response.getWriter().println(p.toString());

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    // Récupération de l'utilisateur google courant

    if (user != null) {
      System.out.println(user.toString());
    } else {
      System.out.println("user null");
    }

    ObjectifyService.ofy().save().entities(p).now();
    response.getWriter().println("Ajout effectué");
  }