Пример #1
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String idparam = req.getParameter("id");
    int id = 0;
    try {
      id = Integer.parseInt(idparam);
    } catch (Exception e) {
    }

    if (id > 0) {
      User user = null;
      for (User u : users) {
        if (u.getId() == id) {
          user = u;
          break;
        }
      }

      if (user != null) {
        resp.getWriter().print(user.toJSON());
      }
    } else {
      StringBuilder sb = new StringBuilder();
      sb.append("[");
      for (int i = 0; i < users.size(); i++) {
        sb.append(users.get(i).toJSON());
        if (i < (users.size() - 1)) {
          sb.append(",");
        }
      }
      sb.append("]");
      resp.getWriter().print(sb.toString());
    }
  }
Пример #2
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    RequestDispatcher dispatcher;
    String car = req.getParameter("car");
    String color = req.getParameter("color");
    String engine = req.getParameter("engine");
    String customer = (String) req.getSession().getAttribute("userEmail");

    if (CustomizedCar.addCustomizedCar(car, color, engine, customer)) {
      System.out.println("success");
      resp.getWriter().println("<script type=\"text/JavaScript\">");
      resp.getWriter().println("alert(\"Order Send\")");
      resp.getWriter().println("</script>");
      dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
      dispatcher.forward(req, resp);
    } else {
      resp.getWriter().println("<script type=\"text/JavaScript\">");
      resp.getWriter().println("alert(\"Insertion Failed\")");
      resp.getWriter().println("</script>");
      System.out.println("failed");
      dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
      dispatcher.forward(req, resp);
    }
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
      Authentication authentication = authenticationService.getAuthentication(httpRequest);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      filterChain.doFilter(httpRequest, httpResponse);

    } catch (SignatureException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "unauthorized JWT (invalid signature or expired token). Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (MalformedJwtException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "malformed token. Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (Exception exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "Internal server error, please contact the backend team.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));
      LOGGER.error(exception.getMessage(), exception);
      SecurityContextHolder.clearContext();
    }
  }
  /**
   * Executes a delete user action.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws Exception if an exception occurs
   */
  private void executeDeleteUser(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    try {
      String[] parts = request.getRequestURI().toString().split("/");
      if (parts.length > 0) {
        String userIdentifier = URLDecoder.decode(parts[5].trim(), "UTF-8");
        if (userIdentifier.endsWith(userDIT)) {
          String attempt = Val.chkStr(request.getParameter("attempt"));
          IdentityAdapter idAdapter = context.newIdentityAdapter();
          User user = new User();
          user.setDistinguishedName(userIdentifier);
          idAdapter.readUserProfile(user);
          idAdapter.readUserGroups(user);

          boolean isSelf = checkSelf(context, userIdentifier);
          if ((isSelf && attempt.equals("2")) || !isSelf) {
            idAdapter.deleteUser(user);
            response
                .getWriter()
                .write(msgBroker.retrieveMessage("catalog.identity.deleteUser.success"));
          } else {
            response.getWriter().write("prompt");
          }
        }
      }
    } finally {
    }
  }
Пример #5
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("vector");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = param;
    if (param != null && param.length() > 1) {
      StringBuilder sbxyz87271 = new StringBuilder(param);
      bar = sbxyz87271.replace(param.length() - "Z".length(), param.length(), "Z").toString();
    }

    double value = new java.util.Random().nextDouble();
    String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextDouble() executed");
  }
  @RequestMapping(value = "/importExcel", method = POST)
  public void importExcel(
      @RequestPart MultipartFile file,
      @RequestParam("dsId") JdbcOeDataSource ds,
      HttpServletResponse response)
      throws IOException, ServletException {

    ObjectMapper mapper = new ObjectMapper();
    try {
      // Ext needs this for the crazy way it does file uploads
      // it's normally bad to manually write JSON, but dealing with a custom Spring MessageConverter
      // seems like overkill
      response.setContentType("text/html;charset=utf-8");
      FileImporter<?> importer = fileImporters.get(ds);
      if (importer == null) {
        log.error("No file importer configured for data source {}", ds.getDataSourceId());
        throw new IllegalArgumentException("No file importer configured");
      }
      response.getWriter().write(mapper.writeValueAsString(importer.importFile(file)));
    } catch (Exception e) {
      // respond to exception as normal, but with content type text/html
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      response.getWriter().write(mapper.writeValueAsString(handleException(e)));
    }
  }
Пример #7
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    SynchronousQueue<Boolean> queue = new SynchronousQueue<Boolean>();
    timeoutService.start(queue);

    Boolean initializedResult;
    try {
      initializedResult = queue.poll(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      throw new ServletException(e);
    }

    resp.getWriter().append("Initialized:" + initializedResult);
    resp.getWriter().append("\n");

    // wait for the request scope created for the async method invocation to be destroyed
    try {
      new Timer()
          .setDelay(2000l)
          .addStopCondition(
              new StopCondition() {
                public boolean isSatisfied() {
                  return observingBean.isDestroyedCalled();
                }
              })
          .start();
    } catch (InterruptedException e) {
      throw new ServletException(e);
    }

    resp.getWriter().append("Destroyed:" + observingBean.isDestroyedCalled());
    resp.setContentType("text/plain");
  }
Пример #8
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession(false);

    if (session != null) {
      if (session.getAttribute("user") != null)
        if (session.getAttribute("user") instanceof User) {
          User user = (User) session.getAttribute("user");
          Gson gson = new Gson();
          String json = gson.toJson(user);
          resp.getWriter().write(json);
        }
    } else {
      if (req.getParameter("id") != null && req.getParameter("password") != null) {
        UserServ serv;
        serv = new UserServ();
        UserDAO udao = new UserDAO();
        udao.setSessionFactory(factory);
        serv.setDao(udao);
        if (serv.isValidUser(req.getParameter("id"), req.getParameter("password"))) {
          User user = serv.getUser();
          Gson gson = new Gson();
          String json = gson.toJson(user);
          resp.getWriter().write(json);
          session = req.getSession();
          session.setAttribute("user", user);
        }
      }
    }
  }
Пример #9
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String user = userManager.getRemoteUsername();
    if (!userManager.isAdmin(user)) {
      resp.sendError(403, "Must be an administrator to configure Speakeasy");
      return;
    }

    webResourceManager.requireResource("com.atlassian.auiplugin:ajs");
    webResourceManager.requireResourcesForContext("speakeasy.admin");

    try {
      final Settings settings = speakeasyService.getSettings(user);
      resp.setContentType("text/html");
      render(
          "templates/admin.vm",
          ImmutableMap.<String, Object>builder()
              .put("user", user)
              .put("contextPath", req.getContextPath())
              .put(
                  "staticResourcesPrefix",
                  webResourceManager.getStaticResourcePrefix(UrlMode.RELATIVE))
              .put("settings", new JsRenderer(jsonMarshaller.marshal(settings)))
              .put("permissionsJson", new JsRenderer(jsonMarshaller.marshal(Permission.ALL)))
              .put("permissions", Permission.ALL)
              .build(),
          resp.getWriter());
    } catch (UnauthorizedAccessException e) {
      resp.sendError(403, e.getMessage());
    }
    resp.getWriter().close();
  }
Пример #10
0
  /**
   * 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();
    }
  }
Пример #11
0
  private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String id = null;
    Integer idIndex = 0;
    final AccessLevelManager layerManager =
        new AccessLevelManager(HibernateUtil.getCurrentSession());
    boolean rollback = false;
    while ((id = request.getParameter("ids[" + idIndex + "][id]")) != null) {
      try {
        layerManager.delete(id);
      } catch (ObjectNotFoundException e) {
        response.getWriter().print(NOTFOUND_MESSAGE);
        rollback = true;
        break;
      } catch (RuntimeException e) {
        rollback = true;
        response.getWriter().print(ERROR_MESSAGE);
        break;
      } finally {
        idIndex++;
      }
    }

    if (rollback == true) {
      HibernateUtil.getCurrentSession().getTransaction().rollback();
    } else {
      response.getWriter().print(OK_MESSAGE);
    }

    response.getWriter().flush();
  }
Пример #12
0
 /**
  * @param aStatusCode
  * @param aMessage
  * @param aResp
  * @throws IOException
  */
 protected static void sendMessage(int aStatusCode, String aMessage, HttpServletResponse aResp)
     throws IOException {
   aResp.setStatus(aStatusCode);
   aResp.getWriter().print(aMessage);
   aResp.flushBuffer();
   aResp.getWriter().close();
 }
  private void write() {
    if (Constants.FORMAT_JSON.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/plain");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionJSON());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } else if (Constants.FORMAT_XML.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/xml");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionXML());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Пример #14
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String prenom = request.getParameter("prenom");
    String pseudo = request.getParameter("pseudo");
    String mdp = request.getParameter("mdp");

    Map<String, Object> config = new HashMap<String, Object>();
    config.put("javax.json.stream.JsonGenerator.prettyPrinting", Boolean.valueOf(true));
    JsonBuilderFactory factory = Json.createBuilderFactory(config);
    JsonObject value;

    try {
      gestionJoueurs.creerJoueur(prenom, pseudo, mdp);
    } catch (JoueurDejaExistantException e) {
      value =
          factory.createObjectBuilder().add("success", "0").add("message", e.getMessage()).build();
      response.setContentType("application/json");
      response.getWriter().write(value.toString());
      return;
    }

    HttpSession session = request.getSession();
    Joueur nouveauJoueur = new Joueur(prenom, pseudo, mdp);

    session.setAttribute("joueur", nouveauJoueur);

    value =
        factory
            .createObjectBuilder()
            .add("success", "1")
            .add("message", "Inscription avec succès!")
            .build();
    response.setContentType("application/json");
    response.getWriter().write(value.toString());
  }
Пример #15
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");

    String remove = request.getParameter("remove");

    if (remove != null) {
      accountServer.removeUser();
      response.getWriter().println("Hasta la vista!");
      response.setStatus(HttpServletResponse.SC_OK);
      return;
    }

    int limit = accountServer.getUsersLimit();
    int count = accountServer.getUsersCount();

    logger.info("Limit: {}. Count {}", limit, count);

    if (limit > count) {
      logger.info("User pass");
      accountServer.addNewUser();
      response.getWriter().println("Hello, world!");
      response.setStatus(HttpServletResponse.SC_OK);
    } else {
      logger.info("User were rejected");
      response.getWriter().println("Server is closed for maintenance!");
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
  }
Пример #16
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
  /**
   * @param titulo
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response, String titulo)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
    HttpSession session = request.getSession();
    String tituloproc = request.getParameter("tituloproc");
    session.setAttribute("tituloproc", tituloproc);
    session.getAttribute("titulo");

    if (tituloproc.equals(titulo)) {
      PrintWriter out = response.getWriter();

      // escreve o texto
      out.println("<html>");
      out.println("<body>");
      out.println("Titulo");
      out.println(tituloproc);
      out.println("</body>");
      out.println("</html>");

    } else {
      PrintWriter out = response.getWriter();
      out.println("Volume desconhecido");
    }
  }
Пример #18
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);
    }
  }
Пример #19
0
  @Override
  public ActionForward execute(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String id = request.getParameter("id");
    String name = request.getParameter("name");
    String gender = request.getParameter("gender");
    String university = request.getParameter("university");
    String className = request.getParameter("className");

    Student stu = new Student();
    stu.setId(id);
    stu.setName(name);
    stu.setGender(gender);
    stu.setUniversity(university);
    stu.setClassName(className);

    response.setContentType("text/plain");
    if (new StudentDAO().insert(stu)) {
      System.out.println("Insert SUCCESS");
      response.getWriter().write("success");
    } else {
      System.err.println("Insert FAIL");
      response.getWriter().write("fail");
    }
    return null;
  }
  protected void streamOperationOutcome(
      BaseServerResponseException theE,
      RestfulServer theServer,
      EncodingEnum theEncodingNotNull,
      HttpServletResponse theResponse,
      RequestDetails theRequest)
      throws IOException {
    theResponse.setStatus(theE.getStatusCode());

    theServer.addHeadersToResponse(theResponse);

    if (theE.getOperationOutcome() != null) {
      theResponse.setContentType(theEncodingNotNull.getResourceContentType());
      IParser parser = theEncodingNotNull.newParser(theServer.getFhirContext());
      parser.setPrettyPrint(RestfulServerUtils.prettyPrintResponse(theServer, theRequest));
      Writer writer = theResponse.getWriter();
      try {
        parser.encodeResourceToWriter(theE.getOperationOutcome(), writer);
      } finally {
        writer.close();
      }
    } else {
      theResponse.setContentType(Constants.CT_TEXT);
      Writer writer = theResponse.getWriter();
      try {
        writer.append(theE.getMessage());
      } finally {
        writer.close();
      }
    }
  }
Пример #21
0
  @RequestMapping("/openid")
  public void getOpenId(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);

    String code = request.getParameter("code");
    try {
      response.getWriter().println("<h1>code</h1>");
      response.getWriter().println(code);
      WxMpOAuth2AccessToken wxMpOAuth2AccessToken =
          WeChatConnector.getMpService().oauth2getAccessToken(code);
      WxMpUser wxMpUser =
          WeChatConnector.getMpService().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
      response.getWriter().println("<h1>user open id</h1>");
      response.getWriter().println(wxMpUser.getOpenId());

    } catch (WxErrorException e) {
      e.printStackTrace();
    }

    response.getWriter().flush();
    response.getWriter().close();
  }
Пример #22
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getParameter("foo");

    String bar =
        new String(
            new sun.misc.BASE64Decoder()
                .decodeBuffer(new sun.misc.BASE64Encoder().encode(param.getBytes())));

    try {
      java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG");

      // Get 40 random bytes
      byte[] randomBytes = new byte[40];
      getNextNumber(numGen, randomBytes);
      response.getWriter().println("Random bytes are: " + new String(randomBytes));

    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
      throw new ServletException(e);
    } finally {
      response
          .getWriter()
          .println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
  }
Пример #23
0
  public static void destroySubscribe(HttpServletRequest req, HttpServletResponse res) {

    try {
      AsyncMessage message = new AsyncMessage();
      message.setMessageType("test_subscribe");

      SubscriberController controller =
          (SubscriberController) BeanFactory.getBean("publish_subscribe_controller");
      controller.unregist(message);
      //			String mseq = req.getParameter("mseq");
      HttpSession session = req.getSession(false);
      //			SSysOperatorsList list =
      // (SSysOperatorsList)req.getSession(false).getAttribute(mseq);
      //			int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Пример #24
0
  /**
   * 超时测试
   *
   * @param req
   * @param res
   */
  public static void asyncTimeout(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    iAsyncMgntInt.setAsyncCall(true); // 标志异步调用
    iAsyncMgntInt.setTimeout(10000);
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    try {

      int result = iAsyncMgntInt.select_sysOperators_timeout(holder, errMsg); // 获取响应结果

      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Пример #25
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String source = req.getParameter("source");
    ImagesService imagesService = ImagesServiceFactory.getImagesService();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    List<Filter> filters = new ArrayList<Filter>();
    Query query = new Query(GAEFeedRepository.FEED_ITEM_KIND);
    filters.add(new Query.FilterPredicate("source", FilterOperator.EQUAL, source));
    filters.add(new Query.FilterPredicate("img1A", FilterOperator.EQUAL, 1));
    filters.add(new Query.FilterPredicate("img2A", FilterOperator.EQUAL, 1));

    query.setFilter(CompositeFilterOperator.and(filters));

    query.addSort("publishedDate", SortDirection.DESCENDING);
    PreparedQuery pq = datastore.prepare(query);
    int pageSize = 30;

    resp.setContentType("text/html");
    resp.getWriter().println(" <ul>");

    FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
    String startCursor = req.getParameter("cursor");

    // If this servlet is passed a cursor parameter, let's use it
    if (startCursor != null) {
      fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
    }

    QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
    for (Entity entity : results) {
      resp.getWriter()
          .println(
              "<li>"
                  + entity.getProperty("imageLink")
                  + " / "
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + " / <img height=40 width=40 src=\""
                  + imagesService.getServingUrl(
                      ServingUrlOptions.Builder.withBlobKey((BlobKey) entity.getProperty("img2")))
                  + "\" />");
    }

    resp.getWriter().println("</li>  </entity></ul>  ");

    String cursor = results.getCursor().toWebSafeString();

    // Assuming this servlet lives at '/people'
    resp.getWriter()
        .println(
            "<a href=\"/p8admin/ListFeedItems?cursor="
                + cursor
                + "&source="
                + source
                + "\">Next page</a>");
  }
Пример #26
0
  /**
   * 获取异步请求结果
   *
   * @param req
   * @param res
   */
  public static void asyncResult(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    iAsyncMgntInt.setAsyncCall(true);

    try {
      String mseq = req.getParameter("mseq");

      MessageSequence ms = new MessageSequence(mseq);

      iAsyncMgntInt.setMseq(ms);
      int result = iAsyncMgntInt.select_sysOperators_response(holder, errMsg);
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      try {
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Пример #27
0
 /**
  * 发起同步请求,获取后台信息,直接显示在页面上
  *
  * @param req
  * @param res
  */
 public static void sync(HttpServletRequest req, HttpServletResponse res) {
   System.setProperty("0", "aaaaaaaa");
   //		h.put(i+"","aaaaaaaaaaaaaaaaaaaaaaaa");
   //		i++;
   //		System.out.println("*************************system prop is " +
   // System.getProperties());
   IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
   SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
   CBSErrorMsg errMsg = new CBSErrorMsg();
   try {
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
     int result = iAsyncMgntInt.select_sysOperators(holder, errMsg);
     System.out.println("*****result is " + result);
     if (result != 0) {
       res.getWriter().println(errMsg.get_errorMsg() + ":" + errMsg.get_errorCode());
     }
     SSysOperatorsList list = holder.value;
     int size = list.size();
     res.getWriter().println("<pre>");
     for (int i = 0; i < size; i++) {
       SSysOperators opers = (SSysOperators) list.get(i);
       res.getWriter().println(i + ":" + opers.get_loginName());
     }
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #28
0
  /**
   * 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
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // String county= request.getParameter("county").toString();
    String countyid = request.getParameter("countyid");
    String id = request.getParameter("id");
    String value = request.getParameter("value");
    String columnName = request.getParameter("columnName");
    String columnId = request.getParameter("columnId");
    String columnPosition = request.getParameter("columnPosition");
    String rowId = request.getParameter("rowId");
    response.getWriter().print(value);
    HttpSession session;

    session = request.getSession(true);
    //  String unique=(String)session.getAttribute("countyid");
    dbConnect conn = new dbConnect();

    String query =
        "update behaviourscode set BehavioursCode='"
            + value
            + "'where BehavioursCodeID='"
            + id
            + "'";

    try {
      conn.state.executeUpdate(query);

      //                   response.sendRedirect("CountyServlet");
    } catch (SQLException ex) {
      Logger.getLogger(UpdateBehaviour.class.getName()).log(Level.SEVERE, null, ex);
      out.println(ex.toString());
    }
  }
Пример #29
0
  @Override
  public final void doFilter(
      final ServletRequest req, final ServletResponse res, final FilterChain chain)
      throws ServletException {
    try {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      HttpSession session = request.getSession(false);

      if (session == null) {
        response.setContentType("application/json");
        response.getWriter().write("{\"error\":\"No active session\"}");
      } else {
        User user = (User) session.getAttribute("user");
        if (user == null) {
          response.setContentType("application/json");
          response.getWriter().write("{\"error\":\"User session not found\"}");
        } else {
          chain.doFilter(req, res);
        }
      }
    } catch (Throwable t) {
      throw new ServletException("Error: " + t.getMessage(), t);
    }
  }
Пример #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é");
  }