@Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = new Test().doSomething(param);

    String a1 = "";
    String a2 = "";
    String osName = System.getProperty("os.name");
    if (osName.indexOf("Windows") != -1) {
      a1 = "cmd.exe";
      a2 = "/c";
    } else {
      a1 = "sh";
      a2 = "-c";
    }
    String[] args = {a1, a2, "echo"};

    String[] argsEnv = {bar};

    Runtime r = Runtime.getRuntime();

    try {
      Process p = r.exec(args, argsEnv);
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  } // end doPost
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

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

    String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo") + bar;

    String[] argsEnv = {"Foo=bar"};
    Runtime r = Runtime.getRuntime();

    try {
      Process p = r.exec(cmd, argsEnv);
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  }
 protected Object getCheckboxesValues(HttpServletRequest request, String id) {
   if (request.getParameterValues(id) != null) {
     return Arrays.asList(request.getParameterValues(id));
   } else {
     return getFromRequest(request, id);
   }
 }
Exemple #4
0
  @RequestMapping("/self/item/add")
  public String addItem(
      Item item, Model model, HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String[] picUrls = request.getParameterValues("picUrl");
    String[] picUrlSmalls = request.getParameterValues("picUrlSmall");

    User user = getCurrentUser();
    item.setUserId(user.getUserId());
    item.setNickName(user.getNickName());
    item.setEmail(user.getEmail());
    item.setCreateDate(DateUtils.now());
    Integer itemId = itemMng.add(item);

    for (int i = 0; i < picUrls.length; i++) {
      ItemPic itemPic = new ItemPic();
      itemPic.setItemId(itemId);
      itemPic.setCreateDate(DateUtils.now());
      itemPic.setPicUrl(picUrls[i]);
      itemPic.setPicUrlSmall(picUrlSmalls[i]);
      itemPicMng.add(itemPic);
    }
    return "redirect:/self";
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar;

    // Simple if statement that assigns param to bar on true condition
    int i = 196;
    if ((500 / 42) + i > 200) bar = param;
    else bar = "This should never happen";

    try {
      javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
  }
  protected void populateBeanFromParams(Object bean, HttpServletRequest request) {
    Map params = request.getParameterMap();
    Enumeration paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
      String key = "";
      try {
        key = (String) paramNames.nextElement();
      } catch (ClassCastException cce) {
        log.error("populateBeanFromParams() could not cast parameter name to String");
      }
      String value = "";
      if (key.equals(MULTIPLEXED_PARAMETER_NAME)) {
        String multiplexedStr = request.getParameterValues(key)[0];
        Map paramMap = FormUtils.beanParamMapFromString(multiplexedStr);
        Iterator paramIt = paramMap.keySet().iterator();
        while (paramIt.hasNext()) {
          String param = (String) paramIt.next();
          String demultiplexedValue = (String) paramMap.get(param);
          FormUtils.beanSet(bean, param, demultiplexedValue);
        }

      } else {
        try {
          value = (String) request.getParameterValues(key)[0];
        } catch (ClassCastException cce) {
          try {
            value = ((Integer) params.get(key)).toString();
          } catch (ClassCastException ccf) {
            log.error("populateBeanFromParams() could not cast parameter name to String");
          }
        }
        FormUtils.beanSet(bean, key, value);
      }
    }
  }
Exemple #7
0
 // 返回指定表单名的数组
 public String[] getParameterValues(HttpServletRequest request, String name) {
   // POST 方法的参数没有编码错误
   // if (request.getMethod().equalsIgnoreCase("POST")) {
   // 文件上传模式
   // if(isUploadMode) {
   //    return request.getParameterValues(name);
   // }
   // -- For Tomcat 4.0
   // return request.getParameterValues(name);
   // -- For JSWDK 1.0.1
   /*
    * String values[] = _request.getParameterValues(name); if(values !=
    * null) { for(int i = 0; i < values.length; i++) { values[i] =
    * toChi(values[i]); } } return values;
    */
   // }
   // else {
   // 将通过 GET 方式发送的中文字符解码(但是必须使用 java.net.URLEncoder 进行中文字符参数的编码)
   // 解码时需使用内码转换, 也可使用反编码, 即: return decode(_request.getParameter(name));
   // 问题: decode() 仅适用于 JDK 1.3 + Tomcat 4.0
   String encoding = request.getCharacterEncoding();
   if ("GBK".equalsIgnoreCase(encoding) || "GB2312".equalsIgnoreCase(encoding)) {
     return request.getParameterValues(name);
   }
   String values[] = request.getParameterValues(name);
   if (values != null) {
     for (int i = 0; i < values.length; i++) {
       values[i] = toChi(values[i]);
     }
   }
   return values;
   // }
 }
  protected void setResource(HttpServletRequest request, boolean config) throws Exception {
    try {
      Subject subject = WebUtility.getSubject(request);
      Integer resourceTypeId =
          WebUtility.getOptionalIntRequestParameter(
              request, ParamConstants.RESOURCE_TYPE_ID_PARAM, -1);
      int groupId = WebUtility.getOptionalIntRequestParameter(request, AttrConstants.GROUP_ID, -1);
      int parent = WebUtility.getOptionalIntRequestParameter(request, "parent", -1);
      String[] r = request.getParameterValues("r");
      String[] resourceIds = request.getParameterValues("resourceIds");

      // TODO rewrite the selection using WebUtility.getMetricsDisplayMode()
      if ((resourceTypeId > 0) && (parent > 0)) // autogroup
      {
        ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager();
        ResourceType resourceType =
            resourceTypeManager.getResourceTypeById(subject, resourceTypeId);
        request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resourceType.getName());
        request.setAttribute("parent", parent);
        request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId);
        if (log.isDebugEnabled()) {
          log.debug("Autogroup p=" + parent + ", ct=" + resourceTypeId);
        }
      } else if (groupId > 0) // compat (or mixed) group
      {
        ResourceGroupManagerLocal resourceGroupManager = LookupUtil.getResourceGroupManager();
        ResourceGroup group = resourceGroupManager.getResourceGroupById(subject, groupId, null);
        request.setAttribute(AttrConstants.GROUP_ID, groupId);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, group.getName());
        // TODO more ?
      } else if ((resourceTypeId > 0) && (parent == -1)) // MeasurementDefinition
      {
        ResourceTypeManagerLocal resourceTypeManager = LookupUtil.getResourceTypeManager();
        ResourceType resourceType =
            resourceTypeManager.getResourceTypeById(subject, resourceTypeId);
        request.setAttribute(AttrConstants.RESOURCE_TYPE_ATTR, resourceType);
        request.setAttribute(ParamConstants.RESOURCE_TYPE_ID_PARAM, resourceTypeId);
      } else if ((r != null) && (r.length > 0)) // multiple scathered resources
      {
        log.trace("Multiple resources not handled yet"); // TODO what do we do here?
      } else if ((resourceIds != null) && (resourceIds.length > 0)) {
        log.trace("Multiple resources not yet handled"); // TODO what to we do here?
      } else // single resource
      {
        Integer resourceId =
            WebUtility.getRequiredIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM);
        ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
        Resource resource = resourceManager.getResourceById(subject, resourceId);
        ResourceUIBean resourceUIBean = new ResourceUIBean(resource, subject);
        request.setAttribute(AttrConstants.RESOURCE_ATTR, resource);
        request.setAttribute(AttrConstants.RESOURCE_ID_ATTR, resourceId);
        request.setAttribute(AttrConstants.TITLE_PARAM_ATTR, resource.getName());
        request.setAttribute(
            AttrConstants.PERFORMANCE_SUPPORTED_ATTR, resourceUIBean.getFacets().isCallTime());
      }
    } catch (ResourceNotFoundException e) {
      RequestUtils.setError(request, MessageConstants.ERR_RESOURCE_NOT_FOUND);
    }
  }
Exemple #9
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");
    try (PrintWriter out = response.getWriter()) {
      /* TODO output your page here. You may use following sample code. */

      HttpSession session = request.getSession();
      HashMap<String, Integer> rights = (HashMap<String, Integer>) session.getAttribute("login");
      Employee emp = new Employee();
      emp.setUserId(rights.get("userId"));
      DAOFactory db = DAOFactory.getDAOFactory(1);
      EmployeeDAO empDB = db.getEmployeeDAO();
      emp = empDB.getEmployeeById(emp);

      String[] Products = request.getParameterValues("checkedRows");
      String[] Quantity = request.getParameterValues("orderquantity");
      PurchaseOrder order = new PurchaseOrder();
      Date d = java.sql.Date.valueOf(request.getParameter("orderdate"));
      order.setOrder_date(d);
      order.setEmployeeID(emp.getEmployeeId());
      order.setStatus("P");
      PurchaseOrderDAO poDB = db.getPurchaseOrderDAO();
      int ordernumber = poDB.addPurchaseOrder(order);
      order.setPurchaseOrderID(ordernumber);
      order.setProducts(Products);
      order.setQuantity(Quantity);
      poDB.addProducts(order);
      response.sendRedirect("ToReqSlip");
    }
  }
  public void pageRequested(PageEvent p) throws Exception {
    HttpServletRequest req = p.getPage().getCurrentRequest();
    String returnVal[] = req.getParameterValues(getFullName());
    if (returnVal != null) {
      if (_editDescription) _hiddenKeyHandle.setValue(returnVal[0], _rowNo);
      else getEditField().setValue(returnVal[0], _rowNo);
    }
    HtmlPage pg = getPage();
    if (pg instanceof JspController) ((JspController) pg).setRemoveFromQueryString(getFullName());

    if (returnVal != null) {
      returnVal = req.getParameterValues("descReturn");
      if (returnVal != null) {
        if (_editDescription) getEditField().setValue(returnVal[0], _rowNo);
        if (_descDs != null && _descriptionColumn != -1) {
          if (_descDs.getColumnDataType(_descriptionColumn) == DataStoreBuffer.DATATYPE_STRING) {
            if (_rowNo == -1) _rowNo = _descDs.getRow();
            _descDs.setString(_rowNo, _descriptionColumn, returnVal[0]);
          }
        }
        if (pg instanceof JspController)
          ((JspController) pg).setRemoveFromQueryString("descReturn");
      }
    }
  }
Exemple #11
0
  private static void putRequestMap(
      Env env,
      ArrayValue post,
      ArrayValue files,
      HttpServletRequest request,
      boolean addSlashesToValues,
      boolean isAllowUploads) {
    // this call consumes the inputstream
    Map<String, String[]> map = request.getParameterMap();

    if (map == null) return;

    long maxFileSize = Long.MAX_VALUE;

    Value maxFileSizeV = post.get(MAX_FILE_SIZE);
    if (maxFileSizeV.isNull()) maxFileSize = maxFileSizeV.toLong();

    if (isAllowUploads) {
      for (Map.Entry<String, String[]> entry : map.entrySet()) {
        String key = entry.getKey();

        int len = key.length();

        if (len < 10 || !key.endsWith(".filename")) continue;

        String name = key.substring(0, len - 9);

        String[] fileNames = request.getParameterValues(name + ".filename");
        String[] tmpNames = request.getParameterValues(name + ".file");
        String[] mimeTypes = request.getParameterValues(name + ".content-type");

        for (int i = 0; i < fileNames.length; i++) {
          long fileLength = new FilePath(tmpNames[i]).getLength();

          addFormFile(
              env,
              files,
              name,
              fileNames[i],
              tmpNames[i],
              mimeTypes[i],
              fileLength,
              addSlashesToValues,
              maxFileSize);
        }
      }
    }

    ArrayList<String> keys = new ArrayList<String>();

    keys.addAll(request.getParameterMap().keySet());

    Collections.sort(keys);

    for (String key : keys) {
      String[] value = request.getParameterValues(key);

      Post.addFormValue(env, post, key, value, addSlashesToValues);
    }
  }
  public void onExpectedRequest(
      String target, HttpServletRequest request, HttpServletResponse response) throws Exception {

    assertTrue(request.getPathInfo().endsWith("/api/rest/getLatestBuildResults.action"));

    final String[] authTokens = request.getParameterValues("auth");
    final String[] buildKeys = request.getParameterValues("buildKey");

    assertEquals(1, authTokens.length);
    assertEquals(1, buildKeys.length);

    final String authToken = authTokens[0];
    final String myBuildKey = buildKeys[0];

    assertEquals(LoginCallback.AUTH_TOKEN, authToken);
    assertEquals(buildKey, myBuildKey);

    VelocityEngine velocityEngine = new VelocityEngine();
    Properties props = new Properties();
    props.setProperty("resource.loader", "class");
    props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.init(props);
    final VelocityContext context = new VelocityContext();
    context.put("buildKey", buildKey);
    context.put("buildNumber", buildNumber);

    final OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
    velocityEngine.mergeTemplate(
        "/mock/bamboo/1_2_4/api/rest/latestBuildResultResponse.vm", "UTF-8", context, writer);
    writer.flush();
    response.getOutputStream().flush();
  }
  /*
   * Return a view sending all params from a request
   *
   * @param request HttpServletRequest to send to the view
   * @param viewname String with the view name to load
   * @return ModelAndView return a view with viewname
   */
  public static ModelAndView buildViewParams(HttpServletRequest request, String viewname) {

    Map<String, Object> map = new HashMap<String, Object>();

    ModelAndView mav = new ModelAndView(viewname, map);

    Enumeration<String> parameterNames = request.getParameterNames();

    while (parameterNames.hasMoreElements()) {
      String paramName = parameterNames.nextElement();

      // if the request var is a Array
      if ((request.getParameterValues(paramName).getClass().isArray())
          // if Array size is more than 1
          && (request.getParameterValues(paramName).length > 1)) {
        map.put(paramName, Arrays.toString(request.getParameterValues(paramName)));
      } else
        // if the request var is a simple var
        map.put(paramName, request.getParameter(paramName));
    }

    mav.addAllObjects(map);

    // return view
    return mav;
  }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] ssns, multipliers;
    MultipleBonus[] multipleBonuses = null;

    log.debug("Getting params from HTTP request");
    ssns = req.getParameterValues("ssn");
    multipliers = req.getParameterValues("multiplier");

    log.debug("Creating ssns...");
    for (String s : ssns) {
      Ssn ssn = new Ssn();
      ssn.setSsn(s);
      ssnSession.createSsn(ssn);
    }

    log.debug("Constucting multiple bonuses ...");
    multipleBonuses = getBonuses(ssns, multipliers);
    for (MultipleBonus multipleBonus : multipleBonuses) {
      log.info(multipleBonus);
      try {
        multipleBonusSession.create(multipleBonus);
      } catch (Exception e) {
        log.error(e.getStackTrace());
      }
    }
    req.setAttribute("multipleBonuses", multipleBonuses);
    log.debug("Finished. Dispatch to result.jsp");
    req.getRequestDispatcher("/index.jsp").forward(req, resp);
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = doSomething(param);

    // FILE URIs are tricky because they are different between Mac and Windows because of lack of
    // standardization.
    // Mac requires an extra slash for some reason.
    String startURIslashes = "";
    if (System.getProperty("os.name").indexOf("Windows") != -1)
      if (System.getProperty("os.name").indexOf("Windows") != -1) startURIslashes = "/";
      else startURIslashes = "//";

    try {
      java.net.URI fileURI =
          new java.net.URI(
              "file:"
                  + startURIslashes
                  + org.owasp.benchmark.helpers.Utils.testfileDir
                      .replace('\\', '/')
                      .replace(' ', '_')
                  + bar);
      new java.io.File(fileURI);
    } catch (java.net.URISyntaxException e) {
      throw new ServletException(e);
    }
  } // end doPost
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = new Test().doSomething(param);

    try {
      javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5Padding");
    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      System.out.println(
          "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
  } // end doPost
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] ssns, multipliers;
    Bonus[] bonuses = null;

    log.debug("Getting params from HTTP request");
    ssns = req.getParameterValues("ssn");
    multipliers = req.getParameterValues("multiplier");

    log.debug("Constucting multiple bonuses ...");
    try {
      bonuses = getBonuses(ssns, multipliers);
      for (Bonus bonus : bonuses) {
        log.debug(bonus);
      }

    } catch (NamingException e) {
      e.printStackTrace();
      // log.error(e.getMessage());

    } finally {
      req.setAttribute("bonuses", bonuses);
      log.debug("Finished. Dispatch to result.jsp");
      req.getRequestDispatcher("/multiple-result.jsp").forward(req, resp);
    }
  }
  @Override
  public String executa(HttpServletRequest req, HttpServletResponse res) {

    Connection conn = null;
    String[] ids = req.getParameterValues("id");
    String[] quantidades = req.getParameterValues("quantidade");
    String codFunc = req.getParameter("funcionario");
    String codHosp = req.getParameter("codigoHospedagem");

    try {
      conn = ConnectionFactory.getConnection();

      // Inicia a transacao
      conn.setAutoCommit(false);

      for (int i = 0; i < ids.length; i++) {
        Consumo c = new Consumo();
        Hospedagem h = new Hospedagem();
        ProdutoServico ps = new ProdutoServico();
        Funcionario f = new Funcionario();

        h.setCdHospedagem(Integer.parseInt(codHosp));
        ps.setCdTipoServico(Integer.parseInt(ids[i]));
        f.setCdPessoa(Integer.parseInt(codFunc));

        c.setQtConsumo(Integer.parseInt(quantidades[i]));
        c.setHospedagem(h);
        c.setProdutoServico(ps);
        c.setFuncionarioConsumo(f);

        boolean confInsert = false;
        if (ConsumoBO.registrar(conn, c) > 0) {
          confInsert = true;
        }

        req.setAttribute("confInsert", confInsert);
      }

      conn.commit();

    } catch (Exception e) {
      try {
        conn.rollback();
      } catch (SQLException sqlExc) {

      }

      Excecoes ex = new Excecoes(e);
      req.setAttribute("error", ex.getMessage());
    }

    setDataPage(req, conn, codHosp);
    req.setAttribute("varRequest", true);

    return "registraConsumo.jsp";
  }
  public ModelAndView save(HttpServletRequest request, HttpServletResponse response)
      throws ParseException, ProductDaoException, SupplierDaoException {

    String[] prsNumbers = request.getParameterValues("prsNumber");
    String[] itemCodes = request.getParameterValues("itemCode");
    String[] supplierCodes = request.getParameterValues("supplierCode");
    String[] selecteds = request.getParameterValues("selected");
    String[] prices = request.getParameterValues("price");
    String[] tops = request.getParameterValues("top");
    String[] topDescs = request.getParameterValues("topDesc");
    String[] tods = request.getParameterValues("tod");
    String[] wps = request.getParameterValues("wp");
    LoginUser lu = (LoginUser) request.getSession().getAttribute("user");

    /* get prs assign to supplier */
    AssignCanvassingDao assignCanvassingDao = DaoFactory.createAssignCanvassingDao();
    for (int i = 0; i < itemCodes.length; i++) {
      AssignCanvassing ac =
          assignCanvassingDao.findForPriceSaving(prsNumbers[i], itemCodes[i], supplierCodes[0]);
      ac.setIsSelected(selecteds[i].equals("on") ? "Y" : "N");
      ac.setUnitPrice(new BigDecimal(prices[i]));
      ac.setTop(tops[i]);
      ac.setTopDesc(topDescs[i]);
      ac.setTod(tods[i]);
      ac.setWp(wps[i].isEmpty() ? null : new SimpleDateFormat("dd/MM/yyyy").parse(wps[i]));
      ac.setUpdatedBy(lu.getUserId());
      ac.setUpdatedDate(new Date());
      assignCanvassingDao.update(ac);
    }

    return findByPrimaryKey(request, response);
  }
  /**
   * Gathers the parameters in the request as a HTTP URL string. to form request parameters and
   * policy advice String array. It collects all the parameters from the original request except the
   * original goto url and any advice parameters. Note: All the paramters will be url decoded by
   * default., we should make sure that these values are encoded again
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @return An String array, index 0 is policy advice, index 1 is rest of the request parameters
   */
  private String[] parseRequestParams(HttpServletRequest request) {
    StringBuilder adviceList = null;
    StringBuilder parameterString = new StringBuilder(100);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paramName = (String) e.nextElement();
      if (adviceParams.contains(paramName.toLowerCase())) {
        if (adviceList == null) {
          adviceList = new StringBuilder();
        } else {
          adviceList.append(AMPERSAND);
        }
        String[] values = request.getParameterValues(paramName);
        for (int i = 0; values != null && i < values.length; i++) {
          adviceList.append(paramName).append(EQUAL_TO).append(values[i]);
        }
      } else {
        if (!paramName.equals(GOTO_PARAMETER)) {
          String[] values = request.getParameterValues(paramName);
          for (int i = 0; values != null && i < values.length; i++) {
            parameterString
                .append(AMPERSAND)
                .append(paramName)
                .append(EQUAL_TO)
                .append(URLEncDec.encode(values[i]));
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.parseRequestParams:" + "Advice List is = " + adviceList);
      debug.message(
          "CDCClientServlet.parseRequestParams:"
              + "Parameter String is = "
              + parameterString.toString());
    }

    String policyAdviceList;
    String requestParams;

    if (adviceList == null) {
      policyAdviceList = null;
    } else {
      policyAdviceList = adviceList.toString();
    }

    if (parameterString.length() > 0) {
      requestParams = (parameterString.deleteCharAt(0).toString());
    } else {
      requestParams = parameterString.toString();
    }

    return new String[] {policyAdviceList, requestParams};
  }
Exemple #21
0
 /**
  * 拼接app下单信息查询SQL
  *
  * @return 查询语句
  */
 private static StringBuffer getAppxxSql() {
   HttpServletRequest request = ServletActionContext.getRequest();
   StringBuffer sql = new StringBuffer();
   sql.append("select t.sn as '订单',");
   sql.append(
       " (select sum(it.quantity*it.price) + t.freight -t.promotion_discount - t.coupon_discount from xx_order_item it where it.orders=t.id) as '总金额',");
   sql.append(
       " t.phone as '手机号', "
           + " CASE WHEN t.`source_type`=0 THEN 'iOS' "
           + " WHEN t.`source_type`=1 THEN 'Android' "
           + " WHEN t.`source_type`=2 THEN '微信' "
           + " END AS '客户端' ");
   String datetime_min = request.getParameter("datetime_min");
   String datetime_max = request.getParameter("datetime_max");
   sql.append(
       "from xx_order t where t.create_date between '"
           + datetime_min
           + "' and '"
           + datetime_max
           + " 23:59:59' ");
   String[] order_status = request.getParameterValues("order_status");
   String[] source_type = request.getParameterValues("source_type");
   StringBuffer status_str = new StringBuffer();
   if (order_status != null) {
     if (order_status.length > 0 & order_status[0] != "") {
       for (int i = 0; i < order_status.length; i++) {
         if (i == order_status.length - 1) {
           status_str.append(order_status[i]);
         } else {
           status_str.append(order_status[i] + ",");
         }
       }
       sql.append(" and t.order_status IN (" + status_str + ") ");
     }
   }
   StringBuffer type_str = new StringBuffer();
   if (source_type != null) {
     if (source_type.length > 0 & source_type[0] != "") {
       for (int i = 0; i < source_type.length; i++) {
         if (i == source_type.length - 1) {
           type_str.append(source_type[i]);
         } else {
           type_str.append(source_type[i] + ",");
         }
       }
       sql.append(" and t.source_type in (" + type_str + ") ");
     }
   }
   sql.append(
       " AND NOT EXISTS(SELECT 1 FROM xx_order_way_log l WHERE t.sn = l.order_sn AND l.type = 2)");
   return sql;
 }
  /** {@inheritDoc} */
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession userSession = request.getSession(false);

    if (userSession != null) {
      // group.modifyGroup.jsp
      WebGroup newGroup = (WebGroup) userSession.getAttribute("group.modifyGroup.jsp");

      // get the rest of the group information from the form
      String users[] = request.getParameterValues("selectedUsers");

      newGroup.setUsers(new ArrayList<String>(Arrays.asList(users)));

      String[] selectedCategories = request.getParameterValues("selectedCategories");

      newGroup.setAuthorizedCategories(new ArrayList<String>(Arrays.asList(selectedCategories)));

      Vector<Object> newSchedule = new Vector<Object>();
      ChoiceFormat days = new ChoiceFormat("0#Mo|1#Tu|2#We|3#Th|4#Fr|5#Sa|6#Su");

      Collection<String> dutySchedules = newGroup.getDutySchedules();
      dutySchedules.clear();

      int dutyCount = WebSecurityUtils.safeParseInt(request.getParameter("dutySchedules"));
      for (int duties = 0; duties < dutyCount; duties++) {
        newSchedule.clear();
        String deleteFlag = request.getParameter("deleteDuty" + duties);
        // don't save any duties that were marked for deletion
        if (deleteFlag == null) {
          for (int i = 0; i < 7; i++) {
            String curDayFlag = request.getParameter("duty" + duties + days.format(i));
            if (curDayFlag != null) {
              newSchedule.addElement(Boolean.TRUE);
            } else {
              newSchedule.addElement(Boolean.FALSE);
            }
          }

          newSchedule.addElement(request.getParameter("duty" + duties + "Begin"));
          newSchedule.addElement(request.getParameter("duty" + duties + "End"));

          DutySchedule newDuty = new DutySchedule(newSchedule);
          dutySchedules.add(newDuty.toString());
        }
      }

      userSession.setAttribute("group.modifyGroup.jsp", newGroup);
    }

    return new ModelAndView(request.getParameter("redirect"));
  }
  /**
   * 方法名: testMethod</br> 详述: 微信支付测试方法</br> 开发人员:lis</br> 创建时间:2015-03-20</br>
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(
      value = "/testMethod",
      method = {RequestMethod.POST, RequestMethod.GET})
  @ResponseBody
  public Object testMethod(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> resultMap = new HashMap<String, Object>();

    String id = request.getParameter("id"); // 商品id(单个商品支付)
    String[] ids = request.getParameterValues("id");
    String[] quantity = request.getParameterValues("quantity");
    String userId = request.getParameter("userId"); // 商户id
    try {
      SysUser user = this.userService.getUserByUserId(userId);
      if (null != user) {
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String xmlparam = "";
        xmlparam += "<xml>";
        xmlparam += "<appid></appid>";
        xmlparam += "<mch_id></mch_id>";
        xmlparam += "<nonce_str></nonce_str>";
        xmlparam += "<sign></sign>";
        xmlparam += "<body><![CDATA[]]></body>";
        xmlparam += "<out_trade_no></out_trade_no>";
        xmlparam += "<total_fee>1</total_fee>";
        xmlparam += "<spbill_create_ip>127.0.0.1</spbill_create_ip>";
        xmlparam += "<notify_url></notify_url>";
        xmlparam += "<trade_type>JSAPI</trade_type>";
        xmlparam += "<openid></openid>";
        xmlparam += "</xml>";
        JSONObject json = ConnectUtil.httpsRequest(url, "POST", xmlparam);
        if (json != null) {
          String b[] = new String[5];
          b[0] = "appId=appid";
          b[1] = "timeStamp=timeStamp";
          b[2] = "nonceStr=nonceStr1";
          b[3] = "package=prepay_id";
          b[4] = "signType=MD5";
          Arrays.sort(b);
          resultMap.put("status", "1");
        } else {
          resultMap.put("status", "0");
        }
      } else {
        resultMap.put("status", "0");
      }
    } catch (Exception e) {
      resultMap.put("status", "0");
      e.printStackTrace();
    }
    return resultMap;
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);

    Object[] obj = {"a", bar};
    response.getWriter().println(obj);
  }
 private void setMainInfo() {
   String none = "None";
   subject =
       GlobalNamespace.fromParam(
           req.getParameterValues(parityPrefix + "subject")[classNumber], none);
   type =
       GlobalNamespace.fromParam(req.getParameterValues(parityPrefix + "type")[classNumber], none);
   classroom =
       GlobalNamespace.fromParam(
           req.getParameterValues(parityPrefix + "classroom")[classNumber], none);
   teacher =
       GlobalNamespace.fromParam(
           req.getParameterValues(parityPrefix + "teacher")[classNumber], none);
 }
 private void setTime() {
   startHour =
       GlobalNamespace.fromParamToInt(
           req.getParameterValues(parityPrefix + "start_hour")[classNumber], 0);
   startMinute =
       GlobalNamespace.fromParamToInt(
           req.getParameterValues(parityPrefix + "start_minute")[classNumber], 0);
   endHour =
       GlobalNamespace.fromParamToInt(
           req.getParameterValues(parityPrefix + "end_hour")[classNumber], 0);
   endMinute =
       GlobalNamespace.fromParamToInt(
           req.getParameterValues(parityPrefix + "end_minute")[classNumber], 0);
 }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = doSomething(param);

    java.io.FileOutputStream fos =
        new java.io.FileOutputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
  } // end doPost
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = new Test().doSomething(param);

    Object[] obj = {"a", bar};
    response.getWriter().println(obj);
  } // end doPost
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String[] values = request.getParameterValues("foo");
    String param;
    if (values.length != 0) param = request.getParameterValues("foo")[0];
    else param = null;

    String bar = doSomething(param);

    float rand = new java.util.Random().nextFloat();

    response.getWriter().println("Weak Randomness Test java.util.Random.nextFloat() executed");
  } // end doPost
 @Override
 public String execute(HttpServletRequest request, HttpServletResponse response) {
   String page = null;
   if (request.getParameterValues("checkUser") == null) {
     request.setAttribute("message", "Please_check_users");
     page = "adminUsersPage";
     return page;
   } else {
     UserServiceImpl service = new UserServiceImpl();
     Long adminId = (Long) request.getSession().getAttribute("userid");
     service.deleteUsers(request.getParameterValues("checkUser"), adminId);
     page = "adminUsersPage";
   }
   return page;
 }